//native
type Square = {
token: string;
};
type Base64 = string;
/**
* CreateInvoiceAttachment
* Uploads a file and attaches it to an invoice. This endpoint accepts HTTP multipart/form-data file uploads
with a JSON `request` part and a `file` part. The `file` part must be a `readable stream` that contains a file
in a supported format: GIF, JPEG, PNG, TIFF, BMP, or PDF.
Invoices can have up to 10 attachments with a total file size of 25 MB. Attachments can be added only to invoices
in the `DRAFT`, `SCHEDULED`, `UNPAID`, or `PARTIALLY_PAID` state.
*/
export async function main(
auth: Square,
invoice_id: string,
body: {
request?: { idempotency_key?: string; description?: string };
image_file?: {
base64: Base64;
type:
| "image/png"
| "image/jpeg"
| "image/gif"
| "application/pdf"
| "appication/json"
| "text/csv"
| "text/plain"
| "audio/mpeg"
| "audio/wav"
| "video/mp4";
name: string;
};
},
) {
const url = new URL(
`https://connect.squareup.com/v2/invoices/${invoice_id}/attachments`,
);
const formData = new FormData();
for (const [k, v] of Object.entries(body)) {
if (v !== undefined) {
if (["image_file"].includes(k)) {
const { base64, type, name } = v as {
base64: Base64;
type: string;
name: string;
};
formData.append(
k,
new Blob([Uint8Array.from(atob(base64), (m) => m.codePointAt(0)!)], {
type,
}),
name,
);
} else {
formData.append(k, String(v));
}
}
}
const response = await fetch(url, {
method: "POST",
headers: {
Authorization: "Bearer " + auth.token,
},
body: formData,
});
if (!response.ok) {
const text = await response.text();
throw new Error(`${response.status} ${text}`);
}
return await response.json();
}
Submitted by hugo697 235 days ago