GraphQL查询响应返回空对象而不是对象数组

问题描述 投票:0回答:1

[我通读并关注了Why does a GraphQL query return null?,但是我仍在获取null字段的对象,我应该在其中获取对象数组。

这是我的解析器。如果我查找单个_id,则测试通过。如果没有_id,我希望它返回所有内容。查询和mongoDB运行良好。我可以console.log response,这正是我要的内容,但是一旦我为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输出:

enter image description here

我该怎么做才能使GraphQL在解析器中返回的promise和我的测试之间混乱?

注意:这是在TypeScript中。

更新:已解决

我在下面回答。我希望它能对某人有所帮助。

javascript node.js graphql express-graphql
1个回答
0
投票

正如@DanielRearden在评论中所说,您不能返回对象或列表。我将查询更改为返回数组:

    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;
            });
        }
    }

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

© www.soinside.com 2019 - 2024. All rights reserved.