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

ama*_*ann 5 redirect node.js graphql apollo-server

我正在使用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;
});
Run Code Online (Sandbox Code Playgroud)

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

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

ama*_*ann 8

这是我实现这个的方式.

在服务器端:

// 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;
  },
});
Run Code Online (Sandbox Code Playgroud)

在客户端:

const networkInterface = createNetworkInterface();

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

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