Skip to content

Commit 588a0aa

Browse files
committed
Function for data parsing based on the data content type
Signed-off-by: Fabio José <[email protected]>
1 parent 1766647 commit 588a0aa

File tree

2 files changed

+76
-1
lines changed

2 files changed

+76
-1
lines changed

lib/utils/fun.js

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,16 @@ const isBase64 = (value) =>
3131
const clone = (o) =>
3232
JSON.parse(JSON.stringify(o));
3333

34+
const isJsonContentType = (contentType) =>
35+
contentType && contentType.match(/(json)/i);
36+
37+
const asData = (data, contentType) =>
38+
((typeof data) !== "string"
39+
? data
40+
: isJsonContentType(contentType)
41+
? JSON.parse(data)
42+
: data);
43+
3444
module.exports = {
3545
isString,
3646
isStringOrThrow,
@@ -42,5 +52,7 @@ module.exports = {
4252

4353
equalsOrThrow,
4454
isBase64,
45-
clone
55+
clone,
56+
57+
asData
4658
};

test/fun_tests.js

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,4 +43,67 @@ describe("Functional approach", () => {
4343
expect(actual).to.equal(true);
4444
});
4545
});
46+
47+
describe("asData" , () => {
48+
it("should throw error when data is not a valid json", () => {
49+
let data = "not a json";
50+
51+
expect(fun.asData.bind(fun, data, "application/json"))
52+
.to
53+
.throws();
54+
});
55+
56+
it("should parse string content type as string", () => {
57+
let expected = "a string";
58+
59+
let actual = fun.asData(expected, "text/plain");
60+
61+
expect((typeof actual)).to.equal("string");
62+
expect(actual).to.equal(expected);
63+
});
64+
65+
it("should parse 'application/json' as json object", () => {
66+
let expected = {
67+
much: "wow",
68+
myext : {
69+
ext : "x04"
70+
}
71+
};
72+
73+
let actual = fun.asData(JSON.stringify(expected), "application/json");
74+
75+
expect((typeof actual)).to.equal("object");
76+
expect(actual).to.deep.equal(expected);
77+
});
78+
79+
it("should parse 'application/cloudevents+json' as json object", () => {
80+
let expected = {
81+
much: "wow",
82+
myext : {
83+
ext : "x04"
84+
}
85+
};
86+
87+
let actual = fun.asData(JSON.stringify(expected),
88+
"application/cloudevents+json");
89+
90+
expect((typeof actual)).to.equal("object");
91+
expect(actual).to.deep.equal(expected);
92+
});
93+
94+
it("should parse 'text/json' as json object", () => {
95+
let expected = {
96+
much: "wow",
97+
myext : {
98+
ext : "x04"
99+
}
100+
};
101+
102+
let actual = fun.asData(JSON.stringify(expected),
103+
"text/json");
104+
105+
expect((typeof actual)).to.equal("object");
106+
expect(actual).to.deep.equal(expected);
107+
});
108+
});
46109
});

0 commit comments

Comments
 (0)