javascript - 我应该在 GraphQL 中使用列表(数组)吗?

标签 javascript node.js api graphql

[以前的标题为“如何从列表中获取 1 条记录...”]

我是 GraphQL 的新手,正在尝试了解如何从查询中获取 1 条记录。

这是我当前查询的结果:

{
    "data": {
        "todos": null
    }
}

我不确定哪里出了问题。我希望结果是这样的:

{
    "data": {
        "todos": {
            "id": 1,
            "title": "wake up",
            "completed": true
        }
    }
}

这是我在尝试学习 GraphQL 时创建的代码。

架构.js:

var graphql = require('graphql');

var TODOs = [
  {
    "id": 1,
    "title": "wake up",
    "completed": true
  },
  {
    "id": 2,
    "title": "Eat Breakfast",
    "completed": true
  },
  {
    "id": 3,
    "title": "Go to school",
    "completed": false
  }
];

var TodoType = new graphql.GraphQLObjectType({
  name: 'todo',
  fields: function () {
    return {
      id: {
        type: graphql.GraphQLID
      },
      title: {
        type: graphql.GraphQLString
      },
      completed: {
        type: graphql.GraphQLBoolean
      }
    };
  }
});

var queryType = new graphql.GraphQLObjectType({
  name: 'Query',
  fields: function () {
    return {
      todos: {
        type: new graphql.GraphQLList(TodoType),
        args: {
          id: { type: graphql.GraphQLID }
        },
      resolve: function (source, args, root, ast) {
        if (args.id) {
          return TODOs.filter(function(item) {
            return item.id === args.id;
            })[0];
          }

          return TODOs;
        }
      }
    }
  }
});

module.exports = new graphql.GraphQLSchema({
  query: queryType
});

index.js:

var graphql = require ('graphql').graphql;
var express = require('express');
var graphQLHTTP = require('express-graphql');
var Schema = require('./schema');

var query = 'query { todos(id: 1) { id, title, completed } }';
graphql(Schema, query).then( function(result) {
  console.log(JSON.stringify(result,null," "));
});

var app = express()
  .use('/', graphQLHTTP({ schema: Schema, pretty: true }))
  .listen(8080, function (err) {
    console.log('GraphQL Server is now running on localhost:8080');
});

要运行此代码,我只需从根目录运行 node index。如何获取记录 ID 返回的一条特定记录?

最佳答案

您的 queryType 的 todos 字段类型错误。它应该是 TodoType,而不是 TodoType 的列表。您收到错误是因为 GraphQL 期望看到一个列表,但您的解析器只返回一个值。

顺便说一下,我建议将 graphiql: true 选项传递给 graphqlHTTP,这样您就可以使用 GraphiQL探索您的架构并进行查询。

关于javascript - 我应该在 GraphQL 中使用列表(数组)吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37981434/

相关文章:

javascript - 时刻.js : The result is always "a few seconds ago" in firefox/ie

javascript - 迭代抓取的数据以作为嵌入内的字段对象返回

javascript - Redux 中间件访问 store

javascript - 我的 NodeJS 初始化给出了一个奇怪的错误并且没有更新

javascript - JavaScript 中这两个函数声明有什么区别?

javascript - 监听特定端口时接收广播包

node.js - 如何绝对确定 socket.io 正在工作?

php - 如何在 PHP cURL 请求中将 OData 发送到 RESTful API

php - 验证对 API 的访问

api - 使用经典 ASP/创建服务器端 REST API 时遇到问题