Skip to content

Commit 16d9bfb

Browse files
committed
asData improvement
asBuffer to transform UintArray to node Buffer Signed-off-by: Fabio José <[email protected]>
1 parent 8b39902 commit 16d9bfb

File tree

1 file changed

+29
-7
lines changed

1 file changed

+29
-7
lines changed

lib/utils/fun.js

Lines changed: 29 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -33,18 +33,39 @@ const equalsOrThrow = (v1, v2, t) =>
3333
const isBase64 = (value) =>
3434
Buffer.from(value, "base64").toString("base64") === value;
3535

36+
const isBuffer = (value) =>
37+
value instanceof Buffer;
38+
39+
const asBuffer = (value) =>
40+
isBinary(value)
41+
? Buffer.from(value)
42+
: isBuffer(value)
43+
? value
44+
: (() => {throw {message: "is not buffer or a valid binary"}})();
45+
46+
const asBase64 = (value) =>
47+
asBuffer(value).toString("base64");
48+
3649
const clone = (o) =>
3750
JSON.parse(JSON.stringify(o));
3851

3952
const isJsonContentType = (contentType) =>
4053
contentType && contentType.match(/(json)/i);
4154

42-
const asData = (data, contentType) =>
43-
((typeof data) !== "string"
44-
? data
45-
: isJsonContentType(contentType)
46-
? JSON.parse(data)
47-
: data);
55+
const asData = (data, contentType) => {
56+
let result = data;
57+
58+
// pattern matching alike
59+
result = isString(result) && isJsonContentType(contentType)
60+
? JSON.parse(result)
61+
: result;
62+
63+
result = isBinary(result)
64+
? asBase64(result)
65+
: result;
66+
67+
return result;
68+
}
4869

4970
module.exports = {
5071
isString,
@@ -64,5 +85,6 @@ module.exports = {
6485
isBase64,
6586
clone,
6687

67-
asData
88+
asData,
89+
asBase64
6890
};

0 commit comments

Comments
 (0)