Removing the cyclomatic complexity

Signed-off-by: Fabio José <fabiojose@gmail.com>
This commit is contained in:
Fabio José 2019-07-17 11:27:54 -03:00
parent 789c4adf6d
commit f5e0ce6a84
2 changed files with 30 additions and 18 deletions

View File

@ -2,28 +2,40 @@ function JSONParser() {
}
const invalidPayloadTypeError =
new Error("invalid payload type, allowed are: string or object");
const nullOrIndefinedPayload =
new Error("null or undefined payload");
// Functions
const isString = (v) => (typeof v) === "string";
const isObject = (v) => (typeof v) === "object";
const isDefined = (v) => v && (typeof v) != "undefined";
const isDefinedOrThrow = (v) =>
(isDefined(v) ? () => true
: (() => {throw nullOrIndefinedPayload})());
const isValidPayloadOrThrow = (v) =>
isDefinedOrThrow(v)()
&& (isString(v)
? true
: isObject(v)
? true
: (() => {throw invalidPayloadTypeError})());
const asJSON = (v) => (isString(v) ? JSON.parse(v) : v);
/**
* Level 0 of validation: is that string? is that JSON?
*/
function validateAndParse(payload) {
var json = payload;
if(payload) {
if( (typeof payload) == "string"){
try {
json = JSON.parse(payload);
}catch(e) {
throw {message: "invalid json payload", errors: e};
}
} else if( (typeof payload) != "object"){
// anything else
throw {message: "invalid payload type, allowed are: string or object"};
}
} else {
throw {message: "null or undefined payload"};
}
var json =
Array.of(payload)
.filter(isValidPayloadOrThrow)
.map(asJSON)
.shift();
return json;
}

View File

@ -63,7 +63,7 @@ describe("JSON Event Format Parser", () => {
// act and assert
expect(parser.parse.bind(parser, payload))
.to.throw("invalid json payload");
.to.throw("Unexpected token g in JSON at position 0");
});
it("Must accept the CloudEvent spec 0.2 as JSON", () => {