From 820259feef1fa5bf0fbf5d8186904bc61f3bd4a6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leosvel=20P=C3=A9rez=20Espinosa?= Date: Fri, 5 May 2023 09:47:24 +0100 Subject: [PATCH] fix(core): handle schema property with const value --- packages/nx/src/utils/params.spec.ts | 21 +++++++++++++++++++++ packages/nx/src/utils/params.ts | 7 +++++++ 2 files changed, 28 insertions(+) diff --git a/packages/nx/src/utils/params.spec.ts b/packages/nx/src/utils/params.spec.ts index bd3abfbfcd7f3..13420d56b269d 100644 --- a/packages/nx/src/utils/params.spec.ts +++ b/packages/nx/src/utils/params.spec.ts @@ -982,6 +982,27 @@ describe('params', () => { ).not.toThrow(); }); + it('should handle const value', () => { + const schema = { + properties: { + a: { + const: 3, + }, + }, + }; + expect(() => validateOptsAgainstSchema({ a: 3 }, schema)).not.toThrow(); + expect(() => + validateOptsAgainstSchema({ a: true }, schema) + ).toThrowErrorMatchingInlineSnapshot( + `"Property 'a' does not match the schema. 'true' should be '3'."` + ); + expect(() => + validateOptsAgainstSchema({ a: 123 }, schema) + ).toThrowErrorMatchingInlineSnapshot( + `"Property 'a' does not match the schema. '123' should be '3'."` + ); + }); + describe('array', () => { it('should handle validating patterns', () => { const schema = { diff --git a/packages/nx/src/utils/params.ts b/packages/nx/src/utils/params.ts index c9ab3b783a88e..5b6ff5717a4c2 100644 --- a/packages/nx/src/utils/params.ts +++ b/packages/nx/src/utils/params.ts @@ -33,6 +33,7 @@ type PropertyDescription = { | { $source: 'projectName' } | { $source: 'unparsed' }; additionalProperties?: boolean; + const?: any; 'x-prompt'?: | string | { message: string; type: string; items?: any[]; multiselect?: boolean }; @@ -359,6 +360,12 @@ function validateProperty( const isPrimitive = typeof value !== 'object'; if (isPrimitive) { + if (schema.const !== undefined && value !== schema.const) { + throw new SchemaError( + `Property '${propName}' does not match the schema. '${value}' should be '${schema.const}'.` + ); + } + if (Array.isArray(schema.type)) { const passes = schema.type.some((t) => { try {