diff --git a/lib/utils/fun.js b/lib/utils/fun.js index e7599db..dfba22a 100644 --- a/lib/utils/fun.js +++ b/lib/utils/fun.js @@ -31,6 +31,16 @@ const isBase64 = (value) => 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); + module.exports = { isString, isStringOrThrow, @@ -42,5 +52,7 @@ module.exports = { equalsOrThrow, isBase64, - clone + clone, + + asData }; diff --git a/test/fun_tests.js b/test/fun_tests.js index d3700f0..8f66cad 100644 --- a/test/fun_tests.js +++ b/test/fun_tests.js @@ -43,4 +43,67 @@ describe("Functional approach", () => { expect(actual).to.equal(true); }); }); + + describe("asData" , () => { + it("should throw error when data is not a valid json", () => { + let data = "not a json"; + + expect(fun.asData.bind(fun, data, "application/json")) + .to + .throws(); + }); + + it("should parse string content type as string", () => { + let expected = "a string"; + + let actual = fun.asData(expected, "text/plain"); + + expect((typeof actual)).to.equal("string"); + expect(actual).to.equal(expected); + }); + + it("should parse 'application/json' as json object", () => { + let expected = { + much: "wow", + myext : { + ext : "x04" + } + }; + + let actual = fun.asData(JSON.stringify(expected), "application/json"); + + expect((typeof actual)).to.equal("object"); + expect(actual).to.deep.equal(expected); + }); + + it("should parse 'application/cloudevents+json' as json object", () => { + let expected = { + much: "wow", + myext : { + ext : "x04" + } + }; + + let actual = fun.asData(JSON.stringify(expected), + "application/cloudevents+json"); + + expect((typeof actual)).to.equal("object"); + expect(actual).to.deep.equal(expected); + }); + + it("should parse 'text/json' as json object", () => { + let expected = { + much: "wow", + myext : { + ext : "x04" + } + }; + + let actual = fun.asData(JSON.stringify(expected), + "text/json"); + + expect((typeof actual)).to.equal("object"); + expect(actual).to.deep.equal(expected); + }); + }); });