Skip to content

Commit

Permalink
[initial-value-templates] Add validation for references, multidimensi…
Browse files Browse the repository at this point in the history
…onal arrays
  • Loading branch information
rexxars committed Oct 24, 2019
1 parent 5ca7191 commit edd6f63
Showing 1 changed file with 32 additions and 1 deletion.
33 changes: 32 additions & 1 deletion packages/@sanity/initial-value-templates/src/validate.ts
Expand Up @@ -7,6 +7,7 @@ import {getDefaultSchema} from './parts/Schema'

export {validateInitialValue, validateTemplates}

const ALLOWED_REF_PROPS = ['_key', '_ref', '_weak', '_type']
const REQUIRED_TEMPLATE_PROPS: (keyof Template)[] = ['id', 'title', 'schemaType', 'value']

function validateTemplates(templates: Template[]) {
Expand Down Expand Up @@ -81,7 +82,15 @@ function validateInitialValue(value: {[key: string]: any}, template: Template) {

function validateValue(value: any, path: (string | number)[] = [], parentIsArray = false): any {
if (Array.isArray(value)) {
return value.map((item, i) => validateValue(item, path.concat(i), true))
return value.map((item, i) => {
if (Array.isArray(item)) {
throw new Error(
`multidimensional arrays are not supported (at path "${pathToString(path)}")`
)
}

return validateValue(item, path.concat(i), true)
})
}

if (!isPlainObject(value)) {
Expand All @@ -101,6 +110,10 @@ function validateValue(value: any, path: (string | number)[] = [], parentIsArray
}
}

if (value._ref) {
validateReference(value, path)
}

// Validate deeply
return Object.keys(value).reduce((acc, key) => {
acc[key] = validateValue(value[key], path.concat([key]))
Expand Down Expand Up @@ -130,3 +143,21 @@ function validateParameter(parameter: TemplateParameter, template: Template, ind
)
}
}

function validateReference(value, path: (string | number)[] = []) {
if (!value._type && value.type) {
throw new Error(
`Reference is missing "_type", but has a "type" property at path "${pathToString(path)}"`
)
}

const disallowed = Object.keys(value).filter(key => !ALLOWED_REF_PROPS.includes(key))
if (disallowed.length > 0) {
const plural = disallowed.length > 1 ? 'properties' : 'property'
throw new Error(
`Disallowed ${plural} found in reference: ${disallowed
.map(quote)
.join(', ')} at path "${pathToString(path)}"`
)
}
}

0 comments on commit edd6f63

Please sign in to comment.