1 | |
2 | type Brevo = { |
3 | apiKey: string; |
4 | }; |
5 | type Base64 = string; |
6 | |
7 | * Upload a file |
8 | * |
9 | */ |
10 | export async function main( |
11 | auth: Brevo, |
12 | body: { |
13 | file: { |
14 | base64: Base64; |
15 | type: |
16 | | "image/png" |
17 | | "image/jpeg" |
18 | | "image/gif" |
19 | | "application/pdf" |
20 | | "appication/json" |
21 | | "text/csv" |
22 | | "text/plain" |
23 | | "audio/mpeg" |
24 | | "audio/wav" |
25 | | "video/mp4"; |
26 | name: string; |
27 | }; |
28 | dealId?: string; |
29 | contactId?: number; |
30 | companyId?: string; |
31 | }, |
32 | ) { |
33 | const url = new URL(`https://api.brevo.com/v3/crm/files`); |
34 |
|
35 | const formData = new FormData(); |
36 | for (const [k, v] of Object.entries(body)) { |
37 | if (v !== undefined && v !== "") { |
38 | if (["file"].includes(k)) { |
39 | const { base64, type, name } = v as { |
40 | base64: Base64; |
41 | type: string; |
42 | name: string; |
43 | }; |
44 | formData.append( |
45 | k, |
46 | new Blob([Uint8Array.from(atob(base64), (m) => m.codePointAt(0)!)], { |
47 | type, |
48 | }), |
49 | name, |
50 | ); |
51 | } else { |
52 | formData.append(k, String(v)); |
53 | } |
54 | } |
55 | } |
56 | const response = await fetch(url, { |
57 | method: "POST", |
58 | headers: { |
59 | "api-key": auth.apiKey, |
60 | }, |
61 | body: formData, |
62 | }); |
63 | if (!response.ok) { |
64 | const text = await response.text(); |
65 | throw new Error(`${response.status} ${text}`); |
66 | } |
67 | return await response.json(); |
68 | } |
69 |
|