获取所有记录时,GraphiQL 返回空值 [英] GraphiQL Returning null Values When Fetching All Records

查看:24
本文介绍了获取所有记录时,GraphiQL 返回空值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试构建一个简单的 GraphQL 架构.我有一个在 localhost 上运行的 json-server 端点,它返回一些简单的 json 数据.

I am trying to build a simple GraphQL schema. I have an json-server endpoint running on localhost which returns some simple json data.

我可以在提供 ID 时返回用户.在架构中执行此操作的查询如下所示:

I can return a user when supplying an id. The query to do this in the schema looks like this:

staff: {
    type: StaffType,
    args: { id: { type: GraphQLInt }},
    resolve(parentValue, { id }) {
        return axios.get(`http://localhost:3000/staff/${id}`)
            .then(resp => resp.data);
    }
}

GraphQL 查询如下所示:

The GraphQL query looks like this:

{
    staff(id: 1){
        id
        Name
    }
}

它会在 GraphiQL 客户端返回这个:

and it returns this in the GraphiQL client:

{
  "data": {
    "staff": {
      "id": 1,
      "Name": "John Doe"
    }
  }
}

当我尝试返回所有用户时,我的问题就开始了.我创建了另一个查询,试图从 http://localhost:3000/staff 获取所有内容,而没有传入参数.如果我直接在浏览器中访问这个 url,它会按预期返回所有用户.但是,如果我通过 GraphiQL 尝试它,它似乎返回一个对象,但所有字段都为空.无论是在 GraphiQL 中还是在控制台上都没有给出错误.下面的代码示例:

My problem starts when I try to return all users. I created another query to try to just fetch everything from http://localhost:3000/staff with no args passed in. If I go directly to this url in the browser it returns all users as expected. If I try it via GraphiQL, however, it seems to return an object, but all the fields are null. There is no error given either in GraphiQL or on the console. Code examples below:

模式中的查询

allStaff: {
    type: StaffType,
    resolve(parentValue, args) {
        return axios.get(`http://localhost:3000/staff/`)
            .then(resp => resp.data);
    }
}

GraphiQL 查询

The GraphiQL query

{
  allStaff {
    id
    Name
  }
}

我得到的结果

{
  "data": {
    "allStaff": {
      "id": null,
      "Name": null,
    }
  }
}

如果我控制台日志 resp.data 有数据返回,正如我所说,当我完全按照预期直接通过浏览器访问端点时,端点返回数据.

if I console log resp.data there is data being returned and, as I say, the endpoint returns data when I access it directly via the browser exactly as expected.

我错过了什么吗?

谢谢

推荐答案

JSON 数据可能是一组用户对象,但 GraphQL 仍然期待只有一个.这是因为在您的架构中,您已将 allStaff 的返回类型定义为 StaffType.您需要使用 List 包装器将其包装起来,如下所示:

The JSON data may be an array of user objects, but GraphQL is still expecting just the one. That's because in your schema, you've defined the return type for allStaff as StaffType. You need to wrap it with the List wrapper, like this:

type: new GraphQLList(StaffType),

这篇关于获取所有记录时,GraphiQL 返回空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆