os/pkgs/fetch-hostingde-invoices/main.ts

60 lines
1.6 KiB
TypeScript

import { normalize, join } from "std/path/mod.ts";
const secretFile = normalize(Deno.args[0]);
const outDir = normalize(Deno.args[1]);
const decoder = new TextDecoder("utf-8");
const authToken = decoder.decode(await Deno.readFile(secretFile)).trim();
const getFromAPI = (url: string, body: Record<string, any>) => fetch(
url,
{
method: 'POST',
headers: new Headers({
'Content-Type': 'application/json',
'Accept': 'application/json',
}),
body: JSON.stringify({ authToken, ...body }),
}
);
const response = await getFromAPI(
"https://secure.hosting.de/api/billing/v1/json/documentsFind",
{ limit: 50, sort: { field: 'documentDate', order: 'DESC' }},
);
const body = await response.json();
if (body.status !== "success") {
console.error(body.errors);
throw new Error();
}
interface InvoiceDocument {
documentId: string;
}
const documents = body.response.data as InvoiceDocument[];
await Promise.all(documents.map(async (doc) => {
const pdfResponse = await getFromAPI(
"https://secure.hosting.de/api/billing/v1/json/accountingDocumentPdfGet",
{ id: doc.documentId },
);
const fileBody = await pdfResponse.json();
if (body.status !== "success") {
console.error(body.errors);
throw new Error();
}
const url = fileBody.response;
const fileResponse = await fetch(url);
console.log(fileResponse);
const fileContents = await fileResponse.blob();
const fileNameHeader = fileResponse.headers.get('content-disposition') || '';
const fileName = fileNameHeader.split('=')[1];
await Deno.writeFile(join(outDir, fileName), fileContents.stream());
}));