Functions: isValidOrThrow, isDefinedOrThrow

Signed-off-by: Fabio José <fabiojose@gmail.com>
This commit is contained in:
Fabio José 2019-07-23 08:57:58 -03:00
parent 8469e04a98
commit cb5f0e377e
2 changed files with 21 additions and 18 deletions

View File

@ -1,7 +1,7 @@
const {
isString,
isObject,
isDefined
isDefinedOrThrow,
isValidOrThrow
} = require("../../utils/fun.js");
function JSONParser() {
@ -14,20 +14,7 @@ const invalidPayloadTypeError =
const nullOrIndefinedPayload =
new Error("null or undefined payload");
// Functions
const isDefinedOrThrow = (v) =>
(isDefined(v)
? () => true
: (() => {throw nullOrIndefinedPayload})());
const isValidPayloadOrThrow = (v) =>
isDefinedOrThrow(v)()
&& (isString(v)
? true
: isObject(v)
? true
: (() => {throw invalidPayloadTypeError})());
// Function
const asJSON = (v) => (isString(v) ? JSON.parse(v) : v);
/**
@ -37,7 +24,8 @@ function validateAndParse(payload) {
var json =
Array.of(payload)
.filter(isValidPayloadOrThrow)
.filter(p => isDefinedOrThrow(p, nullOrIndefinedPayload))
.filter(p => isValidOrThrow(p, invalidPayloadTypeError))
.map(asJSON)
.shift();

View File

@ -3,8 +3,23 @@ const isString = (v) => (typeof v) === "string";
const isObject = (v) => (typeof v) === "object";
const isDefined = (v) => v && (typeof v) != "undefined";
const isDefinedOrThrow = (v, t) =>
(isDefined(v)
? () => true
: (() => {throw t})());
const isValidOrThrow = (v, t) =>
(isString(v)
? true
: isObject(v)
? true
: (() => {throw t})());
module.exports = {
isString : isString,
isObject : isObject,
isDefined : isDefined
isDefined : isDefined,
isDefinedOrThrow : isDefinedOrThrow,
isValidOrThrow : isValidOrThrow
};