maticzav / graphql-shield

🛡 A GraphQL tool to ease the creation of permission layer.

Home Page:https://graphql-shield.com

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Returning a custom response code

leo-petrucci opened this issue · comments

Question about GraphQL Shield

I've looked in the docs as well as googling to my best ablities about this, but forgive me if I missed it.

I'm looking at returning a custom error response from my graphql api. I'm aware that I can return a custom error message inside my rules, however despite the error message, the response from my API will always be 200. How do I return my error so that is contains a 401 response code?

I think that depends on your client. As far as I know, Apollo only returns 400 if there was a connection problem or something similar. GraphQL's error reponse still counts as 200, but I might be wrong.

commented

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

Hey so, I was messing around with something completely unrelated, and figured out how to achieve this with Qraphql Yoga.

The trick is to just make sure you have access to the response object in context:

new GraphQLServer({
  schema,
  context: ({request, response}) => {
    return {
      req: request, 
      res: response,
    }
  }),
  middlewares: [permissions],
}).start(() =>
  console.log(
    `🚀 Server ready at: http://localhost:4000\n⭐️ See sample queries: http://pris.ly/e/ts/graphql-auth#using-the-graphql-api`,
  ),
)

Then you should just be able to access the context from your rules:

  isAuthenticatedUser: rule()(async (parent, args, context) => {
    const userId = getUserId(context)
    if (!userId)
        context.res.status(401)
    return Boolean(userId)
  }),

This shouldn't break any of the existing rules, but should change the response status as well.

Oh wow! This is really cool! Thank you for sharing it.