如何为 GraphQL Mutation 字段编写解析器

How to write resolvers for GraphQL Mutation fields

我的 GraphQL 架构如下所示:

type Outer {
   id: ID
   name: String,
   inner: [Inner]
}

type Inner {
   id: ID
   name: String
}

input OuterInput {
   name: String,
   inner: InnerInput
}

Input InnerInput {
   name: String
}

type Query {
   getOuter(id: ID): Outer
}

type Mutation {
   createOuter(outer: OuterInput): Outer
}

在数据库中,外部对象是这样存储的:

{
   id: 1,
   name: ‘test’,
   inner: [5, 6] //IDs of inner objects. Not the entire inner object
}

外部和内部存储在单独的数据库中collections/tables(我使用的是 DynamoDB)

我的解析器如下所示:

Query: {
   getOuter: (id) => {
      //return ‘Outer’ object with the ‘inner’ IDs from the database since its stored that way
   }
}


Outer: {
   inner: (outer) => {
      //return ‘Inner’ objects with ids from ‘outer.inner’ is returned
   }
}

Mutation: {
   createOuter: (outer) => {
      //extract out the IDs out of the ‘inner’ field in ‘outer’ and store in DB.
   }
}

OuterInput: {
   inner: (outer) => {
      //Take the full ‘Inner’ objects from ‘outer’ and store in DB.
     // This is the cause of the error
   }
}

但我无法为“OuterInput”中的“inner”字段编写类似于我为“Outer”所做的解析器。 GraphQL 抛出一个错误说

Error: OuterInput was defined in resolvers, but it's not an object

如果不允许为输入类型编写解析器,我该如何处理这种情况?

输入类型不需要解析器。输入类型仅作为值传递给字段参数,这意味着它们的值已经知道——它不需要由服务器解析,这与查询中返回的字段值不同。

每个解析器的签名都相同,包括 4 个参数:1) 父对象,2) 正在解析的字段的参数,3) 上下文和 4) 包含有关请求的更详细信息的对象作为一个整体。

因此,要为您的 createOuter 突变访问 outer 参数:

Mutation: {
   createOuter: (root, args, ctx, info) => {
      console.log('Outer: ', args.outer)
      console.log('Outer name: ', args.outer.name)
      console.log('Inner: ', args.outer.inner)
      console.log('Inner name: ', args.outer.inner.name)
      // resolver logic here
   }
}