Uploads a File to a specific folder

Script xero Verified

by hugo697 ยท 12/20/2024

The script

Submitted by hugo697 Bun
Verified 515 days ago
1
//native
2
type Xero = {
3
	token: string
4
}
5
/**
6
 * Uploads a File to a specific folder
7
 *
8
 */
9
export async function main(
10
	auth: Xero,
11
	FolderId: string,
12
	xero_tenant_id: string,
13
	Idempotency_Key: string,
14
	body: { body: string; name: string; filename: string; mimeType?: string }
15
) {
16
	const url = new URL(`https://api.xero.com/files.xro/1.0//Files/${FolderId}`)
17

18
	const formData = new FormData()
19
	for (const [k, v] of Object.entries(body)) {
20
		if (v !== undefined && v !== '') {
21
			formData.append(k, String(v))
22
		}
23
	}
24
	const response = await fetch(url, {
25
		method: 'POST',
26
		headers: {
27
			Accept: 'application/json',
28
			'xero-tenant-id': xero_tenant_id,
29
			'Idempotency-Key': Idempotency_Key,
30
			Authorization: 'Bearer ' + auth.token
31
		},
32
		body: formData
33
	})
34
	if (!response.ok) {
35
		const text = await response.text()
36
		throw new Error(`${response.status} ${text}`)
37
	}
38
	return await response.json()
39
}
40