diff --git a/package-lock.json b/package-lock.json index 75cd7dc..56f3ac8 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "nodegate", - "version": "2.0.0", + "version": "2.0.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "nodegate", - "version": "2.0.0", + "version": "2.0.1", "license": "MIT", "dependencies": { "body-parser": "~2.2.0", diff --git a/package.json b/package.json index 632e144..f45918e 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "nodegate", "description": "API gateway made simple, fast and easy to configure.", - "version": "2.0.0", + "version": "2.0.1", "author": "Julien Martin ", "license": "MIT", "scripts": { diff --git a/test/workers/aggregate.test.js b/test/workers/aggregate.test.js index ce7b1cd..40227c3 100644 --- a/test/workers/aggregate.test.js +++ b/test/workers/aggregate.test.js @@ -458,5 +458,42 @@ describe('workers/aggregate', () => { await aggregate('post', 'https://wiki.federation.com/armaments')(container); expect(container.body.phasers).toBe(16); }); + it('forces text parsing as json when the container headers is application/json', async () => { + const container = { + ...getEmpty(), + headers: { + 'content-type': 'application/json', + }, + }; + fetchMock.mockGlobal().postOnce('https://wiki.federation.com/armaments', { + status: 200, + body: '{ "phasers": 16 }', + headers: { + 'Content-Type': 'text/plain;charset=UTF-8', + }, + }); + await aggregate('post', 'https://wiki.federation.com/armaments')(container); + expect(container.body.phasers).toBe(16); + }); + it('should throw an error when the parsing failed', async () => { + const container = { + ...getEmpty(), + headers: { + 'content-type': 'application/json', + }, + }; + fetchMock.mockGlobal().postOnce('https://wiki.federation.com/armaments', { + status: 200, + body: '{ "badJSON: true }', + headers: { + 'Content-Type': 'text/plain;charset=UTF-8', + }, + }); + try { + await aggregate('post', 'https://wiki.federation.com/armaments')(container); + } catch (err) { + expect(err.message).toEqual('SyntaxError: Unterminated string in JSON at position 18'); + } + }); }); }); diff --git a/workers/aggregate.js b/workers/aggregate.js index 7374000..04c0dbe 100644 --- a/workers/aggregate.js +++ b/workers/aggregate.js @@ -44,7 +44,11 @@ module.exports = (method, url, options = {}) => { container.statusCode = response.status; if (response.headers.get('content-type') && !isJsonContentType(response.headers.get('content-type'))) { const text = await response.text(); - setBodyToContainer(text, container, options); + setBodyToContainer( + container.headers['content-type'] === 'application/json' ? JSON.parse(text) : text, + container, + options, + ); if (!response.ok) { throw new WorkflowError('Fetch error', { text, statusCode: response.status }); }