Skip to content

Commit

Permalink
feat(core): support strict schemas with no additional properties
Browse files Browse the repository at this point in the history
Fixes: 4255
  • Loading branch information
vsavkin committed Dec 24, 2020
1 parent 21697c2 commit 9923ce9
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 1 deletion.
1 change: 1 addition & 0 deletions packages/tao/src/commands/generate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@ function parseGenerateOpts(
delete generatorOptions.interactive;
delete generatorOptions.defaults;
delete generatorOptions.help;
delete generatorOptions.collection;
delete generatorOptions['--'];

return res;
Expand Down
21 changes: 20 additions & 1 deletion packages/tao/src/shared/params.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -376,7 +376,7 @@ describe('params', () => {
});

describe('validateOptsAgainstSchema', () => {
it('should throw if missing the required field', () => {
it('should throw if missing the required property', () => {
expect(() =>
validateOptsAgainstSchema(
{},
Expand All @@ -392,6 +392,25 @@ describe('params', () => {
).toThrow("Required property 'a' is missing");
});

it('should throw if found an unknown property', () => {
expect(() =>
validateOptsAgainstSchema(
{
a: true,
b: false,
},
{
properties: {
a: {
type: 'boolean',
},
},
additionalProperties: false,
}
)
).toThrow("'b' is not found in schema");
});

it("should throw if the type doesn't match (primitive types)", () => {
expect(() =>
validateOptsAgainstSchema(
Expand Down
12 changes: 12 additions & 0 deletions packages/tao/src/shared/params.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ export type Schema = {
required?: string[];
description?: string;
definitions?: Properties;
additionalProperties?: boolean;
};

export type Unmatched = {
Expand Down Expand Up @@ -156,6 +157,7 @@ export function validateOptsAgainstSchema(
opts,
schema.properties || {},
schema.required || [],
schema.additionalProperties,
schema.definitions || {}
);
}
Expand All @@ -164,6 +166,7 @@ export function validateObject(
opts: { [k: string]: any },
properties: Properties,
required: string[],
additionalProperties: boolean | undefined,
definitions: Properties
) {
required.forEach((p) => {
Expand All @@ -172,6 +175,14 @@ export function validateObject(
}
});

if (additionalProperties === false) {
Object.keys(opts).find((p) => {
if (Object.keys(properties).indexOf(p) === -1) {
throw new SchemaError(`'${p}' is not found in schema`);
}
});
}

Object.keys(opts).forEach((p) => {
validateProperty(p, opts[p], properties[p], definitions);
});
Expand Down Expand Up @@ -222,6 +233,7 @@ function validateProperty(
value,
schema.properties || {},
schema.required || [],
schema.additionalProperties,
definitions
);
}
Expand Down

0 comments on commit 9923ce9

Please sign in to comment.