Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(rest): add support for ajv-keywords #3539

Merged
merged 1 commit into from
Aug 16, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions packages/rest/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions packages/rest/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
"@types/serve-static": "1.13.2",
"@types/type-is": "^1.6.2",
"ajv": "^6.10.2",
"ajv-keywords": "^3.4.1",
"body-parser": "^1.19.0",
"cors": "^2.8.5",
"debug": "^4.1.1",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ describe('Validation at REST level', () => {
@property({required: false, type: 'string', jsonSchema: {nullable: true}})
description?: string | null;

@property({required: true})
@property({required: true, jsonSchema: {range: [0, 100]}})
price: number;

constructor(data: Partial<Product>) {
Expand Down Expand Up @@ -115,6 +115,7 @@ describe('Validation at REST level', () => {
givenAnAppAndAClient(ProductController, {
nullable: false,
compiledSchemaCache: new WeakMap(),
ajvKeywords: ['range'],
}),
);
after(() => app.stop());
Expand Down Expand Up @@ -150,6 +151,99 @@ describe('Validation at REST level', () => {
},
});
});

it('rejects requests with price out of range', async () => {
const DATA = {
name: 'iPhone',
description: 'iPhone',
price: 200,
};
const res = await client
.post('/products')
.send(DATA)
.expect(422);

expect(res.body).to.eql({
error: {
statusCode: 422,
name: 'UnprocessableEntityError',
message:
'The request body is invalid. See error object `details` property for more info.',
code: 'VALIDATION_FAILED',
details: [
{
path: '.price',
code: 'maximum',
message: 'should be <= 100',
info: {comparison: '<=', limit: 100, exclusive: false},
},
{
path: '.price',
code: 'range',
message: 'should pass "range" keyword validation',
info: {keyword: 'range'},
},
],
},
});
});
});

context('with request body validation options - {ajvKeywords: true}', () => {
class ProductController {
@post('/products')
async create(
@requestBody({required: true}) data: Product,
): Promise<Product> {
return new Product(data);
}
}

before(() =>
givenAnAppAndAClient(ProductController, {
nullable: false,
compiledSchemaCache: new WeakMap(),
$data: true,
ajvKeywords: true,
}),
);
after(() => app.stop());

it('rejects requests with price out of range', async () => {
const DATA = {
name: 'iPhone',
description: 'iPhone',
price: 200,
};
const res = await client
.post('/products')
.send(DATA)
.expect(422);

expect(res.body).to.eql({
error: {
statusCode: 422,
name: 'UnprocessableEntityError',
message:
'The request body is invalid. See error object `details` property for more info.',
code: 'VALIDATION_FAILED',
details: [
{
path: '.price',
code: 'maximum',
message: 'should be <= 100',
info: {comparison: '<=', limit: 100, exclusive: false},
},
{
path: '.price',
code: 'range',
message: 'should pass "range" keyword validation',
info: {keyword: 'range'},
},
],
},
});
});
});

// A request body schema can be provided explicitly by the user
Expand Down
6 changes: 6 additions & 0 deletions packages/rest/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,12 @@ export interface RequestBodyValidationOptions extends ajv.Options {
* to skip the default cache.
*/
compiledSchemaCache?: SchemaValidatorCache;
/**
* Enable additional AJV keywords from https://github.com/epoberezkin/ajv-keywords
* - `true`: Add all keywords from `ajv-keywords`
* - `string[]`: Add an array of keywords from `ajv-keywords`
*/
ajvKeywords?: true | string[];
}

/* eslint-disable @typescript-eslint/no-explicit-any */
Expand Down
8 changes: 8 additions & 0 deletions packages/rest/src/validation/request-body.validator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ import {RequestBodyValidationOptions, SchemaValidatorCache} from '../types';
const toJsonSchema = require('openapi-schema-to-json-schema');
const debug = debugModule('loopback:rest:validation');

const ajvKeywords = require('ajv-keywords');

/**
* Check whether the request body is valid according to the provided OpenAPI schema.
* The JSON schema is generated from the OpenAPI schema which is typically defined
Expand Down Expand Up @@ -183,5 +185,11 @@ function createValidator(
debug('AJV options', options);
const ajv = new AJV(options);

if (options.ajvKeywords === true) {
ajvKeywords(ajv);
} else if (Array.isArray(options.ajvKeywords)) {
ajvKeywords(ajv, options.ajvKeywords);
}

return ajv.compile(schemaWithRef);
}