Skip to content

Delete all documents from storage - Nodejs

You can delete a single document from your storage by calling the /v1/files/${id} endpoint with the DELETE method.

ts
const path = `/v1/files/${id}`;
const url = `${api_url}${path}`;
const method = "DELETE";
const headers = getAuthorizationHeaders(method, path);

const response = await fetch(url, {
  headers,
  method,
});

if (response.status !== 204) {
  const error = await getError(response);

  console.error(error);
  throw new Error(`Error "${error}" calling UnoPdf API "DELETE ${url}".`);
}

return true;

WARNING

If you run this code sample it will remove all documents from your storage

Code

ts
import dotenv from "dotenv";
dotenv.config();

import { getError } from "./errorhandling";
import { getAuthorizationHeaders } from "./authorization";

const api_url = process.env.UNOPDF_API_URL;

interface Document {
  id: string;
}

async function getAllDocuments() {
  // #region get-all-documents
  const path = "/v1/files";
  const url = `${api_url}${path}`;
  const method = "GET";
  const headers = getAuthorizationHeaders(method, path);

  const response = await fetch(url, {
    headers,
    method,
  });

  // #endregion get-all-documents
  if (response.status !== 200) {
    const error = await getError(response);

    console.error(error);
    throw new Error(`Error "${error}" calling UnoPdf API "${url}".`);
  }

  const body = await response.json();

  if (body && typeof body === "object" && "documents" in body) {
    return body.documents as Document[];
  }

  return [];
}

async function deleteDocument(id: string) {
  // #region delete-document
  const path = `/v1/files/${id}`;
  const url = `${api_url}${path}`;
  const method = "DELETE";
  const headers = getAuthorizationHeaders(method, path);

  const response = await fetch(url, {
    headers,
    method,
  });

  if (response.status !== 204) {
    const error = await getError(response);

    console.error(error);
    throw new Error(`Error "${error}" calling UnoPdf API "DELETE ${url}".`);
  }

  return true;
  // #endregion delete-document
}

getAllDocuments()
  .then((documents) => documents.map((document) => deleteDocument(document.id)))
  .then((promises) => Promise.all(promises))
  .then((documents) => console.log(`Deleted ${documents.length} documents`));

Running the example

  • Download the rest - Delete all documents from storage - Nodejs project
  • Unzip the file to a directory rest-delete-all-documents-nodejs.
    shell
    unzip rest-delete-all-documents-nodejs.zip -d rest-delete-all-documents-nodejs
  • Open a terminal and go to that directory
    shell
    cd rest-delete-all-documents-nodejs
  • Install dependencies
    shell
    npm install
    shell
    yarn
  • Start the project
    shell
    npm run start
    shell
    yarn start