Skip to content

Commit

Permalink
Throw on invalid or unregistered schema
Browse files Browse the repository at this point in the history
  • Loading branch information
carragom committed Jul 27, 2022
1 parent ce5555e commit 45fdd6a
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 4 deletions.
2 changes: 1 addition & 1 deletion src/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -311,7 +311,7 @@ class Context extends EventEmitter {
/**
* Get JSON schema validation function.
*/
schema(schema: Record<string, any> | string): ValidatorFunction | null {
schema(schema: Record<string, any> | string): ValidatorFunction {
return this.app.validator.schema(schema);
}

Expand Down
5 changes: 3 additions & 2 deletions src/validator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ export class Validator {
/**
* Get JSON schema validation function.
*/
schema(schema: JSONObject | string): ValidatorFunction | null {
schema(schema: JSONObject | string): ValidatorFunction {
const ajv = this._ajv;

let validate: ValidateFunction | undefined;
Expand All @@ -30,7 +30,8 @@ export class Validator {
} else {
validate = ajv.compile(schema);
}
if (validate === undefined) return null;

if (validate === undefined) throw new Error(`Invalid schema: '${schema}'`);

return function (data: JSONObject): ValidatorResult {
const isValid = (validate as ValidateFunction)(data);
Expand Down
6 changes: 5 additions & 1 deletion test/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -833,7 +833,11 @@ t.test('App', async t => {
(await ua.putOk('/schema/user', {json: {user: 'kraih'}})).statusIs(200).jsonIs({valid: false});
(await ua.putOk('/schema/user', {json: {username: 'sri'}})).statusIs(200).jsonIs({valid: true});

t.notOk(app.validator.schema('test123'));
const schema = 'test123';
t.throws(() => {
app.validator.schema(schema);
}, new Error(`Invalid schema: '${schema}'`));

(await ua.putOk('/schema/dynamic', {json: {test: 123}})).statusIs(200).jsonIs({valid: true, errors: []});
(await ua.putOk('/schema/dynamic', {json: {test: '123'}})).statusIs(200).jsonIs({valid: true, errors: []});
(await ua.putOk('/schema/dynamic', {json: {test: ' 123'}})).statusIs(200).jsonIs({valid: true, errors: []});
Expand Down

0 comments on commit 45fdd6a

Please sign in to comment.