Skip to content

Commit

Permalink
fix(ajv): Fix ajv validation when obj is undefined or null
Browse files Browse the repository at this point in the history
Closes: #254
  • Loading branch information
Romakita committed Mar 7, 2018
1 parent 4aae6d2 commit d57da29
Show file tree
Hide file tree
Showing 4 changed files with 13 additions and 3 deletions.
4 changes: 2 additions & 2 deletions src/ajv/services/AjvService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import {
ServerSettingsService,
ValidationService
} from "@tsed/common";
import {nameOf, Type} from "@tsed/core";
import {isEmpty, nameOf, Type} from "@tsed/core";
import * as Ajv from "ajv";
import {ErrorObject} from "ajv";
import {BadRequest} from "ts-httpexceptions";
Expand Down Expand Up @@ -42,7 +42,7 @@ export class AjvService extends ValidationService {
public validate(obj: any, targetType: any, baseType?: any): boolean {
let schema = <any>this.jsonSchemaService.getSchemaDefinition(targetType);

if (schema) {
if (schema && !(obj === null || obj === undefined)) {
const collection = baseType ? obj : [obj];
const options = {
ignoreCallback: (obj: any, type: any) => type === Date,
Expand Down
1 change: 1 addition & 0 deletions src/common/filters/class/FilterBuilder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,7 @@ export class FilterBuilder {
try {
validationService.validate(value, type, collectionType);
} catch (err) {
console.error(err);
throw new ParseExpressionError(param.name, param.expression, err.message);
}
return value;
Expand Down
3 changes: 2 additions & 1 deletion test/integration/app/controllers/RestCtrl.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import {Controller, ExpressRouter, Get, Render, RouteService} from "@tsed/common";
import {Controller, ExpressRouter, Get, PathParams, QueryParams, Render, RouteService} from "@tsed/common";
import {Returns, Summary} from "@tsed/swagger";

@Controller("/rest")
export class RestCtrl {
Expand Down
8 changes: 8 additions & 0 deletions test/units/ajv/services/AjvService.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,5 +54,13 @@ describe("AjvService", () => {

return this.ajvService.validate(foo2, JsonFoo2);
});

it("should not throws errors (null)", () => {
return this.ajvService.validate(null, JsonFoo2);
});

it("should not throws errors (undefined)", () => {
return this.ajvService.validate(undefined, JsonFoo2);
});
});
});

0 comments on commit d57da29

Please sign in to comment.