代码之家  ›  专栏  ›  技术社区  ›  Magnus

GraphQL参数如何绑定到字段中?

  •  0
  • Magnus  · 技术社区  · 6 年前

    我已经阅读了两个主要的“学习”指南 graphql.com howtographql.com 辅导的

    我仍在为一些概念而挣扎,其中一个概念与论点有关。

    type Person {
      id: ID!
      name: String!
      age: Int
      country: String!
    }
    
    type Query PersonsByAge {
      person(selectedCountry: String!): [Person]
    }
    
    query PersonsByAge {
      person(selectedCountry: 'Sweden')
    }
    

    问题

    1. selectedCountry 参数应在 country
    2. 是否有多个Person对象类型的实例,如在普通OOP中, 这些可以在一个小时内归还 List 如上所述?
    3. 我不完全相信我上面的语法/代码是正确的,有没有明显的错误?

    我觉得我缺少了一些基本的东西,我只是发现指南缺乏深度和结构。

    非常感谢。


    编辑:

    修正了括号错误,在丹尼尔的回答中指出。没有修复其他语法问题,以保持答案与问题匹配。

    1 回复  |  直到 6 年前
        1
  •  4
  •   Daniel Rearden    6 年前
    1. 为特定字段添加一个或多个参数不会影响字段本身解析为的值。在GraphQL.js中,每个字段都有一个关联的 resolve

    2. 是的,GraphQL包含一种特殊的集合类型,称为 List 变成一个非- 列表 价值,反之亦然。

    3. 你的语法有几个问题。您的查询有一个额外的圆括号,没有子选择 person PersonsByAge 在查询类型上添加无效语法且不是必需的标签。

    下面是您的示例,使用正确的语法和解析器进行了修改,以演示前面的观点。本示例假设您使用 graphql-tools .

    const people = [
      { id: 1, name: 'Oscar', country: 'Sweden' },
      { id: 2, name: 'Sal', country: 'Italy' }
    ]
    const typeDefs = `
      type Person {
        id: ID!
        name: String!
        country: String!
      }
      type Query {
        person(id: ID!): Person
        people(selectedCountry: String!): [Person]
      }
    `
    const resolvers = {
      Query: {
        person: (root, args, context) => {
          // this returns a single object
          return people.find(person => person.id === args.id)
        },
        people: (root, args, context) => {
          // this returns an array
          return people.filter(person => person.country === args.selectedCountry)
        },
      },
    }
    

    然后,您可以像这样查询您的模式客户端:

    query SomeQueryName {
      people(selectedCountry: "Sweden") {
        id
        name
      }
    }
    

    我强烈建议退房 Apollo Launchpad