Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested query for the new GraphQL buildSchema

How can I make resolver for my friendList with the new GraphQL Schema language? friendList have an array of people _id.

My new people type with GraphQL Schema language:

const schema = buildSchema(`
  type People {
    _id: String
    firstName: String
    lastName: String
    demo: String
    friendList: [People]
  }
  type Query {
    getPeople(_id: String): People
  }
`);

My old people type with GraphQLObjectType:

const PeopleType = new GraphQLObjectType({
  name: 'People',
  fields: () => ({
    _id: {
      type: GraphQLString,
    },
    firstName: {
      type: GraphQLString,
    },
    lastName: {
      type: GraphQLString,
    },
    friendList: {
      type: new GraphQLList(PeopleType),
      // pass @friends parentValue
      resolve: ({ friends }) {
        return People.find({ _id: { $in: friends } }).then(res => res);
    },
  }),
});

I want to achieve this query:

{
  people(_id: "ABC123") {
    firstName
    lastName
    friendList {
      firstName
      lastName
    }
  }
like image 278
Abu Coder Avatar asked Sep 22 '16 10:09

Abu Coder


2 Answers

Your resolver should return a new instance of a class as explained in the updated GraphQL documentation: http://graphql.org/graphql-js/object-types/.

class People {
  friendList () {}
}
var rootValue = {
  getPeople: function () {
    return new People();
  }
}
like image 196
xpepermint Avatar answered Nov 10 '22 03:11

xpepermint


I couldn't find a way to do this with graphql-js so I switched to a similar implementation from the folks at Apollo called graphql-tools.

http://dev.apollodata.com/tools/graphql-tools/generate-schema.html

They have a function called makeExecutableSchema that takes a schema written in the GraphQL Schema language and combines it with (nested) resolver functions. This fixes the issue and is actually pretty simple to integrate with if your code uses the GraphQL Schema language.

They also have another agnostic tool for exposing this new schema that replaces express-graphql, its GraphQL-server:

http://dev.apollodata.com/tools/graphql-server/index.html

Check out the docs and hopefully this gives you the flexibility to write complex code using the GraphQL Schema language syntax!

like image 4
Charles Burgess Avatar answered Nov 10 '22 03:11

Charles Burgess