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

View File

@ -3,8 +3,23 @@ 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 isDefinedOrThrow = (v, t) =>
(isDefined(v)
? () => true
: (() => {throw t})());
const isValidOrThrow = (v, t) =>
(isString(v)
? true
: isObject(v)
? true
: (() => {throw t})());
module.exports = { module.exports = {
isString : isString, isString : isString,
isObject : isObject, isObject : isObject,
isDefined : isDefined isDefined : isDefined,
isDefinedOrThrow : isDefinedOrThrow,
isValidOrThrow : isValidOrThrow
}; };