diff --git a/lib/specs/spec_0_2.js b/lib/specs/spec_0_2.js index 9f790fc..3467a45 100644 --- a/lib/specs/spec_0_2.js +++ b/lib/specs/spec_0_2.js @@ -1,5 +1,13 @@ var uuid = require("uuid/v4"); var empty = require("is-empty"); +var Ajv = require("ajv"); + +const schema = require("../../ext/spec_0_2.json"); + +// Default options +const ajv = new Ajv(); + +const validate = ajv.compile(schema); function Spec02(){ this.payload = { @@ -13,22 +21,12 @@ function Spec02(){ */ Spec02.prototype.check = function(){ - if(empty(this.payload["type"])) { - throw {message: "'type' is invalid"}; + var valid = validate(this.payload); + + if(!valid) { + throw {message: "invalid payload"}; } - if(empty(this.payload["specversion"])) { - throw {message: "'specversion' is invalid"}; - } - - if(this.payload["specversion"] !== "0.2") { - throw {message: "'specversion' value is invalid: '" - + this.payload["specversion"] + "'"}; - } - - if(empty(this.payload["id"])) { - throw {message: "'id' is invalid"}; - } }; Spec02.prototype.type = function(_type){ diff --git a/package.json b/package.json index 7b96490..d746d37 100644 --- a/package.json +++ b/package.json @@ -30,6 +30,7 @@ }, "homepage": "https://github.com/cloudevents/sdk-javascript#readme", "dependencies": { + "ajv": "^6.7.0", "axios": "0.18.0", "is-empty": "1.2.0", "uri-js": "4.2.2", diff --git a/test/cloudevent_spec_0_2.js b/test/cloudevent_spec_0_2.js index af751d9..e8fa997 100644 --- a/test/cloudevent_spec_0_2.js +++ b/test/cloudevent_spec_0_2.js @@ -73,7 +73,7 @@ describe("CloudEvents Spec 0.2 - JavaScript SDK", () => { cloudevent.type(""); expect(cloudevent.format.bind(cloudevent)) .to - .throw("'type' is invalid"); + .throw("invalid payload"); }); it("must be a non-empty string", () => { @@ -95,7 +95,15 @@ describe("CloudEvents Spec 0.2 - JavaScript SDK", () => { cloudevent.spec.payload.specversion = ""; expect(cloudevent.format.bind(cloudevent)) .to - .throw("'specversion' is invalid"); + .throw("invalid payload"); + cloudevent.spec.payload.specversion = "0.2"; + }); + + it("should throw an error when the value is not '0.2'", () => { + cloudevent.spec.payload.specversion = "0.4"; + expect(cloudevent.format.bind(cloudevent)) + .to + .throw("invalid payload"); cloudevent.spec.payload.specversion = "0.2"; }); }); @@ -105,7 +113,7 @@ describe("CloudEvents Spec 0.2 - JavaScript SDK", () => { cloudevent.id(""); expect(cloudevent.format.bind(cloudevent)) .to - .throw("'id' is invalid"); + .throw("invalid payload"); }); it("must be a non-empty string", () => { cloudevent.id("my.id-0x0090");