asData improvement

asBuffer to transform UintArray to node Buffer

Signed-off-by: Fabio José <fabiojose@gmail.com>
This commit is contained in:
Fabio José 2019-11-04 13:15:35 -03:00
parent 8b39902910
commit 16d9bfb7e3
1 changed files with 29 additions and 7 deletions

View File

@ -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
};