0

Create 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
	modelData: {
8
		name: string
9
		api_key: string
10
		singleton?: boolean
11
		all_locales_required?: boolean
12
		sortable?: boolean
13
		modular_block?: boolean
14
		draft_mode_active?: boolean
15
		tree?: boolean
16
		collection_appearance?: 'compact' | 'table'
17
		hint?: string
18
		inverse_relationships_enabled?: boolean
19
	}
20
) {
21
	const endpoint = `https://site-api.datocms.com/item-types`
22

23
	// Construct the request body
24
	const body = {
25
		data: {
26
			type: 'item_type',
27
			attributes: modelData
28
		}
29
	}
30

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

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

46
	const data = await response.json()
47

48
	return data
49
}
50