return 来自 graphql yoga 的状态码

return status code from graphql yoga

来自 graphql yoga,在我的解析器内部,我在调用解析器之前检查这个解析器是否受到保护。

如果解析器受到保护,但用户未登录,我可能会抛出如下错误: return new Error('Token is missing');

这会停止请求的执行并returns正确的消息格式,带有错误字段。

{
  "data": null,
  "errors": [
    {
      "message": "Token is missing",
      "locations": [
        {
          "line": 3,
          "column": 3
        }
      ],
      "path": [
        "users"
      ]
    }
  ]
}

尽管响应的状态为 200,但这是不正确的。我希望能够选择自己的状态,例如 403。

这是我当前的解析器实现:

const withAuth = authed => (_, args, context, ...rest) => {
    if (!context.token) {
        return new Error('Token is missing');
    }

    let result = null;

    try {
        result = jwt.verify(context.token, process.env.HASH);
    } catch (__) {
        return new Error('Incorrect token');
    }

    const { username, email } = result;
    if (!username || !email) {
        return new Error('Incorrect token');
    }

    return authed(_, args, { ...context, user: { username, email } }, ...rest);
};


const resolvers = {
    Query: {

        users: withAuth(resolver(User)), //get users from db

}

我会在 express 中添加一个 before request 中间件,但是没有办法告诉正在调用哪个查询,因为所有调用都是针对同一个端点完成的。

如有任何意见,我们将不胜感激!

根据 graphql 规范,端点应始终 return 状态 200:

http://facebook.github.io/graphql/October2016/#sec-Errors

The errors entry in the response is a non‐empty list of errors, where each error is a map.

If no errors were encountered during the requested operation, the errors entry should not be present in the result.

Every error must contain an entry with the key message with a string description of the error intended for the developer as a guide to understand and correct the error.

If an error can be associated to a particular point in the requested GraphQL document, it should contain an entry with the key locations with a list of locations, where each location is a map with the keys line and column, both positive numbers starting from 1 which describe the beginning of an associated syntax element.

GraphQL servers may provide additional entries to error as they choose to produce more helpful or machine‐readable errors, however future versions of the spec may describe additional entries to errors.

If the data entry in the response is null or not present, the errors entry in the response must not be empty. It must contain at least one error. The errors it contains should indicate why no data was able to be returned.

If the data entry in the response is not null, the errors entry in the response may contain any errors that occurred during execution. If errors occurred during execution, it should contain those errors.