2

I have this graphql query, its looking for all services associated with a project( given its id ) and for each services, it returns the list of users who have access to.

query Project ($id: ID!) {
  services {
    mailService {
      users
    }
  }
}

I want to know what's the best solution to pass the id parameter and use it inside the users resolver function.

I am thinking about these solutions :

  • Add $id parameter for both mailService and users nodes in query.
  • In the graphql middleware in server, add parameters object to the context field ( from the request.body)
  • Add a field in context object in Project resolver : context.projectId = $id and use it in sub fields resolvers.

Thanks for help

stubailo
  • 6,077
  • 1
  • 26
  • 32
  • Why does your `users` resolver need to know about the project ID? I feel like that would be confusing from the API consumer point of view. – stubailo Mar 22 '17 at 04:57
  • 3
    The main reason is because i need to call 2 different Rest APIs to get Project basic infos and to get the list of users who have accees to a service. The second API take 2 params: projectId and service identifier. – user2086656 Mar 22 '17 at 07:17

1 Answers1

0

You can do that with native resolve form the object types.

In the resolve of the sub node, you can access the entire parent data. For example:

export const User: GraphQLObjectType = new GraphQLObjectType({
    name: 'User',
    description: 'User type',
    fields: () => ({
        id: {
            type: new GraphQLNonNull(GraphQLID),
            description: 'The user id.',
        },
        name: {
            type: new GraphQLNonNull(GraphQLString),
            description: 'The user name.',
        },
        friends: {
            type: new GraphQLList(User),
            description: 'User friends',
            resolve: (source: any, args: any, context: any, info: any) => {
                console.log('friends source: ', source)
                return [
                    {id: 1, name: "friend1"},
                    {id: 2, name: "friend2"},
                ]
            }
        }
    }),
})

const Query = new GraphQLObjectType({
    name: 'Query',
    description: 'Root Query',
    fields: () => ({
        user: {
            type: User,
            description: User.description,
            args: {
                id: {
                    type: GraphQLInt,
                    description: 'the user id',
                }
            },
            resolve: (source: any, args: any, context: any, info: any) => {
                console.log('user args: ', args)
                return { id: 2, name: "user2" }
            }
        }
    })
})

In the friends resolve the source param has the entire returned values from the parent user resolve. So in here I could fetch all the friends based on the user ID I get from source.

Marco Daniel
  • 5,467
  • 5
  • 28
  • 36