【发布时间】: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