1 | |
2 | type Telnyx = { |
3 | apiKey: string |
4 | } |
5 | type Base64 = string |
6 | |
7 | * Upload file required for a messaging hosted number order |
8 | * |
9 | */ |
10 | export async function main( |
11 | auth: Telnyx, |
12 | id: string, |
13 | body: { |
14 | loa?: { |
15 | base64: Base64 |
16 | type: |
17 | | 'image/png' |
18 | | 'image/jpeg' |
19 | | 'image/gif' |
20 | | 'application/pdf' |
21 | | 'appication/json' |
22 | | 'text/csv' |
23 | | 'text/plain' |
24 | | 'audio/mpeg' |
25 | | 'audio/wav' |
26 | | 'video/mp4' |
27 | name: string |
28 | } |
29 | bill?: { |
30 | base64: Base64 |
31 | type: |
32 | | 'image/png' |
33 | | 'image/jpeg' |
34 | | 'image/gif' |
35 | | 'application/pdf' |
36 | | 'appication/json' |
37 | | 'text/csv' |
38 | | 'text/plain' |
39 | | 'audio/mpeg' |
40 | | 'audio/wav' |
41 | | 'video/mp4' |
42 | name: string |
43 | } |
44 | } |
45 | ) { |
46 | const url = new URL( |
47 | `https://api.telnyx.com/v2/messaging_hosted_number_orders/${id}/actions/file_upload` |
48 | ) |
49 |
|
50 | const formData = new FormData() |
51 | for (const [k, v] of Object.entries(body)) { |
52 | if (v !== undefined) { |
53 | if (['loa', 'bill'].includes(k)) { |
54 | const { base64, type, name } = v as { |
55 | base64: Base64 |
56 | type: string |
57 | name: string |
58 | } |
59 | formData.append( |
60 | k, |
61 | new Blob([Uint8Array.from(atob(base64), (m) => m.codePointAt(0)!)], { |
62 | type |
63 | }), |
64 | name |
65 | ) |
66 | } else { |
67 | formData.append(k, String(v)) |
68 | } |
69 | } |
70 | } |
71 | const response = await fetch(url, { |
72 | method: 'POST', |
73 | headers: { |
74 | Authorization: 'Bearer ' + auth.apiKey |
75 | }, |
76 | body: formData |
77 | }) |
78 | if (!response.ok) { |
79 | const text = await response.text() |
80 | throw new Error(`${response.status} ${text}`) |
81 | } |
82 | return await response.json() |
83 | } |
84 |
|