0

Update Record

by
Published Sep 27, 2024
Script datocms Verified

The script

Submitted by hugo697 Typescript (fetch-only)
Verified 620 days ago
1
type Datocms = {
2
	apiKey: string
3
}
4

5
export async function main(resource: Datocms, recordId: string, recordData: Record<string, any>) {
6
	const endpoint = `https://site-api.datocms.com/items/${recordId}`
7

8
	const body = {
9
		data: {
10
			id: recordId,
11
			type: 'item',
12
			attributes: recordData
13
		}
14
	}
15

16
	const response = await fetch(endpoint, {
17
		method: 'PUT',
18
		headers: {
19
			Authorization: `Bearer ${resource.apiKey}`,
20
			Accept: 'application/json',
21
			'X-Api-Version': '3',
22
			'Content-Type': 'application/vnd.api+json'
23
		},
24
		body: JSON.stringify(body)
25
	})
26

27
	if (!response.ok) {
28
		throw new Error(`HTTP error! status: ${response.status}`)
29
	}
30

31
	const data = await response.json()
32

33
	return data
34
}
35