src: add eslint configuration and npm script

Automatically fixed > 2000 issues. The remaining 200+ issues need
to be fixed by hand. Additionally, all strings are double quotes
which is not typically standard and I wonder about fixing that too.

Signed-off-by: Lance Ball <lball@redhat.com>
This commit is contained in:
Lance Ball 2020-04-14 17:11:42 -04:00
parent b03a243b20
commit 3f238a0124
No known key found for this signature in database
GPG Key ID: DB1D2F8DCDB4EE5C
54 changed files with 3595 additions and 2261 deletions

26
.eslintrc Normal file
View File

@ -0,0 +1,26 @@
{
"extends": "eslint:recommended",
"env": {
"es6": true,
"node": true,
"mocha": true
},
"rules": {
"space-before-function-paren": ["error", "never"],
"standard/no-callback-literal": "off",
"arrow-spacing": "error",
"arrow-parens": ["error", "always"],
"arrow-body-style": ["error", "as-needed"],
"prefer-template": "error",
"max-len": ["warn", { "code": 80 }],
"no-unused-vars": ["warn", {
"argsIgnorePattern": "^_$|^e$|^reject$|^resolve$"
}],
"no-console": ["error", {
"allow": ["warn", "error"]
}],
"valid-jsdoc": "error",
"semi": ["error", "always"],
"quotes": ["error", "double", { "allowTemplateLiterals": true }]
}
}

View File

@ -1,3 +1,5 @@
/* eslint-disable no-console */
const express = require("express"); const express = require("express");
const app = express(); const app = express();
@ -12,103 +14,101 @@ const structured1 = new v1.StructuredHTTPReceiver();
const binary1 = new v1.BinaryHTTPReceiver(); const binary1 = new v1.BinaryHTTPReceiver();
app.use((req, res, next) => { app.use((req, res, next) => {
let data=""; let data = "";
req.setEncoding("utf8"); req.setEncoding("utf8");
req.on("data", function(chunk) { req.on("data", function(chunk) {
data += chunk; data += chunk;
}); });
req.on("end", function() { req.on("end", function() {
req.body = data; req.body = data;
next(); next();
}); });
}); });
app.post("/v1", function (req, res) { app.post("/v1", function(req, res) {
console.log(req.headers); console.log(req.headers);
console.log(req.body); console.log(req.body);
try { try {
let myevent = structured1.parse(req.body, req.headers); const myevent = structured1.parse(req.body, req.headers);
// pretty print // pretty print
console.log("Accepted event:"); console.log("Accepted event:");
console.log(JSON.stringify(myevent.format(), null, 2)); console.log(JSON.stringify(myevent.format(), null, 2));
res.status(201) res.status(201)
.json(myevent.format()); .json(myevent.format());
} catch (err) { } catch (err) {
console.error(err); console.error(err);
res.status(415) res.status(415)
.header("Content-Type", "application/json") .header("Content-Type", "application/json")
.send(JSON.stringify(err)); .send(JSON.stringify(err));
} }
}); });
app.post("/v1/binary", function (req, res) { app.post("/v1/binary", function(req, res) {
console.log(req.headers); console.log(req.headers);
console.log(req.body); console.log(req.body);
try { try {
let myevent = binary1.parse(req.body, req.headers); const myevent = binary1.parse(req.body, req.headers);
// pretty print // pretty print
console.log("Accepted event:"); console.log("Accepted event:");
console.log(JSON.stringify(myevent.format(), null, 2)); console.log(JSON.stringify(myevent.format(), null, 2));
res.status(201) res.status(201)
.json(myevent.format()); .json(myevent.format());
} catch (err) { } catch (err) {
console.error(err); console.error(err);
res.status(415) res.status(415)
.header("Content-Type", "application/json") .header("Content-Type", "application/json")
.send(JSON.stringify(err)); .send(JSON.stringify(err));
} }
}); });
app.post("/v03", function (req, res) { app.post("/v03", function(req, res) {
console.log(req.headers); console.log(req.headers);
console.log(req.body); console.log(req.body);
unmarshaller03.unmarshall(req.body, req.headers) unmarshaller03.unmarshall(req.body, req.headers)
.then(cloudevent => { .then((cloudevent) => {
// pretty print // pretty print
console.log("Accepted event:"); console.log("Accepted event:");
console.log(JSON.stringify(cloudevent.format(), null, 2)); console.log(JSON.stringify(cloudevent.format(), null, 2));
res.status(201) res.status(201)
.json(cloudevent.format()); .json(cloudevent.format());
}) })
.catch(err => { .catch((err) => {
console.error(err); console.error(err);
res.status(415) res.status(415)
.header("Content-Type", "application/json") .header("Content-Type", "application/json")
.send(JSON.stringify(err)); .send(JSON.stringify(err));
}); });
}); });
app.post("/v02", function (req, res) { app.post("/v02", function(req, res) {
console.log(req.headers); console.log(req.headers);
console.log(req.body); console.log(req.body);
unmarshaller02.unmarshall(req.body, req.headers) unmarshaller02.unmarshall(req.body, req.headers)
.then(cloudevent => { .then((cloudevent) => {
// pretty print // pretty print
console.log("Accepted event:"); console.log("Accepted event:");
console.log(JSON.stringify(cloudevent.format(), null, 2)); console.log(JSON.stringify(cloudevent.format(), null, 2));
res.status(201) res.status(201)
.json(cloudevent.format()); .json(cloudevent.format());
}) })
.catch(err => { .catch((err) => {
console.error(err); console.error(err);
res.status(415) res.status(415)
.header("Content-Type", "application/json") .header("Content-Type", "application/json")
.send(JSON.stringify(err)); .send(JSON.stringify(err));
}); });
}); });
app.listen(3000, function () { app.listen(3000, function() {
console.log("Example app listening on port 3000!"); console.log("Example app listening on port 3000!");
}); });

View File

@ -1,4 +1,4 @@
module.exports = { module.exports = {
singleQuote: true, singleQuote: true,
trailingComma: 'es5', trailingComma: "es5"
}; };

View File

@ -2,18 +2,17 @@ const Constants = require("./constants.js");
// Specific sanity for content-type header // Specific sanity for content-type header
function sanityContentType(contentType) { function sanityContentType(contentType) {
if(contentType) { if (contentType) {
return Array.of(contentType) return Array.of(contentType)
.map((c) => c.split(";")) .map((c) => c.split(";"))
.map((c) => c.shift()) .map((c) => c.shift())
.shift(); .shift();
} }
return contentType; return contentType;
} }
function sanityAndClone(headers) { function sanityAndClone(headers) {
const sanityHeaders = {}; const sanityHeaders = {};
Array.from(Object.keys(headers)) Array.from(Object.keys(headers))

View File

@ -1,92 +1,92 @@
// Commons // Commons
module.exports = { module.exports = {
HEADERS : "headers", HEADERS: "headers",
CHARSET_DEFAULT : "utf-8", CHARSET_DEFAULT: "utf-8",
SPEC_V02 : "0.2", SPEC_V02: "0.2",
SPEC_V03 : "0.3", SPEC_V03: "0.3",
SPEC_V1 : "1.0", SPEC_V1: "1.0",
DEFAULT_SPEC_VERSION_HEADER : "ce-specversion", DEFAULT_SPEC_VERSION_HEADER: "ce-specversion",
ENCODING_BASE64 : "base64", ENCODING_BASE64: "base64",
DATA_ATTRIBUTE : "data", DATA_ATTRIBUTE: "data",
MIME_JSON : "application/json", MIME_JSON: "application/json",
MIME_OCTET_STREAM : "application/octet-stream", MIME_OCTET_STREAM: "application/octet-stream",
MIME_CE : "application/cloudevents", MIME_CE: "application/cloudevents",
MIME_CE_JSON : "application/cloudevents+json", MIME_CE_JSON: "application/cloudevents+json",
HEADER_CONTENT_TYPE : "content-type", HEADER_CONTENT_TYPE: "content-type",
DEFAULT_CONTENT_TYPE : "application/json; charset=utf-8", DEFAULT_CONTENT_TYPE: "application/json; charset=utf-8",
DEFAULT_CE_CONTENT_TYPE : "application/cloudevents+json; charset=utf-8", DEFAULT_CE_CONTENT_TYPE: "application/cloudevents+json; charset=utf-8",
BINARY_HEADERS_02 : { BINARY_HEADERS_02: {
TYPE : "ce-type", TYPE: "ce-type",
SPEC_VERSION : "ce-specversion", SPEC_VERSION: "ce-specversion",
SOURCE : "ce-source", SOURCE: "ce-source",
ID : "ce-id", ID: "ce-id",
TIME : "ce-time", TIME: "ce-time",
SCHEMA_URL : "ce-schemaurl", SCHEMA_URL: "ce-schemaurl",
EXTENSIONS_PREFIX : "ce-" EXTENSIONS_PREFIX: "ce-"
}, },
STRUCTURED_ATTRS_02 : { STRUCTURED_ATTRS_02: {
TYPE : "type", TYPE: "type",
SPEC_VERSION : "specversion", SPEC_VERSION: "specversion",
SOURCE : "source", SOURCE: "source",
ID : "id", ID: "id",
TIME : "time", TIME: "time",
SCHEMA_URL : "schemaurl", SCHEMA_URL: "schemaurl",
CONTENT_TYPE : "contenttype", CONTENT_TYPE: "contenttype",
DATA : "data" DATA: "data"
}, },
BINARY_HEADERS_03 : { BINARY_HEADERS_03: {
TYPE : "ce-type", TYPE: "ce-type",
SPEC_VERSION : "ce-specversion", SPEC_VERSION: "ce-specversion",
SOURCE : "ce-source", SOURCE: "ce-source",
ID : "ce-id", ID: "ce-id",
TIME : "ce-time", TIME: "ce-time",
SCHEMA_URL : "ce-schemaurl", SCHEMA_URL: "ce-schemaurl",
CONTENT_ENCONDING : "ce-datacontentencoding", CONTENT_ENCONDING: "ce-datacontentencoding",
SUBJECT : "ce-subject", SUBJECT: "ce-subject",
EXTENSIONS_PREFIX : "ce-" EXTENSIONS_PREFIX: "ce-"
}, },
STRUCTURED_ATTRS_03 : { STRUCTURED_ATTRS_03: {
TYPE : "type", TYPE: "type",
SPEC_VERSION : "specversion", SPEC_VERSION: "specversion",
SOURCE : "source", SOURCE: "source",
ID : "id", ID: "id",
TIME : "time", TIME: "time",
SCHEMA_URL : "schemaurl", SCHEMA_URL: "schemaurl",
CONTENT_ENCONDING : "datacontentencoding", CONTENT_ENCONDING: "datacontentencoding",
CONTENT_TYPE : "datacontenttype", CONTENT_TYPE: "datacontenttype",
SUBJECT : "subject", SUBJECT: "subject",
DATA : "data" DATA: "data"
}, },
BINARY_HEADERS_1 : { BINARY_HEADERS_1: {
TYPE : "ce-type", TYPE: "ce-type",
SPEC_VERSION : "ce-specversion", SPEC_VERSION: "ce-specversion",
SOURCE : "ce-source", SOURCE: "ce-source",
ID : "ce-id", ID: "ce-id",
TIME : "ce-time", TIME: "ce-time",
DATA_SCHEMA : "ce-dataschema", DATA_SCHEMA: "ce-dataschema",
SUBJECT : "ce-subject", SUBJECT: "ce-subject",
EXTENSIONS_PREFIX : "ce-" EXTENSIONS_PREFIX: "ce-"
}, },
STRUCTURED_ATTRS_1 : { STRUCTURED_ATTRS_1: {
TYPE : "type", TYPE: "type",
SPEC_VERSION : "specversion", SPEC_VERSION: "specversion",
SOURCE : "source", SOURCE: "source",
ID : "id", ID: "id",
TIME : "time", TIME: "time",
DATA_SCHEMA : "dataschema", DATA_SCHEMA: "dataschema",
CONTENT_TYPE : "datacontenttype", CONTENT_TYPE: "datacontenttype",
SUBJECT : "subject", SUBJECT: "subject",
DATA : "data", DATA: "data",
DATA_BASE64 : "data_base64" DATA_BASE64: "data_base64"
} }
}; };

View File

@ -1,17 +1,18 @@
var axios = require("axios"); const axios = require("axios");
const Constants = require("./constants.js"); const Constants = require("./constants.js");
const defaults = {}; const defaults = {};
defaults[Constants.HEADERS] = {}; defaults[Constants.HEADERS] = {};
defaults[Constants.HEADERS][Constants.HEADER_CONTENT_TYPE] = Constants.DEFAULT_CONTENT_TYPE; defaults[Constants.HEADERS][Constants.HEADER_CONTENT_TYPE] =
Constants.DEFAULT_CONTENT_TYPE;
function BinaryHTTPEmitter(config, headerByGetter, extensionPrefix){ function BinaryHTTPEmitter(config, headerByGetter, extensionPrefix) {
this.config = Object.assign({}, defaults, config); this.config = Object.assign({}, defaults, config);
this.headerByGetter = headerByGetter; this.headerByGetter = headerByGetter;
this.extensionPrefix = extensionPrefix; this.extensionPrefix = extensionPrefix;
} }
BinaryHTTPEmitter.prototype.emit = function (cloudevent) { BinaryHTTPEmitter.prototype.emit = function(cloudevent) {
const config = Object.assign({}, this.config); const config = Object.assign({}, this.config);
const headers = Object.assign({}, this.config[Constants.HEADERS]); const headers = Object.assign({}, this.config[Constants.HEADERS]);
@ -28,7 +29,7 @@ BinaryHTTPEmitter.prototype.emit = function (cloudevent) {
// Set the cloudevent payload // Set the cloudevent payload
const formatted = cloudevent.format(); const formatted = cloudevent.format();
let data = formatted.data; let data = formatted.data;
data = (formatted.data_base64 ? formatted.data_base64: data); data = (formatted.data_base64 ? formatted.data_base64 : data);
// Have extensions? // Have extensions?
const exts = cloudevent.getExtensions(); const exts = cloudevent.getExtensions();
@ -41,8 +42,8 @@ BinaryHTTPEmitter.prototype.emit = function (cloudevent) {
config[Constants.DATA_ATTRIBUTE] = data; config[Constants.DATA_ATTRIBUTE] = data;
config.headers = headers; config.headers = headers;
// Return the Promise // Return the Promise
return axios.request(config); return axios.request(config);
}; };
module.exports = BinaryHTTPEmitter; module.exports = BinaryHTTPEmitter;

View File

@ -4,70 +4,68 @@ const Constants = require("./constants.js");
const headerByGetter = {}; const headerByGetter = {};
headerByGetter["getContenttype"] = { headerByGetter.getContenttype = {
name : Constants.HEADER_CONTENT_TYPE, name: Constants.HEADER_CONTENT_TYPE,
parser : (v) => v parser: (v) => v
}; };
headerByGetter["getType"] = { headerByGetter.getType = {
name : "CE-EventType", name: "CE-EventType",
parser : (v) => v parser: (v) => v
}; };
headerByGetter["getSpecversion"] = { headerByGetter.getSpecversion = {
name : "CE-CloudEventsVersion", name: "CE-CloudEventsVersion",
parser : (v) => v parser: (v) => v
}; };
headerByGetter["getSource"] = { headerByGetter.getSource = {
name : "CE-Source", name: "CE-Source",
parser : (v) => v parser: (v) => v
}; };
headerByGetter["getId"] = { headerByGetter.getId = {
name : "CE-EventID", name: "CE-EventID",
parser : (v) => v parser: (v) => v
}; };
headerByGetter["getEventTypeVersion"] = { headerByGetter.getEventTypeVersion = {
name : "CE-EventTypeVersion", name: "CE-EventTypeVersion",
parser : (v) => v parser: (v) => v
}; };
headerByGetter["getTime"] = { headerByGetter.getTime = {
name : "CE-EventTime", name: "CE-EventTime",
parser : (v) => v parser: (v) => v
}; };
headerByGetter["getSchemaurl"] = { headerByGetter.getSchemaurl = {
name : "CE-SchemaURL", name: "CE-SchemaURL",
parser : (v) => v parser: (v) => v
}; };
function HTTPBinary(configuration){ function HTTPBinary(configuration) {
this.config = JSON.parse(JSON.stringify(configuration)); this.config = JSON.parse(JSON.stringify(configuration));
if(!this.config["headers"]){ if (!this.config.headers) {
this.config["headers"] = {}; this.config.headers = {};
} }
this.config["headers"] this.config.headers[Constants.HEADER_CONTENT_TYPE] =
[Constants.HEADER_CONTENT_TYPE] = `${Constants.MIME_JSON}; charset=${Constants.CHARSET_DEFAULT}`;
Constants.MIME_JSON + "; charset=" + Constants.CHARSET_DEFAULT;
} }
HTTPBinary.prototype.emit = function(cloudevent){ HTTPBinary.prototype.emit = function(cloudevent) {
// Create new request object // Create new request object
const _config = JSON.parse(JSON.stringify(this.config)); const _config = JSON.parse(JSON.stringify(this.config));
// Always set stuff in _config // Always set stuff in _config
const _headers = _config["headers"]; const _headers = _config.headers;
Object.keys(headerByGetter) Object.keys(headerByGetter)
.filter((getter) => cloudevent[getter]()) .filter((getter) => cloudevent[getter]())
.forEach((getter) => { .forEach((getter) => {
let header = headerByGetter[getter]; const header = headerByGetter[getter];
_headers[header.name] = _headers[header.name] =
header.parser( header.parser(
cloudevent[getter]() cloudevent[getter]()
@ -75,15 +73,15 @@ HTTPBinary.prototype.emit = function(cloudevent){
}); });
// Set the cloudevent payload // Set the cloudevent payload
_config["data"] = cloudevent.format().data; _config.data = cloudevent.format().data;
// EXTENSION CONTEXT ATTRIBUTES // EXTENSION CONTEXT ATTRIBUTES
const exts = cloudevent.getExtensions(); const exts = cloudevent.getExtensions();
Object.keys(exts) Object.keys(exts)
.filter((ext) => Object.hasOwnProperty.call(exts, ext)) .filter((ext) => Object.hasOwnProperty.call(exts, ext))
.forEach((ext) => { .forEach((ext) => {
let capsExt = ext.charAt(0).toUpperCase() + ext.slice(1); const capsExt = ext.charAt(0).toUpperCase() + ext.slice(1);
_headers["CE-X-" + capsExt] = exts[ext]; _headers[`CE-X-${capsExt}`] = exts[ext];
}); });
// Return the Promise // Return the Promise

View File

@ -4,42 +4,42 @@ const Constants = require("./constants.js");
const headerByGetter = {}; const headerByGetter = {};
headerByGetter["getContenttype"] = { headerByGetter.getContenttype = {
name : Constants.HEADER_CONTENT_TYPE, name: Constants.HEADER_CONTENT_TYPE,
parser : (v) => v parser: (v) => v
}; };
headerByGetter["getType"] = { headerByGetter.getType = {
name : Constants.BINARY_HEADERS_02.TYPE, name: Constants.BINARY_HEADERS_02.TYPE,
parser : (v) => v parser: (v) => v
}; };
headerByGetter["getSpecversion"] = { headerByGetter.getSpecversion = {
name : Constants.BINARY_HEADERS_02.SPEC_VERSION, name: Constants.BINARY_HEADERS_02.SPEC_VERSION,
parser : (v) => v parser: (v) => v
}; };
headerByGetter["getSource"] = { headerByGetter.getSource = {
name : Constants.BINARY_HEADERS_02.SOURCE, name: Constants.BINARY_HEADERS_02.SOURCE,
parser : (v) => v parser: (v) => v
}; };
headerByGetter["getId"] = { headerByGetter.getId = {
name : Constants.BINARY_HEADERS_02.ID, name: Constants.BINARY_HEADERS_02.ID,
parser : (v) => v parser: (v) => v
}; };
headerByGetter["getTime"] = { headerByGetter.getTime = {
name : Constants.BINARY_HEADERS_02.TIME, name: Constants.BINARY_HEADERS_02.TIME,
parser : (v) => v parser: (v) => v
}; };
headerByGetter["getSchemaurl"] = { headerByGetter.getSchemaurl = {
name : Constants.BINARY_HEADERS_02.SCHEMA_URL, name: Constants.BINARY_HEADERS_02.SCHEMA_URL,
parser : (v) => v parser: (v) => v
}; };
function HTTPBinary02(configuration){ function HTTPBinary02(configuration) {
this.emitter = new BinaryHTTPEmitter( this.emitter = new BinaryHTTPEmitter(
configuration, configuration,
headerByGetter, headerByGetter,
@ -47,7 +47,7 @@ function HTTPBinary02(configuration){
); );
} }
HTTPBinary02.prototype.emit = function(cloudevent){ HTTPBinary02.prototype.emit = function(cloudevent) {
return this.emitter.emit(cloudevent); return this.emitter.emit(cloudevent);
}; };

View File

@ -4,52 +4,52 @@ const Constants = require("./constants.js");
const headerByGetter = {}; const headerByGetter = {};
headerByGetter["getDataContentType"] = { headerByGetter.getDataContentType = {
name : Constants.HEADER_CONTENT_TYPE, name: Constants.HEADER_CONTENT_TYPE,
parser : (v) => v parser: (v) => v
}; };
headerByGetter["getDataContentEncoding"] = { headerByGetter.getDataContentEncoding = {
name : Constants.BINARY_HEADERS_03.CONTENT_ENCONDING, name: Constants.BINARY_HEADERS_03.CONTENT_ENCONDING,
parser : (v) => v parser: (v) => v
}; };
headerByGetter["getSubject"] = { headerByGetter.getSubject = {
name : Constants.BINARY_HEADERS_03.SUBJECT, name: Constants.BINARY_HEADERS_03.SUBJECT,
parser : (v) => v parser: (v) => v
}; };
headerByGetter["getType"] = { headerByGetter.getType = {
name : Constants.BINARY_HEADERS_03.TYPE, name: Constants.BINARY_HEADERS_03.TYPE,
parser : (v) => v parser: (v) => v
}; };
headerByGetter["getSpecversion"] = { headerByGetter.getSpecversion = {
name : Constants.BINARY_HEADERS_03.SPEC_VERSION, name: Constants.BINARY_HEADERS_03.SPEC_VERSION,
parser : (v) => v parser: (v) => v
}; };
headerByGetter["getSource"] = { headerByGetter.getSource = {
name : Constants.BINARY_HEADERS_03.SOURCE, name: Constants.BINARY_HEADERS_03.SOURCE,
parser : (v) => v parser: (v) => v
}; };
headerByGetter["getId"] = { headerByGetter.getId = {
name : Constants.BINARY_HEADERS_03.ID, name: Constants.BINARY_HEADERS_03.ID,
parser : (v) => v parser: (v) => v
}; };
headerByGetter["getTime"] = { headerByGetter.getTime = {
name : Constants.BINARY_HEADERS_03.TIME, name: Constants.BINARY_HEADERS_03.TIME,
parser : (v) => v parser: (v) => v
}; };
headerByGetter["getSchemaurl"] = { headerByGetter.getSchemaurl = {
name : Constants.BINARY_HEADERS_03.SCHEMA_URL, name: Constants.BINARY_HEADERS_03.SCHEMA_URL,
parser : (v) => v parser: (v) => v
}; };
function HTTPBinary(configuration){ function HTTPBinary(configuration) {
this.emitter = new BinaryHTTPEmitter( this.emitter = new BinaryHTTPEmitter(
configuration, configuration,
headerByGetter, headerByGetter,
@ -57,7 +57,7 @@ function HTTPBinary(configuration){
); );
} }
HTTPBinary.prototype.emit = function(cloudevent){ HTTPBinary.prototype.emit = function(cloudevent) {
return this.emitter.emit(cloudevent); return this.emitter.emit(cloudevent);
}; };

View File

@ -4,47 +4,47 @@ const Constants = require("./constants.js");
const headerByGetter = {}; const headerByGetter = {};
headerByGetter["getDataContentType"] = { headerByGetter.getDataContentType = {
name : Constants.HEADER_CONTENT_TYPE, name: Constants.HEADER_CONTENT_TYPE,
parser : (v) => v parser: (v) => v
}; };
headerByGetter["getSubject"] = { headerByGetter.getSubject = {
name : Constants.BINARY_HEADERS_1.SUBJECT, name: Constants.BINARY_HEADERS_1.SUBJECT,
parser : (v) => v parser: (v) => v
}; };
headerByGetter["getType"] = { headerByGetter.getType = {
name : Constants.BINARY_HEADERS_1.TYPE, name: Constants.BINARY_HEADERS_1.TYPE,
parser : (v) => v parser: (v) => v
}; };
headerByGetter["getSpecversion"] = { headerByGetter.getSpecversion = {
name : Constants.BINARY_HEADERS_1.SPEC_VERSION, name: Constants.BINARY_HEADERS_1.SPEC_VERSION,
parser : (v) => v parser: (v) => v
}; };
headerByGetter["getSource"] = { headerByGetter.getSource = {
name : Constants.BINARY_HEADERS_1.SOURCE, name: Constants.BINARY_HEADERS_1.SOURCE,
parser : (v) => v parser: (v) => v
}; };
headerByGetter["getId"] = { headerByGetter.getId = {
name : Constants.BINARY_HEADERS_1.ID, name: Constants.BINARY_HEADERS_1.ID,
parser : (v) => v parser: (v) => v
}; };
headerByGetter["getTime"] = { headerByGetter.getTime = {
name : Constants.BINARY_HEADERS_1.TIME, name: Constants.BINARY_HEADERS_1.TIME,
parser : (v) => v parser: (v) => v
}; };
headerByGetter["getDataschema"] = { headerByGetter.getDataschema = {
name : Constants.BINARY_HEADERS_1.DATA_SCHEMA, name: Constants.BINARY_HEADERS_1.DATA_SCHEMA,
parser : (v) => v parser: (v) => v
}; };
function HTTPBinary(configuration){ function HTTPBinary(configuration) {
this.emitter = new BinaryHTTPEmitter( this.emitter = new BinaryHTTPEmitter(
configuration, configuration,
headerByGetter, headerByGetter,
@ -52,7 +52,7 @@ function HTTPBinary(configuration){
); );
} }
HTTPBinary.prototype.emit = function(cloudevent){ HTTPBinary.prototype.emit = function(cloudevent) {
return this.emitter.emit(cloudevent); return this.emitter.emit(cloudevent);
}; };

View File

@ -3,13 +3,14 @@ const axios = require("axios");
const Constants = require("./constants.js"); const Constants = require("./constants.js");
const defaults = {}; const defaults = {};
defaults[Constants.HEADERS] = {}; defaults[Constants.HEADERS] = {};
defaults[Constants.HEADERS][Constants.HEADER_CONTENT_TYPE] = Constants.DEFAULT_CE_CONTENT_TYPE; defaults[Constants.HEADERS][Constants.HEADER_CONTENT_TYPE] =
Constants.DEFAULT_CE_CONTENT_TYPE;
function StructuredHTTPEmitter(configuration){ function StructuredHTTPEmitter(configuration) {
this.config = Object.assign({}, defaults, configuration); this.config = Object.assign({}, defaults, configuration);
} }
StructuredHTTPEmitter.prototype.emit = function (cloudevent) { StructuredHTTPEmitter.prototype.emit = function(cloudevent) {
// Set the cloudevent payload // Set the cloudevent payload
this.config[Constants.DATA_ATTRIBUTE] = cloudevent.format(); this.config[Constants.DATA_ATTRIBUTE] = cloudevent.format();

View File

@ -2,26 +2,23 @@ const axios = require("axios");
const Constants = require("./constants.js"); const Constants = require("./constants.js");
function HTTPStructured(configuration){ function HTTPStructured(configuration) {
this.config = JSON.parse(JSON.stringify(configuration)); this.config = JSON.parse(JSON.stringify(configuration));
if(!this.config["headers"]){ if (!this.config.headers) {
this.config["headers"] = {}; this.config.headers = {};
} }
this.config["headers"] this.config.headers[Constants.HEADER_CONTENT_TYPE] =
[Constants.HEADER_CONTENT_TYPE] = `${Constants.MIME_CE_JSON}; charset=${Constants.CHARSET_DEFAULT}`;
Constants.MIME_CE_JSON + "; charset=" + Constants.CHARSET_DEFAULT;
} }
HTTPStructured.prototype.emit = function(cloudevent){ HTTPStructured.prototype.emit = function(cloudevent) {
// Create new request object // Create new request object
const _config = JSON.parse(JSON.stringify(this.config)); const _config = JSON.parse(JSON.stringify(this.config));
// Set the cloudevent payload // Set the cloudevent payload
_config["data"] = cloudevent.format(); _config.data = cloudevent.format();
// Return the Promise // Return the Promise
return axios.request(_config); return axios.request(_config);

View File

@ -1,10 +1,10 @@
const StructuredHTTPEmitter = require("./emitter_structured.js"); const StructuredHTTPEmitter = require("./emitter_structured.js");
function HTTPStructured(configuration){ function HTTPStructured(configuration) {
this.emitter = new StructuredHTTPEmitter(configuration); this.emitter = new StructuredHTTPEmitter(configuration);
} }
HTTPStructured.prototype.emit = function(cloudevent){ HTTPStructured.prototype.emit = function(cloudevent) {
return this.emitter.emit(cloudevent); return this.emitter.emit(cloudevent);
}; };

View File

@ -1,5 +1,5 @@
const Constants = require("./constants.js"); const Constants = require("./constants.js");
const Commons = require("./commons.js"); const Commons = require("./commons.js");
const Cloudevent = require("../../cloudevent.js"); const Cloudevent = require("../../cloudevent.js");
const { const {
@ -8,17 +8,16 @@ const {
} = require("../../utils/fun.js"); } = require("../../utils/fun.js");
function validateArgs(payload, attributes) { function validateArgs(payload, attributes) {
Array.of(payload) Array.of(payload)
.filter((p) => isDefinedOrThrow(p, .filter((p) => isDefinedOrThrow(p,
{message: "payload is null or undefined"})) { message: "payload is null or undefined" }))
.filter((p) => isStringOrObjectOrThrow(p, .filter((p) => isStringOrObjectOrThrow(p,
{message: "payload must be an object or a string"})) { message: "payload must be an object or a string" }))
.shift(); .shift();
Array.of(attributes) Array.of(attributes)
.filter((a) => isDefinedOrThrow(a, .filter((a) => isDefinedOrThrow(a,
{message: "attributes is null or undefined"})) { message: "attributes is null or undefined" }))
.shift(); .shift();
} }
@ -31,7 +30,6 @@ function BinaryHTTPReceiver(
specversion, specversion,
extensionsPrefix, extensionsPrefix,
checkDecorator) { checkDecorator) {
this.parsersByEncoding = parsersByEncoding; this.parsersByEncoding = parsersByEncoding;
this.setterByHeader = setterByHeader; this.setterByHeader = setterByHeader;
this.allowedContentTypes = allowedContentTypes; this.allowedContentTypes = allowedContentTypes;
@ -47,7 +45,7 @@ BinaryHTTPReceiver.prototype.check = function(payload, headers) {
// Validation Level 0 // Validation Level 0
validateArgs(payload, headers); validateArgs(payload, headers);
if(this.checkDecorator) { if (this.checkDecorator) {
this.checkDecorator(payload, headers); this.checkDecorator(payload, headers);
} }
@ -55,32 +53,31 @@ BinaryHTTPReceiver.prototype.check = function(payload, headers) {
const sanityHeaders = Commons.sanityAndClone(headers); const sanityHeaders = Commons.sanityAndClone(headers);
// Validation Level 1 // Validation Level 1
if(!this.allowedContentTypes if (!this.allowedContentTypes
.includes(sanityHeaders[Constants.HEADER_CONTENT_TYPE])){ .includes(sanityHeaders[Constants.HEADER_CONTENT_TYPE])) {
throw { const err = new TypeError("invalid content type");
message: "invalid content type", err.errors = [sanityHeaders[Constants.HEADER_CONTENT_TYPE]];
errors: [sanityHeaders[Constants.HEADER_CONTENT_TYPE]] throw err;
};
} }
this.requiredHeaders this.requiredHeaders
.filter((required) => !sanityHeaders[required]) .filter((required) => !sanityHeaders[required])
.forEach((required) => { .forEach((required) => {
throw {message: "header '" + required + "' not found"}; throw new TypeError(`header '${required}' not found`);
}); });
if(sanityHeaders[Constants.DEFAULT_SPEC_VERSION_HEADER] !== this.specversion){ if (sanityHeaders[Constants.DEFAULT_SPEC_VERSION_HEADER] !==
throw { this.specversion) {
message: "invalid spec version", const err = new TypeError("invalid spec version");
errors: [sanityHeaders[Constants.DEFAULT_SPEC_VERSION_HEADER]] err.errors = [sanityHeaders[Constants.DEFAULT_SPEC_VERSION_HEADER]];
}; throw err;
} }
// No erros! Its contains the minimum required attributes // No erros! Its contains the minimum required attributes
}; };
function parserFor(parsersByEncoding, cloudevent, headers){ function parserFor(parsersByEncoding, cloudevent, headers) {
let encoding = cloudevent.spec.payload["datacontentencoding"]; const encoding = cloudevent.spec.payload.datacontentencoding;
return parsersByEncoding[encoding][headers[Constants.HEADER_CONTENT_TYPE]]; return parsersByEncoding[encoding][headers[Constants.HEADER_CONTENT_TYPE]];
} }
@ -98,7 +95,7 @@ BinaryHTTPReceiver.prototype.parse = function(payload, headers) {
.filter((header) => sanityHeaders[header]) .filter((header) => sanityHeaders[header])
.forEach((header) => { .forEach((header) => {
const setterName = this.setterByHeader[header].name; const setterName = this.setterByHeader[header].name;
const parserFun = this.setterByHeader[header].parser; const parserFun = this.setterByHeader[header].parser;
// invoke the setter function // invoke the setter function
cloudevent[setterName](parserFun(sanityHeaders[header])); cloudevent[setterName](parserFun(sanityHeaders[header]));
@ -108,21 +105,21 @@ BinaryHTTPReceiver.prototype.parse = function(payload, headers) {
}); });
// Parses the payload // Parses the payload
let parsedPayload = const parsedPayload =
parserFor(this.parsersByEncoding, cloudevent, sanityHeaders) parserFor(this.parsersByEncoding, cloudevent, sanityHeaders)
.parse(payload); .parse(payload);
// Every unprocessed header can be an extension // Every unprocessed header can be an extension
Array.from(Object.keys(sanityHeaders)) Array.from(Object.keys(sanityHeaders))
.filter((value) => !processedHeaders.includes(value)) .filter((value) => !processedHeaders.includes(value))
.filter((value) => .filter((value) =>
value.startsWith(this.extensionsPrefix)) value.startsWith(this.extensionsPrefix))
.map((extension) => .map((extension) =>
extension.substring(this.extensionsPrefix.length) extension.substring(this.extensionsPrefix.length)
).forEach((extension) => ).forEach((extension) =>
cloudevent.addExtension(extension, cloudevent.addExtension(extension,
sanityHeaders[this.extensionsPrefix+extension]) sanityHeaders[this.extensionsPrefix + extension])
); );
// Sets the data // Sets the data
cloudevent.data(parsedPayload); cloudevent.data(parsedPayload);

View File

@ -1,15 +1,9 @@
const Constants = require("./constants.js"); const Constants = require("./constants.js");
const Spec02 = require("../../specs/spec_0_2.js"); const Spec02 = require("../../specs/spec_0_2.js");
const JSONParser = require("../../formats/json/parser.js"); const JSONParser = require("../../formats/json/parser.js");
const BinaryHTTPReceiver = require("./receiver_binary.js"); const BinaryHTTPReceiver = require("./receiver_binary.js");
const {
isDefinedOrThrow,
isStringOrObjectOrThrow
} = require("../../utils/fun.js");
const parserByType = {}; const parserByType = {};
parserByType[Constants.MIME_JSON] = new JSONParser(); parserByType[Constants.MIME_JSON] = new JSONParser();
parserByType[Constants.MIME_OCTET_STREAM] = { parserByType[Constants.MIME_OCTET_STREAM] = {
@ -17,7 +11,7 @@ parserByType[Constants.MIME_OCTET_STREAM] = {
}; };
const parsersByEncoding = {}; const parsersByEncoding = {};
parsersByEncoding[null] = parserByType; parsersByEncoding.null = parserByType;
parsersByEncoding[undefined] = parserByType; parsersByEncoding[undefined] = parserByType;
const allowedContentTypes = []; const allowedContentTypes = [];
@ -32,24 +26,24 @@ requiredHeaders.push(Constants.BINARY_HEADERS_02.ID);
const setterByHeader = {}; const setterByHeader = {};
setterByHeader[Constants.BINARY_HEADERS_02.TYPE] = { setterByHeader[Constants.BINARY_HEADERS_02.TYPE] = {
name : "type", name: "type",
parser : (v) => v parser: (v) => v
}; };
setterByHeader[Constants.BINARY_HEADERS_02.SPEC_VERSION] = { setterByHeader[Constants.BINARY_HEADERS_02.SPEC_VERSION] = {
name : "specversion", name: "specversion",
parser : (v) => "0.2" parser: () => "0.2"
}; };
setterByHeader[Constants.BINARY_HEADERS_02.SOURCE] = { setterByHeader[Constants.BINARY_HEADERS_02.SOURCE] = {
name : "source", name: "source",
parser: (v) => v parser: (v) => v
}; };
setterByHeader[Constants.BINARY_HEADERS_02.ID] = { setterByHeader[Constants.BINARY_HEADERS_02.ID] = {
name : "id", name: "id",
parser : (v) => v parser: (v) => v
}; };
setterByHeader[Constants.BINARY_HEADERS_02.TIME] = { setterByHeader[Constants.BINARY_HEADERS_02.TIME] = {
name : "time", name: "time",
parser : (v) => new Date(Date.parse(v)) parser: (v) => new Date(Date.parse(v))
}; };
setterByHeader[Constants.BINARY_HEADERS_02.SCHEMA_URL] = { setterByHeader[Constants.BINARY_HEADERS_02.SCHEMA_URL] = {
name: "schemaurl", name: "schemaurl",
@ -60,6 +54,8 @@ setterByHeader[Constants.HEADER_CONTENT_TYPE] = {
parser: (v) => v parser: (v) => v
}; };
// Leaving this in place for now. TODO: fixme
// eslint-disable-next-line
function Receiver(configuration) { function Receiver(configuration) {
this.receiver = new BinaryHTTPReceiver( this.receiver = new BinaryHTTPReceiver(
parsersByEncoding, parsersByEncoding,

View File

@ -1,16 +1,11 @@
const Constants = require("./constants.js"); const Constants = require("./constants.js");
const Spec = require("../../specs/spec_0_3.js"); const Spec = require("../../specs/spec_0_3.js");
const JSONParser = require("../../formats/json/parser.js"); const JSONParser = require("../../formats/json/parser.js");
const Base64Parser = require("../../formats/base64.js"); const Base64Parser = require("../../formats/base64.js");
const BinaryHTTPReceiver = require("./receiver_binary.js"); const BinaryHTTPReceiver = require("./receiver_binary.js");
const {
isDefinedOrThrow,
isStringOrObjectOrThrow
} = require("../../utils/fun.js");
const parserByType = {}; const parserByType = {};
parserByType[Constants.MIME_JSON] = new JSONParser(); parserByType[Constants.MIME_JSON] = new JSONParser();
parserByType[Constants.MIME_OCTET_STREAM] = { parserByType[Constants.MIME_OCTET_STREAM] = {
@ -18,7 +13,7 @@ parserByType[Constants.MIME_OCTET_STREAM] = {
}; };
const parsersByEncoding = {}; const parsersByEncoding = {};
parsersByEncoding[null] = parserByType; parsersByEncoding.null = parserByType;
parsersByEncoding[undefined] = parserByType; parsersByEncoding[undefined] = parserByType;
// base64 // base64
@ -44,24 +39,24 @@ requiredHeaders.push(Constants.BINARY_HEADERS_03.ID);
const setterByHeader = {}; const setterByHeader = {};
setterByHeader[Constants.BINARY_HEADERS_03.TYPE] = { setterByHeader[Constants.BINARY_HEADERS_03.TYPE] = {
name : "type", name: "type",
parser : (v) => v parser: (v) => v
}; };
setterByHeader[Constants.BINARY_HEADERS_03.SPEC_VERSION] = { setterByHeader[Constants.BINARY_HEADERS_03.SPEC_VERSION] = {
name : "specversion", name: "specversion",
parser : (v) => "0.3" parser: () => "0.3"
}; };
setterByHeader[Constants.BINARY_HEADERS_03.SOURCE] = { setterByHeader[Constants.BINARY_HEADERS_03.SOURCE] = {
name : "source", name: "source",
parser: (v) => v parser: (v) => v
}; };
setterByHeader[Constants.BINARY_HEADERS_03.ID] = { setterByHeader[Constants.BINARY_HEADERS_03.ID] = {
name : "id", name: "id",
parser : (v) => v parser: (v) => v
}; };
setterByHeader[Constants.BINARY_HEADERS_03.TIME] = { setterByHeader[Constants.BINARY_HEADERS_03.TIME] = {
name : "time", name: "time",
parser : (v) => new Date(Date.parse(v)) parser: (v) => new Date(Date.parse(v))
}; };
setterByHeader[Constants.BINARY_HEADERS_03.SCHEMA_URL] = { setterByHeader[Constants.BINARY_HEADERS_03.SCHEMA_URL] = {
name: "schemaurl", name: "schemaurl",
@ -80,19 +75,24 @@ setterByHeader[Constants.BINARY_HEADERS_03.SUBJECT] = {
parser: (v) => v parser: (v) => v
}; };
// Leaving this in place for now. TODO: fixme
// eslint-disable-next-line
function checkDecorator(payload, headers) { function checkDecorator(payload, headers) {
Object.keys(headers) Object.keys(headers)
.map((header) => header.toLocaleLowerCase("en-US")) .map((header) => header.toLocaleLowerCase("en-US"))
.filter((header) => .filter((header) =>
header === Constants.BINARY_HEADERS_03.CONTENT_ENCONDING) header === Constants.BINARY_HEADERS_03.CONTENT_ENCONDING)
.filter((header) => !allowedEncodings.includes(headers[header])) .filter((header) => !allowedEncodings.includes(headers[header]))
.forEach((header) => { .forEach((header) => {
throw {message : "unsupported datacontentencoding", errors: [ // TODO: using forEach here seems off
headers[header] const err = new TypeError("unsupported datacontentencoding");
]}; err.errors = [headers[header]];
throw err;
}); });
} }
// Leaving this in place for now. TODO: fixme
// eslint-disable-next-line
function Receiver(configuration) { function Receiver(configuration) {
this.receiver = new BinaryHTTPReceiver( this.receiver = new BinaryHTTPReceiver(
parsersByEncoding, parsersByEncoding,

View File

@ -1,5 +1,5 @@
const Constants = require("./constants.js"); const Constants = require("./constants.js");
const Spec = require("../../specs/spec_1.js"); const Spec = require("../../specs/spec_1.js");
const JSONParser = require("../../formats/json/parser.js"); const JSONParser = require("../../formats/json/parser.js");
const Base64Parser = require("../../formats/base64.js"); const Base64Parser = require("../../formats/base64.js");
@ -7,8 +7,6 @@ const Base64Parser = require("../../formats/base64.js");
const BinaryHTTPReceiver = require("./receiver_binary.js"); const BinaryHTTPReceiver = require("./receiver_binary.js");
const { const {
isDefinedOrThrow,
isStringOrObjectOrThrow,
isString, isString,
isBase64 isBase64
} = require("../../utils/fun.js"); } = require("../../utils/fun.js");
@ -20,7 +18,7 @@ parserByType[Constants.MIME_OCTET_STREAM] = {
}; };
const parsersByEncoding = {}; const parsersByEncoding = {};
parsersByEncoding[null] = parserByType; parsersByEncoding.null = parserByType;
parsersByEncoding[undefined] = parserByType; parsersByEncoding[undefined] = parserByType;
// base64 // base64
@ -46,24 +44,24 @@ requiredHeaders.push(Constants.BINARY_HEADERS_1.ID);
const setterByHeader = {}; const setterByHeader = {};
setterByHeader[Constants.BINARY_HEADERS_1.TYPE] = { setterByHeader[Constants.BINARY_HEADERS_1.TYPE] = {
name : "type", name: "type",
parser : (v) => v parser: (v) => v
}; };
setterByHeader[Constants.BINARY_HEADERS_1.SPEC_VERSION] = { setterByHeader[Constants.BINARY_HEADERS_1.SPEC_VERSION] = {
name : "specversion", name: "specversion",
parser : (v) => "1.0" parser: () => "1.0"
}; };
setterByHeader[Constants.BINARY_HEADERS_1.SOURCE] = { setterByHeader[Constants.BINARY_HEADERS_1.SOURCE] = {
name : "source", name: "source",
parser: (v) => v parser: (v) => v
}; };
setterByHeader[Constants.BINARY_HEADERS_1.ID] = { setterByHeader[Constants.BINARY_HEADERS_1.ID] = {
name : "id", name: "id",
parser : (v) => v parser: (v) => v
}; };
setterByHeader[Constants.BINARY_HEADERS_1.TIME] = { setterByHeader[Constants.BINARY_HEADERS_1.TIME] = {
name : "time", name: "time",
parser : (v) => new Date(Date.parse(v)) parser: (v) => new Date(Date.parse(v))
}; };
setterByHeader[Constants.BINARY_HEADERS_1.DATA_SCHEMA] = { setterByHeader[Constants.BINARY_HEADERS_1.DATA_SCHEMA] = {
name: "dataschema", name: "dataschema",
@ -78,9 +76,13 @@ setterByHeader[Constants.BINARY_HEADERS_1.SUBJECT] = {
parser: (v) => v parser: (v) => v
}; };
// Leaving these in place for now. TODO: fixme
// eslint-disable-next-line
function checkDecorator(payload, headers) { function checkDecorator(payload, headers) {
} }
// Leaving this in place for now. TODO: fixme
// eslint-disable-next-line
function Receiver(configuration) { function Receiver(configuration) {
this.receiver = new BinaryHTTPReceiver( this.receiver = new BinaryHTTPReceiver(
parsersByEncoding, parsersByEncoding,

View File

@ -1,5 +1,5 @@
const Constants = require("./constants.js"); const Constants = require("./constants.js");
const Commons = require("./commons.js"); const Commons = require("./commons.js");
const Cloudevent = require("../../cloudevent.js"); const Cloudevent = require("../../cloudevent.js");
const { const {
@ -10,14 +10,14 @@ const {
function validateArgs(payload, attributes) { function validateArgs(payload, attributes) {
Array.of(payload) Array.of(payload)
.filter((p) => isDefinedOrThrow(p, .filter((p) => isDefinedOrThrow(p,
{message: "payload is null or undefined"})) { message: "payload is null or undefined" }))
.filter((p) => isStringOrObjectOrThrow(p, .filter((p) => isStringOrObjectOrThrow(p,
{message: "payload must be an object or string"})) { message: "payload must be an object or string" }))
.shift(); .shift();
Array.of(attributes) Array.of(attributes)
.filter((a) => isDefinedOrThrow(a, .filter((a) => isDefinedOrThrow(a,
{message: "attributes is null or undefined"})) { message: "attributes is null or undefined" }))
.shift(); .shift();
} }
@ -26,7 +26,6 @@ function StructuredHTTPReceiver(
setterByAttribute, setterByAttribute,
allowedContentTypes, allowedContentTypes,
Spec) { Spec) {
this.parserByMime = parserByMime; this.parserByMime = parserByMime;
this.setterByAttribute = setterByAttribute; this.setterByAttribute = setterByAttribute;
this.allowedContentTypes = allowedContentTypes; this.allowedContentTypes = allowedContentTypes;
@ -40,12 +39,11 @@ StructuredHTTPReceiver.prototype.check = function(payload, headers) {
const sanityHeaders = Commons.sanityAndClone(headers); const sanityHeaders = Commons.sanityAndClone(headers);
// Validation Level 1 // Validation Level 1
if(!this.allowedContentTypes if (!this.allowedContentTypes
.includes(sanityHeaders[Constants.HEADER_CONTENT_TYPE])){ .includes(sanityHeaders[Constants.HEADER_CONTENT_TYPE])) {
throw { const err = new TypeError("invalid content type");
message: "invalid content type", err.errors = [sanityHeaders[Constants.HEADER_CONTENT_TYPE]];
errors: [sanityHeaders[Constants.HEADER_CONTENT_TYPE]] throw err;
};
} }
// No erros! Its contains the minimum required attributes // No erros! Its contains the minimum required attributes
@ -59,7 +57,7 @@ StructuredHTTPReceiver.prototype.parse = function(payload, headers) {
const contentType = sanityHeaders[Constants.HEADER_CONTENT_TYPE]; const contentType = sanityHeaders[Constants.HEADER_CONTENT_TYPE];
const parser = this.parserByMime[contentType]; const parser = this.parserByMime[contentType];
const event = parser.parse(payload); const event = parser.parse(payload);
this.spec.check(event); this.spec.check(event);
const processedAttributes = []; const processedAttributes = [];
@ -68,8 +66,8 @@ StructuredHTTPReceiver.prototype.parse = function(payload, headers) {
Array.from(Object.keys(this.setterByAttribute)) Array.from(Object.keys(this.setterByAttribute))
.filter((attribute) => event[attribute]) .filter((attribute) => event[attribute])
.forEach((attribute) => { .forEach((attribute) => {
let setterName = this.setterByAttribute[attribute].name; const setterName = this.setterByAttribute[attribute].name;
let parserFun = this.setterByAttribute[attribute].parser; const parserFun = this.setterByAttribute[attribute].parser;
// invoke the setter function // invoke the setter function
cloudevent[setterName](parserFun(event[attribute])); cloudevent[setterName](parserFun(event[attribute]));

View File

@ -1,18 +1,13 @@
const Constants = require("./constants.js"); const Constants = require("./constants.js");
const Spec02 = require("../../specs/spec_0_2.js"); const Spec02 = require("../../specs/spec_0_2.js");
const JSONParser = require("../../formats/json/parser.js"); const JSONParser = require("../../formats/json/parser.js");
const StructuredHTTPReceiver = require("./receiver_structured.js"); const StructuredHTTPReceiver = require("./receiver_structured.js");
const {
isDefinedOrThrow,
isStringOrObjectOrThrow
} = require("../../utils/fun.js");
const jsonParserSpec02 = new JSONParser(); const jsonParserSpec02 = new JSONParser();
const parserByMime = {}; const parserByMime = {};
parserByMime[Constants.MIME_JSON] = jsonParserSpec02; parserByMime[Constants.MIME_JSON] = jsonParserSpec02;
parserByMime[Constants.MIME_CE_JSON] = jsonParserSpec02; parserByMime[Constants.MIME_CE_JSON] = jsonParserSpec02;
const allowedContentTypes = []; const allowedContentTypes = [];
@ -20,24 +15,24 @@ allowedContentTypes.push(Constants.MIME_CE_JSON);
const setterByAttribute = {}; const setterByAttribute = {};
setterByAttribute[Constants.STRUCTURED_ATTRS_02.TYPE] = { setterByAttribute[Constants.STRUCTURED_ATTRS_02.TYPE] = {
name : "type", name: "type",
parser : (v) => v parser: (v) => v
}; };
setterByAttribute[Constants.STRUCTURED_ATTRS_02.SPEC_VERSION] = { setterByAttribute[Constants.STRUCTURED_ATTRS_02.SPEC_VERSION] = {
name : "specversion", name: "specversion",
parser : (v) => v parser: (v) => v
}; };
setterByAttribute[Constants.STRUCTURED_ATTRS_02.SOURCE] = { setterByAttribute[Constants.STRUCTURED_ATTRS_02.SOURCE] = {
name : "source", name: "source",
parser: (v) => v parser: (v) => v
}; };
setterByAttribute[Constants.STRUCTURED_ATTRS_02.ID] = { setterByAttribute[Constants.STRUCTURED_ATTRS_02.ID] = {
name : "id", name: "id",
parser : (v) => v parser: (v) => v
}; };
setterByAttribute[Constants.STRUCTURED_ATTRS_02.TIME] = { setterByAttribute[Constants.STRUCTURED_ATTRS_02.TIME] = {
name : "time", name: "time",
parser : (v) => new Date(Date.parse(v)) parser: (v) => new Date(Date.parse(v))
}; };
setterByAttribute[Constants.STRUCTURED_ATTRS_02.SCHEMA_URL] = { setterByAttribute[Constants.STRUCTURED_ATTRS_02.SCHEMA_URL] = {
name: "schemaurl", name: "schemaurl",
@ -52,6 +47,8 @@ setterByAttribute[Constants.STRUCTURED_ATTRS_02.DATA] = {
parser: (v) => v parser: (v) => v
}; };
// Leaving this in place for now. TODO: fixme
// eslint-disable-next-line
function Receiver(configuration) { function Receiver(configuration) {
this.receiver = new StructuredHTTPReceiver( this.receiver = new StructuredHTTPReceiver(
parserByMime, parserByMime,

View File

@ -1,18 +1,13 @@
const Constants = require("./constants.js"); const Constants = require("./constants.js");
const Spec = require("../../specs/spec_0_3.js"); const Spec = require("../../specs/spec_0_3.js");
const JSONParser = require("../../formats/json/parser.js"); const JSONParser = require("../../formats/json/parser.js");
const StructuredHTTPReceiver = require("./receiver_structured.js"); const StructuredHTTPReceiver = require("./receiver_structured.js");
const {
isDefinedOrThrow,
isStringOrObjectOrThrow
} = require("../../utils/fun.js");
const jsonParserSpec = new JSONParser(); const jsonParserSpec = new JSONParser();
const parserByMime = {}; const parserByMime = {};
parserByMime[Constants.MIME_JSON] = jsonParserSpec; parserByMime[Constants.MIME_JSON] = jsonParserSpec;
parserByMime[Constants.MIME_CE_JSON] = jsonParserSpec; parserByMime[Constants.MIME_CE_JSON] = jsonParserSpec;
const allowedContentTypes = []; const allowedContentTypes = [];
@ -20,24 +15,24 @@ allowedContentTypes.push(Constants.MIME_CE_JSON);
const setterByAttribute = {}; const setterByAttribute = {};
setterByAttribute[Constants.STRUCTURED_ATTRS_03.TYPE] = { setterByAttribute[Constants.STRUCTURED_ATTRS_03.TYPE] = {
name : "type", name: "type",
parser : (v) => v parser: (v) => v
}; };
setterByAttribute[Constants.STRUCTURED_ATTRS_03.SPEC_VERSION] = { setterByAttribute[Constants.STRUCTURED_ATTRS_03.SPEC_VERSION] = {
name : "specversion", name: "specversion",
parser : (v) => v parser: (v) => v
}; };
setterByAttribute[Constants.STRUCTURED_ATTRS_03.SOURCE] = { setterByAttribute[Constants.STRUCTURED_ATTRS_03.SOURCE] = {
name : "source", name: "source",
parser: (v) => v parser: (v) => v
}; };
setterByAttribute[Constants.STRUCTURED_ATTRS_03.ID] = { setterByAttribute[Constants.STRUCTURED_ATTRS_03.ID] = {
name : "id", name: "id",
parser : (v) => v parser: (v) => v
}; };
setterByAttribute[Constants.STRUCTURED_ATTRS_03.TIME] = { setterByAttribute[Constants.STRUCTURED_ATTRS_03.TIME] = {
name : "time", name: "time",
parser : (v) => new Date(Date.parse(v)) parser: (v) => new Date(Date.parse(v))
}; };
setterByAttribute[Constants.STRUCTURED_ATTRS_03.SCHEMA_URL] = { setterByAttribute[Constants.STRUCTURED_ATTRS_03.SCHEMA_URL] = {
name: "schemaurl", name: "schemaurl",
@ -60,6 +55,8 @@ setterByAttribute[Constants.STRUCTURED_ATTRS_03.DATA] = {
parser: (v) => v parser: (v) => v
}; };
// Leaving this in place for now. TODO: fixme
// eslint-disable-next-line
function Receiver(configuration) { function Receiver(configuration) {
this.receiver = new StructuredHTTPReceiver( this.receiver = new StructuredHTTPReceiver(
parserByMime, parserByMime,

View File

@ -1,18 +1,13 @@
const Constants = require("./constants.js"); const Constants = require("./constants.js");
const Spec = require("../../specs/spec_1.js"); const Spec = require("../../specs/spec_1.js");
const JSONParser = require("../../formats/json/parser.js"); const JSONParser = require("../../formats/json/parser.js");
const StructuredHTTPReceiver = require("./receiver_structured.js"); const StructuredHTTPReceiver = require("./receiver_structured.js");
const {
isDefinedOrThrow,
isStringOrObjectOrThrow
} = require("../../utils/fun.js");
const jsonParserSpec = new JSONParser(); const jsonParserSpec = new JSONParser();
const parserByMime = {}; const parserByMime = {};
parserByMime[Constants.MIME_JSON] = jsonParserSpec; parserByMime[Constants.MIME_JSON] = jsonParserSpec;
parserByMime[Constants.MIME_CE_JSON] = jsonParserSpec; parserByMime[Constants.MIME_CE_JSON] = jsonParserSpec;
const allowedContentTypes = []; const allowedContentTypes = [];
@ -20,24 +15,24 @@ allowedContentTypes.push(Constants.MIME_CE_JSON);
const setterByAttribute = {}; const setterByAttribute = {};
setterByAttribute[Constants.STRUCTURED_ATTRS_1.TYPE] = { setterByAttribute[Constants.STRUCTURED_ATTRS_1.TYPE] = {
name : "type", name: "type",
parser : (v) => v parser: (v) => v
}; };
setterByAttribute[Constants.STRUCTURED_ATTRS_1.SPEC_VERSION] = { setterByAttribute[Constants.STRUCTURED_ATTRS_1.SPEC_VERSION] = {
name : "specversion", name: "specversion",
parser : (v) => v parser: (v) => v
}; };
setterByAttribute[Constants.STRUCTURED_ATTRS_1.SOURCE] = { setterByAttribute[Constants.STRUCTURED_ATTRS_1.SOURCE] = {
name : "source", name: "source",
parser: (v) => v parser: (v) => v
}; };
setterByAttribute[Constants.STRUCTURED_ATTRS_1.ID] = { setterByAttribute[Constants.STRUCTURED_ATTRS_1.ID] = {
name : "id", name: "id",
parser : (v) => v parser: (v) => v
}; };
setterByAttribute[Constants.STRUCTURED_ATTRS_1.TIME] = { setterByAttribute[Constants.STRUCTURED_ATTRS_1.TIME] = {
name : "time", name: "time",
parser : (v) => new Date(Date.parse(v)) parser: (v) => new Date(Date.parse(v))
}; };
setterByAttribute[Constants.STRUCTURED_ATTRS_1.DATA_SCHEMA] = { setterByAttribute[Constants.STRUCTURED_ATTRS_1.DATA_SCHEMA] = {
name: "dataschema", name: "dataschema",
@ -60,6 +55,8 @@ setterByAttribute[Constants.STRUCTURED_ATTRS_1.DATA_BASE64] = {
parser: (v) => v parser: (v) => v
}; };
// Leaving this in place for now. TODO: fixme
// eslint-disable-next-line
function Receiver(configuration) { function Receiver(configuration) {
this.receiver = new StructuredHTTPReceiver( this.receiver = new StructuredHTTPReceiver(
parserByMime, parserByMime,

View File

@ -1,17 +1,9 @@
const StructuredReceiver = require("./receiver_structured_0_2.js");
const BinaryReceiver = require("./receiver_binary_0_2.js");
const Constants = require("./constants.js"); const Constants = require("./constants.js");
const Commons = require("./commons.js"); const Commons = require("./commons.js");
const STRUCTURED = "structured"; const STRUCTURED = "structured";
const BINARY = "binary"; const BINARY = "binary";
const receiverByBinding = {
structured : new StructuredReceiver(),
binary : new BinaryReceiver(),
};
const allowedBinaryContentTypes = []; const allowedBinaryContentTypes = [];
allowedBinaryContentTypes.push(Constants.MIME_JSON); allowedBinaryContentTypes.push(Constants.MIME_JSON);
allowedBinaryContentTypes.push(Constants.MIME_OCTET_STREAM); allowedBinaryContentTypes.push(Constants.MIME_OCTET_STREAM);
@ -20,34 +12,37 @@ const allowedStructuredContentTypes = [];
allowedStructuredContentTypes.push(Constants.MIME_CE_JSON); allowedStructuredContentTypes.push(Constants.MIME_CE_JSON);
function validateArgs(payload, headers) { function validateArgs(payload, headers) {
if(!payload){ if (!payload) {
throw {message: "payload is null or undefined"}; throw new TypeError("payload is null or undefined");
} }
if(!headers){ if (!headers) {
throw {message: "headers is null or undefined"}; throw new TypeError("headers is null or undefined");
} }
} }
// Is it binary or structured? // Is it binary or structured?
function resolveBindingName(payload, headers) { function resolveBindingName(payload, headers) {
const contentType = const contentType =
Commons.sanityContentType(headers[Constants.HEADER_CONTENT_TYPE]); Commons.sanityContentType(headers[Constants.HEADER_CONTENT_TYPE]);
if(contentType.startsWith(Constants.MIME_CE)){ if (contentType.startsWith(Constants.MIME_CE)) {
// Structured // Structured
if(allowedStructuredContentTypes.includes(contentType)){ if (allowedStructuredContentTypes.includes(contentType)) {
return STRUCTURED; return STRUCTURED;
} else { } else {
throw {message: "structured+type not allowed", errors: [contentType]}; const err = new TypeError("structured+type not allowed");
err.errors = [contentType];
throw err;
} }
} else { } else {
// Binary // Binary
if(allowedBinaryContentTypes.includes(contentType)){ if (allowedBinaryContentTypes.includes(contentType)) {
return BINARY; return BINARY;
} else { } else {
throw {message: "content type not allowed", errors : [contentType]}; const err = new TypeError("content type not allowed");
err.errors = [contentType];
throw err;
} }
} }
} }
@ -64,18 +59,17 @@ Unmarshaller.prototype.unmarshall = function(payload, headers) {
const sanityHeaders = Commons.sanityAndClone(headers); const sanityHeaders = Commons.sanityAndClone(headers);
// Validation level 1 // Validation level 1
if(!sanityHeaders[Constants.HEADER_CONTENT_TYPE]){ if (!sanityHeaders[Constants.HEADER_CONTENT_TYPE]) {
throw {message: "content-type header not found"}; throw new TypeError("content-type header not found");
} }
// Resolve the binding // Resolve the binding
const bindingName = resolveBindingName(payload, sanityHeaders); const bindingName = resolveBindingName(payload, sanityHeaders);
const cloudevent = this.receiverByBinding[bindingName]
const cloudevent = .parse(payload, sanityHeaders);
this.receiverByBinding[bindingName].parse(payload, sanityHeaders);
resolve(cloudevent); resolve(cloudevent);
}catch(e){ } catch (e) {
reject(e); reject(e);
} }
}); });

View File

@ -1,11 +1,11 @@
const GenericUnmarshaller = require("./unmarshaller.js"); const GenericUnmarshaller = require("./unmarshaller.js");
const StructuredReceiver = require("./receiver_structured_0_2.js"); const StructuredReceiver = require("./receiver_structured_0_2.js");
const BinaryReceiver = require("./receiver_binary_0_2.js"); const BinaryReceiver = require("./receiver_binary_0_2.js");
const RECEIVER_BY_BINDING = { const RECEIVER_BY_BINDING = {
structured : new StructuredReceiver(), structured: new StructuredReceiver(),
binary : new BinaryReceiver(), binary: new BinaryReceiver()
}; };
const Unmarshaller = function() { const Unmarshaller = function() {

View File

@ -1,11 +1,11 @@
const GenericUnmarshaller = require("./unmarshaller.js"); const GenericUnmarshaller = require("./unmarshaller.js");
const StructuredReceiver = require("./receiver_structured_0_3.js"); const StructuredReceiver = require("./receiver_structured_0_3.js");
const BinaryReceiver = require("./receiver_binary_0_3.js"); const BinaryReceiver = require("./receiver_binary_0_3.js");
const RECEIVER_BY_BINDING = { const RECEIVER_BY_BINDING = {
structured : new StructuredReceiver(), structured: new StructuredReceiver(),
binary : new BinaryReceiver(), binary: new BinaryReceiver()
}; };
const Unmarshaller = function() { const Unmarshaller = function() {

View File

@ -1,19 +1,19 @@
const Spec01 = require("./specs/spec_0_1.js"); const Spec01 = require("./specs/spec_0_1.js");
const Spec02 = require("./specs/spec_0_2.js"); const Spec02 = require("./specs/spec_0_2.js");
const JSONFormatter01 = require("./formats/json/formatter.js"); const JSONFormatter01 = require("./formats/json/formatter.js");
const HTTPStructured01 = require("./bindings/http/emitter_structured_0_1.js"); const HTTPStructured01 = require("./bindings/http/emitter_structured_0_1.js");
const HTTPStructured02 = require("./bindings/http/emitter_structured_0_2.js"); const HTTPStructured02 = require("./bindings/http/emitter_structured_0_2.js");
const HTTPBinary01 = require("./bindings/http/emitter_binary_0_1.js"); const HTTPBinary01 = require("./bindings/http/emitter_binary_0_1.js");
const {HTTPBinary02} = require("./bindings/http/emitter_binary_0_2.js"); const { HTTPBinary02 } = require("./bindings/http/emitter_binary_0_2.js");
/* /*
* Class created using the Builder Design Pattern. * Class created using the Builder Design Pattern.
* *
* https://en.wikipedia.org/wiki/Builder_pattern * https://en.wikipedia.org/wiki/Builder_pattern
*/ */
function Cloudevent(_spec, _formatter){ function Cloudevent(_spec, _formatter) {
this.spec = (_spec) ? new _spec(Cloudevent) : new Spec01(Cloudevent); this.spec = (_spec) ? new _spec(Cloudevent) : new Spec01(Cloudevent);
this.formatter = (_formatter) ? _formatter : new JSONFormatter01(); this.formatter = (_formatter) || new JSONFormatter01();
// The map of extensions // The map of extensions
this.extensions = {}; this.extensions = {};
@ -22,7 +22,7 @@ function Cloudevent(_spec, _formatter){
/* /*
* To format the payload using the formatter * To format the payload using the formatter
*/ */
Cloudevent.prototype.format = function(){ Cloudevent.prototype.format = function() {
// Check the constraints // Check the constraints
this.spec.check(); this.spec.check();
@ -33,11 +33,11 @@ Cloudevent.prototype.format = function(){
return this.formatter.format(this.spec.payload); return this.formatter.format(this.spec.payload);
}; };
Cloudevent.prototype.toString = function(){ Cloudevent.prototype.toString = function() {
return this.formatter.toString(this.spec.payload); return this.formatter.toString(this.spec.payload);
}; };
Cloudevent.prototype.type = function(type){ Cloudevent.prototype.type = function(type) {
this.spec.type(type); this.spec.type(type);
return this; return this;
}; };
@ -54,16 +54,16 @@ Cloudevent.prototype.getSpecversion = function() {
return this.spec.getSpecversion(); return this.spec.getSpecversion();
}; };
Cloudevent.prototype.source = function(_source){ Cloudevent.prototype.source = function(_source) {
this.spec.source(_source); this.spec.source(_source);
return this; return this;
}; };
Cloudevent.prototype.getSource = function(){ Cloudevent.prototype.getSource = function() {
return this.spec.getSource(); return this.spec.getSource();
}; };
Cloudevent.prototype.id = function(_id){ Cloudevent.prototype.id = function(_id) {
this.spec.id(_id); this.spec.id(_id);
return this; return this;
}; };
@ -72,7 +72,7 @@ Cloudevent.prototype.getId = function() {
return this.spec.getId(); return this.spec.getId();
}; };
Cloudevent.prototype.time = function(_time){ Cloudevent.prototype.time = function(_time) {
this.spec.time(_time); this.spec.time(_time);
return this; return this;
}; };
@ -90,7 +90,7 @@ Cloudevent.prototype.getSchemaurl = function() {
return this.spec.getSchemaurl(); return this.spec.getSchemaurl();
}; };
Cloudevent.prototype.contenttype = function(_contenttype){ Cloudevent.prototype.contenttype = function(_contenttype) {
this.spec.contenttype(_contenttype); this.spec.contenttype(_contenttype);
return this; return this;
}; };
@ -108,7 +108,7 @@ Cloudevent.prototype.getData = function() {
return this.spec.getData(); return this.spec.getData();
}; };
Cloudevent.prototype.addExtension = function(key, value){ Cloudevent.prototype.addExtension = function(key, value) {
this.spec.addExtension(key, value); this.spec.addExtension(key, value);
// Stores localy // Stores localy
@ -121,29 +121,28 @@ Cloudevent.prototype.getExtensions = function() {
return this.extensions; return this.extensions;
}; };
/* /*
* Export the specs * Export the specs
*/ */
Cloudevent.specs = { Cloudevent.specs = {
"0.1": Spec01, 0.1: Spec01,
"0.2": Spec02 0.2: Spec02
}; };
/* /*
* Export the formats * Export the formats
*/ */
Cloudevent.formats = { Cloudevent.formats = {
"json" : JSONFormatter01, json: JSONFormatter01,
"json0.1": JSONFormatter01 "json0.1": JSONFormatter01
}; };
Cloudevent.bindings = { Cloudevent.bindings = {
"http-structured" : HTTPStructured01, "http-structured": HTTPStructured01,
"http-structured0.1" : HTTPStructured01, "http-structured0.1": HTTPStructured01,
"http-structured0.2" : HTTPStructured02, "http-structured0.2": HTTPStructured02,
"http-binary0.1" : HTTPBinary01, "http-binary0.1": HTTPBinary01,
"http-binary0.2" : HTTPBinary02 "http-binary0.2": HTTPBinary02
}; };
module.exports = Cloudevent; module.exports = Cloudevent;

View File

@ -5,7 +5,7 @@ function Parser(decorator) {
Parser.prototype.parse = function(payload) { Parser.prototype.parse = function(payload) {
let toparse = payload; let toparse = payload;
if(this.decorator){ if (this.decorator) {
toparse = this.decorator.parse(payload); toparse = this.decorator.parse(payload);
} }

View File

@ -1,5 +1,5 @@
function JSONFormatter(){ function JSONFormatter() {
} }
@ -7,11 +7,11 @@ function JSONFormatter(){
* Every internal data structure is JSON by nature, so * Every internal data structure is JSON by nature, so
* no transformation is required * no transformation is required
*/ */
JSONFormatter.prototype.format = function(payload){ JSONFormatter.prototype.format = function(payload) {
return payload; return payload;
}; };
JSONFormatter.prototype.toString = function(payload){ JSONFormatter.prototype.toString = function(payload) {
return JSON.stringify(payload); return JSON.stringify(payload);
}; };

View File

@ -17,12 +17,9 @@ const nullOrIndefinedPayload =
// Function // Function
const asJSON = (v) => (isString(v) ? JSON.parse(v) : v); const asJSON = (v) => (isString(v) ? JSON.parse(v) : v);
/** // Level 0 of validation: is that string? is that JSON?
* Level 0 of validation: is that string? is that JSON?
*/
function validateAndParse(payload) { function validateAndParse(payload) {
var json =
const json =
Array.of(payload) Array.of(payload)
.filter((p) => isDefinedOrThrow(p, nullOrIndefinedPayload)) .filter((p) => isDefinedOrThrow(p, nullOrIndefinedPayload))
.filter((p) => isStringOrObjectOrThrow(p, invalidPayloadTypeError)) .filter((p) => isStringOrObjectOrThrow(p, invalidPayloadTypeError))
@ -32,25 +29,14 @@ function validateAndParse(payload) {
return json; return json;
} }
/*
* Level 1 of validation: is that follow a spec?
*/
function validateSpec(payload, spec) {
// is that follow the spec?
spec.check(payload);
return payload;
}
JSONParser.prototype.parse = function(payload) { JSONParser.prototype.parse = function(payload) {
let toparse = payload; let toparse = payload;
if(this.decorator) { if (this.decorator) {
toparse = this.decorator.parse(payload); toparse = this.decorator.parse(payload);
} }
//is that string? is that JSON? // is that string? is that JSON?
const valid = validateAndParse(toparse); const valid = validateAndParse(toparse);
return valid; return valid;

View File

@ -1,6 +1,6 @@
const uuid = require("uuid/v4"); const uuid = require("uuid/v4");
function Spec01(_caller){ function Spec01(_caller) {
this.payload = { this.payload = {
cloudEventsVersion: "0.1", cloudEventsVersion: "0.1",
eventID: uuid() eventID: uuid()
@ -14,11 +14,11 @@ function Spec01(_caller){
/* /*
* Inject the method to set the version related to data attribute. * Inject the method to set the version related to data attribute.
*/ */
this.caller.prototype.eventTypeVersion = function(_version){ this.caller.prototype.eventTypeVersion = function(_version) {
return this.spec.eventTypeVersion(_version); return this.spec.eventTypeVersion(_version);
}; };
this.caller.prototype.getEventTypeVersion = function(){ this.caller.prototype.getEventTypeVersion = function() {
return this.spec.getEventTypeVersion(); return this.spec.getEventTypeVersion();
}; };
} }
@ -29,94 +29,92 @@ function Spec01(_caller){
* throw an error if do not pass. * throw an error if do not pass.
*/ */
Spec01.prototype.check = function() { Spec01.prototype.check = function() {
if (!this.payload.eventType) {
if(!this.payload["eventType"]){ throw new TypeError("'eventType' is invalid");
throw {message: "'eventType' is invalid"};
} }
}; };
Spec01.prototype.type = function(_type){ Spec01.prototype.type = function(_type) {
this.payload["eventType"] = _type; this.payload.eventType = _type;
return this; return this;
}; };
Spec01.prototype.getType = function(){ Spec01.prototype.getType = function() {
return this.payload["eventType"]; return this.payload.eventType;
}; };
Spec01.prototype.getSpecversion = function() { Spec01.prototype.getSpecversion = function() {
return this.payload["cloudEventsVersion"]; return this.payload.cloudEventsVersion;
}; };
Spec01.prototype.eventTypeVersion = function(version){ Spec01.prototype.eventTypeVersion = function(version) {
this.payload["eventTypeVersion"] = version; this.payload.eventTypeVersion = version;
return this; return this;
}; };
Spec01.prototype.getEventTypeVersion = function() { Spec01.prototype.getEventTypeVersion = function() {
return this.payload["eventTypeVersion"]; return this.payload.eventTypeVersion;
}; };
Spec01.prototype.source = function(_source){ Spec01.prototype.source = function(_source) {
this.payload["source"] = _source; this.payload.source = _source;
return this; return this;
}; };
Spec01.prototype.getSource = function() { Spec01.prototype.getSource = function() {
return this.payload["source"]; return this.payload.source;
}; };
Spec01.prototype.id = function(_id){ Spec01.prototype.id = function(_id) {
this.payload["eventID"] = _id; this.payload.eventID = _id;
return this; return this;
}; };
Spec01.prototype.getId = function() { Spec01.prototype.getId = function() {
return this.payload["eventID"]; return this.payload.eventID;
}; };
Spec01.prototype.time = function(_time){ Spec01.prototype.time = function(_time) {
this.payload["eventTime"] = _time.toISOString(); this.payload.eventTime = _time.toISOString();
return this; return this;
}; };
Spec01.prototype.getTime = function() { Spec01.prototype.getTime = function() {
return this.payload["eventTime"]; return this.payload.eventTime;
}; };
Spec01.prototype.schemaurl = function(_schemaurl){ Spec01.prototype.schemaurl = function(_schemaurl) {
this.payload["schemaURL"] = _schemaurl; this.payload.schemaURL = _schemaurl;
return this; return this;
}; };
Spec01.prototype.getSchemaurl = function() { Spec01.prototype.getSchemaurl = function() {
return this.payload["schemaURL"]; return this.payload.schemaURL;
}; };
Spec01.prototype.contenttype = function(_contenttype){ Spec01.prototype.contenttype = function(_contenttype) {
this.payload["contentType"] = _contenttype; this.payload.contentType = _contenttype;
return this; return this;
}; };
Spec01.prototype.getContenttype = function() { Spec01.prototype.getContenttype = function() {
return this.payload["contentType"]; return this.payload.contentType;
}; };
Spec01.prototype.data = function(_data){ Spec01.prototype.data = function(_data) {
this.payload["data"] = _data; this.payload.data = _data;
return this; return this;
}; };
Spec01.prototype.getData = function() { Spec01.prototype.getData = function() {
return this.payload["data"]; return this.payload.data;
}; };
Spec01.prototype.addExtension = function(key, value){ Spec01.prototype.addExtension = function(key, value) {
if(!this.payload["extensions"]){ if (!this.payload.extensions) {
this.payload["extensions"] = {}; this.payload.extensions = {};
} }
this.payload["extensions"][key] = value; this.payload.extensions[key] = value;
return this; return this;
}; };

View File

@ -1,5 +1,5 @@
var uuid = require("uuid/v4"); const uuid = require("uuid/v4");
var Ajv = require("ajv"); const Ajv = require("ajv");
// Reserved attributes names // Reserved attributes names
const reserved = { const reserved = {
@ -16,12 +16,13 @@ const reserved = {
const schema = require("../../ext/spec_0_2.json"); const schema = require("../../ext/spec_0_2.json");
const ajv = new Ajv({ const ajv = new Ajv({
extendRefs: true // validate all keywords in the schemas with $ref (the default behaviour in versions before 5.0.0) // validate all keywords in the schemas with $ref
extendRefs: true
}); });
const validate = ajv.compile(schema); const validate = ajv.compile(schema);
function Spec02(){ function Spec02() {
this.payload = { this.payload = {
specversion: "0.2", specversion: "0.2",
id: uuid() id: uuid()
@ -31,95 +32,97 @@ function Spec02(){
/* /*
* Check the spec constraints * Check the spec constraints
*/ */
Spec02.prototype.check = function(ce){ Spec02.prototype.check = function(ce) {
var toCheck = ce; var toCheck = ce;
if(!toCheck) { if (!toCheck) {
toCheck = this.payload; toCheck = this.payload;
} }
const valid = validate(toCheck); const valid = validate(toCheck);
if(!valid) { if (!valid) {
throw {message: "invalid payload", errors: validate.errors}; const err = new TypeError("invalid payload");
err.errors = validate.errors;
throw err;
} }
}; };
Spec02.prototype.type = function(_type){ Spec02.prototype.type = function(_type) {
this.payload["type"] = _type; this.payload.type = _type;
return this; return this;
}; };
Spec02.prototype.getType = function(){ Spec02.prototype.getType = function() {
return this.payload["type"]; return this.payload.type;
}; };
Spec02.prototype.specversion = function(_specversion){ Spec02.prototype.specversion = function() {
// does not set! This is right // does not set! This is right
return this; return this;
}; };
Spec02.prototype.getSpecversion = function() { Spec02.prototype.getSpecversion = function() {
return this.payload["specversion"]; return this.payload.specversion;
}; };
Spec02.prototype.source = function(_source){ Spec02.prototype.source = function(_source) {
this.payload["source"] = _source; this.payload.source = _source;
return this; return this;
}; };
Spec02.prototype.getSource = function() { Spec02.prototype.getSource = function() {
return this.payload["source"]; return this.payload.source;
}; };
Spec02.prototype.id = function(_id){ Spec02.prototype.id = function(_id) {
this.payload["id"] = _id; this.payload.id = _id;
return this; return this;
}; };
Spec02.prototype.getId = function() { Spec02.prototype.getId = function() {
return this.payload["id"]; return this.payload.id;
}; };
Spec02.prototype.time = function(_time){ Spec02.prototype.time = function(_time) {
this.payload["time"] = _time.toISOString(); this.payload.time = _time.toISOString();
return this; return this;
}; };
Spec02.prototype.getTime = function() { Spec02.prototype.getTime = function() {
return this.payload["time"]; return this.payload.time;
}; };
Spec02.prototype.schemaurl = function(_schemaurl){ Spec02.prototype.schemaurl = function(_schemaurl) {
this.payload["schemaurl"] = _schemaurl; this.payload.schemaurl = _schemaurl;
return this; return this;
}; };
Spec02.prototype.getSchemaurl = function() { Spec02.prototype.getSchemaurl = function() {
return this.payload["schemaurl"]; return this.payload.schemaurl;
}; };
Spec02.prototype.contenttype = function(_contenttype){ Spec02.prototype.contenttype = function(_contenttype) {
this.payload["contenttype"] = _contenttype; this.payload.contenttype = _contenttype;
return this; return this;
}; };
Spec02.prototype.getContenttype = function() { Spec02.prototype.getContenttype = function() {
return this.payload["contenttype"]; return this.payload.contenttype;
}; };
Spec02.prototype.data = function(_data){ Spec02.prototype.data = function(_data) {
this.payload["data"] = _data; this.payload.data = _data;
return this; return this;
}; };
Spec02.prototype.getData = function() { Spec02.prototype.getData = function() {
return this.payload["data"]; return this.payload.data;
}; };
Spec02.prototype.addExtension = function(key, value){ Spec02.prototype.addExtension = function(key, value) {
if(!reserved.hasOwnProperty(key)){ if (!Object.prototype.hasOwnProperty.call(reserved, key)) {
this.payload[key] = value; this.payload[key] = value;
} else { } else {
throw {message: "Reserved attribute name: '" + key + "'"}; throw new TypeError(`Reserved attribute name: '${key}'`);
} }
return this; return this;
}; };

View File

@ -1,8 +1,7 @@
const uuid = require("uuid/v4"); const uuid = require("uuid/v4");
const Ajv = require("ajv"); const Ajv = require("ajv");
const { const {
equalsOrThrow,
isBase64, isBase64,
clone, clone,
asData asData
@ -17,13 +16,13 @@ const RESERVED_ATTRIBUTES = {
schemaurl: "schemaurl", schemaurl: "schemaurl",
datacontentencoding: "datacontentencoding", datacontentencoding: "datacontentencoding",
datacontenttype: "datacontenttype", datacontenttype: "datacontenttype",
subject : "subject", subject: "subject",
data: "data" data: "data"
}; };
const SUPPORTED_CONTENT_ENCODING = {}; const SUPPORTED_CONTENT_ENCODING = {};
SUPPORTED_CONTENT_ENCODING["base64"] = { SUPPORTED_CONTENT_ENCODING.base64 = {
check : (data) => isBase64(data) check: (data) => isBase64(data)
}; };
const schema = require("../../ext/spec_0_3.json"); const schema = require("../../ext/spec_0_3.json");
@ -34,13 +33,13 @@ const ajv = new Ajv({
const isValidAgainstSchema = ajv.compile(schema); const isValidAgainstSchema = ajv.compile(schema);
function Spec03(_caller){ function Spec03(_caller) {
this.payload = { this.payload = {
specversion: "0.3", specversion: "0.3",
id: uuid() id: uuid()
}; };
if(!_caller){ if (!_caller) {
_caller = require("../cloudevent.js"); _caller = require("../cloudevent.js");
} }
@ -52,178 +51,184 @@ function Spec03(_caller){
/* /*
* Inject compatibility methods * Inject compatibility methods
*/ */
this.caller.prototype.dataContentEncoding = function(encoding){ this.caller.prototype.dataContentEncoding = function(encoding) {
this.spec.dataContentEncoding(encoding); this.spec.dataContentEncoding(encoding);
return this; return this;
}; };
this.caller.prototype.getDataContentEncoding = function(){ this.caller.prototype.getDataContentEncoding = function() {
return this.spec.getDataContentEncoding(); return this.spec.getDataContentEncoding();
}; };
this.caller.prototype.dataContentType = function(contentType){ this.caller.prototype.dataContentType = function(contentType) {
this.spec.dataContentType(contentType); this.spec.dataContentType(contentType);
return this; return this;
}; };
this.caller.prototype.getDataContentType = function(){ this.caller.prototype.getDataContentType = function() {
return this.spec.getDataContentType(); return this.spec.getDataContentType();
}; };
this.caller.prototype.subject = function(_subject){ this.caller.prototype.subject = function(_subject) {
this.spec.subject(_subject); this.spec.subject(_subject);
return this; return this;
}; };
this.caller.prototype.getSubject = function(){ this.caller.prototype.getSubject = function() {
return this.spec.getSubject(); return this.spec.getSubject();
}; };
} }
/* /*
* Check the spec constraints * Check the spec constraints
*/ */
Spec03.prototype.check = function(ce){ Spec03.prototype.check = function(ce) {
const toCheck = (!ce ? this.payload : ce); const toCheck = (!ce ? this.payload : ce);
if(!isValidAgainstSchema(toCheck)) { if (!isValidAgainstSchema(toCheck)) {
throw {message: "invalid payload", errors: isValidAgainstSchema.errors}; const err = new TypeError("invalid payload");
err.errors = isValidAgainstSchema.errors;
throw err;
} }
Array.of(toCheck) Array.of(toCheck)
.filter((tc) => tc["datacontentencoding"]) .filter((tc) => tc.datacontentencoding)
.map((tc) => tc["datacontentencoding"].toLocaleLowerCase("en-US")) .map((tc) => tc.datacontentencoding.toLocaleLowerCase("en-US"))
.filter((dce) => !Object.keys(SUPPORTED_CONTENT_ENCODING).includes(dce)) .filter((dce) => !Object.keys(SUPPORTED_CONTENT_ENCODING).includes(dce))
.forEach((dce) => { .forEach((dce) => {
throw {message: "invalid payload", errors: [ const err = new TypeError("invalid payload");
"Unsupported content encoding: " + dce err.errors = [
]}; `Unsupported content encoding: ${dce}`
];
throw err;
}); });
Array.of(toCheck) Array.of(toCheck)
.filter((tc) => tc["datacontentencoding"]) .filter((tc) => tc.datacontentencoding)
.filter((tc) => (typeof tc.data) === "string") .filter((tc) => (typeof tc.data) === "string")
.map((tc) => { .map((tc) => {
let newtc = clone(tc); const newtc = clone(tc);
newtc.datacontentencoding = newtc.datacontentencoding =
newtc.datacontentencoding.toLocaleLowerCase("en-US"); newtc.datacontentencoding.toLocaleLowerCase("en-US");
return newtc; return newtc;
}) })
.filter((tc) => Object.keys(SUPPORTED_CONTENT_ENCODING) .filter((tc) => Object.keys(SUPPORTED_CONTENT_ENCODING)
.includes(tc.datacontentencoding)) .includes(tc.datacontentencoding))
.filter((tc) => !SUPPORTED_CONTENT_ENCODING[tc.datacontentencoding] .filter((tc) => !SUPPORTED_CONTENT_ENCODING[tc.datacontentencoding]
.check(tc.data)) .check(tc.data))
.forEach((tc) => { .forEach((tc) => {
throw {message: "invalid payload", errors: [ const err = new TypeError("invalid payload");
"Invalid content encoding of data: " + tc.data err.errors = [
]}; `Invalid content encoding of data: ${tc.data}`
];
throw err;
}); });
}; };
Spec03.prototype.id = function(_id){ Spec03.prototype.id = function(_id) {
this.payload["id"] = _id; this.payload.id = _id;
return this; return this;
}; };
Spec03.prototype.getId = function() { Spec03.prototype.getId = function() {
return this.payload["id"]; return this.payload.id;
}; };
Spec03.prototype.source = function(_source){ Spec03.prototype.source = function(_source) {
this.payload["source"] = _source; this.payload.source = _source;
return this; return this;
}; };
Spec03.prototype.getSource = function() { Spec03.prototype.getSource = function() {
return this.payload["source"]; return this.payload.source;
}; };
Spec03.prototype.specversion = function(_specversion){ Spec03.prototype.specversion = function() {
// does not set! This is right // does not set! This is right
return this; return this;
}; };
Spec03.prototype.getSpecversion = function() { Spec03.prototype.getSpecversion = function() {
return this.payload["specversion"]; return this.payload.specversion;
}; };
Spec03.prototype.type = function(_type){ Spec03.prototype.type = function(_type) {
this.payload["type"] = _type; this.payload.type = _type;
return this; return this;
}; };
Spec03.prototype.getType = function(){ Spec03.prototype.getType = function() {
return this.payload["type"]; return this.payload.type;
}; };
Spec03.prototype.dataContentEncoding = function(encoding) { Spec03.prototype.dataContentEncoding = function(encoding) {
this.payload["datacontentencoding"] = encoding; this.payload.datacontentencoding = encoding;
return this; return this;
}; };
Spec03.prototype.getDataContentEncoding = function() { Spec03.prototype.getDataContentEncoding = function() {
return this.payload["datacontentencoding"]; return this.payload.datacontentencoding;
}; };
// maps to datacontenttype // maps to datacontenttype
Spec03.prototype.contenttype = function(_contenttype){ Spec03.prototype.contenttype = function(_contenttype) {
this.payload["datacontenttype"] = _contenttype; this.payload.datacontenttype = _contenttype;
return this; return this;
}; };
Spec03.prototype.getContenttype = function() { Spec03.prototype.getContenttype = function() {
return this.payload["datacontenttype"]; return this.payload.datacontenttype;
}; };
Spec03.prototype.dataContentType = function(_contenttype){ Spec03.prototype.dataContentType = function(_contenttype) {
this.payload["datacontenttype"] = _contenttype; this.payload.datacontenttype = _contenttype;
return this; return this;
}; };
Spec03.prototype.getDataContentType = function() { Spec03.prototype.getDataContentType = function() {
return this.payload["datacontenttype"]; return this.payload.datacontenttype;
}; };
Spec03.prototype.schemaurl = function(_schemaurl){ Spec03.prototype.schemaurl = function(_schemaurl) {
this.payload["schemaurl"] = _schemaurl; this.payload.schemaurl = _schemaurl;
return this; return this;
}; };
Spec03.prototype.getSchemaurl = function() { Spec03.prototype.getSchemaurl = function() {
return this.payload["schemaurl"]; return this.payload.schemaurl;
}; };
Spec03.prototype.subject = function(_subject){ Spec03.prototype.subject = function(_subject) {
this.payload["subject"] = _subject; this.payload.subject = _subject;
return this; return this;
}; };
Spec03.prototype.getSubject = function() { Spec03.prototype.getSubject = function() {
return this.payload["subject"]; return this.payload.subject;
}; };
Spec03.prototype.time = function(_time){ Spec03.prototype.time = function(_time) {
this.payload["time"] = _time.toISOString(); this.payload.time = _time.toISOString();
return this; return this;
}; };
Spec03.prototype.getTime = function() { Spec03.prototype.getTime = function() {
return this.payload["time"]; return this.payload.time;
}; };
Spec03.prototype.data = function(_data){ Spec03.prototype.data = function(_data) {
this.payload["data"] = _data; this.payload.data = _data;
return this; return this;
}; };
Spec03.prototype.getData = function() { Spec03.prototype.getData = function() {
let dct = this.payload["datacontenttype"]; const dct = this.payload.datacontenttype;
let dce = this.payload["datacontentencoding"]; const dce = this.payload.datacontentencoding;
if(dct && !dce){ if (dct && !dce) {
this.payload["data"] = asData(this.payload["data"], dct); this.payload.data = asData(this.payload.data, dct);
} }
return this.payload["data"]; return this.payload.data;
}; };
Spec03.prototype.addExtension = function(key, value){ Spec03.prototype.addExtension = function(key, value) {
if(!RESERVED_ATTRIBUTES.hasOwnProperty(key)){ if (!Object.prototype.hasOwnProperty.call(RESERVED_ATTRIBUTES, key)) {
this.payload[key] = value; this.payload[key] = value;
} else { } else {
throw {message: "Reserved attribute name: '" + key + "'"}; throw new TypeError(`Reserved attribute name: '${key}'`);
} }
return this; return this;
}; };

View File

@ -1,5 +1,5 @@
const uuid = require("uuid/v4"); const uuid = require("uuid/v4");
const Ajv = require("ajv"); const Ajv = require("ajv");
const { const {
asData, asData,
@ -22,7 +22,7 @@ const RESERVED_ATTRIBUTES = {
time: "time", time: "time",
dataschema: "schemaurl", dataschema: "schemaurl",
datacontenttype: "datacontenttype", datacontenttype: "datacontenttype",
subject : "subject", subject: "subject",
data: "data", data: "data",
data_base64: "data_base64" data_base64: "data_base64"
}; };
@ -41,7 +41,7 @@ function Spec1(_caller) {
id: uuid() id: uuid()
}; };
if(!_caller){ if (!_caller) {
_caller = require("../cloudevent.js"); _caller = require("../cloudevent.js");
} }
@ -51,7 +51,7 @@ function Spec1(_caller) {
this.caller = _caller; this.caller = _caller;
// dataschema attribute // dataschema attribute
this.caller.prototype.dataschema = function(dataschema){ this.caller.prototype.dataschema = function(dataschema) {
this.spec.dataschema(dataschema); this.spec.dataschema(dataschema);
return this; return this;
}; };
@ -60,40 +60,41 @@ function Spec1(_caller) {
}; };
// datacontenttype attribute // datacontenttype attribute
this.caller.prototype.dataContentType = function(contentType){ this.caller.prototype.dataContentType = function(contentType) {
this.spec.dataContentType(contentType); this.spec.dataContentType(contentType);
return this; return this;
}; };
this.caller.prototype.getDataContentType = function(){ this.caller.prototype.getDataContentType = function() {
return this.spec.getDataContentType(); return this.spec.getDataContentType();
}; };
// subject attribute // subject attribute
this.caller.prototype.subject = function(_subject){ this.caller.prototype.subject = function(_subject) {
this.spec.subject(_subject); this.spec.subject(_subject);
return this; return this;
}; };
this.caller.prototype.getSubject = function(){ this.caller.prototype.getSubject = function() {
return this.spec.getSubject(); return this.spec.getSubject();
}; };
// format() method override // format() method override
this.caller.prototype.format = function(){ this.caller.prototype.format = function() {
// Check the constraints // Check the constraints
this.spec.check(); this.spec.check();
// Check before getData() call // Check before getData() call
let isbin = isBinary(this.spec.payload[RESERVED_ATTRIBUTES.data]); const isbin = isBinary(this.spec.payload[RESERVED_ATTRIBUTES.data]);
// May be used, if isbin==true // May be used, if isbin==true
let payload = clone(this.spec.payload); const payload = clone(this.spec.payload);
// To run asData() // To run asData()
this.getData(); this.getData();
// Handle when is binary, creating the data_base64 // Handle when is binary, creating the data_base64
if(isbin) { if (isbin) {
payload[RESERVED_ATTRIBUTES.data_base64] = this.spec.payload[RESERVED_ATTRIBUTES.data]; payload[RESERVED_ATTRIBUTES.data_base64] =
this.spec.payload[RESERVED_ATTRIBUTES.data];
delete payload[RESERVED_ATTRIBUTES.data]; delete payload[RESERVED_ATTRIBUTES.data];
return this.formatter.format(payload); return this.formatter.format(payload);
@ -107,105 +108,107 @@ function Spec1(_caller) {
/* /*
* Check the spec constraints * Check the spec constraints
*/ */
Spec1.prototype.check = function(ce){ Spec1.prototype.check = function(ce) {
const toCheck = (!ce ? this.payload : ce); var toCheck = (!ce ? this.payload : ce);
if(!isValidAgainstSchema(toCheck)) { if (!isValidAgainstSchema(toCheck)) {
throw {message: "invalid payload", errors: isValidAgainstSchema.errors}; const err = new TypeError("invalid payload");
err.errors = isValidAgainstSchema.errors;
throw err;
} }
}; };
Spec1.prototype.id = function(_id){ Spec1.prototype.id = function(_id) {
this.payload["id"] = _id; this.payload.id = _id;
return this; return this;
}; };
Spec1.prototype.getId = function() { Spec1.prototype.getId = function() {
return this.payload["id"]; return this.payload.id;
}; };
Spec1.prototype.source = function(_source){ Spec1.prototype.source = function(_source) {
this.payload["source"] = _source; this.payload.source = _source;
return this; return this;
}; };
Spec1.prototype.getSource = function() { Spec1.prototype.getSource = function() {
return this.payload["source"]; return this.payload.source;
}; };
Spec1.prototype.specversion = function(_specversion){ Spec1.prototype.specversion = function() {
// does not set! This is right // does not set! This is right
return this; return this;
}; };
Spec1.prototype.getSpecversion = function() { Spec1.prototype.getSpecversion = function() {
return this.payload["specversion"]; return this.payload.specversion;
}; };
Spec1.prototype.type = function(_type){ Spec1.prototype.type = function(_type) {
this.payload["type"] = _type; this.payload.type = _type;
return this; return this;
}; };
Spec1.prototype.getType = function(){ Spec1.prototype.getType = function() {
return this.payload["type"]; return this.payload.type;
}; };
Spec1.prototype.dataContentType = function(_contenttype){ Spec1.prototype.dataContentType = function(_contenttype) {
this.payload["datacontenttype"] = _contenttype; this.payload.datacontenttype = _contenttype;
return this; return this;
}; };
Spec1.prototype.getDataContentType = function() { Spec1.prototype.getDataContentType = function() {
return this.payload["datacontenttype"]; return this.payload.datacontenttype;
}; };
Spec1.prototype.dataschema = function(_schema){ Spec1.prototype.dataschema = function(_schema) {
this.payload["dataschema"] = _schema; this.payload.dataschema = _schema;
return this; return this;
}; };
Spec1.prototype.getDataschema = function() { Spec1.prototype.getDataschema = function() {
return this.payload["dataschema"]; return this.payload.dataschema;
}; };
Spec1.prototype.subject = function(_subject){ Spec1.prototype.subject = function(_subject) {
this.payload["subject"] = _subject; this.payload.subject = _subject;
return this; return this;
}; };
Spec1.prototype.getSubject = function() { Spec1.prototype.getSubject = function() {
return this.payload["subject"]; return this.payload.subject;
}; };
Spec1.prototype.time = function(_time){ Spec1.prototype.time = function(_time) {
this.payload["time"] = _time.toISOString(); this.payload.time = _time.toISOString();
return this; return this;
}; };
Spec1.prototype.getTime = function() { Spec1.prototype.getTime = function() {
return this.payload["time"]; return this.payload.time;
}; };
Spec1.prototype.data = function(_data){ Spec1.prototype.data = function(_data) {
this.payload["data"] = _data; this.payload.data = _data;
return this; return this;
}; };
Spec1.prototype.getData = function() { Spec1.prototype.getData = function() {
let dct = this.payload["datacontenttype"]; const dct = this.payload.datacontenttype;
if(dct){ if (dct) {
this.payload["data"] = asData(this.payload["data"], dct); this.payload.data = asData(this.payload.data, dct);
} }
return this.payload["data"]; return this.payload.data;
}; };
Spec1.prototype.addExtension = function(key, value){ Spec1.prototype.addExtension = function(key, value) {
if(!RESERVED_ATTRIBUTES.hasOwnProperty(key)){ if (!Object.prototype.hasOwnProperty.call(RESERVED_ATTRIBUTES, key)) {
if(isValidType(value)){ if (isValidType(value)) {
this.payload[key] = value; this.payload[key] = value;
} else { } else {
throw {message: "Invalid type of extension value"}; throw new TypeError("Invalid type of extension value");
} }
} else { } else {
throw {message: "Reserved attribute name: '" + key + "'"}; throw new TypeError(`Reserved attribute name: '${key}'`);
} }
return this; return this;
}; };

View File

@ -1,7 +1,7 @@
// Functional approach // Functional approach
const isString = (v) => (typeof v) === "string"; const isString = (v) => (typeof v) === "string";
const isObject = (v) => (typeof v) === "object"; const isObject = (v) => (typeof v) === "object";
const isDefined = (v) => v && (typeof v) != "undefined"; const isDefined = (v) => v && (typeof v) !== "undefined";
const isBoolean = (v) => (typeof v) === "boolean"; const isBoolean = (v) => (typeof v) === "boolean";
const isInteger = (v) => Number.isInteger(v); const isInteger = (v) => Number.isInteger(v);
@ -11,24 +11,24 @@ const isBinary = (v) => (v instanceof Uint32Array);
const isStringOrThrow = (v, t) => const isStringOrThrow = (v, t) =>
(isString(v) (isString(v)
? true ? true
: (() => {throw t;})()); : (() => { throw t; })());
const isDefinedOrThrow = (v, t) => const isDefinedOrThrow = (v, t) =>
(isDefined(v) (isDefined(v)
? () => true ? () => true
: (() => {throw t;})()); : (() => { throw t; })());
const isStringOrObjectOrThrow = (v, t) => const isStringOrObjectOrThrow = (v, t) =>
(isString(v) (isString(v)
? true ? true
: isObject(v) : isObject(v)
? true ? true
: (() => {throw t;})()); : (() => { throw t; })());
const equalsOrThrow = (v1, v2, t) => const equalsOrThrow = (v1, v2, t) =>
(v1 === v2 (v1 === v2
? true ? true
: (() => {throw t;})()); : (() => { throw t; })());
const isBase64 = (value) => const isBase64 = (value) =>
Buffer.from(value, "base64").toString("base64") === value; Buffer.from(value, "base64").toString("base64") === value;
@ -41,7 +41,7 @@ const asBuffer = (value) =>
? Buffer.from(value) ? Buffer.from(value)
: isBuffer(value) : isBuffer(value)
? value ? value
: (() => {throw {message: "is not buffer or a valid binary"};})(); : (() => { throw new TypeError("is not buffer or a valid binary"); })();
const asBase64 = (value) => const asBase64 = (value) =>
asBuffer(value).toString("base64"); asBuffer(value).toString("base64");
@ -56,7 +56,9 @@ const asData = (data, contentType) => {
let result = data; let result = data;
// pattern matching alike // pattern matching alike
result = isString(result) && !isBase64(result) && isJsonContentType(contentType) result = isString(result) &&
!isBase64(result) &&
isJsonContentType(contentType)
? JSON.parse(result) ? JSON.parse(result)
: result; : result;

1524
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -4,6 +4,8 @@
"description": "CloudEvents SDK for JavaScript", "description": "CloudEvents SDK for JavaScript",
"main": "index.js", "main": "index.js",
"scripts": { "scripts": {
"lint": "standardx",
"pretest": "npm run lint",
"test": "mocha test/**/*.js", "test": "mocha test/**/*.js",
"coverage": "nyc --reporter=lcov --reporter=text npm run test", "coverage": "nyc --reporter=lcov --reporter=text npm run test",
"precoverage-publish": "npm run coverage", "precoverage-publish": "npm run coverage",
@ -40,7 +42,11 @@
"chai": "~4.2.0", "chai": "~4.2.0",
"mocha": "~7.1.1", "mocha": "~7.1.1",
"nock": "~12.0.3", "nock": "~12.0.3",
"nyc": "~15.0.0" "nyc": "~15.0.0",
"eslint-config-standard": "^14.1.1",
"eslint-plugin-import": "^2.20.2",
"eslint-plugin-node": "^11.1.0",
"standardx": "^5.0.0"
}, },
"publishConfig": { "publishConfig": {
"access": "public" "access": "public"

View File

@ -41,10 +41,10 @@ describe("HTTP Transport Binding Binary Receiver for CloudEvents v0.2", () => {
// setup // setup
var payload = {}; var payload = {};
var attributes = { var attributes = {
"ce-specversion" : "specversion", "ce-specversion": "specversion",
"ce-source" : "source", "ce-source": "source",
"ce-id" : "id", "ce-id": "id",
"Content-Type" : "application/json" "Content-Type": "application/json"
}; };
// act and assert // act and assert
@ -56,10 +56,10 @@ describe("HTTP Transport Binding Binary Receiver for CloudEvents v0.2", () => {
// setup // setup
var payload = {}; var payload = {};
var attributes = { var attributes = {
"ce-type" : "type", "ce-type": "type",
"ce-source" : "source", "ce-source": "source",
"ce-id" : "id", "ce-id": "id",
"Content-Type" : "application/json" "Content-Type": "application/json"
}; };
// act and assert // act and assert
@ -71,10 +71,10 @@ describe("HTTP Transport Binding Binary Receiver for CloudEvents v0.2", () => {
// setup // setup
var payload = {}; var payload = {};
var attributes = { var attributes = {
"ce-type" : "type", "ce-type": "type",
"ce-specversion" : "specversion", "ce-specversion": "specversion",
"ce-id" : "id", "ce-id": "id",
"Content-Type" : "application/json" "Content-Type": "application/json"
}; };
// act and assert // act and assert
@ -86,10 +86,10 @@ describe("HTTP Transport Binding Binary Receiver for CloudEvents v0.2", () => {
// setup // setup
var payload = {}; var payload = {};
var attributes = { var attributes = {
"ce-type" : "type", "ce-type": "type",
"ce-specversion" : "specversion", "ce-specversion": "specversion",
"ce-source" : "source", "ce-source": "source",
"Content-Type" : "application/json" "Content-Type": "application/json"
}; };
// act and assert // act and assert
@ -101,11 +101,11 @@ describe("HTTP Transport Binding Binary Receiver for CloudEvents v0.2", () => {
// setup // setup
var payload = {}; var payload = {};
var attributes = { var attributes = {
"ce-type" : "type", "ce-type": "type",
"ce-specversion" : "specversion", "ce-specversion": "specversion",
"ce-source" : "source", "ce-source": "source",
"ce-id" : "id", "ce-id": "id",
"Content-Type" : "application/json" "Content-Type": "application/json"
}; };
// act and assert // act and assert
@ -117,11 +117,11 @@ describe("HTTP Transport Binding Binary Receiver for CloudEvents v0.2", () => {
// setup // setup
var payload = {}; var payload = {};
var attributes = { var attributes = {
"ce-type" : "type", "ce-type": "type",
"ce-specversion" : "specversion", "ce-specversion": "specversion",
"ce-source" : "source", "ce-source": "source",
"ce-id" : "id", "ce-id": "id",
"Content-Type" : "text/html" "Content-Type": "text/html"
}; };
// act and assert // act and assert
@ -133,11 +133,11 @@ describe("HTTP Transport Binding Binary Receiver for CloudEvents v0.2", () => {
// setup // setup
var payload = {}; var payload = {};
var attributes = { var attributes = {
"ce-type" : "type", "ce-type": "type",
"ce-specversion" : "0.2", "ce-specversion": "0.2",
"ce-source" : "source", "ce-source": "source",
"ce-id" : "id", "ce-id": "id",
"Content-Type" : "application/json" "Content-Type": "application/json"
}; };
// act and assert // act and assert
@ -150,16 +150,16 @@ describe("HTTP Transport Binding Binary Receiver for CloudEvents v0.2", () => {
it("Cloudevent contains 'type'", () => { it("Cloudevent contains 'type'", () => {
// setup // setup
var payload = { var payload = {
"data" : "dataString" data: "dataString"
}; };
var attributes = { var attributes = {
"ce-type" : "type", "ce-type": "type",
"ce-specversion" : "0.2", "ce-specversion": "0.2",
"ce-source" : "source", "ce-source": "source",
"ce-id" : "id", "ce-id": "id",
"ce-time" : "2019-06-16T11:42:00Z", "ce-time": "2019-06-16T11:42:00Z",
"ce-schemaurl" : "http://schema.registry/v1", "ce-schemaurl": "http://schema.registry/v1",
"Content-Type" : "application/json" "Content-Type": "application/json"
}; };
// act // act
@ -173,16 +173,16 @@ describe("HTTP Transport Binding Binary Receiver for CloudEvents v0.2", () => {
it("Cloudevent contains 'specversion'", () => { it("Cloudevent contains 'specversion'", () => {
// setup // setup
var payload = { var payload = {
"data" : "dataString" data: "dataString"
}; };
var attributes = { var attributes = {
"ce-type" : "type", "ce-type": "type",
"ce-specversion" : "0.2", "ce-specversion": "0.2",
"ce-source" : "source", "ce-source": "source",
"ce-id" : "id", "ce-id": "id",
"ce-time" : "2019-06-16T11:42:00Z", "ce-time": "2019-06-16T11:42:00Z",
"ce-schemaurl" : "http://schema.registry/v1", "ce-schemaurl": "http://schema.registry/v1",
"Content-Type" : "application/json" "Content-Type": "application/json"
}; };
// act // act
@ -196,16 +196,16 @@ describe("HTTP Transport Binding Binary Receiver for CloudEvents v0.2", () => {
it("Cloudevent contains 'source'", () => { it("Cloudevent contains 'source'", () => {
// setup // setup
var payload = { var payload = {
"data" : "dataString" data: "dataString"
}; };
var attributes = { var attributes = {
"ce-type" : "type", "ce-type": "type",
"ce-specversion" : "0.2", "ce-specversion": "0.2",
"ce-source" : "/source", "ce-source": "/source",
"ce-id" : "id", "ce-id": "id",
"ce-time" : "2019-06-16T11:42:00Z", "ce-time": "2019-06-16T11:42:00Z",
"ce-schemaurl" : "http://schema.registry/v1", "ce-schemaurl": "http://schema.registry/v1",
"Content-Type" : "application/json" "Content-Type": "application/json"
}; };
// act // act
@ -219,16 +219,16 @@ describe("HTTP Transport Binding Binary Receiver for CloudEvents v0.2", () => {
it("Cloudevent contains 'id'", () => { it("Cloudevent contains 'id'", () => {
// setup // setup
var payload = { var payload = {
"data" : "dataString" data: "dataString"
}; };
var attributes = { var attributes = {
"ce-type" : "type", "ce-type": "type",
"ce-specversion" : "0.2", "ce-specversion": "0.2",
"ce-source" : "/source", "ce-source": "/source",
"ce-id" : "id", "ce-id": "id",
"ce-time" : "2019-06-16T11:42:00Z", "ce-time": "2019-06-16T11:42:00Z",
"ce-schemaurl" : "http://schema.registry/v1", "ce-schemaurl": "http://schema.registry/v1",
"Content-Type" : "application/json" "Content-Type": "application/json"
}; };
// act // act
@ -242,16 +242,16 @@ describe("HTTP Transport Binding Binary Receiver for CloudEvents v0.2", () => {
it("Cloudevent contains 'time'", () => { it("Cloudevent contains 'time'", () => {
// setup // setup
var payload = { var payload = {
"data" : "dataString" data: "dataString"
}; };
var attributes = { var attributes = {
"ce-type" : "type", "ce-type": "type",
"ce-specversion" : "0.2", "ce-specversion": "0.2",
"ce-source" : "/source", "ce-source": "/source",
"ce-id" : "id", "ce-id": "id",
"ce-time" : "2019-06-16T11:42:00.000Z", "ce-time": "2019-06-16T11:42:00.000Z",
"ce-schemaurl" : "http://schema.registry/v1", "ce-schemaurl": "http://schema.registry/v1",
"Content-Type" : "application/json" "Content-Type": "application/json"
}; };
// act // act
@ -265,16 +265,16 @@ describe("HTTP Transport Binding Binary Receiver for CloudEvents v0.2", () => {
it("Cloudevent contains 'schemaurl'", () => { it("Cloudevent contains 'schemaurl'", () => {
// setup // setup
var payload = { var payload = {
"data" : "dataString" data: "dataString"
}; };
var attributes = { var attributes = {
"ce-type" : "type", "ce-type": "type",
"ce-specversion" : "0.2", "ce-specversion": "0.2",
"ce-source" : "/source", "ce-source": "/source",
"ce-id" : "id", "ce-id": "id",
"ce-time" : "2019-06-16T11:42:00Z", "ce-time": "2019-06-16T11:42:00Z",
"ce-schemaurl" : "http://schema.registry/v1", "ce-schemaurl": "http://schema.registry/v1",
"Content-Type" : "application/json" "Content-Type": "application/json"
}; };
// act // act
@ -288,16 +288,16 @@ describe("HTTP Transport Binding Binary Receiver for CloudEvents v0.2", () => {
it("Cloudevent contains 'contenttype' (application/json)", () => { it("Cloudevent contains 'contenttype' (application/json)", () => {
// setup // setup
var payload = { var payload = {
"data" : "dataString" data: "dataString"
}; };
var attributes = { var attributes = {
"ce-type" : "type", "ce-type": "type",
"ce-specversion" : "0.2", "ce-specversion": "0.2",
"ce-source" : "/source", "ce-source": "/source",
"ce-id" : "id", "ce-id": "id",
"ce-time" : "2019-06-16T11:42:00Z", "ce-time": "2019-06-16T11:42:00Z",
"ce-schemaurl" : "http://schema.registry/v1", "ce-schemaurl": "http://schema.registry/v1",
"Content-Type" : "application/json" "Content-Type": "application/json"
}; };
// act // act
@ -312,13 +312,13 @@ describe("HTTP Transport Binding Binary Receiver for CloudEvents v0.2", () => {
// setup // setup
var payload = "The payload is binary data"; var payload = "The payload is binary data";
var attributes = { var attributes = {
"ce-type" : "type", "ce-type": "type",
"ce-specversion" : "0.2", "ce-specversion": "0.2",
"ce-source" : "/source", "ce-source": "/source",
"ce-id" : "id", "ce-id": "id",
"ce-time" : "2019-06-16T11:42:00Z", "ce-time": "2019-06-16T11:42:00Z",
"ce-schemaurl" : "http://schema.registry/v1", "ce-schemaurl": "http://schema.registry/v1",
"Content-Type" : "application/octet-stream" "Content-Type": "application/octet-stream"
}; };
// act // act
@ -332,16 +332,16 @@ describe("HTTP Transport Binding Binary Receiver for CloudEvents v0.2", () => {
it("Cloudevent contains 'data' (application/json)", () => { it("Cloudevent contains 'data' (application/json)", () => {
// setup // setup
var payload = { var payload = {
"data" : "dataString" data: "dataString"
}; };
var attributes = { var attributes = {
"ce-type" : "type", "ce-type": "type",
"ce-specversion" : "0.2", "ce-specversion": "0.2",
"ce-source" : "/source", "ce-source": "/source",
"ce-id" : "id", "ce-id": "id",
"ce-time" : "2019-06-16T11:42:00Z", "ce-time": "2019-06-16T11:42:00Z",
"ce-schemaurl" : "http://schema.registry/v1", "ce-schemaurl": "http://schema.registry/v1",
"Content-Type" : "application/json" "Content-Type": "application/json"
}; };
// act // act
@ -356,13 +356,13 @@ describe("HTTP Transport Binding Binary Receiver for CloudEvents v0.2", () => {
// setup // setup
var payload = "The payload is binary data"; var payload = "The payload is binary data";
var attributes = { var attributes = {
"ce-type" : "type", "ce-type": "type",
"ce-specversion" : "0.2", "ce-specversion": "0.2",
"ce-source" : "/source", "ce-source": "/source",
"ce-id" : "id", "ce-id": "id",
"ce-time" : "2019-06-16T11:42:00Z", "ce-time": "2019-06-16T11:42:00Z",
"ce-schemaurl" : "http://schema.registry/v1", "ce-schemaurl": "http://schema.registry/v1",
"Content-Type" : "application/octet-stream" "Content-Type": "application/octet-stream"
}; };
// act // act
@ -376,16 +376,16 @@ describe("HTTP Transport Binding Binary Receiver for CloudEvents v0.2", () => {
it("No error when all attributes are in place", () => { it("No error when all attributes are in place", () => {
// setup // setup
var payload = { var payload = {
"data" : "dataString" data: "dataString"
}; };
var attributes = { var attributes = {
"ce-type" : "type", "ce-type": "type",
"ce-specversion" : "0.2", "ce-specversion": "0.2",
"ce-source" : "source", "ce-source": "source",
"ce-id" : "id", "ce-id": "id",
"ce-time" : "2019-06-16T11:42:00Z", "ce-time": "2019-06-16T11:42:00Z",
"ce-schemaurl" : "http://schema.registry/v1", "ce-schemaurl": "http://schema.registry/v1",
"Content-Type" : "application/json" "Content-Type": "application/json"
}; };
// act // act
@ -393,27 +393,27 @@ describe("HTTP Transport Binding Binary Receiver for CloudEvents v0.2", () => {
// assert // assert
expect(actual) expect(actual)
.to.be.an("object"); .to.be.an("object");
expect(actual) expect(actual)
.to.have.property("format"); .to.have.property("format");
}); });
it("Should accept 'extension1'", () => { it("Should accept 'extension1'", () => {
// setup // setup
var extension1 = "mycuston-ext1"; var extension1 = "mycuston-ext1";
var payload = { var payload = {
"data" : "dataString" data: "dataString"
}; };
var attributes = { var attributes = {
"ce-type" : "type", "ce-type": "type",
"ce-specversion" : "0.2", "ce-specversion": "0.2",
"ce-source" : "source", "ce-source": "source",
"ce-id" : "id", "ce-id": "id",
"ce-time" : "2019-06-16T11:42:00Z", "ce-time": "2019-06-16T11:42:00Z",
"ce-schemaurl" : "http://schema.registry/v1", "ce-schemaurl": "http://schema.registry/v1",
"Content-Type" : "application/json", "Content-Type": "application/json",
"ce-extension1" : extension1 "ce-extension1": extension1
}; };
// act // act
@ -421,8 +421,8 @@ describe("HTTP Transport Binding Binary Receiver for CloudEvents v0.2", () => {
var actualExtensions = actual.getExtensions(); var actualExtensions = actual.getExtensions();
// assert // assert
expect(actualExtensions["extension1"]) expect(actualExtensions.extension1)
.to.equal(extension1); .to.equal(extension1);
}); });
}); });
}); });

View File

@ -41,10 +41,10 @@ describe("HTTP Transport Binding Binary Receiver for CloudEvents v0.3", () => {
// setup // setup
var payload = {}; var payload = {};
var attributes = { var attributes = {
"ce-specversion" : "specversion", "ce-specversion": "specversion",
"ce-source" : "source", "ce-source": "source",
"ce-id" : "id", "ce-id": "id",
"Content-Type" : "application/json" "Content-Type": "application/json"
}; };
// act and assert // act and assert
@ -56,10 +56,10 @@ describe("HTTP Transport Binding Binary Receiver for CloudEvents v0.3", () => {
// setup // setup
var payload = {}; var payload = {};
var attributes = { var attributes = {
"ce-type" : "type", "ce-type": "type",
"ce-source" : "source", "ce-source": "source",
"ce-id" : "id", "ce-id": "id",
"Content-Type" : "application/json" "Content-Type": "application/json"
}; };
// act and assert // act and assert
@ -71,10 +71,10 @@ describe("HTTP Transport Binding Binary Receiver for CloudEvents v0.3", () => {
// setup // setup
var payload = {}; var payload = {};
var attributes = { var attributes = {
"ce-type" : "type", "ce-type": "type",
"ce-specversion" : "specversion", "ce-specversion": "specversion",
"ce-id" : "id", "ce-id": "id",
"Content-Type" : "application/json" "Content-Type": "application/json"
}; };
// act and assert // act and assert
@ -86,10 +86,10 @@ describe("HTTP Transport Binding Binary Receiver for CloudEvents v0.3", () => {
// setup // setup
var payload = {}; var payload = {};
var attributes = { var attributes = {
"ce-type" : "type", "ce-type": "type",
"ce-specversion" : "specversion", "ce-specversion": "specversion",
"ce-source" : "source", "ce-source": "source",
"Content-Type" : "application/json" "Content-Type": "application/json"
}; };
// act and assert // act and assert
@ -101,11 +101,11 @@ describe("HTTP Transport Binding Binary Receiver for CloudEvents v0.3", () => {
// setup // setup
var payload = {}; var payload = {};
var attributes = { var attributes = {
"ce-type" : "type", "ce-type": "type",
"ce-specversion" : "0.2", "ce-specversion": "0.2",
"ce-source" : "source", "ce-source": "source",
"ce-id" : "id", "ce-id": "id",
"Content-Type" : "application/json" "Content-Type": "application/json"
}; };
// act and assert // act and assert
@ -117,11 +117,11 @@ describe("HTTP Transport Binding Binary Receiver for CloudEvents v0.3", () => {
// setup // setup
var payload = {}; var payload = {};
var attributes = { var attributes = {
"ce-type" : "type", "ce-type": "type",
"ce-specversion" : "specversion", "ce-specversion": "specversion",
"ce-source" : "source", "ce-source": "source",
"ce-id" : "id", "ce-id": "id",
"Content-Type" : "text/html" "Content-Type": "text/html"
}; };
// act and assert // act and assert
@ -133,11 +133,11 @@ describe("HTTP Transport Binding Binary Receiver for CloudEvents v0.3", () => {
// setup // setup
var payload = {}; var payload = {};
var attributes = { var attributes = {
"ce-type" : "type", "ce-type": "type",
"ce-specversion" : "0.3", "ce-specversion": "0.3",
"ce-source" : "source", "ce-source": "source",
"ce-id" : "id", "ce-id": "id",
"Content-Type" : "application/json" "Content-Type": "application/json"
}; };
// act and assert // act and assert
@ -150,16 +150,16 @@ describe("HTTP Transport Binding Binary Receiver for CloudEvents v0.3", () => {
it("Cloudevent contains 'type'", () => { it("Cloudevent contains 'type'", () => {
// setup // setup
var payload = { var payload = {
"data" : "dataString" data: "dataString"
}; };
var attributes = { var attributes = {
"ce-type" : "type", "ce-type": "type",
"ce-specversion" : "0.3", "ce-specversion": "0.3",
"ce-source" : "source", "ce-source": "source",
"ce-id" : "id", "ce-id": "id",
"ce-time" : "2019-06-16T11:42:00Z", "ce-time": "2019-06-16T11:42:00Z",
"ce-schemaurl" : "http://schema.registry/v1", "ce-schemaurl": "http://schema.registry/v1",
"Content-Type" : "application/json" "Content-Type": "application/json"
}; };
// act // act
@ -173,16 +173,16 @@ describe("HTTP Transport Binding Binary Receiver for CloudEvents v0.3", () => {
it("Cloudevent contains 'specversion'", () => { it("Cloudevent contains 'specversion'", () => {
// setup // setup
var payload = { var payload = {
"data" : "dataString" data: "dataString"
}; };
var attributes = { var attributes = {
"ce-type" : "type", "ce-type": "type",
"ce-specversion" : "0.3", "ce-specversion": "0.3",
"ce-source" : "source", "ce-source": "source",
"ce-id" : "id", "ce-id": "id",
"ce-time" : "2019-06-16T11:42:00Z", "ce-time": "2019-06-16T11:42:00Z",
"ce-schemaurl" : "http://schema.registry/v1", "ce-schemaurl": "http://schema.registry/v1",
"Content-Type" : "application/json" "Content-Type": "application/json"
}; };
// act // act
@ -196,16 +196,16 @@ describe("HTTP Transport Binding Binary Receiver for CloudEvents v0.3", () => {
it("Cloudevent contains 'source'", () => { it("Cloudevent contains 'source'", () => {
// setup // setup
var payload = { var payload = {
"data" : "dataString" data: "dataString"
}; };
var attributes = { var attributes = {
"ce-type" : "type", "ce-type": "type",
"ce-specversion" : "0.3", "ce-specversion": "0.3",
"ce-source" : "/source", "ce-source": "/source",
"ce-id" : "id", "ce-id": "id",
"ce-time" : "2019-06-16T11:42:00Z", "ce-time": "2019-06-16T11:42:00Z",
"ce-schemaurl" : "http://schema.registry/v1", "ce-schemaurl": "http://schema.registry/v1",
"Content-Type" : "application/json" "Content-Type": "application/json"
}; };
// act // act
@ -219,16 +219,16 @@ describe("HTTP Transport Binding Binary Receiver for CloudEvents v0.3", () => {
it("Cloudevent contains 'id'", () => { it("Cloudevent contains 'id'", () => {
// setup // setup
var payload = { var payload = {
"data" : "dataString" data: "dataString"
}; };
var attributes = { var attributes = {
"ce-type" : "type", "ce-type": "type",
"ce-specversion" : "0.3", "ce-specversion": "0.3",
"ce-source" : "/source", "ce-source": "/source",
"ce-id" : "id", "ce-id": "id",
"ce-time" : "2019-06-16T11:42:00Z", "ce-time": "2019-06-16T11:42:00Z",
"ce-schemaurl" : "http://schema.registry/v1", "ce-schemaurl": "http://schema.registry/v1",
"Content-Type" : "application/json" "Content-Type": "application/json"
}; };
// act // act
@ -242,16 +242,16 @@ describe("HTTP Transport Binding Binary Receiver for CloudEvents v0.3", () => {
it("Cloudevent contains 'time'", () => { it("Cloudevent contains 'time'", () => {
// setup // setup
var payload = { var payload = {
"data" : "dataString" data: "dataString"
}; };
var attributes = { var attributes = {
"ce-type" : "type", "ce-type": "type",
"ce-specversion" : "0.3", "ce-specversion": "0.3",
"ce-source" : "/source", "ce-source": "/source",
"ce-id" : "id", "ce-id": "id",
"ce-time" : "2019-06-16T11:42:00.000Z", "ce-time": "2019-06-16T11:42:00.000Z",
"ce-schemaurl" : "http://schema.registry/v1", "ce-schemaurl": "http://schema.registry/v1",
"Content-Type" : "application/json" "Content-Type": "application/json"
}; };
// act // act
@ -265,16 +265,16 @@ describe("HTTP Transport Binding Binary Receiver for CloudEvents v0.3", () => {
it("Cloudevent contains 'schemaurl'", () => { it("Cloudevent contains 'schemaurl'", () => {
// setup // setup
var payload = { var payload = {
"data" : "dataString" data: "dataString"
}; };
var attributes = { var attributes = {
"ce-type" : "type", "ce-type": "type",
"ce-specversion" : "0.3", "ce-specversion": "0.3",
"ce-source" : "/source", "ce-source": "/source",
"ce-id" : "id", "ce-id": "id",
"ce-time" : "2019-06-16T11:42:00Z", "ce-time": "2019-06-16T11:42:00Z",
"ce-schemaurl" : "http://schema.registry/v1", "ce-schemaurl": "http://schema.registry/v1",
"Content-Type" : "application/json" "Content-Type": "application/json"
}; };
// act // act
@ -288,16 +288,16 @@ describe("HTTP Transport Binding Binary Receiver for CloudEvents v0.3", () => {
it("Cloudevent contains 'contenttype' (application/json)", () => { it("Cloudevent contains 'contenttype' (application/json)", () => {
// setup // setup
var payload = { var payload = {
"data" : "dataString" data: "dataString"
}; };
var attributes = { var attributes = {
"ce-type" : "type", "ce-type": "type",
"ce-specversion" : "0.3", "ce-specversion": "0.3",
"ce-source" : "/source", "ce-source": "/source",
"ce-id" : "id", "ce-id": "id",
"ce-time" : "2019-06-16T11:42:00Z", "ce-time": "2019-06-16T11:42:00Z",
"ce-schemaurl" : "http://schema.registry/v1", "ce-schemaurl": "http://schema.registry/v1",
"Content-Type" : "application/json" "Content-Type": "application/json"
}; };
// act // act
@ -312,13 +312,13 @@ describe("HTTP Transport Binding Binary Receiver for CloudEvents v0.3", () => {
// setup // setup
var payload = "The payload is binary data"; var payload = "The payload is binary data";
var attributes = { var attributes = {
"ce-type" : "type", "ce-type": "type",
"ce-specversion" : "0.3", "ce-specversion": "0.3",
"ce-source" : "/source", "ce-source": "/source",
"ce-id" : "id", "ce-id": "id",
"ce-time" : "2019-06-16T11:42:00Z", "ce-time": "2019-06-16T11:42:00Z",
"ce-schemaurl" : "http://schema.registry/v1", "ce-schemaurl": "http://schema.registry/v1",
"Content-Type" : "application/octet-stream" "Content-Type": "application/octet-stream"
}; };
// act // act
@ -332,16 +332,16 @@ describe("HTTP Transport Binding Binary Receiver for CloudEvents v0.3", () => {
it("Cloudevent contains 'data' (application/json)", () => { it("Cloudevent contains 'data' (application/json)", () => {
// setup // setup
var payload = { var payload = {
"data" : "dataString" data: "dataString"
}; };
var attributes = { var attributes = {
"ce-type" : "type", "ce-type": "type",
"ce-specversion" : "0.3", "ce-specversion": "0.3",
"ce-source" : "/source", "ce-source": "/source",
"ce-id" : "id", "ce-id": "id",
"ce-time" : "2019-06-16T11:42:00Z", "ce-time": "2019-06-16T11:42:00Z",
"ce-schemaurl" : "http://schema.registry/v1", "ce-schemaurl": "http://schema.registry/v1",
"Content-Type" : "application/json" "Content-Type": "application/json"
}; };
// act // act
@ -356,13 +356,13 @@ describe("HTTP Transport Binding Binary Receiver for CloudEvents v0.3", () => {
// setup // setup
var payload = "The payload is binary data"; var payload = "The payload is binary data";
var attributes = { var attributes = {
"ce-type" : "type", "ce-type": "type",
"ce-specversion" : "0.3", "ce-specversion": "0.3",
"ce-source" : "/source", "ce-source": "/source",
"ce-id" : "id", "ce-id": "id",
"ce-time" : "2019-06-16T11:42:00Z", "ce-time": "2019-06-16T11:42:00Z",
"ce-schemaurl" : "http://schema.registry/v1", "ce-schemaurl": "http://schema.registry/v1",
"Content-Type" : "application/octet-stream" "Content-Type": "application/octet-stream"
}; };
// act // act
@ -376,16 +376,16 @@ describe("HTTP Transport Binding Binary Receiver for CloudEvents v0.3", () => {
it("No error when all attributes are in place", () => { it("No error when all attributes are in place", () => {
// setup // setup
var payload = { var payload = {
"data" : "dataString" data: "dataString"
}; };
var attributes = { var attributes = {
"ce-type" : "type", "ce-type": "type",
"ce-specversion" : "0.3", "ce-specversion": "0.3",
"ce-source" : "source", "ce-source": "source",
"ce-id" : "id", "ce-id": "id",
"ce-time" : "2019-06-16T11:42:00Z", "ce-time": "2019-06-16T11:42:00Z",
"ce-schemaurl" : "http://schema.registry/v1", "ce-schemaurl": "http://schema.registry/v1",
"Content-Type" : "application/json" "Content-Type": "application/json"
}; };
// act // act
@ -393,27 +393,27 @@ describe("HTTP Transport Binding Binary Receiver for CloudEvents v0.3", () => {
// assert // assert
expect(actual) expect(actual)
.to.be.an("object"); .to.be.an("object");
expect(actual) expect(actual)
.to.have.property("format"); .to.have.property("format");
}); });
it("Should accept 'extension1'", () => { it("Should accept 'extension1'", () => {
// setup // setup
var extension1 = "mycuston-ext1"; var extension1 = "mycuston-ext1";
var payload = { var payload = {
"data" : "dataString" data: "dataString"
}; };
var attributes = { var attributes = {
"ce-type" : "type", "ce-type": "type",
"ce-specversion" : "0.3", "ce-specversion": "0.3",
"ce-source" : "source", "ce-source": "source",
"ce-id" : "id", "ce-id": "id",
"ce-time" : "2019-06-16T11:42:00Z", "ce-time": "2019-06-16T11:42:00Z",
"ce-schemaurl" : "http://schema.registry/v1", "ce-schemaurl": "http://schema.registry/v1",
"Content-Type" : "application/json", "Content-Type": "application/json",
"ce-extension1" : extension1 "ce-extension1": extension1
}; };
// act // act
@ -421,8 +421,8 @@ describe("HTTP Transport Binding Binary Receiver for CloudEvents v0.3", () => {
var actualExtensions = actual.getExtensions(); var actualExtensions = actual.getExtensions();
// assert // assert
expect(actualExtensions["extension1"]) expect(actualExtensions.extension1)
.to.equal(extension1); .to.equal(extension1);
}); });
}); });
}); });

View File

@ -1,5 +1,5 @@
const expect = require("chai").expect; const expect = require("chai").expect;
const {asBase64} = require("../../../lib/utils/fun.js"); const { asBase64 } = require("../../../lib/utils/fun.js");
const HTTPBinaryReceiver = const HTTPBinaryReceiver =
require("../../../lib/bindings/http/receiver_binary_1.js"); require("../../../lib/bindings/http/receiver_binary_1.js");
@ -42,10 +42,10 @@ describe("HTTP Transport Binding Binary Receiver for CloudEvents v1.0", () => {
// setup // setup
var payload = {}; var payload = {};
var attributes = { var attributes = {
"ce-specversion" : "specversion", "ce-specversion": "specversion",
"ce-source" : "source", "ce-source": "source",
"ce-id" : "id", "ce-id": "id",
"Content-Type" : "application/json" "Content-Type": "application/json"
}; };
// act and assert // act and assert
@ -57,10 +57,10 @@ describe("HTTP Transport Binding Binary Receiver for CloudEvents v1.0", () => {
// setup // setup
var payload = {}; var payload = {};
var attributes = { var attributes = {
"ce-type" : "type", "ce-type": "type",
"ce-source" : "source", "ce-source": "source",
"ce-id" : "id", "ce-id": "id",
"Content-Type" : "application/json" "Content-Type": "application/json"
}; };
// act and assert // act and assert
@ -72,10 +72,10 @@ describe("HTTP Transport Binding Binary Receiver for CloudEvents v1.0", () => {
// setup // setup
var payload = {}; var payload = {};
var attributes = { var attributes = {
"ce-type" : "type", "ce-type": "type",
"ce-specversion" : "specversion", "ce-specversion": "specversion",
"ce-id" : "id", "ce-id": "id",
"Content-Type" : "application/json" "Content-Type": "application/json"
}; };
// act and assert // act and assert
@ -87,10 +87,10 @@ describe("HTTP Transport Binding Binary Receiver for CloudEvents v1.0", () => {
// setup // setup
var payload = {}; var payload = {};
var attributes = { var attributes = {
"ce-type" : "type", "ce-type": "type",
"ce-specversion" : "specversion", "ce-specversion": "specversion",
"ce-source" : "source", "ce-source": "source",
"Content-Type" : "application/json" "Content-Type": "application/json"
}; };
// act and assert // act and assert
@ -102,11 +102,11 @@ describe("HTTP Transport Binding Binary Receiver for CloudEvents v1.0", () => {
// setup // setup
var payload = {}; var payload = {};
var attributes = { var attributes = {
"ce-type" : "type", "ce-type": "type",
"ce-specversion" : "0.2", "ce-specversion": "0.2",
"ce-source" : "source", "ce-source": "source",
"ce-id" : "id", "ce-id": "id",
"Content-Type" : "application/json" "Content-Type": "application/json"
}; };
// act and assert // act and assert
@ -118,11 +118,11 @@ describe("HTTP Transport Binding Binary Receiver for CloudEvents v1.0", () => {
// setup // setup
var payload = {}; var payload = {};
var attributes = { var attributes = {
"ce-type" : "type", "ce-type": "type",
"ce-specversion" : "specversion", "ce-specversion": "specversion",
"ce-source" : "source", "ce-source": "source",
"ce-id" : "id", "ce-id": "id",
"Content-Type" : "text/html" "Content-Type": "text/html"
}; };
// act and assert // act and assert
@ -134,11 +134,11 @@ describe("HTTP Transport Binding Binary Receiver for CloudEvents v1.0", () => {
// setup // setup
var payload = {}; var payload = {};
var attributes = { var attributes = {
"ce-type" : "type", "ce-type": "type",
"ce-specversion" : "1.0", "ce-specversion": "1.0",
"ce-source" : "source", "ce-source": "source",
"ce-id" : "id", "ce-id": "id",
"Content-Type" : "application/json" "Content-Type": "application/json"
}; };
// act and assert // act and assert
@ -151,16 +151,16 @@ describe("HTTP Transport Binding Binary Receiver for CloudEvents v1.0", () => {
it("Cloudevent contains 'type'", () => { it("Cloudevent contains 'type'", () => {
// setup // setup
var payload = { var payload = {
"data" : "dataString" data: "dataString"
}; };
var attributes = { var attributes = {
"ce-type" : "type", "ce-type": "type",
"ce-specversion" : "1.0", "ce-specversion": "1.0",
"ce-source" : "source", "ce-source": "source",
"ce-id" : "id", "ce-id": "id",
"ce-time" : "2019-06-16T11:42:00Z", "ce-time": "2019-06-16T11:42:00Z",
"ce-dataschema" : "http://schema.registry/v1", "ce-dataschema": "http://schema.registry/v1",
"Content-Type" : "application/json" "Content-Type": "application/json"
}; };
// act // act
@ -174,16 +174,16 @@ describe("HTTP Transport Binding Binary Receiver for CloudEvents v1.0", () => {
it("Cloudevent contains 'specversion'", () => { it("Cloudevent contains 'specversion'", () => {
// setup // setup
var payload = { var payload = {
"data" : "dataString" data: "dataString"
}; };
var attributes = { var attributes = {
"ce-type" : "type", "ce-type": "type",
"ce-specversion" : "1.0", "ce-specversion": "1.0",
"ce-source" : "source", "ce-source": "source",
"ce-id" : "id", "ce-id": "id",
"ce-time" : "2019-06-16T11:42:00Z", "ce-time": "2019-06-16T11:42:00Z",
"ce-dataschema" : "http://schema.registry/v1", "ce-dataschema": "http://schema.registry/v1",
"Content-Type" : "application/json" "Content-Type": "application/json"
}; };
// act // act
@ -197,16 +197,16 @@ describe("HTTP Transport Binding Binary Receiver for CloudEvents v1.0", () => {
it("Cloudevent contains 'source'", () => { it("Cloudevent contains 'source'", () => {
// setup // setup
var payload = { var payload = {
"data" : "dataString" data: "dataString"
}; };
var attributes = { var attributes = {
"ce-type" : "type", "ce-type": "type",
"ce-specversion" : "1.0", "ce-specversion": "1.0",
"ce-source" : "/source", "ce-source": "/source",
"ce-id" : "id", "ce-id": "id",
"ce-time" : "2019-06-16T11:42:00Z", "ce-time": "2019-06-16T11:42:00Z",
"ce-dataschema" : "http://schema.registry/v1", "ce-dataschema": "http://schema.registry/v1",
"Content-Type" : "application/json" "Content-Type": "application/json"
}; };
// act // act
@ -220,16 +220,16 @@ describe("HTTP Transport Binding Binary Receiver for CloudEvents v1.0", () => {
it("Cloudevent contains 'id'", () => { it("Cloudevent contains 'id'", () => {
// setup // setup
var payload = { var payload = {
"data" : "dataString" data: "dataString"
}; };
var attributes = { var attributes = {
"ce-type" : "type", "ce-type": "type",
"ce-specversion" : "1.0", "ce-specversion": "1.0",
"ce-source" : "/source", "ce-source": "/source",
"ce-id" : "id", "ce-id": "id",
"ce-time" : "2019-06-16T11:42:00Z", "ce-time": "2019-06-16T11:42:00Z",
"ce-dataschema" : "http://schema.registry/v1", "ce-dataschema": "http://schema.registry/v1",
"Content-Type" : "application/json" "Content-Type": "application/json"
}; };
// act // act
@ -243,16 +243,16 @@ describe("HTTP Transport Binding Binary Receiver for CloudEvents v1.0", () => {
it("Cloudevent contains 'time'", () => { it("Cloudevent contains 'time'", () => {
// setup // setup
var payload = { var payload = {
"data" : "dataString" data: "dataString"
}; };
var attributes = { var attributes = {
"ce-type" : "type", "ce-type": "type",
"ce-specversion" : "1.0", "ce-specversion": "1.0",
"ce-source" : "/source", "ce-source": "/source",
"ce-id" : "id", "ce-id": "id",
"ce-time" : "2019-06-16T11:42:00.000Z", "ce-time": "2019-06-16T11:42:00.000Z",
"ce-dataschema" : "http://schema.registry/v1", "ce-dataschema": "http://schema.registry/v1",
"Content-Type" : "application/json" "Content-Type": "application/json"
}; };
// act // act
@ -266,16 +266,16 @@ describe("HTTP Transport Binding Binary Receiver for CloudEvents v1.0", () => {
it("Cloudevent contains 'dataschema'", () => { it("Cloudevent contains 'dataschema'", () => {
// setup // setup
var payload = { var payload = {
"data" : "dataString" data: "dataString"
}; };
var attributes = { var attributes = {
"ce-type" : "type", "ce-type": "type",
"ce-specversion" : "1.0", "ce-specversion": "1.0",
"ce-source" : "/source", "ce-source": "/source",
"ce-id" : "id", "ce-id": "id",
"ce-time" : "2019-06-16T11:42:00Z", "ce-time": "2019-06-16T11:42:00Z",
"ce-dataschema" : "http://schema.registry/v1", "ce-dataschema": "http://schema.registry/v1",
"Content-Type" : "application/json" "Content-Type": "application/json"
}; };
// act // act
@ -289,16 +289,16 @@ describe("HTTP Transport Binding Binary Receiver for CloudEvents v1.0", () => {
it("Cloudevent contains 'contenttype' (application/json)", () => { it("Cloudevent contains 'contenttype' (application/json)", () => {
// setup // setup
var payload = { var payload = {
"data" : "dataString" data: "dataString"
}; };
var attributes = { var attributes = {
"ce-type" : "type", "ce-type": "type",
"ce-specversion" : "1.0", "ce-specversion": "1.0",
"ce-source" : "/source", "ce-source": "/source",
"ce-id" : "id", "ce-id": "id",
"ce-time" : "2019-06-16T11:42:00Z", "ce-time": "2019-06-16T11:42:00Z",
"ce-dataschema" : "http://schema.registry/v1", "ce-dataschema": "http://schema.registry/v1",
"Content-Type" : "application/json" "Content-Type": "application/json"
}; };
// act // act
@ -313,13 +313,13 @@ describe("HTTP Transport Binding Binary Receiver for CloudEvents v1.0", () => {
// setup // setup
var payload = "The payload is binary data"; var payload = "The payload is binary data";
var attributes = { var attributes = {
"ce-type" : "type", "ce-type": "type",
"ce-specversion" : "1.0", "ce-specversion": "1.0",
"ce-source" : "/source", "ce-source": "/source",
"ce-id" : "id", "ce-id": "id",
"ce-time" : "2019-06-16T11:42:00Z", "ce-time": "2019-06-16T11:42:00Z",
"ce-dataschema" : "http://schema.registry/v1", "ce-dataschema": "http://schema.registry/v1",
"Content-Type" : "application/octet-stream" "Content-Type": "application/octet-stream"
}; };
// act // act
@ -333,16 +333,16 @@ describe("HTTP Transport Binding Binary Receiver for CloudEvents v1.0", () => {
it("Cloudevent contains 'data' (application/json)", () => { it("Cloudevent contains 'data' (application/json)", () => {
// setup // setup
var payload = { var payload = {
"data" : "dataString" data: "dataString"
}; };
var attributes = { var attributes = {
"ce-type" : "type", "ce-type": "type",
"ce-specversion" : "1.0", "ce-specversion": "1.0",
"ce-source" : "/source", "ce-source": "/source",
"ce-id" : "id", "ce-id": "id",
"ce-time" : "2019-06-16T11:42:00Z", "ce-time": "2019-06-16T11:42:00Z",
"ce-dataschema" : "http://schema.registry/v1", "ce-dataschema": "http://schema.registry/v1",
"Content-Type" : "application/json" "Content-Type": "application/json"
}; };
// act // act
@ -357,13 +357,13 @@ describe("HTTP Transport Binding Binary Receiver for CloudEvents v1.0", () => {
// setup // setup
var payload = "The payload is binary data"; var payload = "The payload is binary data";
var attributes = { var attributes = {
"ce-type" : "type", "ce-type": "type",
"ce-specversion" : "1.0", "ce-specversion": "1.0",
"ce-source" : "/source", "ce-source": "/source",
"ce-id" : "id", "ce-id": "id",
"ce-time" : "2019-06-16T11:42:00Z", "ce-time": "2019-06-16T11:42:00Z",
"ce-dataschema" : "http://schema.registry/v1", "ce-dataschema": "http://schema.registry/v1",
"Content-Type" : "application/octet-stream" "Content-Type": "application/octet-stream"
}; };
// act // act
@ -377,20 +377,21 @@ describe("HTTP Transport Binding Binary Receiver for CloudEvents v1.0", () => {
it("The content of 'data' is base64 for binary", () => { it("The content of 'data' is base64 for binary", () => {
// setup // setup
var expected = { var expected = {
"data" : "dataString" data: "dataString"
}; };
let bindata = Uint32Array.from(JSON.stringify(expected), (c) => c.codePointAt(0)); const bindata = Uint32Array
let payload = asBase64(bindata); .from(JSON.stringify(expected), (c) => c.codePointAt(0));
const payload = asBase64(bindata);
var attributes = { var attributes = {
"ce-type" : "type", "ce-type": "type",
"ce-specversion" : "1.0", "ce-specversion": "1.0",
"ce-source" : "/source", "ce-source": "/source",
"ce-id" : "id", "ce-id": "id",
"ce-time" : "2019-06-16T11:42:00Z", "ce-time": "2019-06-16T11:42:00Z",
"ce-dataschema" : "http://schema.registry/v1", "ce-dataschema": "http://schema.registry/v1",
"Content-Type" : "application/json" "Content-Type": "application/json"
}; };
// act // act
@ -404,16 +405,16 @@ describe("HTTP Transport Binding Binary Receiver for CloudEvents v1.0", () => {
it("No error when all attributes are in place", () => { it("No error when all attributes are in place", () => {
// setup // setup
var payload = { var payload = {
"data" : "dataString" data: "dataString"
}; };
var attributes = { var attributes = {
"ce-type" : "type", "ce-type": "type",
"ce-specversion" : "1.0", "ce-specversion": "1.0",
"ce-source" : "source", "ce-source": "source",
"ce-id" : "id", "ce-id": "id",
"ce-time" : "2019-06-16T11:42:00Z", "ce-time": "2019-06-16T11:42:00Z",
"ce-dataschema" : "http://schema.registry/v1", "ce-dataschema": "http://schema.registry/v1",
"Content-Type" : "application/json" "Content-Type": "application/json"
}; };
// act // act
@ -421,27 +422,27 @@ describe("HTTP Transport Binding Binary Receiver for CloudEvents v1.0", () => {
// assert // assert
expect(actual) expect(actual)
.to.be.an("object"); .to.be.an("object");
expect(actual) expect(actual)
.to.have.property("format"); .to.have.property("format");
}); });
it("Should accept 'extension1'", () => { it("Should accept 'extension1'", () => {
// setup // setup
var extension1 = "mycuston-ext1"; var extension1 = "mycuston-ext1";
var payload = { var payload = {
"data" : "dataString" data: "dataString"
}; };
var attributes = { var attributes = {
"ce-type" : "type", "ce-type": "type",
"ce-specversion" : "1.0", "ce-specversion": "1.0",
"ce-source" : "source", "ce-source": "source",
"ce-id" : "id", "ce-id": "id",
"ce-time" : "2019-06-16T11:42:00Z", "ce-time": "2019-06-16T11:42:00Z",
"ce-dataschema" : "http://schema.registry/v1", "ce-dataschema": "http://schema.registry/v1",
"Content-Type" : "application/json", "Content-Type": "application/json",
"ce-extension1" : extension1 "ce-extension1": extension1
}; };
// act // act
@ -449,8 +450,8 @@ describe("HTTP Transport Binding Binary Receiver for CloudEvents v1.0", () => {
var actualExtensions = actual.getExtensions(); var actualExtensions = actual.getExtensions();
// assert // assert
expect(actualExtensions["extension1"]) expect(actualExtensions.extension1)
.to.equal(extension1); .to.equal(extension1);
}); });
}); });
}); });

View File

@ -1,18 +1,15 @@
var expect = require("chai").expect; var expect = require("chai").expect;
var Cloudevent = require("../../../index.js"); var Cloudevent = require("../../../index.js");
var Spec02 = require("../../../lib/specs/spec_0_2.js");
var HTTPStructuredReceiver02 = var HTTPStructuredReceiver02 =
require("../../../lib/bindings/http/receiver_structured_0_2.js"); require("../../../lib/bindings/http/receiver_structured_0_2.js");
var receiver = new HTTPStructuredReceiver02(); var receiver = new HTTPStructuredReceiver02();
const type = "com.github.pull.create"; const type = "com.github.pull.create";
const source = "urn:event:from:myapi/resourse/123"; const source = "urn:event:from:myapi/resourse/123";
const webhook = "https://cloudevents.io/webhook"; const now = new Date();
const contentType = "application/cloudevents+json; charset=utf-8"; const schemaurl = "http://cloudevents.io/schema.json";
const now = new Date();
const schemaurl = "http://cloudevents.io/schema.json";
const ceContentType = "application/json"; const ceContentType = "application/json";
@ -20,83 +17,68 @@ const data = {
foo: "bar" foo: "bar"
}; };
const ext1Name = "extension1"; describe("HTTP Transport Binding Structured Receiver for CloudEvents v0.2",
const ext1Value = "foobar"; () => {
const ext2Name = "extension2"; describe("Check", () => {
const ext2Value = "acme"; it("Throw error when payload arg is null or undefined", () => {
var cloudevent =
new Cloudevent(Spec02)
.type(type)
.source(source)
.contenttype(ceContentType)
.time(now)
.schemaurl(schemaurl)
.data(data)
.addExtension(ext1Name, ext1Value)
.addExtension(ext2Name, ext2Value);
describe("HTTP Transport Binding Structured Receiver for CloudEvents v0.2", () => {
describe("Check", () => {
it("Throw error when payload arg is null or undefined", () => {
// setup // setup
var payload = null; var payload = null;
var attributes = {}; var attributes = {};
// act and assert // act and assert
expect(receiver.check.bind(receiver, payload, attributes)) expect(receiver.check.bind(receiver, payload, attributes))
.to.throw("payload is null or undefined"); .to.throw("payload is null or undefined");
});
it("Throw error when attributes arg is null or undefined", () => {
// setup
var payload = {};
var attributes = null;
// act and assert
expect(receiver.check.bind(receiver, payload, attributes))
.to.throw("attributes is null or undefined");
});
it("Throw error when payload is not an object or string", () => {
// setup
var payload = 1.0;
var attributes = {};
// act and assert
expect(receiver.check.bind(receiver, payload, attributes))
.to.throw("payload must be an object or string");
});
it("Throw error when the content-type is invalid", () => {
// setup
var payload = {};
var attributes = {
"Content-Type": "text/html"
};
// act and assert
expect(receiver.check.bind(receiver, payload, attributes))
.to.throw("invalid content type");
});
it("No error when all required stuff are in place", () => {
// setup
var payload = {};
var attributes = {
"Content-Type": "application/cloudevents+json"
};
// act and assert
expect(receiver.check.bind(receiver, payload, attributes))
.to.not.throw();
});
}); });
it("Throw error when attributes arg is null or undefined", () => { describe("Parse", () => {
it("Throw error when the event does not follow the spec 0.2", () => {
// setup // setup
var payload = {}; var payload =
var attributes = null;
// act and assert
expect(receiver.check.bind(receiver, payload, attributes))
.to.throw("attributes is null or undefined");
});
it("Throw error when payload is not an object or string", () => {
// setup
var payload = 1.0;
var attributes = {};
// act and assert
expect(receiver.check.bind(receiver, payload, attributes))
.to.throw("payload must be an object or string");
});
it("Throw error when the content-type is invalid", () => {
// setup
var payload = {};
var attributes = {
"Content-Type" : "text/html"
};
// act and assert
expect(receiver.check.bind(receiver, payload, attributes))
.to.throw("invalid content type");
});
it("No error when all required stuff are in place", () => {
// setup
var payload = {};
var attributes = {
"Content-Type" : "application/cloudevents+json"
};
// act and assert
expect(receiver.check.bind(receiver, payload, attributes))
.to.not.throw();
});
});
describe("Parse", () => {
it("Throw error when the event does not follow the spec 0.2", () => {
// setup
var payload =
new Cloudevent() new Cloudevent()
.type(type) .type(type)
.source(source) .source(source)
@ -106,19 +88,19 @@ describe("HTTP Transport Binding Structured Receiver for CloudEvents v0.2", () =
.data(data) .data(data)
.toString(); .toString();
var headers = { var headers = {
"Content-Type":"application/cloudevents+json" "Content-Type": "application/cloudevents+json"
}; };
// act and assert // act and assert
expect(receiver.parse.bind(receiver, payload, headers)) expect(receiver.parse.bind(receiver, payload, headers))
.to.throw("invalid payload"); .to.throw("invalid payload");
}); });
it("Should accept event that follow the spec 0.2", () => { it("Should accept event that follow the spec 0.2", () => {
// setup // setup
var id = "id-x0dk"; var id = "id-x0dk";
var payload = var payload =
new Cloudevent(Cloudevent.specs["0.2"]) new Cloudevent(Cloudevent.specs["0.2"])
.type(type) .type(type)
.source(source) .source(source)
@ -128,28 +110,28 @@ describe("HTTP Transport Binding Structured Receiver for CloudEvents v0.2", () =
.schemaurl(schemaurl) .schemaurl(schemaurl)
.data(data) .data(data)
.toString(); .toString();
var headers = { var headers = {
"content-type":"application/cloudevents+json" "content-type": "application/cloudevents+json"
}; };
// act // act
var actual = receiver.parse(payload, headers); var actual = receiver.parse(payload, headers);
// assert // assert
expect(actual) expect(actual)
.to.be.an("object"); .to.be.an("object");
expect(actual) expect(actual)
.to.have.property("format"); .to.have.property("format");
expect(actual.getId()) expect(actual.getId())
.to.equals(id); .to.equals(id);
}); });
it("Should accept 'extension1'", () => { it("Should accept 'extension1'", () => {
// setup // setup
var extension1 = "mycuston-ext1" var extension1 = "mycuston-ext1";
var payload = var payload =
new Cloudevent(Cloudevent.specs["0.2"]) new Cloudevent(Cloudevent.specs["0.2"])
.type(type) .type(type)
.source(source) .source(source)
@ -160,17 +142,17 @@ describe("HTTP Transport Binding Structured Receiver for CloudEvents v0.2", () =
.addExtension("extension1", extension1) .addExtension("extension1", extension1)
.toString(); .toString();
var headers = { var headers = {
"content-type":"application/cloudevents+json" "content-type": "application/cloudevents+json"
}; };
// act // act
var actual = receiver.parse(payload, headers); var actual = receiver.parse(payload, headers);
var actualExtensions = actual.getExtensions(); var actualExtensions = actual.getExtensions();
// assert // assert
expect(actualExtensions["extension1"]) expect(actualExtensions.extension1)
.to.equal(extension1); .to.equal(extension1);
});
}); });
}); });
});

View File

@ -1,138 +1,114 @@
var expect = require("chai").expect; var expect = require("chai").expect;
var v03 = require("../../../v03/index.js"); var v03 = require("../../../v03/index.js");
var Cloudevent = require("../../../index.js"); var Cloudevent = require("../../../index.js");
var Spec = require("../../../lib/specs/spec_0_3.js");
var HTTPStructuredReceiver = var HTTPStructuredReceiver =
require("../../../lib/bindings/http/receiver_structured_0_3.js"); require("../../../lib/bindings/http/receiver_structured_0_3.js");
var receiver = new HTTPStructuredReceiver(); var receiver = new HTTPStructuredReceiver();
const type = "com.github.pull.create"; const type = "com.github.pull.create";
const source = "urn:event:from:myapi/resourse/123"; const source = "urn:event:from:myapi/resourse/123";
const webhook = "https://cloudevents.io/webhook"; const now = new Date();
const contentEncoding = "base64"; const schemaurl = "http://cloudevents.io/schema.json";
const contentType = "application/cloudevents+json; charset=utf-8";
const now = new Date();
const schemaurl = "http://cloudevents.io/schema.json";
const ceContentType = "application/json"; const ceContentType = "application/json";
const data = { const data = {
foo: "bar" foo: "bar"
}; };
const dataBase64 = "Y2xvdWRldmVudHMK";
const ext1Name = "extension1"; const ext1Name = "extension1";
const ext1Value = "foobar"; const ext1Value = "foobar";
const ext2Name = "extension2"; const ext2Name = "extension2";
const ext2Value = "acme"; const ext2Value = "acme";
var cloudevent = v03.event() describe("HTTP Transport Binding Structured Receiver for CloudEvents v0.3",
.type(type) () => {
.source(source) describe("Check", () => {
.contenttype(ceContentType) it("Throw error when payload arg is null or undefined", () => {
.time(now)
.schemaurl(schemaurl)
.data(data)
.addExtension(ext1Name, ext1Value)
.addExtension(ext2Name, ext2Value);
const cebase64 = v03.event()
.type(type)
.source(source)
.dataContentType(ceContentType)
.dataContentEncoding(contentEncoding)
.time(now)
.schemaurl(schemaurl)
.data(dataBase64)
.addExtension(ext1Name, ext1Value)
.addExtension(ext2Name, ext2Value);
describe("HTTP Transport Binding Structured Receiver for CloudEvents v0.3", () => {
describe("Check", () => {
it("Throw error when payload arg is null or undefined", () => {
// setup // setup
var payload = null; var payload = null;
var attributes = {}; var attributes = {};
// act and assert // act and assert
expect(receiver.check.bind(receiver, payload, attributes)) expect(receiver.check.bind(receiver, payload, attributes))
.to.throw("payload is null or undefined"); .to.throw("payload is null or undefined");
});
it("Throw error when attributes arg is null or undefined", () => {
// setup
var payload = {};
var attributes = null;
// act and assert
expect(receiver.check.bind(receiver, payload, attributes))
.to.throw("attributes is null or undefined");
});
it("Throw error when payload is not an object or string", () => {
// setup
var payload = 1.0;
var attributes = {};
// act and assert
expect(receiver.check.bind(receiver, payload, attributes))
.to.throw("payload must be an object or string");
});
it("Throw error when the content-type is invalid", () => {
// setup
var payload = {};
var attributes = {
"Content-Type": "text/html"
};
// act and assert
expect(receiver.check.bind(receiver, payload, attributes))
.to.throw("invalid content type");
});
it("Throw error data content encoding is base64, but 'data' is not",
() => {
// setup
const payload = v03.event()
.type(type)
.source(source)
.dataContentType("text/plain")
.dataContentEncoding("base64")
.time(now)
.schemaurl(schemaurl)
.data("No base 64 value")
.addExtension(ext1Name, ext1Value)
.addExtension(ext2Name, ext2Value)
.toString();
const attributes = {
"Content-Type": "application/cloudevents+json"
};
// act and assert
expect(receiver.parse.bind(receiver, payload, attributes))
.to.throw("invalid payload");
});
it("No error when all required stuff are in place", () => {
// setup
var payload = {};
var attributes = {
"Content-Type": "application/cloudevents+json"
};
// act and assert
expect(receiver.check.bind(receiver, payload, attributes))
.to.not.throw();
});
}); });
it("Throw error when attributes arg is null or undefined", () => { describe("Parse", () => {
it("Throw error when the event does not follow the spec", () => {
// setup // setup
var payload = {}; var payload =
var attributes = null;
// act and assert
expect(receiver.check.bind(receiver, payload, attributes))
.to.throw("attributes is null or undefined");
});
it("Throw error when payload is not an object or string", () => {
// setup
var payload = 1.0;
var attributes = {};
// act and assert
expect(receiver.check.bind(receiver, payload, attributes))
.to.throw("payload must be an object or string");
});
it("Throw error when the content-type is invalid", () => {
// setup
var payload = {};
var attributes = {
"Content-Type" : "text/html"
};
// act and assert
expect(receiver.check.bind(receiver, payload, attributes))
.to.throw("invalid content type");
});
it("Throw error data content encoding is base64, but 'data' is not", () => {
// setup
let payload = v03.event()
.type(type)
.source(source)
.dataContentType("text/plain")
.dataContentEncoding("base64")
.time(now)
.schemaurl(schemaurl)
.data("No base 64 value")
.addExtension(ext1Name, ext1Value)
.addExtension(ext2Name, ext2Value)
.toString();
let attributes = {
"Content-Type" : "application/cloudevents+json"
};
// act and assert
expect(receiver.parse.bind(receiver, payload, attributes))
.to.throw("invalid payload");
});
it("No error when all required stuff are in place", () => {
// setup
var payload = {};
var attributes = {
"Content-Type" : "application/cloudevents+json"
};
// act and assert
expect(receiver.check.bind(receiver, payload, attributes))
.to.not.throw();
});
});
describe("Parse", () => {
it("Throw error when the event does not follow the spec", () => {
// setup
var payload =
new Cloudevent() new Cloudevent()
.type(type) .type(type)
.source(source) .source(source)
@ -142,19 +118,19 @@ describe("HTTP Transport Binding Structured Receiver for CloudEvents v0.3", () =
.data(data) .data(data)
.toString(); .toString();
var headers = { var headers = {
"Content-Type":"application/cloudevents+json" "Content-Type": "application/cloudevents+json"
}; };
// act and assert // act and assert
expect(receiver.parse.bind(receiver, payload, headers)) expect(receiver.parse.bind(receiver, payload, headers))
.to.throw("invalid payload"); .to.throw("invalid payload");
}); });
it("Should accept event that follows the spec", () => { it("Should accept event that follows the spec", () => {
// setup // setup
var id = "id-x0dk"; var id = "id-x0dk";
var payload = v03.event() var payload = v03.event()
.type(type) .type(type)
.source(source) .source(source)
.id(id) .id(id)
@ -163,28 +139,28 @@ describe("HTTP Transport Binding Structured Receiver for CloudEvents v0.3", () =
.schemaurl(schemaurl) .schemaurl(schemaurl)
.data(data) .data(data)
.toString(); .toString();
var headers = { var headers = {
"content-type":"application/cloudevents+json" "content-type": "application/cloudevents+json"
}; };
// act // act
var actual = receiver.parse(payload, headers); var actual = receiver.parse(payload, headers);
// assert // assert
expect(actual) expect(actual)
.to.be.an("object"); .to.be.an("object");
expect(actual) expect(actual)
.to.have.property("format"); .to.have.property("format");
expect(actual.getId()) expect(actual.getId())
.to.equals(id); .to.equals(id);
}); });
it("Should accept 'extension1'", () => { it("Should accept 'extension1'", () => {
// setup // setup
var extension1 = "mycuston-ext1" var extension1 = "mycuston-ext1";
var payload = v03.event() var payload = v03.event()
.type(type) .type(type)
.source(source) .source(source)
.contenttype(ceContentType) .contenttype(ceContentType)
@ -194,22 +170,22 @@ describe("HTTP Transport Binding Structured Receiver for CloudEvents v0.3", () =
.addExtension("extension1", extension1) .addExtension("extension1", extension1)
.toString(); .toString();
var headers = { var headers = {
"content-type":"application/cloudevents+json" "content-type": "application/cloudevents+json"
}; };
// act // act
var actual = receiver.parse(payload, headers); var actual = receiver.parse(payload, headers);
var actualExtensions = actual.getExtensions(); var actualExtensions = actual.getExtensions();
// assert // assert
expect(actualExtensions["extension1"]) expect(actualExtensions.extension1)
.to.equal(extension1); .to.equal(extension1);
}); });
it("Should parse 'data' stringfied json to json object", () => { it("Should parse 'data' stringfied json to json object", () => {
// setup // setup
var payload = v03.event() var payload = v03.event()
.type(type) .type(type)
.source(source) .source(source)
.contenttype(ceContentType) .contenttype(ceContentType)
@ -218,15 +194,15 @@ describe("HTTP Transport Binding Structured Receiver for CloudEvents v0.3", () =
.data(JSON.stringify(data)) .data(JSON.stringify(data))
.toString(); .toString();
var headers = { var headers = {
"content-type":"application/cloudevents+json" "content-type": "application/cloudevents+json"
}; };
// act // act
var actual = receiver.parse(payload, headers); var actual = receiver.parse(payload, headers);
// assert // assert
expect(actual.getData()).to.deep.equal(data); expect(actual.getData()).to.deep.equal(data);
});
}); });
}); });
});

View File

@ -1,22 +1,18 @@
var expect = require("chai").expect; var expect = require("chai").expect;
var v1 = require("../../../v1/index.js"); var v1 = require("../../../v1/index.js");
var Cloudevent = require("../../../index.js"); var Cloudevent = require("../../../index.js");
var Spec = require("../../../lib/specs/spec_1.js");
const {asBase64} = require("../../../lib/utils/fun.js"); const { asBase64 } = require("../../../lib/utils/fun.js");
var HTTPStructuredReceiver = var HTTPStructuredReceiver =
require("../../../lib/bindings/http/receiver_structured_1.js"); require("../../../lib/bindings/http/receiver_structured_1.js");
var receiver = new HTTPStructuredReceiver(); var receiver = new HTTPStructuredReceiver();
const type = "com.github.pull.create"; const type = "com.github.pull.create";
const source = "urn:event:from:myapi/resourse/123"; const source = "urn:event:from:myapi/resourse/123";
const webhook = "https://cloudevents.io/webhook"; const now = new Date();
const contentEncoding = "base64"; const dataschema = "http://cloudevents.io/schema.json";
const contentType = "application/cloudevents+json; charset=utf-8";
const now = new Date();
const dataschema = "http://cloudevents.io/schema.json";
const ceContentType = "application/json"; const ceContentType = "application/json";
@ -24,72 +20,68 @@ const data = {
foo: "bar" foo: "bar"
}; };
const ext1Name = "extension1"; describe("HTTP Transport Binding Structured Receiver for CloudEvents v1.0",
const ext1Value = "foobar"; () => {
const ext2Name = "extension2"; describe("Check", () => {
const ext2Value = "acme"; it("Throw error when payload arg is null or undefined", () => {
describe("HTTP Transport Binding Structured Receiver for CloudEvents v1.0", () => {
describe("Check", () => {
it("Throw error when payload arg is null or undefined", () => {
// setup // setup
var payload = null; var payload = null;
var attributes = {}; var attributes = {};
// act and assert // act and assert
expect(receiver.check.bind(receiver, payload, attributes)) expect(receiver.check.bind(receiver, payload, attributes))
.to.throw("payload is null or undefined"); .to.throw("payload is null or undefined");
});
it("Throw error when attributes arg is null or undefined", () => {
// setup
var payload = {};
var attributes = null;
// act and assert
expect(receiver.check.bind(receiver, payload, attributes))
.to.throw("attributes is null or undefined");
});
it("Throw error when payload is not an object or string", () => {
// setup
var payload = 1.0;
var attributes = {};
// act and assert
expect(receiver.check.bind(receiver, payload, attributes))
.to.throw("payload must be an object or string");
});
it("Throw error when the content-type is invalid", () => {
// setup
var payload = {};
var attributes = {
"Content-Type": "text/html"
};
// act and assert
expect(receiver.check.bind(receiver, payload, attributes))
.to.throw("invalid content type");
});
it("No error when all required stuff are in place", () => {
// setup
var payload = {};
var attributes = {
"Content-Type": "application/cloudevents+json"
};
// act and assert
expect(receiver.check.bind(receiver, payload, attributes))
.to.not.throw();
});
}); });
it("Throw error when attributes arg is null or undefined", () => { describe("Parse", () => {
it("Throw error when the event does not follow the spec", () => {
// setup // setup
var payload = {}; var payload =
var attributes = null;
// act and assert
expect(receiver.check.bind(receiver, payload, attributes))
.to.throw("attributes is null or undefined");
});
it("Throw error when payload is not an object or string", () => {
// setup
var payload = 1.0;
var attributes = {};
// act and assert
expect(receiver.check.bind(receiver, payload, attributes))
.to.throw("payload must be an object or string");
});
it("Throw error when the content-type is invalid", () => {
// setup
var payload = {};
var attributes = {
"Content-Type" : "text/html"
};
// act and assert
expect(receiver.check.bind(receiver, payload, attributes))
.to.throw("invalid content type");
});
it("No error when all required stuff are in place", () => {
// setup
var payload = {};
var attributes = {
"Content-Type" : "application/cloudevents+json"
};
// act and assert
expect(receiver.check.bind(receiver, payload, attributes))
.to.not.throw();
});
});
describe("Parse", () => {
it("Throw error when the event does not follow the spec", () => {
// setup
var payload =
new Cloudevent() new Cloudevent()
.type(type) .type(type)
.source(source) .source(source)
@ -97,19 +89,19 @@ describe("HTTP Transport Binding Structured Receiver for CloudEvents v1.0", () =
.data(data) .data(data)
.toString(); .toString();
var headers = { var headers = {
"Content-Type":"application/cloudevents+json" "Content-Type": "application/cloudevents+json"
}; };
// act and assert // act and assert
expect(receiver.parse.bind(receiver, payload, headers)) expect(receiver.parse.bind(receiver, payload, headers))
.to.throw("invalid payload"); .to.throw("invalid payload");
}); });
it("Should accept event that follows the spec", () => { it("Should accept event that follows the spec", () => {
// setup // setup
var id = "id-x0dk"; var id = "id-x0dk";
var payload = v1.event() var payload = v1.event()
.type(type) .type(type)
.source(source) .source(source)
.id(id) .id(id)
@ -118,28 +110,28 @@ describe("HTTP Transport Binding Structured Receiver for CloudEvents v1.0", () =
.dataschema(dataschema) .dataschema(dataschema)
.data(data) .data(data)
.toString(); .toString();
var headers = { var headers = {
"content-type":"application/cloudevents+json" "content-type": "application/cloudevents+json"
}; };
// act // act
var actual = receiver.parse(payload, headers); var actual = receiver.parse(payload, headers);
// assert // assert
expect(actual) expect(actual)
.to.be.an("object"); .to.be.an("object");
expect(actual) expect(actual)
.to.have.property("format"); .to.have.property("format");
expect(actual.getId()) expect(actual.getId())
.to.equals(id); .to.equals(id);
}); });
it("Should accept 'extension1'", () => { it("Should accept 'extension1'", () => {
// setup // setup
var extension1 = "mycuston-ext1" var extension1 = "mycuston-ext1";
var payload = v1.event() var payload = v1.event()
.type(type) .type(type)
.source(source) .source(source)
.dataContentType(ceContentType) .dataContentType(ceContentType)
@ -149,22 +141,22 @@ describe("HTTP Transport Binding Structured Receiver for CloudEvents v1.0", () =
.addExtension("extension1", extension1) .addExtension("extension1", extension1)
.toString(); .toString();
var headers = { var headers = {
"content-type":"application/cloudevents+json" "content-type": "application/cloudevents+json"
}; };
// act // act
var actual = receiver.parse(payload, headers); var actual = receiver.parse(payload, headers);
var actualExtensions = actual.getExtensions(); var actualExtensions = actual.getExtensions();
// assert // assert
expect(actualExtensions["extension1"]) expect(actualExtensions.extension1)
.to.equal(extension1); .to.equal(extension1);
}); });
it("Should parse 'data' stringfied json to json object", () => { it("Should parse 'data' stringfied json to json object", () => {
// setup // setup
var payload = v1.event() var payload = v1.event()
.type(type) .type(type)
.source(source) .source(source)
.dataContentType(ceContentType) .dataContentType(ceContentType)
@ -173,37 +165,38 @@ describe("HTTP Transport Binding Structured Receiver for CloudEvents v1.0", () =
.data(JSON.stringify(data)) .data(JSON.stringify(data))
.toString(); .toString();
var headers = { var headers = {
"content-type":"application/cloudevents+json" "content-type": "application/cloudevents+json"
}; };
// act // act
var actual = receiver.parse(payload, headers); var actual = receiver.parse(payload, headers);
// assert // assert
expect(actual.getData()).to.deep.equal(data); expect(actual.getData()).to.deep.equal(data);
}); });
it("Should maps 'data_base64' to 'data' attribute", () => { it("Should maps 'data_base64' to 'data' attribute", () => {
// setup // setup
let bindata = Uint32Array.from(JSON.stringify(data), (c) => c.codePointAt(0)); const bindata = Uint32Array
let expected = asBase64(bindata); .from(JSON.stringify(data), (c) => c.codePointAt(0));
let payload = v1.event() const expected = asBase64(bindata);
.type(type) const payload = v1.event()
.source(source) .type(type)
.dataContentType(ceContentType) .source(source)
.data(bindata) .dataContentType(ceContentType)
.format(); .data(bindata)
.format();
var headers = { var headers = {
"content-type":"application/cloudevents+json" "content-type": "application/cloudevents+json"
}; };
// act // act
var actual = receiver.parse(JSON.stringify(payload), headers); var actual = receiver.parse(JSON.stringify(payload), headers);
// assert // assert
expect(actual.getData()).to.equal(expected); expect(actual.getData()).to.equal(expected);
});
}); });
}); });
});

View File

@ -1,13 +1,11 @@
var expect = require("chai").expect; var expect = require("chai").expect;
var Unmarshaller = require("../../../http/unmarshaller/v02.js"); var Unmarshaller = require("../../../http/unmarshaller/v02.js");
var Cloudevent = require("../../../index.js"); var Cloudevent = require("../../../index.js");
const type = "com.github.pull.create"; const type = "com.github.pull.create";
const source = "urn:event:from:myapi/resourse/123"; const source = "urn:event:from:myapi/resourse/123";
const webhook = "https://cloudevents.io/webhook"; const now = new Date();
const contentType = "application/cloudevents+json; charset=utf-8"; const schemaurl = "http://cloudevents.io/schema.json";
const now = new Date();
const schemaurl = "http://cloudevents.io/schema.json";
const ceContentType = "application/json"; const ceContentType = "application/json";
@ -16,7 +14,6 @@ const data = {
}; };
describe("HTTP Transport Binding Unmarshaller for CloudEvents v0.2", () => { describe("HTTP Transport Binding Unmarshaller for CloudEvents v0.2", () => {
it("Throw error when payload is null", () => { it("Throw error when payload is null", () => {
// setup // setup
var payload = null; var payload = null;
@ -24,8 +21,8 @@ describe("HTTP Transport Binding Unmarshaller for CloudEvents v0.2", () => {
// act and assert // act and assert
return un.unmarshall(payload) return un.unmarshall(payload)
.then(actual => {throw {message: "failed"}}) .then(() => { throw new Error("failed"); })
.catch(err => .catch((err) =>
expect(err.message).to.equal("payload is null or undefined")); expect(err.message).to.equal("payload is null or undefined"));
}); });
@ -37,8 +34,8 @@ describe("HTTP Transport Binding Unmarshaller for CloudEvents v0.2", () => {
// act and assert // act and assert
return un.unmarshall(payload, headers) return un.unmarshall(payload, headers)
.then(actual => {throw {message: "failed"}}) .then(() => { throw new Error("failed"); })
.catch(err => .catch((err) =>
expect(err.message).to.equal("headers is null or undefined")); expect(err.message).to.equal("headers is null or undefined"));
}); });
@ -50,8 +47,8 @@ describe("HTTP Transport Binding Unmarshaller for CloudEvents v0.2", () => {
// act and assert // act and assert
un.unmarshall(payload, headers) un.unmarshall(payload, headers)
.then(actual => {throw {message: "failed"}}) .then(() => { throw new Error("failed"); })
.catch(err => .catch((err) =>
expect(err.message).to.equal("content-type header not found")); expect(err.message).to.equal("content-type header not found"));
}); });
@ -59,14 +56,14 @@ describe("HTTP Transport Binding Unmarshaller for CloudEvents v0.2", () => {
// setup // setup
var payload = {}; var payload = {};
var headers = { var headers = {
"content-type":"text/xml" "content-type": "text/xml"
}; };
var un = new Unmarshaller(); var un = new Unmarshaller();
// act and assert // act and assert
un.unmarshall(payload, headers) un.unmarshall(payload, headers)
.then(actual => {throw {message: "failed"}}) .then(() => { throw new Error("failed"); })
.catch(err => .catch((err) =>
expect(err.message).to.equal("content type not allowed")); expect(err.message).to.equal("content type not allowed"));
}); });
@ -75,14 +72,14 @@ describe("HTTP Transport Binding Unmarshaller for CloudEvents v0.2", () => {
// setup // setup
var payload = {}; var payload = {};
var headers = { var headers = {
"content-type":"application/cloudevents+zip" "content-type": "application/cloudevents+zip"
}; };
var un = new Unmarshaller(); var un = new Unmarshaller();
// act and assert // act and assert
un.unmarshall(payload, headers) un.unmarshall(payload, headers)
.then(actual => {throw {message: "failed"}}) .then(() => { throw new Error("failed"); })
.catch(err => .catch((err) =>
expect(err.message).to.equal("structured+type not allowed")); expect(err.message).to.equal("structured+type not allowed"));
}); });
@ -99,15 +96,15 @@ describe("HTTP Transport Binding Unmarshaller for CloudEvents v0.2", () => {
.toString(); .toString();
var headers = { var headers = {
"content-type":"application/cloudevents+json" "content-type": "application/cloudevents+json"
}; };
var un = new Unmarshaller(); var un = new Unmarshaller();
// act and assert // act and assert
un.unmarshall(payload, headers) un.unmarshall(payload, headers)
.then(actual => {throw {message: "failed"}}) .then(() => { throw new Error("failed"); })
.catch(err => .catch((err) =>
expect(err.message).to.equal("invalid payload")); expect(err.message).to.equal("invalid payload"));
}); });
@ -124,16 +121,15 @@ describe("HTTP Transport Binding Unmarshaller for CloudEvents v0.2", () => {
.toString(); .toString();
var headers = { var headers = {
"content-type":"application/cloudevents+json" "content-type": "application/cloudevents+json"
}; };
var un = new Unmarshaller(); var un = new Unmarshaller();
// act and assert // act and assert
un.unmarshall(payload, headers) un.unmarshall(payload, headers)
.then(actual => .then((actual) =>
expect(actual).to.be.an("object")); expect(actual).to.be.an("object"));
}); });
}); });
@ -141,73 +137,71 @@ describe("HTTP Transport Binding Unmarshaller for CloudEvents v0.2", () => {
it("Throw error when has not allowed mime", () => { it("Throw error when has not allowed mime", () => {
// setup // setup
var payload = { var payload = {
"data" : "dataString" data: "dataString"
}; };
var attributes = { var attributes = {
"ce-type" : "type", "ce-type": "type",
"ce-specversion" : "0.2", "ce-specversion": "0.2",
"ce-source" : "source", "ce-source": "source",
"ce-id" : "id", "ce-id": "id",
"ce-time" : "2019-06-16T11:42:00Z", "ce-time": "2019-06-16T11:42:00Z",
"ce-schemaurl" : "http://schema.registry/v1", "ce-schemaurl": "http://schema.registry/v1",
"Content-Type" : "text/html" "Content-Type": "text/html"
}; };
var un = new Unmarshaller(); var un = new Unmarshaller();
// act and assert // act and assert
un.unmarshall(payload, attributes) un.unmarshall(payload, attributes)
.then(actual => {throw {message: "failed"}}) .then(() => { throw new Error("failed"); })
.catch(err => .catch((err) =>
expect(err.message).to.equal("content type not allowed")); expect(err.message).to.equal("content type not allowed"));
}); });
it("Throw error when the event does not follow the spec 0.2", () => { it("Throw error when the event does not follow the spec 0.2", () => {
// setup // setup
var payload = { var payload = {
"data" : "dataString" data: "dataString"
}; };
var attributes = { var attributes = {
"ce-type" : "type", "ce-type": "type",
"CE-CloudEventsVersion" : "0.1", "CE-CloudEventsVersion": "0.1",
"ce-source" : "source", "ce-source": "source",
"ce-id" : "id", "ce-id": "id",
"ce-time" : "2019-06-16T11:42:00Z", "ce-time": "2019-06-16T11:42:00Z",
"ce-schemaurl" : "http://schema.registry/v1", "ce-schemaurl": "http://schema.registry/v1",
"Content-Type" : "application/json" "Content-Type": "application/json"
}; };
var un = new Unmarshaller(); var un = new Unmarshaller();
// act and assert // act and assert
un.unmarshall(payload, attributes) un.unmarshall(payload, attributes)
.then(actual => {throw {message: "failed"}}) .then(() => { throw new Error("failed"); })
.catch(err => .catch((err) =>
expect(err.message).to.not.empty); expect(err.message).to.not.empty);
}); });
it("No error when all attributes are in place", () => { it("No error when all attributes are in place", () => {
// setup // setup
var payload = { var payload = {
"data" : "dataString" data: "dataString"
}; };
var attributes = { var attributes = {
"ce-type" : "type", "ce-type": "type",
"ce-specversion" : "0.2", "ce-specversion": "0.2",
"ce-source" : "source", "ce-source": "source",
"ce-id" : "id", "ce-id": "id",
"ce-time" : "2019-06-16T11:42:00Z", "ce-time": "2019-06-16T11:42:00Z",
"ce-schemaurl" : "http://schema.registry/v1", "ce-schemaurl": "http://schema.registry/v1",
"Content-Type" : "application/json" "Content-Type": "application/json"
}; };
var un = new Unmarshaller(); var un = new Unmarshaller();
// act and assert // act and assert
un.unmarshall(payload, attributes) un.unmarshall(payload, attributes)
.then(actual => expect(actual).to.be.an("object")); .then((actual) => expect(actual).to.be.an("object"));
}); });
}); });
}); });

View File

@ -1,15 +1,13 @@
var expect = require("chai").expect; var expect = require("chai").expect;
var Unmarshaller = require("../../../lib/bindings/http/unmarshaller_0_3.js"); var Unmarshaller = require("../../../lib/bindings/http/unmarshaller_0_3.js");
var Cloudevent = require("../../../index.js"); var Cloudevent = require("../../../index.js");
var v03 = require("../../../v03/index.js"); var v03 = require("../../../v03/index.js");
const type = "com.github.pull.create"; const type = "com.github.pull.create";
const source = "urn:event:from:myapi/resourse/123"; const source = "urn:event:from:myapi/resourse/123";
const webhook = "https://cloudevents.io/webhook"; const now = new Date();
const contentType = "application/cloudevents+json; charset=utf-8"; const schemaurl = "http://cloudevents.io/schema.json";
const now = new Date(); const subject = "subject.ext";
const schemaurl = "http://cloudevents.io/schema.json";
const subject = "subject.ext";
const ceContentType = "application/json"; const ceContentType = "application/json";
const data = { const data = {
@ -17,7 +15,6 @@ const data = {
}; };
describe("HTTP Transport Binding Unmarshaller for CloudEvents v0.3", () => { describe("HTTP Transport Binding Unmarshaller for CloudEvents v0.3", () => {
it("Throw error when payload is null", () => { it("Throw error when payload is null", () => {
// setup // setup
var payload = null; var payload = null;
@ -25,8 +22,8 @@ describe("HTTP Transport Binding Unmarshaller for CloudEvents v0.3", () => {
// act and assert // act and assert
return un.unmarshall(payload) return un.unmarshall(payload)
.then(actual => {throw {message: "failed"}}) .then(() => { throw new Error("failed"); })
.catch(err => .catch((err) =>
expect(err.message).to.equal("payload is null or undefined")); expect(err.message).to.equal("payload is null or undefined"));
}); });
@ -38,8 +35,8 @@ describe("HTTP Transport Binding Unmarshaller for CloudEvents v0.3", () => {
// act and assert // act and assert
return un.unmarshall(payload, headers) return un.unmarshall(payload, headers)
.then(actual => {throw {message: "failed"}}) .then(() => { throw new Error("failed"); })
.catch(err => .catch((err) =>
expect(err.message).to.equal("headers is null or undefined")); expect(err.message).to.equal("headers is null or undefined"));
}); });
@ -51,8 +48,8 @@ describe("HTTP Transport Binding Unmarshaller for CloudEvents v0.3", () => {
// act and assert // act and assert
un.unmarshall(payload, headers) un.unmarshall(payload, headers)
.then(actual => {throw {message: "failed"}}) .then(() => { throw new Error("failed"); })
.catch(err => .catch((err) =>
expect(err.message).to.equal("content-type header not found")); expect(err.message).to.equal("content-type header not found"));
}); });
@ -60,14 +57,14 @@ describe("HTTP Transport Binding Unmarshaller for CloudEvents v0.3", () => {
// setup // setup
var payload = {}; var payload = {};
var headers = { var headers = {
"content-type":"text/xml" "content-type": "text/xml"
}; };
var un = new Unmarshaller(); var un = new Unmarshaller();
// act and assert // act and assert
un.unmarshall(payload, headers) un.unmarshall(payload, headers)
.then(actual => {throw {message: "failed"}}) .then(() => { throw new Error("failed"); })
.catch(err => .catch((err) =>
expect(err.message).to.equal("content type not allowed")); expect(err.message).to.equal("content type not allowed"));
}); });
@ -76,14 +73,14 @@ describe("HTTP Transport Binding Unmarshaller for CloudEvents v0.3", () => {
// setup // setup
var payload = {}; var payload = {};
var headers = { var headers = {
"content-type":"application/cloudevents+zip" "content-type": "application/cloudevents+zip"
}; };
var un = new Unmarshaller(); var un = new Unmarshaller();
// act and assert // act and assert
un.unmarshall(payload, headers) un.unmarshall(payload, headers)
.then(actual => {throw {message: "failed"}}) .then(() => { throw new Error("failed"); })
.catch(err => .catch((err) =>
expect(err.message).to.equal("structured+type not allowed")); expect(err.message).to.equal("structured+type not allowed"));
}); });
@ -100,15 +97,15 @@ describe("HTTP Transport Binding Unmarshaller for CloudEvents v0.3", () => {
.toString(); .toString();
var headers = { var headers = {
"content-type":"application/cloudevents+json" "content-type": "application/cloudevents+json"
}; };
var un = new Unmarshaller(); var un = new Unmarshaller();
// act and assert // act and assert
un.unmarshall(payload, headers) un.unmarshall(payload, headers)
.then(actual => {throw {message: "failed"}}) .then(() => { throw new Error("failed"); })
.catch(err => .catch((err) =>
expect(err.message).to.equal("invalid payload")); expect(err.message).to.equal("invalid payload"));
}); });
@ -126,20 +123,19 @@ describe("HTTP Transport Binding Unmarshaller for CloudEvents v0.3", () => {
.toString(); .toString();
var headers = { var headers = {
"content-type":"application/cloudevents+json" "content-type": "application/cloudevents+json"
}; };
var un = new Unmarshaller(); var un = new Unmarshaller();
// act and assert // act and assert
return un.unmarshall(payload, headers) return un.unmarshall(payload, headers)
.then(actual => .then((actual) =>
expect(actual).to.be.an("object")) expect(actual).to.be.an("object"))
.catch((err) => { .catch((err) => {
console.log(err); console.error(err);
throw err; throw err;
}); });
}); });
it("Should parse 'data' stringfied json to json object", () => { it("Should parse 'data' stringfied json to json object", () => {
@ -156,21 +152,20 @@ describe("HTTP Transport Binding Unmarshaller for CloudEvents v0.3", () => {
.toString(); .toString();
var headers = { var headers = {
"content-type":"application/cloudevents+json" "content-type": "application/cloudevents+json"
}; };
var un = new Unmarshaller(); var un = new Unmarshaller();
// act and assert // act and assert
return un.unmarshall(payload, headers) return un.unmarshall(payload, headers)
.then(actual => { .then((actual) => {
expect(actual.getData()).to.deep.equal(data) expect(actual.getData()).to.deep.equal(data);
}) })
.catch((err) => { .catch((err) => {
console.log(err); console.error(err);
throw err; throw err;
}); });
}); });
}); });
@ -178,72 +173,71 @@ describe("HTTP Transport Binding Unmarshaller for CloudEvents v0.3", () => {
it("Throw error when has not allowed mime", () => { it("Throw error when has not allowed mime", () => {
// setup // setup
var payload = { var payload = {
"data" : "dataString" data: "dataString"
}; };
var attributes = { var attributes = {
"ce-type" : "type", "ce-type": "type",
"ce-specversion" : "0.3", "ce-specversion": "0.3",
"ce-source" : "source", "ce-source": "source",
"ce-id" : "id", "ce-id": "id",
"ce-time" : "2019-06-16T11:42:00Z", "ce-time": "2019-06-16T11:42:00Z",
"ce-schemaurl" : "http://schema.registry/v1", "ce-schemaurl": "http://schema.registry/v1",
"Content-Type" : "text/html" "Content-Type": "text/html"
}; };
var un = new Unmarshaller(); var un = new Unmarshaller();
// act and assert // act and assert
un.unmarshall(payload, attributes) un.unmarshall(payload, attributes)
.then(actual => {throw {message: "failed"}}) .then(() => { throw new Error("failed"); })
.catch(err => .catch((err) =>
expect(err.message).to.equal("content type not allowed")); expect(err.message).to.equal("content type not allowed"));
}); });
it("Throw error when the event does not follow the spec 0.3", () => { it("Throw error when the event does not follow the spec 0.3", () => {
// setup // setup
var payload = { var payload = {
"data" : "dataString" data: "dataString"
}; };
var attributes = { var attributes = {
"ce-type" : "type", "ce-type": "type",
"CE-CloudEventsVersion" : "0.1", "CE-CloudEventsVersion": "0.1",
"ce-source" : "source", "ce-source": "source",
"ce-id" : "id", "ce-id": "id",
"ce-time" : "2019-06-16T11:42:00Z", "ce-time": "2019-06-16T11:42:00Z",
"ce-schemaurl" : "http://schema.registry/v1", "ce-schemaurl": "http://schema.registry/v1",
"Content-Type" : "application/json" "Content-Type": "application/json"
}; };
var un = new Unmarshaller(); var un = new Unmarshaller();
// act and assert // act and assert
un.unmarshall(payload, attributes) un.unmarshall(payload, attributes)
.then(actual => {throw {message: "failed"}}) .then(() => { throw new Error("failed"); })
.catch(err => .catch((err) =>
expect(err.message).to.not.empty); expect(err.message).to.not.empty);
}); });
it("No error when all attributes are in place", () => { it("No error when all attributes are in place", () => {
// setup // setup
var payload = { var payload = {
"data" : "dataString" data: "dataString"
}; };
var attributes = { var attributes = {
"ce-type" : "type", "ce-type": "type",
"ce-specversion" : "0.3", "ce-specversion": "0.3",
"ce-source" : "source", "ce-source": "source",
"ce-id" : "id", "ce-id": "id",
"ce-time" : "2019-06-16T11:42:00Z", "ce-time": "2019-06-16T11:42:00Z",
"ce-schemaurl" : "http://schema.registry/v1", "ce-schemaurl": "http://schema.registry/v1",
"Content-Type" : "application/json" "Content-Type": "application/json"
}; };
var un = new Unmarshaller(); var un = new Unmarshaller();
// act and assert // act and assert
un.unmarshall(payload, attributes) un.unmarshall(payload, attributes)
.then(actual => expect(actual).to.be.an("object")); .then((actual) => expect(actual).to.be.an("object"));
}); });
it("Throw error when 'ce-datacontentencoding' is not allowed", () => { it("Throw error when 'ce-datacontentencoding' is not allowed", () => {
@ -251,22 +245,22 @@ describe("HTTP Transport Binding Unmarshaller for CloudEvents v0.3", () => {
var payload = "eyJtdWNoIjoid293In0="; var payload = "eyJtdWNoIjoid293In0=";
var attributes = { var attributes = {
"ce-type" : "type", "ce-type": "type",
"ce-specversion" : "0.3", "ce-specversion": "0.3",
"ce-source" : "source", "ce-source": "source",
"ce-id" : "id", "ce-id": "id",
"ce-time" : "2019-06-16T11:42:00Z", "ce-time": "2019-06-16T11:42:00Z",
"ce-schemaurl" : "http://schema.registry/v1", "ce-schemaurl": "http://schema.registry/v1",
"Content-Type" : "application/json", "Content-Type": "application/json",
"ce-datacontentencoding" : "binary" "ce-datacontentencoding": "binary"
}; };
var un = new Unmarshaller(); var un = new Unmarshaller();
// act and assert // act and assert
return un.unmarshall(payload, attributes) return un.unmarshall(payload, attributes)
.then(actual => {throw {message: "failed"}}) .then(() => { throw new Error("failed"); })
.catch(err => { .catch((err) => {
expect(err.message).to.equal("unsupported datacontentencoding"); expect(err.message).to.equal("unsupported datacontentencoding");
}); });
}); });
@ -274,28 +268,28 @@ describe("HTTP Transport Binding Unmarshaller for CloudEvents v0.3", () => {
it("No error when 'ce-datacontentencoding' is base64", () => { it("No error when 'ce-datacontentencoding' is base64", () => {
// setup // setup
var payload = "eyJtdWNoIjoid293In0="; var payload = "eyJtdWNoIjoid293In0=";
let expected = { const expected = {
much : "wow" much: "wow"
}; };
var attributes = { var attributes = {
"ce-type" : "type", "ce-type": "type",
"ce-specversion" : "0.3", "ce-specversion": "0.3",
"ce-source" : "source", "ce-source": "source",
"ce-id" : "id", "ce-id": "id",
"ce-time" : "2019-06-16T11:42:00Z", "ce-time": "2019-06-16T11:42:00Z",
"ce-schemaurl" : "http://schema.registry/v1", "ce-schemaurl": "http://schema.registry/v1",
"Content-Type" : "application/json", "Content-Type": "application/json",
"ce-datacontentencoding" : "base64" "ce-datacontentencoding": "base64"
}; };
var un = new Unmarshaller(); var un = new Unmarshaller();
// act and assert // act and assert
return un.unmarshall(payload, attributes) return un.unmarshall(payload, attributes)
.then(actual => expect(actual.getData()).to.deep.equal(expected)) .then((actual) => expect(actual.getData()).to.deep.equal(expected))
.catch(err => { .catch((err) => {
console.log(err); console.error(err);
throw err; throw err;
}); });
}); });

View File

@ -1,22 +1,19 @@
var expect = require("chai").expect; var expect = require("chai").expect;
var Cloudevent = require("../index.js"); var Cloudevent = require("../index.js");
const type = "com.github.pull.create01"; const type = "com.github.pull.create01";
const source = "urn:event:from:myapi/resourse/01"; const source = "urn:event:from:myapi/resourse/01";
const time = new Date(); const time = new Date();
const schemaurl = "http://example.com/registry/v01/myschema.json"; const schemaurl = "http://example.com/registry/v01/myschema.json";
const contenttype = "application/json"; const contenttype = "application/json";
const data = {}; const data = {};
const extensions = {};
var cloudevent = new Cloudevent() var cloudevent = new Cloudevent()
.type(type) .type(type)
.source(source); .source(source);
describe("CloudEvents Spec 0.1 - JavaScript SDK", () => { describe("CloudEvents Spec 0.1 - JavaScript SDK", () => {
describe("Object properties", () => { describe("Object properties", () => {
describe("Attribute getters", () => { describe("Attribute getters", () => {
it("returns 'type'", () => { it("returns 'type'", () => {
expect(cloudevent.getType()).to.equal(type); expect(cloudevent.getType()).to.equal(type);
@ -29,7 +26,6 @@ describe("CloudEvents Spec 0.1 - JavaScript SDK", () => {
}); });
describe("JSON Format", () => { describe("JSON Format", () => {
describe("Required context attributes", () => { describe("Required context attributes", () => {
it("requires 'eventType'", () => { it("requires 'eventType'", () => {
expect(cloudevent.format()).to.have.property("eventType"); expect(cloudevent.format()).to.have.property("eventType");
@ -84,7 +80,6 @@ describe("CloudEvents Spec 0.1 - JavaScript SDK", () => {
expect(cloudevent.format().extensions) expect(cloudevent.format().extensions)
.to.have.property("foo"); .to.have.property("foo");
}); });
}); });
describe("The Constraints check", () => { describe("The Constraints check", () => {
@ -102,20 +97,18 @@ describe("CloudEvents Spec 0.1 - JavaScript SDK", () => {
}); });
it("should be prefixed with a reverse-DNS name", () => { it("should be prefixed with a reverse-DNS name", () => {
//TODO how to assert it? // TODO how to assert it?
}); });
}); });
//TODO another attributes . . . // TODO another attributes . . .
describe("'eventTime'", () => { describe("'eventTime'", () => {
it("must adhere to the format specified in RFC 3339", () => { it("must adhere to the format specified in RFC 3339", () => {
cloudevent.time(time); cloudevent.time(time);
expect(cloudevent.format()["eventTime"]).to.equal(time.toISOString()); expect(cloudevent.format().eventTime).to.equal(time.toISOString());
}); });
}); });
}); });
}); });
}); });

View File

@ -1,23 +1,20 @@
var expect = require("chai").expect; var expect = require("chai").expect;
var Cloudevent = require("../index.js"); var Cloudevent = require("../index.js");
const type = "com.github.pull.create"; const type = "com.github.pull.create";
const source = "urn:event:from:myapi/resourse/123"; const source = "urn:event:from:myapi/resourse/123";
const time = new Date(); const time = new Date();
const schemaurl = "http://example.com/registry/myschema.json"; const schemaurl = "http://example.com/registry/myschema.json";
const contenttype = "application/json"; const contenttype = "application/json";
const data = {}; const data = {};
const extensions = {};
var cloudevent = var cloudevent =
new Cloudevent(Cloudevent.specs["0.2"]) new Cloudevent(Cloudevent.specs["0.2"])
.type(type) .type(type)
.source(source); .source(source);
describe("CloudEvents Spec 0.2 - JavaScript SDK", () => { describe("CloudEvents Spec 0.2 - JavaScript SDK", () => {
describe("Object properties", () => { describe("Object properties", () => {
describe("Attribute getters", () => { describe("Attribute getters", () => {
it("returns 'type'", () => { it("returns 'type'", () => {
expect(cloudevent.getType()).to.equal(type); expect(cloudevent.getType()).to.equal(type);
@ -30,7 +27,6 @@ describe("CloudEvents Spec 0.2 - JavaScript SDK", () => {
}); });
describe("JSON Format", () => { describe("JSON Format", () => {
describe("Required context attributes", () => { describe("Required context attributes", () => {
it("requires 'type'", () => { it("requires 'type'", () => {
expect(cloudevent.format()).to.have.property("type"); expect(cloudevent.format()).to.have.property("type");
@ -93,15 +89,14 @@ describe("CloudEvents Spec 0.2 - JavaScript SDK", () => {
it("'extension2' should have value equals to 'value1'", () => { it("'extension2' should have value equals to 'value1'", () => {
cloudevent.addExtension("extension2", "value2"); cloudevent.addExtension("extension2", "value2");
expect(cloudevent.format()["extension2"]).to.equal("value2"); expect(cloudevent.format().extension2).to.equal("value2");
}); });
it("should throw an error when employ reserved name as extension", () => { it("should throw an error when employ reserved name as extension", () => {
var cevt = var cevt =
new Cloudevent(Cloudevent.specs["0.2"]) new Cloudevent(Cloudevent.specs["0.2"])
.type(type) .type(type)
.source(source); .source(source);
expect(cevt.addExtension.bind(cevt, "id")) expect(cevt.addExtension.bind(cevt, "id"))
.to .to
.throw("Reserved attribute name: 'id'"); .throw("Reserved attribute name: 'id'");
@ -123,13 +118,13 @@ describe("CloudEvents Spec 0.2 - JavaScript SDK", () => {
}); });
it("should be prefixed with a reverse-DNS name", () => { it("should be prefixed with a reverse-DNS name", () => {
//TODO how to assert it? // TODO how to assert it?
}); });
}); });
describe("'specversion'", () => { describe("'specversion'", () => {
it("compliant event producers must use a value of '0.2'", () => { it("compliant event producers must use a value of '0.2'", () => {
expect(cloudevent.format()["specversion"]).to.equal("0.2"); expect(cloudevent.format().specversion).to.equal("0.2");
}); });
it("should throw an error when is an empty string", () => { it("should throw an error when is an empty string", () => {
@ -165,10 +160,9 @@ describe("CloudEvents Spec 0.2 - JavaScript SDK", () => {
describe("'time'", () => { describe("'time'", () => {
it("must adhere to the format specified in RFC 3339", () => { it("must adhere to the format specified in RFC 3339", () => {
cloudevent.time(time); cloudevent.time(time);
expect(cloudevent.format()["time"]).to.equal(time.toISOString()); expect(cloudevent.format().time).to.equal(time.toISOString());
}); });
}); });
}); });
}); });
}); });

View File

@ -2,12 +2,10 @@ var expect = require("chai").expect;
var Parser = require("../../../lib/formats/json/parser.js"); var Parser = require("../../../lib/formats/json/parser.js");
var Cloudevent = require("../../../index.js"); var Cloudevent = require("../../../index.js");
const type = "com.github.pull.create"; const type = "com.github.pull.create";
const source = "urn:event:from:myapi/resourse/123"; const source = "urn:event:from:myapi/resourse/123";
const webhook = "https://cloudevents.io/webhook"; const now = new Date();
const contentType = "application/cloudevents+json; charset=utf-8"; const schemaurl = "http://cloudevents.io/schema.json";
const now = new Date();
const schemaurl = "http://cloudevents.io/schema.json";
const ceContentType = "application/json"; const ceContentType = "application/json";
@ -16,7 +14,6 @@ const data = {
}; };
describe("JSON Event Format Parser", () => { describe("JSON Event Format Parser", () => {
it("Throw error when payload is an integer", () => { it("Throw error when payload is an integer", () => {
// setup // setup
var payload = 83; var payload = 83;
@ -24,7 +21,7 @@ describe("JSON Event Format Parser", () => {
// act and assert // act and assert
expect(parser.parse.bind(parser, payload)) expect(parser.parse.bind(parser, payload))
.to.throw("invalid payload type, allowed are: string or object"); .to.throw("invalid payload type, allowed are: string or object");
}); });
it("Throw error when payload is null", () => { it("Throw error when payload is null", () => {
@ -34,7 +31,7 @@ describe("JSON Event Format Parser", () => {
// act and assert // act and assert
expect(parser.parse.bind(parser, payload)) expect(parser.parse.bind(parser, payload))
.to.throw("null or undefined payload"); .to.throw("null or undefined payload");
}); });
it("Throw error when payload is undefined", () => { it("Throw error when payload is undefined", () => {
@ -43,7 +40,7 @@ describe("JSON Event Format Parser", () => {
// act and assert // act and assert
expect(parser.parse.bind(parser)) expect(parser.parse.bind(parser))
.to.throw("null or undefined payload"); .to.throw("null or undefined payload");
}); });
it("Throw error when payload is a float", () => { it("Throw error when payload is a float", () => {
@ -53,7 +50,7 @@ describe("JSON Event Format Parser", () => {
// act and assert // act and assert
expect(parser.parse.bind(parser, payload)) expect(parser.parse.bind(parser, payload))
.to.throw("invalid payload type, allowed are: string or object"); .to.throw("invalid payload type, allowed are: string or object");
}); });
it("Throw error when payload is an invalid JSON", () => { it("Throw error when payload is an invalid JSON", () => {
@ -63,7 +60,7 @@ describe("JSON Event Format Parser", () => {
// act and assert // act and assert
expect(parser.parse.bind(parser, payload)) expect(parser.parse.bind(parser, payload))
.to.throw("Unexpected token g in JSON at position 0"); .to.throw("Unexpected token g in JSON at position 0");
}); });
it("Must accept the CloudEvent spec 0.2 as JSON", () => { it("Must accept the CloudEvent spec 0.2 as JSON", () => {
@ -85,7 +82,7 @@ describe("JSON Event Format Parser", () => {
// assert // assert
expect(actual) expect(actual)
.to.be.an("object"); .to.be.an("object");
}); });
it("Must accept when the payload is a string well formed as JSON", () => { it("Must accept when the payload is a string well formed as JSON", () => {
@ -98,6 +95,6 @@ describe("JSON Event Format Parser", () => {
// assert // assert
expect(actual) expect(actual)
.to.be.an("object"); .to.be.an("object");
}); });
}); });

View File

@ -4,13 +4,13 @@ const fun = require("../lib/utils/fun.js");
describe("Functional approach", () => { describe("Functional approach", () => {
describe("isStringOrThrow", () => { describe("isStringOrThrow", () => {
it("should throw when is not a string", () => { it("should throw when is not a string", () => {
expect(fun.isStringOrThrow.bind(fun, 3.6, {message: "works!"})) expect(fun.isStringOrThrow.bind(fun, 3.6, { message: "works!" }))
.to .to
.throw("works!"); .throw("works!");
}); });
it("should return true when is a string", () => { it("should return true when is a string", () => {
expect(fun.isStringOrThrow("cool", {message: "not throws!"})) expect(fun.isStringOrThrow("cool", { message: "not throws!" }))
.to .to
.equals(true); .equals(true);
}); });
@ -18,13 +18,13 @@ describe("Functional approach", () => {
describe("equalsOrThrow", () => { describe("equalsOrThrow", () => {
it("should throw when they are not equals", () => { it("should throw when they are not equals", () => {
expect(fun.equalsOrThrow.bind(fun, "z", "a", {message: "works!"})) expect(fun.equalsOrThrow.bind(fun, "z", "a", { message: "works!" }))
.to .to
.throw("works!"); .throw("works!");
}); });
it("should return true when they are equals", () => { it("should return true when they are equals", () => {
expect(fun.equalsOrThrow("z", "z", {message: "not throws!"})) expect(fun.equalsOrThrow("z", "z", { message: "not throws!" }))
.to .to
.equals(true); .equals(true);
}); });
@ -32,21 +32,21 @@ describe("Functional approach", () => {
describe("isBase64", () => { describe("isBase64", () => {
it("should return false when is not base64 string", () => { it("should return false when is not base64 string", () => {
let actual = fun.isBase64("non base 64"); const actual = fun.isBase64("non base 64");
expect(actual).to.equal(false); expect(actual).to.equal(false);
}); });
it("should return true when is a base64 string", () => { it("should return true when is a base64 string", () => {
let actual = fun.isBase64("Y2xvdWRldmVudHMK"); const actual = fun.isBase64("Y2xvdWRldmVudHMK");
expect(actual).to.equal(true); expect(actual).to.equal(true);
}); });
}); });
describe("asData" , () => { describe("asData", () => {
it("should throw error when data is not a valid json", () => { it("should throw error when data is not a valid json", () => {
let data = "not a json"; const data = "not a json";
expect(fun.asData.bind(fun, data, "application/json")) expect(fun.asData.bind(fun, data, "application/json"))
.to .to
@ -54,37 +54,37 @@ describe("Functional approach", () => {
}); });
it("should parse string content type as string", () => { it("should parse string content type as string", () => {
let expected = "a string"; const expected = "a string";
let actual = fun.asData(expected, "text/plain"); const actual = fun.asData(expected, "text/plain");
expect((typeof actual)).to.equal("string"); expect((typeof actual)).to.equal("string");
expect(actual).to.equal(expected); expect(actual).to.equal(expected);
}); });
it("should parse 'application/json' as json object", () => { it("should parse 'application/json' as json object", () => {
let expected = { const expected = {
much: "wow", much: "wow",
myext : { myext: {
ext : "x04" ext: "x04"
} }
}; };
let actual = fun.asData(JSON.stringify(expected), "application/json"); const actual = fun.asData(JSON.stringify(expected), "application/json");
expect((typeof actual)).to.equal("object"); expect((typeof actual)).to.equal("object");
expect(actual).to.deep.equal(expected); expect(actual).to.deep.equal(expected);
}); });
it("should parse 'application/cloudevents+json' as json object", () => { it("should parse 'application/cloudevents+json' as json object", () => {
let expected = { const expected = {
much: "wow", much: "wow",
myext : { myext: {
ext : "x04" ext: "x04"
} }
}; };
let actual = fun.asData(JSON.stringify(expected), const actual = fun.asData(JSON.stringify(expected),
"application/cloudevents+json"); "application/cloudevents+json");
expect((typeof actual)).to.equal("object"); expect((typeof actual)).to.equal("object");
@ -92,14 +92,14 @@ describe("Functional approach", () => {
}); });
it("should parse 'text/json' as json object", () => { it("should parse 'text/json' as json object", () => {
let expected = { const expected = {
much: "wow", much: "wow",
myext : { myext: {
ext : "x04" ext: "x04"
} }
}; };
let actual = fun.asData(JSON.stringify(expected), const actual = fun.asData(JSON.stringify(expected),
"text/json"); "text/json");
expect((typeof actual)).to.equal("object"); expect((typeof actual)).to.equal("object");

View File

@ -1,13 +1,13 @@
var expect = require("chai").expect; var expect = require("chai").expect;
var Cloudevent = require("../index.js"); var Cloudevent = require("../index.js");
var nock = require("nock"); var nock = require("nock");
const type = "com.github.pull.create"; const type = "com.github.pull.create";
const source = "urn:event:from:myapi/resourse/123"; const source = "urn:event:from:myapi/resourse/123";
const webhook = "https://cloudevents.io/webhook"; const webhook = "https://cloudevents.io/webhook";
const contentType = "application/cloudevents+json; charset=utf-8"; const contentType = "application/cloudevents+json; charset=utf-8";
const now = new Date(); const now = new Date();
const schemaurl = "http://cloudevents.io/schema.json"; const schemaurl = "http://cloudevents.io/schema.json";
const ceContentType = "application/json"; const ceContentType = "application/json";
@ -15,13 +15,13 @@ const data = {
foo: "bar" foo: "bar"
}; };
const ext1Name = "extension1"; const ext1Name = "extension1";
const ext1Value = "foobar"; const ext1Value = "foobar";
const ext2Name = "extension2"; const ext2Name = "extension2";
const ext2Value = "acme"; const ext2Value = "acme";
const Structured01 = Cloudevent.bindings["http-structured0.1"]; const Structured01 = Cloudevent.bindings["http-structured0.1"];
const Binary01 = Cloudevent.bindings["http-binary0.1"]; const Binary01 = Cloudevent.bindings["http-binary0.1"];
var cloudevent = var cloudevent =
new Cloudevent() new Cloudevent()
@ -37,122 +37,109 @@ var cloudevent =
cloudevent.eventTypeVersion("1.0.0"); cloudevent.eventTypeVersion("1.0.0");
var httpcfg = { var httpcfg = {
method : "POST", method: "POST",
url : webhook + "/json" url: `${webhook}/json`
}; };
var httpstructured01 = new Structured01(httpcfg); var httpstructured01 = new Structured01(httpcfg);
var httpbinary01 = new Binary01(httpcfg); var httpbinary01 = new Binary01(httpcfg);
describe("HTTP Transport Binding - Version 0.1", () => { describe("HTTP Transport Binding - Version 0.1", () => {
beforeEach(() => { beforeEach(() => {
// Mocking the webhook // Mocking the webhook
nock(webhook) nock(webhook)
.post("/json") .post("/json")
.reply(201, {status: "accepted"}); .reply(201, { status: "accepted" });
}); });
describe("Structured", () => { describe("Structured", () => {
describe("JSON Format", () => { describe("JSON Format", () => {
it("requires '" + contentType + "' Content-Type in the header", () => { it(`requires '${contentType}' Content-Type in the header`,
return httpstructured01.emit(cloudevent) () => httpstructured01.emit(cloudevent)
.then((response) => { .then((response) => {
expect(response.config.headers["Content-Type"]) expect(response.config.headers["Content-Type"])
.to.equal(contentType); .to.equal(contentType);
}); }));
});
it("the request payload should be correct", () => { it("the request payload should be correct",
return httpstructured01.emit(cloudevent) () => httpstructured01.emit(cloudevent)
.then((response) => { .then((response) => {
expect(JSON.parse(response.config.data)) expect(JSON.parse(response.config.data))
.to.deep.equal(cloudevent.format()); .to.deep.equal(cloudevent.format());
}); }));
});
}); });
}); });
describe("Binary", () => { describe("Binary", () => {
describe("JSON Format", () => { describe("JSON Format", () => {
it("requires '" + cloudevent.getContenttype() + "' Content-Type in the header", () => { it(`requires '${cloudevent.getContenttype()}' Content-Type in the header`,
return httpbinary01.emit(cloudevent) () => httpbinary01.emit(cloudevent)
.then((response) => { .then((response) => {
expect(response.config.headers["Content-Type"]) expect(response.config.headers["Content-Type"])
.to.equal(cloudevent.getContenttype()); .to.equal(cloudevent.getContenttype());
}); }));
});
it("the request payload should be correct", () => { it("the request payload should be correct",
return httpbinary01.emit(cloudevent) () => httpbinary01.emit(cloudevent)
.then((response) => { .then((response) => {
expect(JSON.parse(response.config.data)) expect(JSON.parse(response.config.data))
.to.deep.equal(cloudevent.getData()); .to.deep.equal(cloudevent.getData());
}); }));
});
it("HTTP Header contains 'CE-EventType'", () => { it("HTTP Header contains 'CE-EventType'",
return httpbinary01.emit(cloudevent) () => httpbinary01.emit(cloudevent)
.then((response) => { .then((response) => {
expect(response.config.headers) expect(response.config.headers)
.to.have.property("CE-EventType"); .to.have.property("CE-EventType");
}); }));
});
it("HTTP Header contains 'CE-EventTypeVersion'", () => { it("HTTP Header contains 'CE-EventTypeVersion'",
return httpbinary01.emit(cloudevent) () => httpbinary01.emit(cloudevent)
.then((response) => { .then((response) => {
expect(response.config.headers) expect(response.config.headers)
.to.have.property("CE-EventTypeVersion"); .to.have.property("CE-EventTypeVersion");
}); }));
});
it("HTTP Header contains 'CE-CloudEventsVersion'", () => { it("HTTP Header contains 'CE-CloudEventsVersion'",
return httpbinary01.emit(cloudevent) () => httpbinary01.emit(cloudevent)
.then((response) => { .then((response) => {
expect(response.config.headers) expect(response.config.headers)
.to.have.property("CE-CloudEventsVersion"); .to.have.property("CE-CloudEventsVersion");
}); }));
});
it("HTTP Header contains 'CE-Source'", () => { it("HTTP Header contains 'CE-Source'", () => httpbinary01.emit(cloudevent)
return httpbinary01.emit(cloudevent) .then((response) => {
.then((response) => { expect(response.config.headers)
expect(response.config.headers) .to.have.property("CE-Source");
.to.have.property("CE-Source"); }));
});
});
it("HTTP Header contains 'CE-EventID'", () => { it("HTTP Header contains 'CE-EventID'",
return httpbinary01.emit(cloudevent) () => httpbinary01.emit(cloudevent)
.then((response) => { .then((response) => {
expect(response.config.headers) expect(response.config.headers)
.to.have.property("CE-EventID"); .to.have.property("CE-EventID");
}); }));
});
it("HTTP Header contains 'CE-EventTime'", () => { it("HTTP Header contains 'CE-EventTime'",
return httpbinary01.emit(cloudevent) () => httpbinary01.emit(cloudevent)
.then((response) => { .then((response) => {
expect(response.config.headers) expect(response.config.headers)
.to.have.property("CE-EventTime"); .to.have.property("CE-EventTime");
}); }));
});
it("HTTP Header contains 'CE-SchemaURL'", () => { it("HTTP Header contains 'CE-SchemaURL'",
return httpbinary01.emit(cloudevent) () => httpbinary01.emit(cloudevent)
.then((response) => { .then((response) => {
expect(response.config.headers) expect(response.config.headers)
.to.have.property("CE-SchemaURL"); .to.have.property("CE-SchemaURL");
}); }));
});
it("HTTP Header contains 'CE-X-Extension1' as extension", () => { it("HTTP Header contains 'CE-X-Extension1' as extension",
return httpbinary01.emit(cloudevent) () => httpbinary01.emit(cloudevent)
.then((response) => { .then((response) => {
expect(response.config.headers) expect(response.config.headers)
.to.have.property("CE-X-Extension1"); .to.have.property("CE-X-Extension1");
}); }));
});
}); });
}); });
}); });

View File

@ -1,16 +1,13 @@
var expect = require("chai").expect; var expect = require("chai").expect;
var Cloudevent = require("../index.js"); var Cloudevent = require("../index.js");
var nock = require("nock"); var nock = require("nock");
var Spec02 = require("../lib/specs/spec_0_2.js");
var {HTTPBinary02} = require("../lib/bindings/http/emitter_binary_0_2.js"); const type = "com.github.pull.create";
const source = "urn:event:from:myapi/resourse/123";
const type = "com.github.pull.create"; const webhook = "https://cloudevents.io/webhook";
const source = "urn:event:from:myapi/resourse/123";
const webhook = "https://cloudevents.io/webhook";
const contentType = "application/cloudevents+json; charset=utf-8"; const contentType = "application/cloudevents+json; charset=utf-8";
const now = new Date(); const now = new Date();
const schemaurl = "http://cloudevents.io/schema.json"; const schemaurl = "http://cloudevents.io/schema.json";
const ceContentType = "application/json"; const ceContentType = "application/json";
@ -18,19 +15,13 @@ const data = {
foo: "bar" foo: "bar"
}; };
const ext1Name = "extension1"; const ext1Name = "extension1";
const ext1Value = "foobar"; const ext1Value = "foobar";
const ext2Name = "extension2"; const ext2Name = "extension2";
const ext2Value = "acme"; const ext2Value = "acme";
const receiverConfig = {
path : "/events",
port : 10300,
method : "POST"
};
const Structured02 = Cloudevent.bindings["http-structured0.2"]; const Structured02 = Cloudevent.bindings["http-structured0.2"];
const Binary02 = Cloudevent.bindings["http-binary0.2"]; const Binary02 = Cloudevent.bindings["http-binary0.2"];
var cloudevent = var cloudevent =
new Cloudevent() new Cloudevent()
@ -44,122 +35,106 @@ var cloudevent =
.addExtension(ext2Name, ext2Value); .addExtension(ext2Name, ext2Value);
var httpcfg = { var httpcfg = {
method : "POST", method: "POST",
url : webhook + "/json" url: `${webhook}/json`
}; };
var httpstructured02 = new Structured02(httpcfg); var httpstructured02 = new Structured02(httpcfg);
var httpbinary02 = new Binary02(httpcfg); var httpbinary02 = new Binary02(httpcfg);
describe("HTTP Transport Binding - Version 0.2", () => { describe("HTTP Transport Binding - Version 0.2", () => {
beforeEach(() => { beforeEach(() => {
// Mocking the webhook // Mocking the webhook
nock(webhook) nock(webhook)
.post("/json") .post("/json")
.reply(201, {status: "accepted"}); .reply(201, { status: "accepted" });
}); });
describe("Structured", () => { describe("Structured", () => {
describe("JSON Format", () => { describe("JSON Format", () => {
it("requires '" + contentType + "' Content-Type in the header", () => { it(`requires '${contentType}' Content-Type in the header`,
return httpstructured02.emit(cloudevent) () => httpstructured02.emit(cloudevent)
.then((response) => { .then((response) => {
expect(response.config.headers["Content-Type"]) expect(response.config.headers["Content-Type"])
.to.equal(contentType); .to.equal(contentType);
}); }));
});
it("the request payload should be correct", () => { it("the request payload should be correct",
return httpstructured02.emit(cloudevent) () => httpstructured02.emit(cloudevent)
.then((response) => { .then((response) => {
expect(JSON.parse(response.config.data)) expect(JSON.parse(response.config.data))
.to.deep.equal(cloudevent.format()); .to.deep.equal(cloudevent.format());
}); }));
});
}); });
}); });
describe("Binary", () => { describe("Binary", () => {
describe("JSON Format", () => { describe("JSON Format", () => {
it("requires '" + cloudevent.getContenttype() + "' Content-Type in the header", () => { it(`requires ${cloudevent.getContenttype()} Content-Type in the header`,
return httpbinary02.emit(cloudevent) () => httpbinary02.emit(cloudevent)
.then((response) => { .then((response) => {
expect(response.config.headers["Content-Type"]) expect(response.config.headers["Content-Type"])
.to.equal(cloudevent.getContenttype()); .to.equal(cloudevent.getContenttype());
}); }));
});
it("the request payload should be correct", () => { it("the request payload should be correct",
return httpbinary02.emit(cloudevent) () => httpbinary02.emit(cloudevent)
.then((response) => { .then((response) => {
expect(JSON.parse(response.config.data)) expect(JSON.parse(response.config.data))
.to.deep.equal(cloudevent.getData()); .to.deep.equal(cloudevent.getData());
}); }));
});
it("HTTP Header contains 'ce-type'", () => { it("HTTP Header contains 'ce-type'", () => httpbinary02.emit(cloudevent)
return httpbinary02.emit(cloudevent) .then((response) => {
.then((response) => { expect(response.config.headers)
expect(response.config.headers) .to.have.property("ce-type");
.to.have.property("ce-type"); }));
});
});
it("HTTP Header contains 'ce-specversion'", () => { it("HTTP Header contains 'ce-specversion'",
return httpbinary02.emit(cloudevent) () => httpbinary02.emit(cloudevent)
.then((response) => { .then((response) => {
expect(response.config.headers) expect(response.config.headers)
.to.have.property("ce-specversion"); .to.have.property("ce-specversion");
}); }));
});
it("HTTP Header contains 'ce-source'", () => { it("HTTP Header contains 'ce-source'", () => httpbinary02.emit(cloudevent)
return httpbinary02.emit(cloudevent) .then((response) => {
.then((response) => { expect(response.config.headers)
expect(response.config.headers) .to.have.property("ce-source");
.to.have.property("ce-source"); }));
});
});
it("HTTP Header contains 'ce-id'", () => { it("HTTP Header contains 'ce-id'", () => httpbinary02.emit(cloudevent)
return httpbinary02.emit(cloudevent) .then((response) => {
.then((response) => { expect(response.config.headers)
expect(response.config.headers) .to.have.property("ce-id");
.to.have.property("ce-id"); }));
});
});
it("HTTP Header contains 'ce-time'", () => { it("HTTP Header contains 'ce-time'", () => httpbinary02.emit(cloudevent)
return httpbinary02.emit(cloudevent) .then((response) => {
.then((response) => { expect(response.config.headers)
expect(response.config.headers) .to.have.property("ce-time");
.to.have.property("ce-time"); }));
});
});
it("HTTP Header contains 'ce-schemaurl'", () => { it("HTTP Header contains 'ce-schemaurl'",
return httpbinary02.emit(cloudevent) () => httpbinary02.emit(cloudevent)
.then((response) => { .then((response) => {
expect(response.config.headers) expect(response.config.headers)
.to.have.property("ce-schemaurl"); .to.have.property("ce-schemaurl");
}); }));
});
it("HTTP Header contains 'ce-" + ext1Name + "'", () => { it(`HTTP Header contains 'ce-${ext1Name}'`,
return httpbinary02.emit(cloudevent) () => httpbinary02.emit(cloudevent)
.then((response) => { .then((response) => {
expect(response.config.headers) expect(response.config.headers)
.to.have.property("ce-" + ext1Name); .to.have.property(`ce-${ext1Name}`);
}); }));
});
it("HTTP Header contains 'ce-" + ext2Name + "'", () => { it(`HTTP Header contains 'ce-${ext2Name}'`,
return httpbinary02.emit(cloudevent) () => httpbinary02.emit(cloudevent)
.then((response) => { .then((response) => {
expect(response.config.headers) expect(response.config.headers)
.to.have.property("ce-" + ext2Name); .to.have.property(`ce-${ext2Name}`);
}); }));
});
}); });
}); });
}); });

View File

@ -5,12 +5,12 @@ const BinaryHTTPEmitter =
const Cloudevent = require("../lib/cloudevent.js"); const Cloudevent = require("../lib/cloudevent.js");
const v03 = require("../v03/index.js"); const v03 = require("../v03/index.js");
const type = "com.github.pull.create"; const type = "com.github.pull.create";
const source = "urn:event:from:myapi/resourse/123"; const source = "urn:event:from:myapi/resourse/123";
const contentEncoding = "base64"; const contentEncoding = "base64";
const contentType = "application/cloudevents+json; charset=utf-8"; const contentType = "application/cloudevents+json; charset=utf-8";
const now = new Date(); const now = new Date();
const schemaurl = "http://cloudevents.io/schema.json"; const schemaurl = "http://cloudevents.io/schema.json";
const ceContentType = "application/json"; const ceContentType = "application/json";
@ -19,9 +19,9 @@ const data = {
}; };
const dataBase64 = "Y2xvdWRldmVudHMK"; const dataBase64 = "Y2xvdWRldmVudHMK";
const ext1Name = "extension1"; const ext1Name = "extension1";
const ext1Value = "foobar"; const ext1Value = "foobar";
const ext2Name = "extension2"; const ext2Name = "extension2";
const ext2Value = "acme"; const ext2Value = "acme";
const cloudevent = const cloudevent =
@ -48,11 +48,10 @@ const cebase64 =
.addExtension(ext1Name, ext1Value) .addExtension(ext1Name, ext1Value)
.addExtension(ext2Name, ext2Value); .addExtension(ext2Name, ext2Value);
const webhook = "https://cloudevents.io/webhook"; const webhook = "https://cloudevents.io/webhook";
const httpcfg = { const httpcfg = {
method : "POST", method: "POST",
url : webhook + "/json" url: `${webhook}/json`
}; };
const binary = new BinaryHTTPEmitter(httpcfg); const binary = new BinaryHTTPEmitter(httpcfg);
@ -63,219 +62,180 @@ describe("HTTP Transport Binding - Version 0.3", () => {
// Mocking the webhook // Mocking the webhook
nock(webhook) nock(webhook)
.post("/json") .post("/json")
.reply(201, {status: "accepted"}); .reply(201, { status: "accepted" });
}); });
describe("Structured", () => { describe("Structured", () => {
describe("JSON Format", () => { describe("JSON Format", () => {
it("requires '" + contentType + "' Content-Type in the header", () => { it(`requires '${contentType}' Content-Type in the header`,
return structured.emit(cloudevent) () => structured.emit(cloudevent)
.then((response) => { .then((response) => {
expect(response.config.headers["Content-Type"]) expect(response.config.headers["Content-Type"])
.to.equal(contentType); .to.equal(contentType);
}); }));
});
it("the request payload should be correct", () => { it("the request payload should be correct",
return structured.emit(cloudevent) () => structured.emit(cloudevent)
.then((response) => { .then((response) => {
expect(JSON.parse(response.config.data)) expect(JSON.parse(response.config.data))
.to.deep.equal(cloudevent.format()); .to.deep.equal(cloudevent.format());
}); }));
});
describe("'data' attribute with 'base64' encoding", () => { describe("'data' attribute with 'base64' encoding", () => {
it("the request payload should be correct", () => { it("the request payload should be correct",
return structured.emit(cebase64) () => structured.emit(cebase64)
.then((response) => { .then((response) => {
expect(JSON.parse(response.config.data).data) expect(JSON.parse(response.config.data).data)
.to.equal(cebase64.format().data); .to.equal(cebase64.format().data);
}); }));
});
}); });
}); });
}); });
describe("Binary", () => { describe("Binary", () => {
describe("JSON Format", () => { describe("JSON Format", () => {
it("requires '" + cloudevent.getDataContentType() + "' Content-Type in the header", () => { it(`requires ${cloudevent.getDataContentType()} in the header`,
return binary.emit(cloudevent) () => binary.emit(cloudevent)
.then((response) => { .then((response) => {
expect(response.config.headers["Content-Type"]) expect(response.config.headers["Content-Type"])
.to.equal(cloudevent.getDataContentType()); .to.equal(cloudevent.getDataContentType());
}); }));
});
it("the request payload should be correct", () => { it("the request payload should be correct", () => binary.emit(cloudevent)
return binary.emit(cloudevent) .then((response) => {
.then((response) => { expect(JSON.parse(response.config.data))
expect(JSON.parse(response.config.data)) .to.deep.equal(cloudevent.getData());
.to.deep.equal(cloudevent.getData()); }));
});
});
it("HTTP Header contains 'ce-type'", () => { it("HTTP Header contains 'ce-type'", () => binary.emit(cloudevent)
return binary.emit(cloudevent) .then((response) => {
.then((response) => { expect(response.config.headers)
expect(response.config.headers) .to.have.property("ce-type");
.to.have.property("ce-type"); }));
});
});
it("HTTP Header contains 'ce-specversion'", () => { it("HTTP Header contains 'ce-specversion'", () => binary.emit(cloudevent)
return binary.emit(cloudevent) .then((response) => {
.then((response) => { expect(response.config.headers)
expect(response.config.headers) .to.have.property("ce-specversion");
.to.have.property("ce-specversion"); }));
});
});
it("HTTP Header contains 'ce-source'", () => { it("HTTP Header contains 'ce-source'", () => binary.emit(cloudevent)
return binary.emit(cloudevent) .then((response) => {
.then((response) => { expect(response.config.headers)
expect(response.config.headers) .to.have.property("ce-source");
.to.have.property("ce-source"); }));
});
});
it("HTTP Header contains 'ce-id'", () => { it("HTTP Header contains 'ce-id'", () => binary.emit(cloudevent)
return binary.emit(cloudevent) .then((response) => {
.then((response) => { expect(response.config.headers)
expect(response.config.headers) .to.have.property("ce-id");
.to.have.property("ce-id"); }));
});
});
it("HTTP Header contains 'ce-time'", () => { it("HTTP Header contains 'ce-time'", () => binary.emit(cloudevent)
return binary.emit(cloudevent) .then((response) => {
.then((response) => { expect(response.config.headers)
expect(response.config.headers) .to.have.property("ce-time");
.to.have.property("ce-time"); }));
});
});
it("HTTP Header contains 'ce-schemaurl'", () => { it("HTTP Header contains 'ce-schemaurl'", () => binary.emit(cloudevent)
return binary.emit(cloudevent) .then((response) => {
.then((response) => { expect(response.config.headers)
expect(response.config.headers) .to.have.property("ce-schemaurl");
.to.have.property("ce-schemaurl"); }));
});
});
it("HTTP Header contains 'ce-" + ext1Name + "'", () => { it(`HTTP Header contains 'ce-${ext1Name}'`, () => binary.emit(cloudevent)
return binary.emit(cloudevent) .then((response) => {
.then((response) => { expect(response.config.headers)
expect(response.config.headers) .to.have.property(`ce-${ext1Name}`);
.to.have.property("ce-" + ext1Name); }));
});
});
it("HTTP Header contains 'ce-" + ext2Name + "'", () => { it(`HTTP Header contains 'ce-${ext2Name}'`, () => binary.emit(cloudevent)
return binary.emit(cloudevent) .then((response) => {
.then((response) => { expect(response.config.headers)
expect(response.config.headers) .to.have.property(`ce-${ext2Name}`);
.to.have.property("ce-" + ext2Name); }));
});
});
it("HTTP Header contains 'ce-subject'", () => { it("HTTP Header contains 'ce-subject'", () => binary.emit(cloudevent)
return binary.emit(cloudevent) .then((response) => {
.then((response) => { expect(response.config.headers)
expect(response.config.headers) .to.have.property("ce-subject");
.to.have.property("ce-subject"); }));
});
});
it("should 'ce-type' have the right value", () => { it("should 'ce-type' have the right value", () => binary.emit(cloudevent)
return binary.emit(cloudevent) .then((response) => {
.then((response) => { expect(cloudevent.getType())
expect(cloudevent.getType()) .to.equal(response.config.headers["ce-type"]);
.to.equal(response.config.headers["ce-type"]); }));
});
});
it("should 'ce-specversion' have the right value", () => { it("should 'ce-specversion' have the right value",
return binary.emit(cloudevent) () => binary.emit(cloudevent)
.then((response) => { .then((response) => {
expect(cloudevent.getSpecversion()) expect(cloudevent.getSpecversion())
.to.equal(response.config.headers["ce-specversion"]); .to.equal(response.config.headers["ce-specversion"]);
}); }));
});
it("should 'ce-source' have the right value", () => { it("should 'ce-source' have the right value",
return binary.emit(cloudevent) () => binary.emit(cloudevent)
.then((response) => { .then((response) => {
expect(cloudevent.getSource()) expect(cloudevent.getSource())
.to.equal(response.config.headers["ce-source"]); .to.equal(response.config.headers["ce-source"]);
}); }));
});
it("should 'ce-id' have the right value", () => { it("should 'ce-id' have the right value", () => binary.emit(cloudevent)
return binary.emit(cloudevent) .then((response) => {
.then((response) => { expect(cloudevent.getId())
expect(cloudevent.getId()) .to.equal(response.config.headers["ce-id"]);
.to.equal(response.config.headers["ce-id"]); }));
});
});
it("should 'ce-time' have the right value", () => { it("should 'ce-time' have the right value", () => binary.emit(cloudevent)
return binary.emit(cloudevent) .then((response) => {
.then((response) => { expect(cloudevent.getTime())
expect(cloudevent.getTime()) .to.equal(response.config.headers["ce-time"]);
.to.equal(response.config.headers["ce-time"]); }));
});
});
it("should 'ce-schemaurl' have the right value", () => { it("should 'ce-schemaurl' have the right value",
return binary.emit(cloudevent) () => binary.emit(cloudevent)
.then((response) => { .then((response) => {
expect(cloudevent.getSchemaurl()) expect(cloudevent.getSchemaurl())
.to.equal(response.config.headers["ce-schemaurl"]); .to.equal(response.config.headers["ce-schemaurl"]);
}); }));
});
it("should 'ce-" + ext1Name + "' have the right value", () => { it(`should 'ce-${ext1Name}' have the right value`,
return binary.emit(cloudevent) () => binary.emit(cloudevent)
.then((response) => { .then((response) => {
expect(cloudevent.getExtensions()[ext1Name]) expect(cloudevent.getExtensions()[ext1Name])
.to.equal(response.config.headers["ce-" + ext1Name]); .to.equal(response.config.headers[`ce-${ext1Name}`]);
}); }));
});
it("should 'ce-" + ext2Name + "' have the right value", () => { it(`should 'ce-${ext2Name}' have the right value`,
return binary.emit(cloudevent) () => binary.emit(cloudevent)
.then((response) => { .then((response) => {
expect(cloudevent.getExtensions()[ext2Name]) expect(cloudevent.getExtensions()[ext2Name])
.to.equal(response.config.headers["ce-" + ext2Name]); .to.equal(response.config.headers[`ce-${ext2Name}`]);
}); }));
});
it("should 'ce-subject' have the right value", () => { it("should 'ce-subject' have the right value",
return binary.emit(cloudevent) () => binary.emit(cloudevent)
.then((response) => { .then((response) => {
expect(cloudevent.getSubject()) expect(cloudevent.getSubject())
.to.equal(response.config.headers["ce-subject"]); .to.equal(response.config.headers["ce-subject"]);
}); }));
});
describe("'data' attribute with 'base64' encoding", () => { describe("'data' attribute with 'base64' encoding", () => {
it("HTTP Header contains 'ce-datacontentencoding'", () => { it("HTTP Header contains 'ce-datacontentencoding'",
return binary.emit(cebase64) () => binary.emit(cebase64)
.then((response) => { .then((response) => {
expect(response.config.headers) expect(response.config.headers)
.to.have.property("ce-datacontentencoding"); .to.have.property("ce-datacontentencoding");
}); }));
});
it("should 'ce-datacontentencoding' have the right value", () => { it("should 'ce-datacontentencoding' have the right value",
return binary.emit(cloudevent) () => binary.emit(cloudevent)
.then((response) => { .then((response) => {
expect(cloudevent.getDataContentEncoding()) expect(cloudevent.getDataContentEncoding())
.to.equal(response.config.headers["ce-datacontentencoding"]); .to.equal(response.config.headers["ce-datacontentencoding"]);
}); }));
});
}); });
}); });
}); });
}); });

View File

@ -1,7 +1,7 @@
const expect = require("chai").expect; const expect = require("chai").expect;
const nock = require("nock"); const nock = require("nock");
const https = require("https"); const https = require("https");
const {asBase64} = require("../lib/utils/fun.js"); const { asBase64 } = require("../lib/utils/fun.js");
const { const {
Spec, Spec,
@ -10,11 +10,11 @@ const {
Cloudevent Cloudevent
} = require("../v1/index.js"); } = require("../v1/index.js");
const type = "com.github.pull.create"; const type = "com.github.pull.create";
const source = "urn:event:from:myapi/resourse/123"; const source = "urn:event:from:myapi/resourse/123";
const contentType = "application/cloudevents+json; charset=utf-8"; const contentType = "application/cloudevents+json; charset=utf-8";
const now = new Date(); const now = new Date();
const dataschema = "http://cloudevents.io/schema.json"; const dataschema = "http://cloudevents.io/schema.json";
const ceContentType = "application/json"; const ceContentType = "application/json";
@ -22,9 +22,9 @@ const data = {
foo: "bar" foo: "bar"
}; };
const ext1Name = "extension1"; const ext1Name = "extension1";
const ext1Value = "foobar"; const ext1Value = "foobar";
const ext2Name = "extension2"; const ext2Name = "extension2";
const ext2Value = "acme"; const ext2Value = "acme";
const cloudevent = const cloudevent =
@ -39,12 +39,12 @@ const cloudevent =
.addExtension(ext1Name, ext1Value) .addExtension(ext1Name, ext1Value)
.addExtension(ext2Name, ext2Value); .addExtension(ext2Name, ext2Value);
const dataString = ")(*~^my data for ce#@#$%" const dataString = ")(*~^my data for ce#@#$%";
const webhook = "https://cloudevents.io/webhook/v1"; const webhook = "https://cloudevents.io/webhook/v1";
const httpcfg = { const httpcfg = {
method : "POST", method: "POST",
url : webhook + "/json" url: `${webhook}/json`
}; };
const binary = new BinaryHTTPEmitter(httpcfg); const binary = new BinaryHTTPEmitter(httpcfg);
@ -55,47 +55,45 @@ describe("HTTP Transport Binding - Version 1.0", () => {
// Mocking the webhook // Mocking the webhook
nock(webhook) nock(webhook)
.post("/json") .post("/json")
.reply(201, {status: "accepted"}); .reply(201, { status: "accepted" });
}); });
describe("Structured", () => { describe("Structured", () => {
it('works with mTLS authentication', () => { it("works with mTLS authentication", () => {
const event = new StructuredHTTPEmitter({ const event = new StructuredHTTPEmitter({
method: 'POST', method: "POST",
url: `${webhook}/json`, url: `${webhook}/json`,
httpsAgent: new https.Agent({ httpsAgent: new https.Agent({
cert: 'some value', cert: "some value",
key: 'other value' key: "other value"
}) })
}) });
return event.emit(cloudevent).then(response => { return event.emit(cloudevent).then((response) => {
expect(response.config.headers['Content-Type']) expect(response.config.headers["Content-Type"])
.to.equal(contentType); .to.equal(contentType);
}); });
}); });
describe("JSON Format", () => { describe("JSON Format", () => {
it("requires '" + contentType + "' Content-Type in the header", () => { it(`requires '${contentType}' Content-Type in the header`,
return structured.emit(cloudevent) () => structured.emit(cloudevent)
.then((response) => { .then((response) => {
expect(response.config.headers["Content-Type"]) expect(response.config.headers["Content-Type"])
.to.equal(contentType); .to.equal(contentType);
}); }));
});
it("the request payload should be correct", () => { it("the request payload should be correct",
return structured.emit(cloudevent) () => structured.emit(cloudevent)
.then((response) => { .then((response) => {
expect(JSON.parse(response.config.data)) expect(JSON.parse(response.config.data))
.to.deep.equal(cloudevent.format()); .to.deep.equal(cloudevent.format());
}); }));
});
describe("Binary event data", () => { describe("Binary event data", () => {
it("the request payload should be correct when data is binary", () => { it("the request payload should be correct when data is binary", () => {
let bindata = Uint32Array.from(dataString, (c) => c.codePointAt(0)); const bindata = Uint32Array.from(dataString, (c) => c.codePointAt(0));
let expected = asBase64(bindata); const expected = asBase64(bindata);
let binevent = const binevent =
new Cloudevent(Spec) new Cloudevent(Spec)
.type(type) .type(type)
.source(source) .source(source)
@ -112,7 +110,7 @@ describe("HTTP Transport Binding - Version 1.0", () => {
}); });
it("the payload must have 'data_base64' when data is binary", () => { it("the payload must have 'data_base64' when data is binary", () => {
let binevent = const binevent =
new Cloudevent(Spec) new Cloudevent(Spec)
.type(type) .type(type)
.source(source) .source(source)
@ -132,42 +130,40 @@ describe("HTTP Transport Binding - Version 1.0", () => {
}); });
describe("Binary", () => { describe("Binary", () => {
it('works with mTLS authentication', () => { it("works with mTLS authentication", () => {
const event = new BinaryHTTPEmitter({ const event = new BinaryHTTPEmitter({
method: 'POST', method: "POST",
url: `${webhook}/json`, url: `${webhook}/json`,
httpsAgent: new https.Agent({ httpsAgent: new https.Agent({
cert: 'some value', cert: "some value",
key: 'other value' key: "other value"
}) })
}) });
return event.emit(cloudevent).then(response => { return event.emit(cloudevent).then((response) => {
expect(response.config.headers['Content-Type']) expect(response.config.headers["Content-Type"])
.to.equal(cloudevent.getDataContentType()); .to.equal(cloudevent.getDataContentType());
}); });
}); });
describe("JSON Format", () => { describe("JSON Format", () => {
it("requires '" + cloudevent.getDataContentType() + "' Content-Type in the header", () => { it(`requires '${cloudevent.getDataContentType()}' in the header`,
return binary.emit(cloudevent) () => binary.emit(cloudevent)
.then((response) => { .then((response) => {
expect(response.config.headers["Content-Type"]) expect(response.config.headers["Content-Type"])
.to.equal(cloudevent.getDataContentType()); .to.equal(cloudevent.getDataContentType());
}); }));
});
it("the request payload should be correct", () => { it("the request payload should be correct", () => binary.emit(cloudevent)
return binary.emit(cloudevent) .then((response) => {
.then((response) => { expect(JSON.parse(response.config.data))
expect(JSON.parse(response.config.data)) .to.deep.equal(cloudevent.getData());
.to.deep.equal(cloudevent.getData()); }));
});
});
it("the request payload should be correct when event data is binary", () => { it("the request payload should be correct when event data is binary",
let bindata = Uint32Array.from(dataString, (c) => c.codePointAt(0)); () => {
let expected = asBase64(bindata); const bindata = Uint32Array.from(dataString, (c) => c.codePointAt(0));
let binevent = const expected = asBase64(bindata);
const binevent =
new Cloudevent(Spec) new Cloudevent(Spec)
.type(type) .type(type)
.source(source) .source(source)
@ -176,156 +172,126 @@ describe("HTTP Transport Binding - Version 1.0", () => {
.addExtension(ext1Name, ext1Value) .addExtension(ext1Name, ext1Value)
.addExtension(ext2Name, ext2Value); .addExtension(ext2Name, ext2Value);
return binary.emit(binevent) return binary.emit(binevent)
.then((response) => { .then((response) => {
expect(response.config.data) expect(response.config.data)
.to.equal(expected); .to.equal(expected);
}); });
}); });
it("HTTP Header contains 'ce-type'", () => { it("HTTP Header contains 'ce-type'", () => binary.emit(cloudevent)
return binary.emit(cloudevent) .then((response) => {
.then((response) => { expect(response.config.headers)
expect(response.config.headers) .to.have.property("ce-type");
.to.have.property("ce-type"); }));
});
});
it("HTTP Header contains 'ce-specversion'", () => { it("HTTP Header contains 'ce-specversion'", () => binary.emit(cloudevent)
return binary.emit(cloudevent) .then((response) => {
.then((response) => { expect(response.config.headers)
expect(response.config.headers) .to.have.property("ce-specversion");
.to.have.property("ce-specversion"); }));
});
});
it("HTTP Header contains 'ce-source'", () => { it("HTTP Header contains 'ce-source'", () => binary.emit(cloudevent)
return binary.emit(cloudevent) .then((response) => {
.then((response) => { expect(response.config.headers)
expect(response.config.headers) .to.have.property("ce-source");
.to.have.property("ce-source"); }));
});
});
it("HTTP Header contains 'ce-id'", () => { it("HTTP Header contains 'ce-id'", () => binary.emit(cloudevent)
return binary.emit(cloudevent) .then((response) => {
.then((response) => { expect(response.config.headers)
expect(response.config.headers) .to.have.property("ce-id");
.to.have.property("ce-id"); }));
});
});
it("HTTP Header contains 'ce-time'", () => { it("HTTP Header contains 'ce-time'", () => binary.emit(cloudevent)
return binary.emit(cloudevent) .then((response) => {
.then((response) => { expect(response.config.headers)
expect(response.config.headers) .to.have.property("ce-time");
.to.have.property("ce-time"); }));
});
});
it("HTTP Header contains 'ce-dataschema'", () => { it("HTTP Header contains 'ce-dataschema'", () => binary.emit(cloudevent)
return binary.emit(cloudevent) .then((response) => {
.then((response) => { expect(response.config.headers)
expect(response.config.headers) .to.have.property("ce-dataschema");
.to.have.property("ce-dataschema"); }));
});
});
it("HTTP Header contains 'ce-" + ext1Name + "'", () => { it(`HTTP Header contains 'ce-${ext1Name}'`, () => binary.emit(cloudevent)
return binary.emit(cloudevent) .then((response) => {
.then((response) => { expect(response.config.headers)
expect(response.config.headers) .to.have.property(`ce-${ext1Name}`);
.to.have.property("ce-" + ext1Name); }));
});
});
it("HTTP Header contains 'ce-" + ext2Name + "'", () => { it(`HTTP Header contains 'ce-${ext2Name}'`, () => binary.emit(cloudevent)
return binary.emit(cloudevent) .then((response) => {
.then((response) => { expect(response.config.headers)
expect(response.config.headers) .to.have.property(`ce-${ext2Name}`);
.to.have.property("ce-" + ext2Name); }));
});
});
it("HTTP Header contains 'ce-subject'", () => { it("HTTP Header contains 'ce-subject'", () => binary.emit(cloudevent)
return binary.emit(cloudevent) .then((response) => {
.then((response) => { expect(response.config.headers)
expect(response.config.headers) .to.have.property("ce-subject");
.to.have.property("ce-subject"); }));
});
});
it("should 'ce-type' have the right value", () => { it("should 'ce-type' have the right value", () => binary.emit(cloudevent)
return binary.emit(cloudevent) .then((response) => {
.then((response) => { expect(cloudevent.getType())
expect(cloudevent.getType()) .to.equal(response.config.headers["ce-type"]);
.to.equal(response.config.headers["ce-type"]); }));
});
});
it("should 'ce-specversion' have the right value", () => { it("should 'ce-specversion' have the right value",
return binary.emit(cloudevent) () => binary.emit(cloudevent)
.then((response) => { .then((response) => {
expect(cloudevent.getSpecversion()) expect(cloudevent.getSpecversion())
.to.equal(response.config.headers["ce-specversion"]); .to.equal(response.config.headers["ce-specversion"]);
}); }));
});
it("should 'ce-source' have the right value", () => { it("should 'ce-source' have the right value",
return binary.emit(cloudevent) () => binary.emit(cloudevent)
.then((response) => { .then((response) => {
expect(cloudevent.getSource()) expect(cloudevent.getSource())
.to.equal(response.config.headers["ce-source"]); .to.equal(response.config.headers["ce-source"]);
}); }));
});
it("should 'ce-id' have the right value", () => { it("should 'ce-id' have the right value", () => binary.emit(cloudevent)
return binary.emit(cloudevent) .then((response) => {
.then((response) => { expect(cloudevent.getId())
expect(cloudevent.getId()) .to.equal(response.config.headers["ce-id"]);
.to.equal(response.config.headers["ce-id"]); }));
});
});
it("should 'ce-time' have the right value", () => { it("should 'ce-time' have the right value", () => binary.emit(cloudevent)
return binary.emit(cloudevent) .then((response) => {
.then((response) => { expect(cloudevent.getTime())
expect(cloudevent.getTime()) .to.equal(response.config.headers["ce-time"]);
.to.equal(response.config.headers["ce-time"]); }));
});
});
it("should 'ce-dataschema' have the right value", () => { it("should 'ce-dataschema' have the right value",
return binary.emit(cloudevent) () => binary.emit(cloudevent)
.then((response) => { .then((response) => {
expect(cloudevent.getDataschema()) expect(cloudevent.getDataschema())
.to.equal(response.config.headers["ce-dataschema"]); .to.equal(response.config.headers["ce-dataschema"]);
}); }));
});
it("should 'ce-" + ext1Name + "' have the right value", () => { it(`should 'ce-${ext1Name}' have the right value`,
return binary.emit(cloudevent) () => binary.emit(cloudevent)
.then((response) => { .then((response) => {
expect(cloudevent.getExtensions()[ext1Name]) expect(cloudevent.getExtensions()[ext1Name])
.to.equal(response.config.headers["ce-" + ext1Name]); .to.equal(response.config.headers[`ce-${ext1Name}`]);
}); }));
});
it("should 'ce-" + ext2Name + "' have the right value", () => { it(`should 'ce-${ext2Name}' have the right value`,
return binary.emit(cloudevent) () => binary.emit(cloudevent)
.then((response) => { .then((response) => {
expect(cloudevent.getExtensions()[ext2Name]) expect(cloudevent.getExtensions()[ext2Name])
.to.equal(response.config.headers["ce-" + ext2Name]); .to.equal(response.config.headers[`ce-${ext2Name}`]);
}); }));
});
it("should 'ce-subject' have the right value", () => { it("should 'ce-subject' have the right value",
return binary.emit(cloudevent) () => binary.emit(cloudevent)
.then((response) => { .then((response) => {
expect(cloudevent.getSubject()) expect(cloudevent.getSubject())
.to.equal(response.config.headers["ce-subject"]); .to.equal(response.config.headers["ce-subject"]);
}); }));
});
}); });
}); });
}); });

View File

@ -1,19 +1,18 @@
const expect = require("chai").expect; const expect = require("chai").expect;
const Spec03 = require("../lib/specs/spec_0_3.js"); const Spec03 = require("../lib/specs/spec_0_3.js");
const Cloudevent = require("../index.js"); const Cloudevent = require("../index.js");
const uuid = require("uuid/v4"); const uuid = require("uuid/v4");
const id = uuid(); const id = uuid();
const type = "com.github.pull.create"; const type = "com.github.pull.create";
const source = "urn:event:from:myapi/resourse/123"; const source = "urn:event:from:myapi/resourse/123";
const time = new Date(); const time = new Date();
const schemaurl = "http://example.com/registry/myschema.json"; const schemaurl = "http://example.com/registry/myschema.json";
const dataContentEncoding = "base64"; const dataContentEncoding = "base64";
const dataContentType = "application/json"; const dataContentType = "application/json";
const data = { const data = {
much : "wow" much: "wow"
}; };
const extensions = {};
const subject = "subject-x0"; const subject = "subject-x0";
var cloudevent = var cloudevent =
@ -28,7 +27,6 @@ var cloudevent =
.data(data); .data(data);
describe("CloudEvents Spec v0.3", () => { describe("CloudEvents Spec v0.3", () => {
describe("REQUIRED Attributes", () => { describe("REQUIRED Attributes", () => {
it("Should have 'id'", () => { it("Should have 'id'", () => {
expect(cloudevent.getId()).to.equal(id); expect(cloudevent.getId()).to.equal(id);
@ -83,7 +81,7 @@ describe("CloudEvents Spec v0.3", () => {
it("Should have the 'extension1'", () => { it("Should have the 'extension1'", () => {
cloudevent.addExtension("extension1", "value1"); cloudevent.addExtension("extension1", "value1");
expect(cloudevent.spec.payload["extension1"]) expect(cloudevent.spec.payload.extension1)
.to.equal("value1"); .to.equal("value1");
}); });
@ -96,11 +94,11 @@ describe("CloudEvents Spec v0.3", () => {
describe("The Constraints check", () => { describe("The Constraints check", () => {
describe("'id'", () => { describe("'id'", () => {
it("should throw an error when is absent", () => { it("should throw an error when is absent", () => {
delete cloudevent.spec.payload.id; delete cloudevent.spec.payload.id;
expect(cloudevent.format.bind(cloudevent)) expect(cloudevent.format.bind(cloudevent))
.to .to
.throw("invalid payload"); .throw("invalid payload");
cloudevent.spec.payload.id = id; cloudevent.spec.payload.id = id;
}); });
it("should throw an erro when is empty", () => { it("should throw an erro when is empty", () => {
@ -114,21 +112,21 @@ describe("CloudEvents Spec v0.3", () => {
describe("'source'", () => { describe("'source'", () => {
it("should throw an error when is absent", () => { it("should throw an error when is absent", () => {
delete cloudevent.spec.payload.source; delete cloudevent.spec.payload.source;
expect(cloudevent.format.bind(cloudevent)) expect(cloudevent.format.bind(cloudevent))
.to .to
.throw("invalid payload"); .throw("invalid payload");
cloudevent.spec.payload.source = source; cloudevent.spec.payload.source = source;
}); });
}); });
describe("'specversion'", () => { describe("'specversion'", () => {
it("should throw an error when is absent", () => { it("should throw an error when is absent", () => {
delete cloudevent.spec.payload.specversion; delete cloudevent.spec.payload.specversion;
expect(cloudevent.format.bind(cloudevent)) expect(cloudevent.format.bind(cloudevent))
.to .to
.throw("invalid payload"); .throw("invalid payload");
cloudevent.spec.payload.specversion = "0.3"; cloudevent.spec.payload.specversion = "0.3";
}); });
it("should throw an error when is empty", () => { it("should throw an error when is empty", () => {
@ -142,11 +140,11 @@ describe("CloudEvents Spec v0.3", () => {
describe("'type'", () => { describe("'type'", () => {
it("should throw an error when is absent", () => { it("should throw an error when is absent", () => {
delete cloudevent.spec.payload.type; delete cloudevent.spec.payload.type;
expect(cloudevent.format.bind(cloudevent)) expect(cloudevent.format.bind(cloudevent))
.to .to
.throw("invalid payload"); .throw("invalid payload");
cloudevent.spec.payload.type = type; cloudevent.spec.payload.type = type;
}); });
it("should throw an error when is an empty string", () => { it("should throw an error when is an empty string", () => {
@ -164,7 +162,7 @@ describe("CloudEvents Spec v0.3", () => {
}); });
describe("'datacontentencoding'", () => { describe("'datacontentencoding'", () => {
it("should throw an error when is a unsupported encoding" , () => { it("should throw an error when is a unsupported encoding", () => {
cloudevent cloudevent
.data("Y2xvdWRldmVudHMK") .data("Y2xvdWRldmVudHMK")
.dataContentEncoding("binary"); .dataContentEncoding("binary");
@ -177,19 +175,18 @@ describe("CloudEvents Spec v0.3", () => {
it("should throw an error when 'data' does not carry base64", it("should throw an error when 'data' does not carry base64",
() => { () => {
cloudevent
.data("no base 64 value")
.dataContentEncoding("base64")
.dataContentType("text/plain");
cloudevent expect(cloudevent.format.bind(cloudevent))
.data("no base 64 value") .to
.dataContentEncoding("base64") .throw("invalid payload");
.dataContentType("text/plain");
expect(cloudevent.format.bind(cloudevent)) delete cloudevent.spec.payload.datacontentencoding;
.to cloudevent.data(data);
.throw("invalid payload"); });
delete cloudevent.spec.payload.datacontentencoding;
cloudevent.data(data);
});
it("should accept when 'data' is a string", () => { it("should accept when 'data' is a string", () => {
cloudevent cloudevent
@ -202,7 +199,7 @@ describe("CloudEvents Spec v0.3", () => {
}); });
describe("'data'", () => { describe("'data'", () => {
it("should maintain the type of data when no data content type", () =>{ it("should maintain the type of data when no data content type", () => {
delete cloudevent.spec.payload.datacontenttype; delete cloudevent.spec.payload.datacontenttype;
cloudevent cloudevent
.data(JSON.stringify(data)); .data(JSON.stringify(data));
@ -232,9 +229,8 @@ describe("CloudEvents Spec v0.3", () => {
describe("'time'", () => { describe("'time'", () => {
it("must adhere to the format specified in RFC 3339", () => { it("must adhere to the format specified in RFC 3339", () => {
cloudevent.time(time); cloudevent.time(time);
expect(cloudevent.format()["time"]).to.equal(time.toISOString()); expect(cloudevent.format().time).to.equal(time.toISOString());
}); });
}); });
}); });
}); });

View File

@ -1,19 +1,18 @@
const expect = require("chai").expect; const expect = require("chai").expect;
const Spec1 = require("../lib/specs/spec_1.js"); const Spec1 = require("../lib/specs/spec_1.js");
const Cloudevent = require("../index.js"); const Cloudevent = require("../index.js");
const uuid = require("uuid/v4"); const uuid = require("uuid/v4");
const {asBase64} = require("../lib/utils/fun.js"); const { asBase64 } = require("../lib/utils/fun.js");
const id = uuid(); const id = uuid();
const type = "com.github.pull.create"; const type = "com.github.pull.create";
const source = "urn:event:from:myapi/resourse/123"; const source = "urn:event:from:myapi/resourse/123";
const time = new Date(); const time = new Date();
const dataschema = "http://example.com/registry/myschema.json"; const dataschema = "http://example.com/registry/myschema.json";
const dataContentType = "application/json"; const dataContentType = "application/json";
const data = { const data = {
much : "wow" much: "wow"
}; };
const extensions = {};
const subject = "subject-x0"; const subject = "subject-x0";
const cloudevent = const cloudevent =
@ -78,13 +77,13 @@ describe("CloudEvents Spec v1.0", () => {
}); });
it("should be ok when type is 'string'", () => { it("should be ok when type is 'string'", () => {
cloudevent.addExtension("ext-string", 'an-string'); cloudevent.addExtension("ext-string", "an-string");
expect(cloudevent.spec.payload["ext-string"]) expect(cloudevent.spec.payload["ext-string"])
.to.equal("an-string"); .to.equal("an-string");
}); });
it("should be ok when type is 'Uint32Array' for 'Binary'", () => { it("should be ok when type is 'Uint32Array' for 'Binary'", () => {
let myBinary = new Uint32Array(2019); const myBinary = new Uint32Array(2019);
cloudevent.addExtension("ext-binary", myBinary); cloudevent.addExtension("ext-binary", myBinary);
expect(cloudevent.spec.payload["ext-binary"]) expect(cloudevent.spec.payload["ext-binary"])
.to.equal(myBinary); .to.equal(myBinary);
@ -93,7 +92,7 @@ describe("CloudEvents Spec v1.0", () => {
// URI // URI
it("should be ok when type is 'Date' for 'Timestamp'", () => { it("should be ok when type is 'Date' for 'Timestamp'", () => {
let myDate = new Date(); const myDate = new Date();
cloudevent.addExtension("ext-date", myDate); cloudevent.addExtension("ext-date", myDate);
expect(cloudevent.spec.payload["ext-date"]) expect(cloudevent.spec.payload["ext-date"])
.to.equal(myDate); .to.equal(myDate);
@ -101,7 +100,7 @@ describe("CloudEvents Spec v1.0", () => {
it("Should have the 'extension1'", () => { it("Should have the 'extension1'", () => {
cloudevent.addExtension("extension1", "value1"); cloudevent.addExtension("extension1", "value1");
expect(cloudevent.spec.payload["extension1"]) expect(cloudevent.spec.payload.extension1)
.to.equal("value1"); .to.equal("value1");
}); });
@ -111,7 +110,8 @@ describe("CloudEvents Spec v1.0", () => {
}); });
it("should throw an error when use an invalid type", () => { it("should throw an error when use an invalid type", () => {
expect(cloudevent.addExtension.bind(cloudevent, "invalid-val", {cool:'nice'})) expect(cloudevent
.addExtension.bind(cloudevent, "invalid-val", { cool: "nice" }))
.to.throw("Invalid type of extension value"); .to.throw("Invalid type of extension value");
}); });
}); });
@ -119,11 +119,11 @@ describe("CloudEvents Spec v1.0", () => {
describe("The Constraints check", () => { describe("The Constraints check", () => {
describe("'id'", () => { describe("'id'", () => {
it("should throw an error when is absent", () => { it("should throw an error when is absent", () => {
delete cloudevent.spec.payload.id; delete cloudevent.spec.payload.id;
expect(cloudevent.format.bind(cloudevent)) expect(cloudevent.format.bind(cloudevent))
.to .to
.throw("invalid payload"); .throw("invalid payload");
cloudevent.spec.payload.id = id; cloudevent.spec.payload.id = id;
}); });
it("should throw an erro when is empty", () => { it("should throw an erro when is empty", () => {
@ -137,21 +137,21 @@ describe("CloudEvents Spec v1.0", () => {
describe("'source'", () => { describe("'source'", () => {
it("should throw an error when is absent", () => { it("should throw an error when is absent", () => {
delete cloudevent.spec.payload.source; delete cloudevent.spec.payload.source;
expect(cloudevent.format.bind(cloudevent)) expect(cloudevent.format.bind(cloudevent))
.to .to
.throw("invalid payload"); .throw("invalid payload");
cloudevent.spec.payload.source = source; cloudevent.spec.payload.source = source;
}); });
}); });
describe("'specversion'", () => { describe("'specversion'", () => {
it("should throw an error when is absent", () => { it("should throw an error when is absent", () => {
delete cloudevent.spec.payload.specversion; delete cloudevent.spec.payload.specversion;
expect(cloudevent.format.bind(cloudevent)) expect(cloudevent.format.bind(cloudevent))
.to .to
.throw("invalid payload"); .throw("invalid payload");
cloudevent.spec.payload.specversion = "1.0"; cloudevent.spec.payload.specversion = "1.0";
}); });
it("should throw an error when is empty", () => { it("should throw an error when is empty", () => {
@ -165,11 +165,11 @@ describe("CloudEvents Spec v1.0", () => {
describe("'type'", () => { describe("'type'", () => {
it("should throw an error when is absent", () => { it("should throw an error when is absent", () => {
delete cloudevent.spec.payload.type; delete cloudevent.spec.payload.type;
expect(cloudevent.format.bind(cloudevent)) expect(cloudevent.format.bind(cloudevent))
.to .to
.throw("invalid payload"); .throw("invalid payload");
cloudevent.spec.payload.type = type; cloudevent.spec.payload.type = type;
}); });
it("should throw an error when is an empty string", () => { it("should throw an error when is an empty string", () => {
@ -199,7 +199,7 @@ describe("CloudEvents Spec v1.0", () => {
describe("'time'", () => { describe("'time'", () => {
it("must adhere to the format specified in RFC 3339", () => { it("must adhere to the format specified in RFC 3339", () => {
cloudevent.time(time); cloudevent.time(time);
expect(cloudevent.format()["time"]).to.equal(time.toISOString()); expect(cloudevent.format().time).to.equal(time.toISOString());
}); });
}); });
}); });
@ -209,7 +209,7 @@ describe("CloudEvents Spec v1.0", () => {
expect(cloudevent.getData()).to.deep.equal(data); expect(cloudevent.getData()).to.deep.equal(data);
}); });
it("should maintain the type of data when no data content type", () =>{ it("should maintain the type of data when no data content type", () => {
delete cloudevent.spec.payload.datacontenttype; delete cloudevent.spec.payload.datacontenttype;
cloudevent cloudevent
.data(JSON.stringify(data)); .data(JSON.stringify(data));
@ -226,11 +226,11 @@ describe("CloudEvents Spec v1.0", () => {
}); });
it("should be ok when type is 'Uint32Array' for 'Binary'", () => { it("should be ok when type is 'Uint32Array' for 'Binary'", () => {
let dataString = ")(*~^my data for ce#@#$%" const dataString = ")(*~^my data for ce#@#$%";
let dataBinary = Uint32Array.from(dataString, (c) => c.codePointAt(0)); const dataBinary = Uint32Array.from(dataString, (c) => c.codePointAt(0));
let expected = asBase64(dataBinary); const expected = asBase64(dataBinary);
let olddct = cloudevent.getDataContentType(); const olddct = cloudevent.getDataContentType();
cloudevent cloudevent
.dataContentType("text/plain") .dataContentType("text/plain")

View File

@ -2,7 +2,7 @@ const Cloudevent = require("../lib/cloudevent.js");
const Spec = require("../lib/specs/spec_0_2.js"); const Spec = require("../lib/specs/spec_0_2.js");
const StructuredHTTPEmitter = const StructuredHTTPEmitter =
require("../lib/bindings/http/emitter_structured_0_2.js"); require("../lib/bindings/http/emitter_structured_0_2.js");
const {HTTPBinary02} = require("../lib/bindings/http/emitter_binary_0_2.js"); const { HTTPBinary02 } = require("../lib/bindings/http/emitter_binary_0_2.js");
const StructuredHTTPReceiver = const StructuredHTTPReceiver =
require("../lib/bindings/http/receiver_structured_0_2.js"); require("../lib/bindings/http/receiver_structured_0_2.js");
const BinaryHTTPReceiver = const BinaryHTTPReceiver =
@ -18,7 +18,7 @@ module.exports = {
Spec, Spec,
StructuredHTTPEmitter, StructuredHTTPEmitter,
StructuredHTTPReceiver, StructuredHTTPReceiver,
BinaryHTTPEmitter : HTTPBinary02, BinaryHTTPEmitter: HTTPBinary02,
BinaryHTTPReceiver, BinaryHTTPReceiver,
HTTPUnmarshaller, HTTPUnmarshaller,
event event