GraphQL 查询有效,现在返回 null;

问题描述

所以我正在尝试 GraphQL,但遇到了一个奇怪的问题。返回 data 的相同查询现在返回 null。
我正在使用数组形式的虚拟“数据库”
当我尝试添加新数组和类型 Authors 时出现此问题。我已经删除了所有内容以返回到初始代码,但它仍然无法从数组中返回正确的数据。

schema.js

    const graphql = require('graphql');
    const _ = require('lodash');
    
    
    const {
        GraphQLObjectType,GraphQLID,GraphQLString,GraphQLSchema
    } = graphql;
    
    // dummy data
    var booksarr = [
        {name: 'Name of the Wind',genre: 'Fantasy',id: 1},{name: 'The Final Empire',id: 2},{name: 'The Long Earth',genre: 'Sci-Fi',id: 3}
    ];
    
    
    const BookType = new GraphQLObjectType({
        name: 'Book',fields: () =>({
            id: {type: GraphQLID},name: {type: GraphQLString},genre: {type: GraphQLString}
        })
    });
    
    
    const RootQuery = new GraphQLObjectType({
        name: "RootQueryType",fields: {
            book: {
                type: BookType,args: { id: { type: GraphQLID } },resolve(parent,args){
                    //Get data from db / sources
                    return _.find(booksarr,{id: args.id});
                }
            }
        }
    });
    
    module.exports = new GraphQLSchema({
        query: RootQuery
    });

app.js

    const express = require('express');
    const {graphqlHTTP} = require('express-graphql');
    const schema = require('./schema/schema');
    
    
    const app = express();
    
    app.use('/graphql',graphqlHTTP({
        schema,graphiql: true
    }));
    
    app.listen(8080,() =>{
        console.log("Now listening on port 8080");
    });

Image from graphiql

解决方法

您的查询将 ID 作为字符串传递,但在 booksarr 中,ID 是一个数字。要么您的代码需要同时处理两者,要么您的查询需要传递一个整数。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...