From edd6f6384ffdee958f07dbc564e4ffc8297de64f Mon Sep 17 00:00:00 2001 From: Espen Hovlandsdal Date: Mon, 21 Oct 2019 10:56:00 -0700 Subject: [PATCH] [initial-value-templates] Add validation for references, multidimensional arrays --- .../initial-value-templates/src/validate.ts | 33 ++++++++++++++++++- 1 file changed, 32 insertions(+), 1 deletion(-) diff --git a/packages/@sanity/initial-value-templates/src/validate.ts b/packages/@sanity/initial-value-templates/src/validate.ts index 3fe88a69c1b..f2961b3b005 100644 --- a/packages/@sanity/initial-value-templates/src/validate.ts +++ b/packages/@sanity/initial-value-templates/src/validate.ts @@ -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[]) { @@ -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)) { @@ -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])) @@ -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)}"` + ) + } +}