Skip to content

Commit

Permalink
adding another parsing test and extra guard
Browse files Browse the repository at this point in the history
  • Loading branch information
chanind committed Oct 10, 2019
1 parent ffcb6f8 commit 61056cc
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 2 deletions.
2 changes: 1 addition & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
56 changes: 55 additions & 1 deletion test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down Expand Up @@ -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
Expand Down

0 comments on commit 61056cc

Please sign in to comment.