解析器抛出错误时的GraphQL重定向

问题描述 投票:5回答:1

我正在使用graphql-server-express构建一个使用REST API的GraphQL服务器。

我遇到的情况是,当用户未经过身份验证访问资源时,REST调用可能会返回301或401状态代码。我正在使用在客户端上设置的cookie,并在解析GraphQL查询时转发到REST API。

当发生此类错误时,是否可以向客户端发送301重定向以响应对GraphQL端点的调用?

我在res.sendStatus(301) …尝试了像formatError这样的东西,但这不能很好,因为graphql-server-express试图在此之后设置标题。

我也试图用这样的东西来短路graphqlExpress中间件:

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

当客户端收到正确的结果时,服务器仍然会输出错误(在这种情况下TypeError: Cannot read property 'formatError' of undefined - 很可能是因为中间件收到空选项)。

有一个很好的方法如何使这个工作?谢谢!

node.js redirect graphql apollo-server
1个回答
7
投票

这是我实现这个的方式。

在服务器端:

// 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;
  },
});

在客户端:

const networkInterface = createNetworkInterface();

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

在Apollo Client 2.0中,您可以在客户端使用apollo-link-error

© www.soinside.com 2019 - 2024. All rights reserved.