Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add multiple resolvers in a type (Apollo-server)

I have used express-graphql and there i used to do something like this.

const SubCategoryType = new ObjectType({
  name: 'SubCategory',
  fields: () => ({
    id: { type: IDType },
    name: { type: StringType },
    category: {
      type: CategoryType,
      resolve: parentValue => getCategoryBySubCategory(parentValue.id)
    },
    products: {
      type: List(ProductType),
      resolve: parentValue => getProductsBySubCategory(parentValue.id)
    }
  })
});

Here I have multiple resolvers, id and name are fetched directly from the result. and the category and products have there own database operation. and so on. Now I am working on apollo-server and I can't find a way to replicate this.

for example I have a type

   type Test {
    something: String
    yo: String
    comment: Comment
  }
   type Comment {
    text: String
    createdAt: String
    author: User
  }

and in my resolver I want to split it up, for example something like this

text: {
    something: 'value',
    yo: 'value',
    comment: getComments();
}

NOTE: this is just a representation of what I need.

like image 723
Sarmad Shah Avatar asked Mar 10 '19 19:03

Sarmad Shah


1 Answers

You can add type-specific resolvers to handle specific fields. Let's say you have the following schema (based on your example):

type Query {
  getTest: Test
}
type Test {
  id: Int!
  something: String
  yo: String
  comment: Comment
}
type Comment {
  id: Int!
  text: String
  createdAt: String
  author: User
}
type User {
  id: Int!
  name: String
  email: String
}

Let's also assume you have the following DB methods:

  • getTest() returns an object with fields something, yo and commentId
  • getComment(id) returns an object with fields id, text, createdAt and userId
  • getUser(id) returns an object with fields id, name and email

Your resolver will be something like the following:

const resolver = {
  // root Query resolver
  Query: {
    getTest: (root, args, ctx, info) => getTest()
  },
  // Test resolver
  Test: {
    // resolves field 'comment' on Test
    // the 'parent' arg contains the result from the parent resolver (here, getTest on root)
    comment: (parent, args, ctx, info) => getComment(parent.commentId)
  },
  // Comment resolver
  Comment: {
    // resolves field 'author' on Comment
    // the 'parent' arg contains the result from the parent resolver (here, comment on Test)
    author: (parent, args, ctx, info) => getUser(parent.userId)
  },
}

Hope this helps.

like image 166
Thomas Hennes Avatar answered Sep 22 '22 12:09

Thomas Hennes