diff --git a/src/helpers.js b/src/helpers.js index f5b6f384..6ac00d2c 100644 --- a/src/helpers.js +++ b/src/helpers.js @@ -88,7 +88,7 @@ function ensureCharacterEncoding(response, defaultEncoding = "UTF-8") { if (!contentTypeHeader) { contentTypeHeader = "Content-Type"; - response[contentTypeHeader] ||= "application/json; charset=UTF-8"; + response.headers[contentTypeHeader] ||= "application/json; charset=UTF-8"; } const value = parseHeader(response.headers[contentTypeHeader]); diff --git a/test/unit/api/helpers.test.js b/test/unit/api/helpers.test.js index 15bac641..b4009369 100644 --- a/test/unit/api/helpers.test.js +++ b/test/unit/api/helpers.test.js @@ -11,6 +11,7 @@ const { baseUrl, decodeEventBody, decodeToken, + ensureCharacterEncoding, isFromReadingRoom, maybeUseProxiedIp, normalizeHeaders, @@ -403,4 +404,35 @@ describe("helpers", () => { expect(result.queryStringParameters).to.eql({}); }); }); + + describe("ensureCharacterEncoding", () => { + const response = { statusCode: 200, body: "Hello, World!" }; + + it("passes through an existing character set", () => { + const result = ensureCharacterEncoding({ + ...response, + headers: { "Content-Type": "text/plain; charset=ISO-8859-1" }, + }); + expect(result.headers["Content-Type"]).to.eql( + "text/plain; charset=ISO-8859-1" + ); + }); + + it("adds character set if it's missing", () => { + const result = ensureCharacterEncoding({ + ...response, + headers: { "Content-Type": "text/plain" }, + }); + expect(result.headers["Content-Type"]).to.eql( + "text/plain; charset=UTF-8" + ); + }); + + it("adds content type if it's missing", () => { + const result = ensureCharacterEncoding({ ...response, headers: {} }); + expect(result.headers["Content-Type"]).to.eql( + "application/json; charset=UTF-8" + ); + }); + }); });