本文介绍了如何在 GraphQL 中设置 http 状态码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的 GraphQL 身份验证查询中设置一个 http 状态代码,具体取决于身份验证尝试是成功 (200)、未授权 (401) 还是缺少参数 (422).

I want to set an http status code in my GraphQL authentication query, depending on if auth attempt was successful (200), unauthorised (401) or missing parameters (422).

我正在使用 Koa 和 Apollo 并像这样配置了我的服务器:

I am using Koa and Apollo and have configured my server like so:

const graphqlKoaMiddleware = graphqlKoa(ctx => {
  return ({
    schema,
    formatError: (err) => ({ message: err.message, status: err.status }),
    context: {
      stationConnector: new StationConnector(),
      passengerTypeConnector: new PassengerTypeConnector(),
      authConnector: new AuthConnector(),
      cookies: ctx.cookies
    }
  })
})

router.post("/graphql", graphqlKoaMiddleware)

如您所见,我已将 formatError 设置为返回消息和状态,但目前仅返回消息.错误消息来自我在解析器函数中抛出的错误.

As you can see, I have set my formatError to return a message and status but currently only the message is getting returned. The error message comes from the error that I throw in my resolver function.

例如:

const resolvers = {
  Query: {
    me: async (obj, {username, password}, ctx) => {
      try {
        return await ctx.authConnector.getUser(ctx.cookies)
      }catch(err){
        throw new Error(`Could not get user: ${err}`);
      }
    }
  }
}

我对这种方法的唯一问题是它在错误消息中设置状态代码,而不是实际更新响应对象.

My only issue with this method is it is setting the status code in the error message and not actually updating the response object.

GraphQL 是否需要 200 响应,即使对于失败的查询/突变,我是否可以更新响应对象的状态代码?如果没有,如何设置上述错误对象状态代码?

Does GraphQL require a 200 response even for failed queries / mutations or can I some how update the response objects status code? If not, How do I set the aforementioned error object status code?

推荐答案

对于 apollo-server,安装 apollo-server-errors 包.对于身份验证错误,

For apollo-server, install the apollo-server-errors package. For authentication errors,

import { AuthenticationError } from "apollo-server-errors";

然后,在您的解析器中throw new AuthenticationError('unknown user');

这将返回 400 状态代码.

This will return a 400 status code.

此博客中阅读有关此主题的更多信息

这篇关于如何在 GraphQL 中设置 http 状态码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 05:08