GraphQL嵌套查询查找

时间:2018-01-04 06:46:40

标签: node.js graphql graphql-js apollo-server express-graphql

我使用graphql-tools进行模式生成。此查询工作正常

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

我的问题是"解析器"将用于嵌套查询,以便它返回8902 id的资源。

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

代码如下:

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!'));

1 个答案:

答案 0 :(得分:2)

您可以为resources类型的Link字段添加解析器,如下所示:

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

关键区别在于不是从某些来源过滤数据,而是在查看父字段(在这种情况下Link字段中的每个links)解析为什么。< / p>

传递给解析器的第一个参数是表示该信息的对象。对于顶级类型,例如QueryMutation,这称为根值,可以为整个模式定义,但在实践中应该很少使用(几乎任何你可以放在根值中的东西)应该进入你的上下文)。对于任何其他类型,第一个参数将始终反映父字段解析的内容。

相关问题