繁体   English   中英

GraphQL嵌套查询查找

[英]GraphQL nested query Lookup

我正在使用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!'));

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

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

关键的区别是,而不是过滤从一些源中的数据,我们看到的是什么父字段(在这种情况下,每个Linklinks字段)决心。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM