0

Update Field

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(
6
	resource: Datocms,
7
	fieldId: string,
8
	fieldData: {
9
		label?: string
10
		api_key?: string
11
		localized?: boolean
12
		hint?: string
13
		validators?: Record<string, any>
14
		appearance?: Record<string, any>
15
		default_value?: any
16
		required?: boolean
17
	}
18
) {
19
	const endpoint = `https://site-api.datocms.com/fields/${fieldId}`
20

21
	// Construct the request body
22
	const body = {
23
		data: {
24
			type: 'field',
25
			id: fieldId,
26
			attributes: fieldData
27
		}
28
	}
29

30
	const response = await fetch(endpoint, {
31
		method: 'PUT',
32
		headers: {
33
			Authorization: `Bearer ${resource.apiKey}`,
34
			Accept: 'application/json',
35
			'X-Api-Version': '3',
36
			'Content-Type': 'application/vnd.api+json'
37
		},
38
		body: JSON.stringify(body)
39
	})
40

41
	if (!response.ok) {
42
		throw new Error(`HTTP error! status: ${response.status}`)
43
	}
44

45
	const data = await response.json()
46

47
	return data
48
}
49