node.js - GraphQL 嵌套查询查找

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

最佳答案

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

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

关键区别在于,我们不是从某个来源过滤数据,而是查看父字段(在本例中为 links 字段中的每个 Link)决心。

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

关于node.js - GraphQL 嵌套查询查找,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48090030/

相关文章:

javascript - 运行 socket.io 和express-nodejs 设置时出错

node.js - Alexa Node.js 技能未进入 intent

java - 如何获取查询/变异操作名称

node.js - babel-node 与 Node : graphql files with import/exports

javascript - knex 中的排水管连接需要比预期更多的时间

Heroku 上的 Node.js Socket.io 抛出 H13

node.js - 如何模拟 mongodb 以进行单元测试 graphql 解析器

java - 如何使用 graphql-java 从请求 header 设置上下文

javascript - ReactDOM 期望 String 但返回一个 Object

javascript - GraphQL:错误:必须提供文档