//native
type Gorgias = {
username: string;
apiKey: string;
domain: string;
};
type Base64 = string;
/**
* Upload files
* You can upload several files at a time by adding parameters to the root of the request body. The name of each parameter will be used as the label of the file once uploaded. E.g:
- parameter name: `package-damaged.png`
- parameter value: Content of the file.
*/
export async function main(
auth: Gorgias,
body: {
your_unique_file_label?: {
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://${auth.domain}.gorgias.com/api/upload`);
const formData = new FormData();
for (const [k, v] of Object.entries(body)) {
if (v !== undefined) {
if (["your_unique_file_label"].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: "Basic " + btoa(`${auth.username}:${auth.apiKey}`),
},
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