From 16d9bfb7e3d4c966f61a8342d69d4eed813ded02 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fabio=20Jos=C3=A9?= Date: Mon, 4 Nov 2019 13:15:35 -0300 Subject: [PATCH] asData improvement MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit asBuffer to transform UintArray to node Buffer Signed-off-by: Fabio José --- lib/utils/fun.js | 36 +++++++++++++++++++++++++++++------- 1 file changed, 29 insertions(+), 7 deletions(-) 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 };