import { readFile } from 'node:fs/promises';
const GRAPHQL_URL = process.env.BONX_GRAPHQL_URL;
const API_KEY = process.env.BONX_API_KEY;
const PDF_CONTENT_TYPE = 'application/pdf';
async function graphql(query, variables) {
const response = await fetch(GRAPHQL_URL, {
method: 'POST',
headers: {
'x-api-key': API_KEY,
'Content-Type': 'application/json',
},
body: JSON.stringify({ query, variables }),
});
if (!response.ok) {
throw new Error(`GraphQL HTTP error: ${response.status}`);
}
const result = await response.json();
if (result.errors) {
throw new Error(JSON.stringify(result.errors));
}
return result.data;
}
async function uploadPdfToSalesOrder({ salesOrderId, filePath, fileName }) {
const pdf = await readFile(filePath);
// 1. Request a temporary upload URL
const { generatePresignedUrlUpload: upload } = await graphql(
`
mutation CreateUploadUrl($fileName: String!, $contentType: String) {
generatePresignedUrlUpload(fileName: $fileName, contentType: $contentType) {
uploadUrl
fileName
}
}
`,
{ fileName, contentType: PDF_CONTENT_TYPE },
);
// 2. Send the PDF to this URL
const uploadResponse = await fetch(upload.uploadUrl, {
method: 'PUT',
headers: { 'Content-Type': PDF_CONTENT_TYPE },
body: pdf,
});
if (!uploadResponse.ok) {
throw new Error(`PDF upload failed: ${uploadResponse.status}`);
}
// 3. Link the file to the sales order
const { insertFilesOne: file } = await graphql(
`
mutation AttachFile($fileId: String!, $name: String!, $size: Int!, $recordId: Int!) {
insertFilesOne(
object: {
fileId: $fileId
name: $name
contentType: "application/pdf"
size: $size
recordId: $recordId
recordType: "salesOrders"
}
) {
id
}
}
`,
{
fileId: upload.fileName,
name: fileName,
size: pdf.length,
recordId: salesOrderId,
},
);
return file;
}
const file = await uploadPdfToSalesOrder({
salesOrderId: 42,
filePath: './customer-purchase-order.pdf',
fileName: 'Customer purchase order.pdf',
});
console.log('PDF added:', file.id);