简体   繁体   中英

GraphQL query response coming back a null object instead of an array of objects

I read through and followed Why does a GraphQL query return null? , but I'm still getting an object of null fields where I should be getting an array of objects.

This is my resolver. My tests pass if I'm looking up a single _id . If there is no _id I want it to return everything. The query and mongoDB are working good. I can console.log the response and it's exactly what I'm looking for, but once I return the response for GraphQL, GraphQL messes it up.

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

So when it gets to my test, it returns a data object instead of an array and all the fields are null. Here is my test:

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

The console.log output:

在此处输入图片说明

What am I doing to mess GraphQL up between the returned promise in the resolver and my test?

NOTE: This is in TypeScript.

Update: Solved

I put my answer below. I hope it helps somebody.

As @DanielRearden said in the comments, you can't return either an object or a list. I changed my query to return an array:

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

And updated my resolver like so to get the test to pass:

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

Of course, I had to update a previous test to expect an array instead of a single object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM