简体   繁体   中英

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

I have many graphql types in my application.

I use graphql-js to construct them.

// 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?

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. Something like

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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