Shopify / quilt

[⚠️ Deprecated] A loosely related set of packages for JavaScript/TypeScript projects at Shopify
MIT License
1.7k stars 220 forks source link

GraphQL Proxy is not working with koa-bodyparser #1405

Closed janpfischer closed 4 years ago

janpfischer commented 4 years ago

Overview

In my project I am using koa-bodyparser which parses ctx.body for my JSON POST requests. It seems that the graphQL proxy break when I am using this module. I got the response from the shopify graphql api that "a required parameter is missing". So I think that something in the request, which is sent with the proxy to the api will broke by the koa-bodyparser or vice versa.

I have now changed my bodyparser to this: server.use(async (ctx, next) => { if (ctx.path === "/graphql") ctx.disableBodyParser = true; await next(); }); server.use(bodyParser());

So now the bodyparser is disables if /graphql is called. Maybe you can look into this issue.

simonhaenisch commented 4 years ago

I ran into the same thing a few months ago, when implementing the graphql proxy endpoint as a Next.js API route... for that you can export a config object to disable the built-in body parser for that specific api route:

export const config = {
  api: { bodyParser: false },
};

I think it's a requirement because the request body has to be passed through the proxy as-is, i. e. without being parsed first. After all, it's a proxy, so the payload is meant for the receiving end, not the proxy.

So it's not an issue, but I think it would definitely be worth mentioning that in the readme because it took me a while to figure it out and more people might run into that as "serverless" becomes more popular.

michenly commented 4 years ago

Thank you for filing the issue, @simonhaenisch is correct in his explanation. We will keep this issue open for now as a reminder to document this.

janpfischer commented 4 years ago

Thank you both! I think it would be great if this gets documented, as this for sure saves some pain :)

@simonhaenisch So thats basically the same I did, but with nextjs and I used Koa Routes and I disabled the koa-bodyparser package for that prebuild route /graphql by koa-shopify-graphql-proxy package.

rorz commented 4 years ago

Building on @simonhaenisch's fix, if you are just using normal routes (such as in server.js), I found a disableBodyParser feature of koa-bodyparser that allows you to just ignore the /graphql endpoints at entry.

Modified from the body parser repo:

server.use(async (ctx, next) => {
  if (ctx.path === '/graphql') ctx.disableBodyParser = true;
  await next();
});
server.use(bodyParser());
marutypes commented 4 years ago

Seems like this issue is solved! :)