2

I am using graphql-tools for schema generation. This query works fine

query{
  links(id: 1) {
    url
    resources{
      type
      active
    }
  }
}

My question is what the "resolver" will be for nested query so that it returns resource of 8902 id.

query{
  links(id: 1) {
    url
    resources(id: 8902) {
      type
      active
    }
  }
}

Code is as follow:

const express = require('express');
const bodyParser = require('body-parser');
const {graphqlExpress, graphiqlExpress} = require('apollo-server-express');
const {makeExecutableSchema} = require('graphql-tools');
const _ = require('lodash');

const links = [
    {
        id: 1, url: "http://bit.com/xDerS",
        resources: [
            {id: 8901, type: "file", active: true, cacheable: true},
            {id: 8902, type: "file", active: false, cacheable: true}
        ]
    },
    {
        id: 2,
        url: "http://bit.com/aDeRe",
        resources: [{id: 8903, type: "file", active: true, cacheable: true}]
    }
];

const typeDefs = `type Query { links(id: Int, ): [Link]} 
  type Link { id: Int, url: String, resources(id: Int): [Resource] }
  type Resource {id: Int, type: String, active: Boolean, cacheable: Boolean}`;

const resolvers = {
    Query: {
        links: (root, arg, context) => {
            return arg == null ? links : _.filter(links, {id: arg.id});
        }

    }
};

const schema = makeExecutableSchema({typeDefs, resolvers});
const app = express();
app.use('/graphql', bodyParser.json(), graphqlExpress({schema}));
app.use('/graphiql', graphiqlExpress({endpointURL: '/graphql'}));
app.listen(3000, () => console.log('Go to http://localhost:3000/graphiql to run queries!'));
Daniel Rearden
  • 80,636
  • 11
  • 185
  • 183
Pujan
  • 3,154
  • 3
  • 38
  • 52
  • 1
    Also, you may want to modify your resolver for `links`. If no arguments are passed in, the second parameter of the resolver (`arg`) will be an empty object (`{ }`), so it will never be null. You should instead check if arg.id is defined. – Daniel Rearden Jan 04 '18 at 13:21

1 Answers1

3

You can add a resolver for the resources field of the Link type, like so:

Query: {
  // Query fields
}
Link: {
  resources: ({ resources }, { id }) => id
    ? _.filter(resources, { id })
    : resources
}

The key difference is instead of filtering the data from some source, we're looking at what the parent field (in this case each Link in the links field) resolved to.

The first argument passed to a resolver is an object representing that information. For top level types, like Query and Mutation, this is called the root value, which can be defined for the entire schema but in practice should rarely be used (almost anything you could put in the root value should probably go inside your context instead). For any other types, that first argument will always reflect whatever the parent field resolved to.

Daniel Rearden
  • 80,636
  • 11
  • 185
  • 183