Skip to content

Commit e42c88d

Browse files
committed
fix: fixing a bug where the middleware won't rewrite already-decoded posted body
1 parent 8c9ce42 commit e42c88d

File tree

2 files changed

+53
-1
lines changed

2 files changed

+53
-1
lines changed

src/index.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ const graphqlRewriterMiddleware = ({
4141
variables: newQueryAndVariables.variables
4242
};
4343
if (typeof req.body === 'object' && !(req.body instanceof Buffer)) {
44-
req.body = { ...req.body, newBody };
44+
req.body = { ...req.body, ...newBody };
4545
} else {
4646
req.body = newBody;
4747
}

test/index.test.ts

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,58 @@ describe('middleware test', () => {
114114
});
115115
});
116116

117+
it('works with already-decoded response.body', async () => {
118+
const app = express();
119+
120+
// decode the request before it gets to our middleware
121+
app.use('/graphql', async (req, res, next) => {
122+
req.body = await (graphqlHTTP as any).getGraphQLParams(req);
123+
next();
124+
});
125+
126+
app.use(
127+
'/graphql',
128+
graphqlRewriterMiddleware({
129+
rewriters: [
130+
new FieldArgTypeRewriter({
131+
fieldName: 'getPokemon',
132+
argName: 'id',
133+
oldType: 'String!',
134+
newType: 'ID!'
135+
})
136+
]
137+
})
138+
);
139+
140+
app.use(
141+
'/graphql',
142+
graphqlHTTP({
143+
schema,
144+
rootValue
145+
})
146+
);
147+
148+
// in the past, we accidentally used `String!` instead of `ID`
149+
// so we need to rewrite the query to this old query will work still
150+
const deprecatedQuery = `
151+
query getByIdWithWrongType($id: String!) {
152+
getPokemon(id: $id) {
153+
id
154+
name
155+
}
156+
}
157+
`;
158+
159+
const deprecatedRes = await request(app)
160+
.post('/graphql')
161+
.send({ query: deprecatedQuery, variables: { id: '7' } });
162+
expect(deprecatedRes.body.errors).toBe(undefined);
163+
expect(deprecatedRes.body.data.getPokemon).toEqual({
164+
id: '7',
165+
name: 'Charmander'
166+
});
167+
});
168+
117169
const setupMutationApp = () => {
118170
const app = express();
119171

0 commit comments

Comments
 (0)