0
Create Record
One script reply has been approved by the moderators Verified

Creates a new Contentful record for a given Content Model

Created by hugo697 26 days ago Viewed 10 times
0
Submitted by hugo697 Bun
Verified 26 days ago
1
import Contentful from 'contentful-management'
2

3
type Contentful = {
4
	accessToken: string
5
	environment: string
6
	spaceId: string
7
}
8

9
const makeClient = (resource: Contentful) => {
10
	return Contentful.createClient(
11
		{ accessToken: resource.accessToken },
12
		{
13
			type: 'plain',
14
			defaults: { spaceId: resource.spaceId, environmentId: resource.environment }
15
		}
16
	)
17
}
18

19
// Utility function to key an array by a specific key
20
function keyBy<T>(array: T[], key: keyof T): { [key: string]: T } {
21
	return (array || []).reduce((result, item) => {
22
		const keyValue = key ? item[key] : (item as unknown as string)
23
		result[keyValue as unknown as string] = item
24
		return result
25
	}, {} as { [key: string]: T })
26
}
27

28
type FieldProcessor = (field: Contentful.ContentFields, value: any) => any
29

30
const FieldProcessors: Record<string, FieldProcessor> = {
31
	Link: (field, value) => {
32
		return {
33
			sys: {
34
				type: 'Link',
35
				linkType: field.linkType,
36
				id: value
37
			}
38
		}
39
	},
40
	Array: (field, value) => {
41
		if (field.items?.type === 'Symbol') {
42
			return value
43
		}
44
		if (field.items?.type === 'Link') {
45
			return value.map((v: string) => ({
46
				sys: {
47
					type: 'Link',
48
					linkType: field.items?.linkType,
49
					id: v
50
				}
51
			}))
52
		}
53
	},
54
	Basic: (field, value) => value
55
}
56

57
export async function main(
58
	resource: Contentful,
59
	metadata: {
60
		locale: string
61
		contentTypeId: string
62
		publishOnCreate: boolean
63
		fields: Record<string, any>
64
	}
65
) {
66
	const client = makeClient(resource)
67

68
	const model = await client.contentType.get({
69
		contentTypeId: metadata.contentTypeId
70
	})
71

72
	const fields = keyBy(model.fields, 'id')
73
	const values = metadata.fields
74

75
	// Remove empty fields and process values
76
	for (const key in values) {
77
		if (
78
			values[key] === '' ||
79
			values[key] === null ||
80
			values[key] === undefined ||
81
			(Array.isArray(values[key]) && values[key].length === 0)
82
		) {
83
			delete values[key]
84
			continue
85
		}
86
		const fieldType = fields[key].type
87
		const processor = FieldProcessors[fieldType] || FieldProcessors['Basic']
88
		values[key] = {
89
			[metadata.locale]: await processor(fields[key], values[key])
90
		}
91
	}
92

93
	const record = await client.entry.create({ contentTypeId: model.sys.id }, { fields: values })
94

95
	if (metadata.publishOnCreate) {
96
		await client.entry.publish({ entryId: record.sys.id }, record)
97
	}
98

99
	return record
100
}
101