๐ฅList, Fetch, and Download Documents
// Requires Node.js 18+ for the built-in fetch API.
import { writeFile } from "node:fs/promises";
const token = process.env.AUTOCONTENT_TOKEN ?? "YOUR_API_TOKEN";
const documentId = process.env.DOCUMENT_ID ?? "YOUR_REQUEST_ID";
const baseUrl = "https://api.autocontentapi.com";
async function api(path, options = {}) {
const response = await fetch(`${baseUrl}${path}`, {
...options,
headers: {
Authorization: `Bearer ${token}`,
Accept: "application/json",
...(options.headers ?? {})
}
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(`Request failed: ${response.status} ${response.statusText}\n${errorText}`);
}
return response;
}
function extensionFromContentType(contentType) {
if (contentType.includes("pdf")) return ".pdf";
if (contentType.includes("html")) return ".html";
return ".txt";
}
async function run() {
const listResponse = await api("/documents/get?page=1&pageSize=10");
const listJson = await listResponse.json();
console.log("Documents page:", listJson);
const documentResponse = await api(`/documents/${documentId}`);
const documentJson = await documentResponse.json();
console.log("Single document:", documentJson);
const downloadResponse = await fetch(`${baseUrl}/documents/${documentId}/download`, {
headers: { Authorization: `Bearer ${token}` }
});
if (!downloadResponse.ok) {
const errorText = await downloadResponse.text();
throw new Error(`Download failed: ${downloadResponse.status} ${downloadResponse.statusText}\n${errorText}`);
}
const contentType = downloadResponse.headers.get("content-type") ?? "application/octet-stream";
const extension = extensionFromContentType(contentType);
const buffer = Buffer.from(await downloadResponse.arrayBuffer());
const outputPath = `briefing-document-${documentId}${extension}`;
await writeFile(outputPath, buffer);
console.log(`Saved ${outputPath}`);
}
run().catch(error => {
console.error(error);
process.exit(1);
});Last updated