0

Document Attachment Create

by
Published Nov 5, 2024

Creates an attachment for a particular document

Script pandadoc Verified

The script

Submitted by hugo697 Bun
Verified 581 days ago
1
//native
2
type Pandadoc = {
3
	apiKey: string
4
}
5

6
export async function main(
7
	auth: Pandadoc,
8
	id: string,
9
	body: {
10
		file?: {
11
			base64: string
12
			type:
13
				| 'image/png'
14
				| 'image/jpeg'
15
				| 'image/gif'
16
				| 'application/pdf'
17
				| 'appication/json'
18
				| 'text/csv'
19
				| 'text/plain'
20
				| 'audio/mpeg'
21
				| 'audio/wav'
22
				| 'video/mp4'
23
			name: string
24
		}
25
		source?: string
26
		name?: string
27
	}
28
) {
29
	const url = new URL(`https://api.pandadoc.com/public/v1/documents/${id}/attachments`)
30

31
	const formData = new FormData()
32

33
	for (const [k, v] of Object.entries(body)) {
34
		if (v !== undefined && v !== '') {
35
			if (['file'].includes(k)) {
36
				const { base64, type, name } = v as {
37
					base64: string
38
					type: string
39
					name: string
40
				}
41
				formData.append(
42
					k,
43
					new Blob([Uint8Array.from(atob(base64), (m) => m.codePointAt(0)!)], {
44
						type
45
					}),
46
					name
47
				)
48
			} else {
49
				formData.append(k, String(v))
50
			}
51
		}
52
	}
53

54
	const response = await fetch(url, {
55
		method: 'POST',
56
		headers: {
57
			Authorization: `API-Key ${auth.apiKey}`
58
		},
59
		body: formData
60
	})
61

62
	if (!response.ok) {
63
		const text = await response.text()
64
		throw new Error(`${response.status} ${text}`)
65
	}
66

67
	return await response.json()
68
}
69