From cd6decd74904888557bfc53045c87efe630fb88c Mon Sep 17 00:00:00 2001 From: Grant Timmerman Date: Thu, 30 Apr 2020 15:32:37 -0700 Subject: [PATCH] chore: es6 parser (#98) Signed-off-by: Grant Timmerman --- lib/formats/json/parser.js | 43 ++++++++++++++++---------------------- 1 file changed, 18 insertions(+), 25 deletions(-) diff --git a/lib/formats/json/parser.js b/lib/formats/json/parser.js index a410833..4f8bf41 100644 --- a/lib/formats/json/parser.js +++ b/lib/formats/json/parser.js @@ -4,42 +4,35 @@ const { isStringOrObjectOrThrow } = require("../../utils/fun.js"); -function JSONParser(decorator) { - this.decorator = decorator; -} - const invalidPayloadTypeError = new Error("invalid payload type, allowed are: string or object"); - const nullOrIndefinedPayload = new Error("null or undefined payload"); -// Function const asJSON = (v) => (isString(v) ? JSON.parse(v) : v); -// Level 0 of validation: is that string? is that JSON? -function validateAndParse(payload) { - const json = - Array.of(payload) +class JSONParser { + constructor(decorator) { + this.decorator = decorator; + } + + /** + * Parses the payload with an optional decorator + * @param {object|string} payload the JSON payload + * @return {object} the parsed JSON payload. + */ + parse(payload) { + if (this.decorator) { + payload = this.decorator.parse(payload); + } + + return Array.of(payload) + .filter((p) => isDefinedOrThrow(p, nullOrIndefinedPayload)) .filter((p) => isStringOrObjectOrThrow(p, invalidPayloadTypeError)) .map(asJSON) .shift(); - - return json; + } } -JSONParser.prototype.parse = function(payload) { - let toparse = payload; - - if (this.decorator) { - toparse = this.decorator.parse(payload); - } - - // is that string? is that JSON? - const valid = validateAndParse(toparse); - - return valid; -}; - module.exports = JSONParser;