diff --git a/lib/utils/fun.js b/lib/utils/fun.js index 884ed11..573eda8 100644 --- a/lib/utils/fun.js +++ b/lib/utils/fun.js @@ -33,18 +33,39 @@ const equalsOrThrow = (v1, v2, t) => const isBase64 = (value) => Buffer.from(value, "base64").toString("base64") === value; +const isBuffer = (value) => + value instanceof Buffer; + +const asBuffer = (value) => + isBinary(value) + ? Buffer.from(value) + : isBuffer(value) + ? value + : (() => {throw {message: "is not buffer or a valid binary"}})(); + +const asBase64 = (value) => + asBuffer(value).toString("base64"); + const clone = (o) => JSON.parse(JSON.stringify(o)); const isJsonContentType = (contentType) => contentType && contentType.match(/(json)/i); -const asData = (data, contentType) => - ((typeof data) !== "string" - ? data - : isJsonContentType(contentType) - ? JSON.parse(data) - : data); +const asData = (data, contentType) => { + let result = data; + + // pattern matching alike + result = isString(result) && isJsonContentType(contentType) + ? JSON.parse(result) + : result; + + result = isBinary(result) + ? asBase64(result) + : result; + + return result; +} module.exports = { isString, @@ -64,5 +85,6 @@ module.exports = { isBase64, clone, - asData + asData, + asBase64 };