GraphQL redirects when an error occurs

I use graphql-server-express to create a GraphQL server that uses the REST API.

I am in a situation where a REST call can return a status code of 301 or 401, when the user is not authenticated to access the resource. I use a cookie that is set on the client and redirected to the REST API when resolving a GraphQL request.

Is it possible to send 301 redirects to the client in response to a call to the GraphQL endpoint when such an error occurs?

I tried something like res.sendStatus(301) … in formatError , but this will not work, as graphql-server-express tries to set the headers after that.

I also tried to short-circuit the graphqlExpress as follows:

 export default graphqlExpress((req, res) => { res.sendStatus(301); return; }); 

As long as the client gets the correct result, the server still prints errors (in this case, TypeError: Cannot read property 'formatError' of undefined - most likely because the middleware receives empty options).

Is there a good way to make this work? Thanks!

+5
source share
1 answer

Here is how I did it.

On the server side:

 // Setup export default class UnauthorizedError extends Error { constructor({statusCode = 401, url}) { super('Unauthorized request to ' + url); this.statusCode = statusCode; } } // In a resolver throw new UnauthorizedError({url}); // Setup of the request handler graphqlExpress(async (req, res) => ({ schema: ..., formatError(error) { if (error.originalError instanceof UnauthorizedError) { res.status(error.originalError.statusCode); res.set('Location', 'http://domain.tld/login'); } else { res.status(500); } return error; }, }); 

On the client side:

 const networkInterface = createNetworkInterface(); networkInterface.useAfter([{ applyAfterware({response}, next) { if ([401, 403].includes(response.status)) { document.location = response.headers.get('Location'); } else { next(); } } }]); 

In Apollo Client 2.0, you can use apollo-link-error on the client side for this.

+5
source

Source: https://habr.com/ru/post/1261705/


All Articles