Employ JSON Schema to validate payloads

Signed-off-by: Fabio José <fabiojose@gmail.com>
This commit is contained in:
Fabio José 2019-01-19 23:45:58 -02:00
parent 6f066de091
commit 2bd26d6b8f
3 changed files with 24 additions and 17 deletions

View File

@ -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){

View File

@ -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",

View File

@ -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");