fix(node): the type keyword may either be a string or an array (#8744)
ISSUES CLOSED: #8112
This commit is contained in:
parent
08dae54011
commit
5a74c02a49
@ -803,6 +803,29 @@ describe('params', () => {
|
||||
).not.toThrow();
|
||||
});
|
||||
|
||||
describe('array', () => {
|
||||
it('should handle validating patterns', () => {
|
||||
const schema = {
|
||||
properties: {
|
||||
a: {
|
||||
type: ['string', 'boolean'],
|
||||
},
|
||||
},
|
||||
};
|
||||
expect(() =>
|
||||
validateOptsAgainstSchema({ a: 'abc' }, schema)
|
||||
).not.toThrow();
|
||||
expect(() =>
|
||||
validateOptsAgainstSchema({ a: true }, schema)
|
||||
).not.toThrow();
|
||||
expect(() =>
|
||||
validateOptsAgainstSchema({ a: 123 }, schema)
|
||||
).toThrowErrorMatchingInlineSnapshot(
|
||||
`"Property 'a' does not match the schema. '123' should be a 'string,boolean'."`
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('string', () => {
|
||||
it('should handle validating patterns', () => {
|
||||
const schema = {
|
||||
|
||||
@ -4,7 +4,7 @@ import { logger } from './logger';
|
||||
import { NxJsonConfiguration } from './nx';
|
||||
|
||||
type PropertyDescription = {
|
||||
type?: string;
|
||||
type?: string | string[];
|
||||
required?: string[];
|
||||
enum?: string[];
|
||||
properties?: any;
|
||||
@ -128,6 +128,14 @@ function coerceType(prop: PropertyDescription | undefined, value: any) {
|
||||
}
|
||||
}
|
||||
return value;
|
||||
} else if (Array.isArray(prop.type)) {
|
||||
for (let i = 0; i < prop.type.length; ++i) {
|
||||
const coerced = coerceType({ type: prop.type[i] }, value);
|
||||
if (coerced !== value) {
|
||||
return coerced;
|
||||
}
|
||||
}
|
||||
return value;
|
||||
} else if (
|
||||
normalizedPrimitiveType(prop.type) == 'boolean' &&
|
||||
isConvertibleToBoolean(value)
|
||||
@ -287,7 +295,25 @@ function validateProperty(
|
||||
|
||||
const isPrimitive = typeof value !== 'object';
|
||||
if (isPrimitive) {
|
||||
if (schema.type && typeof value !== normalizedPrimitiveType(schema.type)) {
|
||||
if (Array.isArray(schema.type)) {
|
||||
const passes = schema.type.some((t) => {
|
||||
try {
|
||||
const rule = { type: t };
|
||||
validateProperty(propName, value, rule, definitions);
|
||||
return true;
|
||||
} catch (e) {
|
||||
return false;
|
||||
}
|
||||
});
|
||||
if (!passes) {
|
||||
throw new SchemaError(
|
||||
`Property '${propName}' does not match the schema. '${value}' should be a '${schema.type}'.`
|
||||
);
|
||||
}
|
||||
} else if (
|
||||
schema.type &&
|
||||
typeof value !== normalizedPrimitiveType(schema.type)
|
||||
) {
|
||||
throw new SchemaError(
|
||||
`Property '${propName}' does not match the schema. '${value}' should be a '${schema.type}'.`
|
||||
);
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user