diff --git a/src/index.ts b/src/index.ts index cb13b8d..6d9ffa0 100644 --- a/src/index.ts +++ b/src/index.ts @@ -35,7 +35,7 @@ const rewriteResRaw = (res: Response) => { if (isJsonContent && body instanceof Buffer) { try { const bodyJson = JSON.parse(body.toString('utf8')); - if (bodyJson.data) { + if (bodyJson && bodyJson.data) { const newResponseData = rewriteHandler.rewriteResponse(bodyJson.data); const newResBodyJson = { ...bodyJson, data: newResponseData }; // assume this was pretty-printed if we're here and not in the res.json handler diff --git a/test/index.test.ts b/test/index.test.ts index 66a8969..b724e3a 100644 --- a/test/index.test.ts +++ b/test/index.test.ts @@ -363,7 +363,7 @@ describe('middleware test', () => { expect(invalidQueryRes.body.data).toEqual({ random: true }); }); - it('ignores invalid json responses', async () => { + it('ignores invalid json responses sent via response.json()', async () => { const app = express(); app.use( @@ -402,6 +402,60 @@ describe('middleware test', () => { expect(invalidQueryRes.body).toEqual('jimmy'); }); + it('ignores invalid json responses sent via response.end()', async () => { + const app = express(); + + app.use( + '/graphql', + graphqlRewriterMiddleware({ + rewriters: [ + new FieldArgsToInputTypeRewriter({ + fieldName: 'makePokemon', + argNames: ['name'] + }), + new NestFieldOutputsRewriter({ + fieldName: 'makePokemon', + newOutputName: 'pokemon', + outputsToNest: ['id', 'name'] + }) + ] + }) + ); + + app.use('/graphql', (req, res) => { + const messedUpRes = Buffer.from('jisdhfiods{{{{', 'utf8'); + res.setHeader('Content-Type', 'application/json; charset=utf-8'); + res.setHeader('Content-Length', String(messedUpRes.length)); + res.end(messedUpRes); + }); + + const deprecatedQuery = ` + mutation { + makePokemon(name: "Squirtle") { + id + name + } + } + `; + + const invalidQueryRes = await request(app) + .post('/graphql') + .send({ query: deprecatedQuery }) + // disable supertest json parsing + .buffer(true) + .parse((res, cb) => { + let data = Buffer.from(''); + res.on('data', chunk => { + data = Buffer.concat([data, chunk]); + }); + res.on('end', () => { + cb(null, data.toString()); + }); + }); + + expect(invalidQueryRes.body).toEqual('jisdhfiods{{{{'); + }); + it('is able to rewriter responses with pretty printing enabled on express-graphql', async () => { const app = setupMutationApp({ pretty: true }); // in the past, we didn't use input or output types correctly