diff --git a/lib/bindings/http/unmarshaller_0_2.js b/lib/bindings/http/unmarshaller_0_2.js index d16b60c..90ed60d 100644 --- a/lib/bindings/http/unmarshaller_0_2.js +++ b/lib/bindings/http/unmarshaller_0_2.js @@ -1,84 +1,19 @@ +const GenericUnmarshaller = require("./unmarshaller.js"); + var StructuredReceiver = require("./receiver_structured_0_2.js"); var BinaryReceiver = require("./receiver_binary_0_2.js"); -const Constants = require("./constants.js"); -const Commons = require("./commons.js"); - -const structured = "structured"; -const binary = "binary"; - -const receiverByBinding = { +const RECEIVER_BY_BINDING = { structured : new StructuredReceiver(), binary : new BinaryReceiver(), }; -const allowedBinaryContentTypes = []; -allowedBinaryContentTypes.push(Constants.MIME_JSON); -allowedBinaryContentTypes.push(Constants.MIME_OCTET_STREAM); - -const allowedStructuredContentTypes = []; -allowedStructuredContentTypes.push(Constants.MIME_CE_JSON); - -function validateArgs(payload, headers) { - if(!payload){ - throw {message: "payload is null or undefined"}; - } - - if(!headers){ - throw {message: "headers is null or undefined"}; - } -} - -// Is it binary or structured? -function resolveBindingName(payload, headers) { - - var contentType = - Commons.sanityContentType(headers[Constants.HEADER_CONTENT_TYPE]); - - if(contentType.startsWith(Constants.MIME_CE)){ - // Structured - if(allowedStructuredContentTypes.includes(contentType)){ - return structured; - } else { - throw {message: "structured+type not allowed", errors: [contentType]}; - } - } else { - // Binary - if(allowedBinaryContentTypes.includes(contentType)){ - return binary; - } else { - throw {message: "content type not allowed", errors : [contentType]}; - } - } -} - var Unmarshaller = function() { - + this.unmarshaller = new GenericUnmarshaller(RECEIVER_BY_BINDING); }; Unmarshaller.prototype.unmarshall = function(payload, headers) { - return new Promise((resolve, reject) => { - try { - validateArgs(payload, headers); - - var sanityHeaders = Commons.sanityAndClone(headers); - - // Validation level 1 - if(!sanityHeaders[Constants.HEADER_CONTENT_TYPE]){ - throw {message: "content-type header not found"}; - } - - // Resolve the binding - var bindingName = resolveBindingName(payload, sanityHeaders); - - var cloudevent = - receiverByBinding[bindingName].parse(payload, sanityHeaders); - - resolve(cloudevent); - }catch(e){ - reject(e); - } - }); + return this.unmarshaller.unmarshall(payload, headers); }; module.exports = Unmarshaller;