【问题标题】:GraphQL Query worked, now returns null;GraphQL 查询工作,现在返回 null;
【发布时间】:2021-08-25 19:50:03
【问题描述】:

所以我正在尝试 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', genre: 'Fantasy' , 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");
    });

【问题讨论】:

    标签: node.js graphql express-graphql


    【解决方案1】:

    您的书单中的 id 是数字类型,将其更改为字符串类型,它将起作用。从 1 到“1”

    【讨论】:

    • 这与the other answer 中的解决方案相同。 在回答已有答案的旧问题时,请确保提供新颖的解决方案或比现有答案更好的解释。
    • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
    【解决方案2】:

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

    【讨论】:

    • ID 类型应该接受 Int 还是 Strings ?我已经通过和 Int 并且它仍然返回 null。
    • ID 接受字符串和整数,但 _.find 不接受。如果它仍然不起作用,那么您需要调试您的 _.find 代码以查看您得到的参数并查看它为什么不匹配。
    • 换句话说,这将解决它return _.find(booksarr, { id: Number(args.id) });
    猜你喜欢
    • 2019-06-14
    • 2020-01-07
    • 2023-03-05
    • 2020-01-15
    • 2021-01-15
    • 2020-03-01
    相关资源
    最近更新 更多