MCPcopy Create free account
hub / github.com/vercel/examples / validateTemplate

Function validateTemplate

internal/scripts/lib/contentful/validate-template.ts:4–105  ·  view source on GitHub ↗
(template: Template)

Source from the content-addressed store, hash-verified

2import getTemplateFields from './get-template-fields'
3
4export default async function validateTemplate(template: Template) {
5 const fields = await getTemplateFields()
6 const errors: Error[] = []
7
8 fields.forEach(({ id, type, required, validations, items }) => {
9 const val = template[id]
10
11 if (required && !val?.length) {
12 errors.push(
13 new Error(
14 `Error in \`${template.slug}\` template -- missing required template field: \`${id}\``
15 )
16 )
17 return
18 }
19 // Ignore unrequired values that are empty
20 if (!val?.length) return
21
22 if ((type === 'Text' || type === 'Symbol') && typeof val !== 'string') {
23 errors.push(new Error(`"${id}" must be a string`))
24 return
25 }
26
27 if (type === 'Array') {
28 if (!Array.isArray(val)) {
29 errors.push(new Error(`"${id}" must be an array`))
30 return
31 }
32
33 // Validate links
34 if (
35 items?.type === 'Link' &&
36 val.some((item) => typeof item === 'string' || !item.sys)
37 ) {
38 errors.push(
39 new Error(`"${id}" is a link but the value is not a valid link.`)
40 )
41 return
42 }
43
44 items?.validations?.forEach((validation) => {
45 if (
46 validation.in?.length &&
47 val.some((item) =>
48 typeof item === 'string' ? !validation.in!.includes(item) : true
49 )
50 ) {
51 errors.push(
52 new Error(
53 `Error in \`${
54 template.slug
55 }\` template -- "${id}" has an unknown item: "${val.join(
56 ', '
57 )}", it must be one of "${validation.in.join(', ')}"`
58 )
59 )
60 return
61 }

Callers 1

updateTemplateFunction · 0.85

Calls 1

getTemplateFieldsFunction · 0.85

Tested by

no test coverage detected