簡體   English   中英

GraphQL 查詢響應返回空對象而不是對象數組

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

我通讀並遵循了為什么 GraphQL 查詢返回 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 輸出:

在此處輸入圖片說明

我在做什么來混淆解析器中返回的承諾和我的測試之間的 GraphQL?

注意:這是在 TypeScript 中。

更新:已解決

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

正如@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;
            });
        }
    }

當然,我必須更新之前的測試以期望使用數組而不是單個對象。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM