简体   繁体   English

如何在 graphql-js 中为 object 类型定义解析器?

[英]How can I define resolver for object type in graphql-js?

I have many graphql types in my application.我的应用程序中有许多 graphql 类型。

I use graphql-js to construct them.我使用 graphql-js 来构建它们。

// example
const TruckDriver: GraphQLObjectType = new GraphQLObjectType({
  name: 'TruckDriver',
  fields: () => ({
    id: { type: GraphQLString },
  }),
})

Then I import such types in my different queries and mutations to define type of returned values.然后我在不同的查询和突变中导入这些类型来定义返回值的类型。

But my resolvers don't return objects, they return instances of classes where fields information are in nested property 'info'.但是我的解析器不返回对象,它们返回字段信息位于嵌套属性“信息”中的类的实例。 For example above resolver will return例如上面的解析器将返回

{
   info: {
     id: '123'
   }
   ...
}

I wanted to add resolver in my types but I found that types don't have resolvers.我想在我的类型中添加解析器,但我发现类型没有解析器。

How can I easy implement logic of fields data parsing for my object types?如何轻松实现 object 类型的字段数据解析逻辑?

You can either specify a resolver for each individual field, like this:您可以为每个单独的字段指定一个解析器,如下所示:

const TruckDriver: GraphQLObjectType = new GraphQLObjectType({
  name: 'TruckDriver',
  fields: () => ({
    id: {
      type: GraphQLString
      resolve: truck => truck.info.id
    },
  }),
})

or modify the resolvers for your Query and Mutation fields to return objects of the appropriate shape.或修改 Query 和 Mutation 字段的解析器以返回适当形状的对象。 Something like就像是

async function resolve () {
  const trucks = await getTrucks()
  return trucks.map(truck => truck.info)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM