0

Update Model

by
Published Sep 27, 2024
Script datocms Verified

The script

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

5
export async function main(
6
	resource: Datocms,
7
	modelId: string,
8
	payload: {
9
		name?: string
10
		api_key?: string
11
		collection_appearance?: 'compact' | 'table'
12
		singleton?: boolean
13
		all_locales_required?: boolean
14
		sortable?: boolean
15
		modular_block?: boolean
16
		draft_mode_active?: boolean
17
		tree?: boolean
18
		hint?: string
19
		inverse_relationships_enabled?: boolean
20
	}
21
) {
22
	const endpoint = `https://site-api.datocms.com/item-types/${modelId}`
23

24
	const body = {
25
		data: {
26
			type: 'item_type',
27
			id: modelId,
28
			attributes: payload
29
		}
30
	}
31

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

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

47
	const data = await response.json()
48

49
	return data
50
}
51