Skip to content

Commit

Permalink
fix(@angular-devkit/core): handle async schema validations
Browse files Browse the repository at this point in the history
  • Loading branch information
alan-agius4 authored and filipesilva committed May 31, 2021
1 parent 9f85bc5 commit 06af7d7
Show file tree
Hide file tree
Showing 5 changed files with 36 additions and 22 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -793,7 +793,7 @@ export interface SchemaValidator {
(data: JsonValue, options?: SchemaValidatorOptions): Observable<SchemaValidatorResult>;
}

export declare type SchemaValidatorError = ErrorObject;
export declare type SchemaValidatorError = Partial<ErrorObject>;

export interface SchemaValidatorOptions {
applyPostTransforms?: boolean;
Expand Down
2 changes: 1 addition & 1 deletion packages/angular/cli/models/architect-command.ts
Original file line number Diff line number Diff line change
Expand Up @@ -281,7 +281,7 @@ export abstract class ArchitectCommand<
const newErrors: schema.SchemaValidatorError[] = [];
for (const schemaError of e.errors) {
if (schemaError.keyword === 'additionalProperties') {
const unknownProperty = schemaError.params.additionalProperty;
const unknownProperty = schemaError.params?.additionalProperty;
if (unknownProperty in options) {
const dashes = unknownProperty.length === 1 ? '-' : '--';
this.logger.fatal(`Unknown option: '${dashes}${unknownProperty}'`);
Expand Down
2 changes: 1 addition & 1 deletion packages/angular_devkit/core/src/json/schema/interface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ export interface SchemaValidatorResult {
errors?: SchemaValidatorError[];
}

export type SchemaValidatorError = ErrorObject;
export type SchemaValidatorError = Partial<ErrorObject>;

export interface SchemaValidatorOptions {
applyPreTransforms?: boolean;
Expand Down
46 changes: 31 additions & 15 deletions packages/angular_devkit/core/src/json/schema/registry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,16 +63,18 @@ export class SchemaValidationException extends BaseException {

const messages = errors.map((err) => {
let message = `Data path ${JSON.stringify(err.instancePath)} ${err.message}`;
switch (err.keyword) {
case 'additionalProperties':
message += `(${err.params.additionalProperty})`;
break;

case 'enum':
message += `. Allowed values are: ${(err.params.allowedValues as string[] | undefined)
?.map((v) => `"${v}"`)
.join(', ')}`;
break;
if (err.params) {
switch (err.keyword) {
case 'additionalProperties':
message += `(${err.params.additionalProperty})`;
break;

case 'enum':
message += `. Allowed values are: ${(err.params.allowedValues as string[] | undefined)
?.map((v) => `"${v}"`)
.join(', ')}`;
break;
}
}

return message + '.';
Expand Down Expand Up @@ -300,12 +302,17 @@ export class CoreSchemaRegistry implements SchemaRegistry {
};

this._ajv.removeSchema(schema);

let validator: ValidateFunction;

try {
this._currentCompilationSchemaInfo = schemaInfo;
validator = this._ajv.compile(schema);
} catch {
} catch (e) {
// This should eventually be refactored so that we we handle race condition where the same schema is validated at the same time.
if (!(e instanceof Ajv.MissingRefError)) {
throw e;
}

validator = await this._ajv.compileAsync(schema);
} finally {
this._currentCompilationSchemaInfo = undefined;
Expand Down Expand Up @@ -361,9 +368,18 @@ export class CoreSchemaRegistry implements SchemaRegistry {
}

// Validate using ajv
const success = await validator.call(validationContext, data);
if (!success) {
return { data, success, errors: validator.errors ?? [] };
try {
const success = await validator.call(validationContext, data);

if (!success) {
return { data, success, errors: validator.errors ?? [] };
}
} catch (error) {
if (error instanceof Ajv.ValidationError) {
return { data, success: false, errors: error.errors };
}

throw error;
}

// Apply post-validation transforms
Expand Down
6 changes: 2 additions & 4 deletions packages/angular_devkit/core/src/json/schema/registry_spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -180,9 +180,7 @@ describe('CoreSchemaRegistry', () => {
mergeMap((validator) => validator(data)),
map((result) => {
expect(result.success).toBe(false);
expect(result.errors?.[0].message).toContain(
'must NOT have additional properties',
);
expect(result.errors?.[0].message).toContain('must NOT have additional properties');
expect(result.errors?.[0].keyword).toBe('additionalProperties');
}),
)
Expand Down Expand Up @@ -279,7 +277,7 @@ describe('CoreSchemaRegistry', () => {
expect(result.errors && (result.errors[0].params as any).format).toBe('is-hotdog');
}),
)
.toPromise()
.toPromise();
});

it('supports smart defaults', (done) => {
Expand Down

0 comments on commit 06af7d7

Please sign in to comment.