【问题标题】:GraphQL query response coming back a null object instead of an array of objectsGraphQL 查询响应返回一个空对象而不是对象数组
【发布时间】:2020-04-08 12:54:13
【问题描述】:

我通读并关注了Why does a GraphQL query return null?,但我仍然得到了一个null 字段的对象,我应该得到一个对象数组。

这是我的解析器。如果我正在查找单个 _id,我的测试将通过。如果没有 _id 我希望它返回所有内容。查询和 mongoDB 运行良好。我可以console.logresponse,这正是我想要的,但是一旦我为 GraphQL 返回response,GraphQL 就搞砸了。

comment: ({_id}: {_id: string}) => {
        if (_id) {
            return Comment.findOne({_id}).exec();
        } else {
            return Comment.find({}).exec().then((response) => {
                console.log("response inside resolver: ", response); // <-- THIS HAS THE ARRAY OF OBJECTS!
                return response;
            });
        }
    }

所以当它进入我的测试时,它返回一个数据对象而不是一个数组,并且所有字段都为空。这是我的测试:

 it("should retrieve all records from database", (done) => {

        const query: string = `query {
            comment { _id author text }
          }`;

        request(app)
            .post("/comments")
            .send({query})
            .expect(200)
            .end((err, res) => {
                console.log("response inside test: ", res.body.data.comment); // <-- OBJECT WITH NULL FIELDS!
                if (err) { return done(err); }
                expect(res.body.data.comment).to.have.lengthOf(arrayOfNewElements.length);
                res.body.data.comment.sort((a: IComment, b: IComment) => parseInt(a._id, 10) - parseInt(b._id, 10));
                expect(res.body.data.comment).to.deep.equal(arrayOfNewElements);
                done();
            });
    });

console.log 输出:

在解析器中返回的承诺和我的测试之间,我在做什么来搞乱 GraphQL?

注意:这是在 TypeScript 中。

更新:已解决

我把我的答案放在下面。我希望它可以帮助某人。

【问题讨论】:

  • 如果你得到空字段的对象,那么你的字段类型不是列表。请参阅您链接的帖子中的常见场景#2。顺便说一句,你不能返回一个对象或一个列表——你必须使用一个或另一个。这意味着您的解析器不应同时使用 find 和 findOne
  • 是的,我刚刚想通了。非常感谢@DanielRearden! GraphQL 天使。

标签: javascript node.js graphql express-graphql


【解决方案1】:

正如@DanielRearden 在 cmets 中所说,您不能返回对象或列表。我更改了查询以返回一个数组:

    type Query {
        comment(_id: String): [Comment]
    }

并像这样更新了我的解析器以使测试通过:

    comment: ({_id}: {_id: string}) => {
        if (_id) {
            return Comment.findOne({_id}).exec().then((response) => {
                return [response];
            });
        } else {
            return Comment.find({}).exec().then((response) => {
                return response;
            });
        }
    }

当然,我必须更新之前的测试以期望一个数组而不是单个对象。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-01
    • 1970-01-01
    • 2019-06-05
    • 2019-11-09
    • 2020-05-06
    • 2020-01-25
    • 2020-11-02
    相关资源
    最近更新 更多