我是一名前端开发人员,试图在一个新的 Next 项目上扩展我的视野,第一次学习 Node、Mongo 和 GraphQL 的服务器端。Apollo 让我印象深刻,因为我已经在以前的项目中使用过客户端 Apollo。
我一直在关注官方文档,在那里我了解到apollo-datasource-mongodb(似乎是将我的 Apollo 服务器直接插入本地 Mongo 数据库的最佳方法。不幸的是,似乎没有这个包的任何示例存储库采取行动让我作弊,所以我只能蒙混过关。
我有 mongo 在本地运行mongod,我可以通过 mongo shell 执行成功find()的查询,所以我知道数据库本身状况良好并且包含近600,000 条记录(我正在使用一个相当大的数据集)。
我还可以访问 Apollo Playground,localhost:4000因此我知道服务器正在正常启动并连接到数据库(我已经设法解决了适当的 Schema 提示/错误)。
这是我在 Playground 中使用的查询:
{
item(id: 22298006) {
title
}
}
这就是我得到的回应:
{
"errors": [
{
"message": "Topology is closed, please connect",
"locations": [
{
"line": 2,
"column": 3
}
],
"path": [
"item"
],
"extensions": {
"code": "INTERNAL_SERVER_ERROR",
"exception": {
"name": "MongoError",
"stacktrace": [
"MongoError: Topology is closed, please connect",
...
]
}
}
}
],
"data": {
"item": null
}
}
我在下面附上了我的服务器文件。我怀疑这可能是某种超时错误,例如梳理所有 600k 记录以找到具有我提供的 ID 的记录需要很长时间?当我useUnifiedTopology: true从 MongoClient 定义中删除时,我得到一个不同的错误:
UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
但我自己没有使用异步或承诺。我在想哪一个——我应该是吗?我可以在等待返回时以某种方式阻止该过程findOneById()(如果这确实是问题)?
顺便说一句,我至少看到了一个示例代码库,其中 MongoClient 在其自身中包含了一个服务器声明(也来自'mongodb'npm 包)。实施这样的事情会让我不必在mongod每次我想处理我的项目时都阻塞终端窗口吗?
非常感谢您的参与!如果我能完成这项工作,我肯定会在 Medium 上写一篇完整的文章,或者为其他希望将 MongoClient 与 ApolloServer 配对以获得快速简便的 API 的人铺平道路。
index.js
const { MongoClient } = require('mongodb');
const assert = require('assert');
const { ApolloServer, gql } = require('apollo-server');
const { MongoDataSource } = require('apollo-datasource-mongodb');
const client = new MongoClient('mongodb://localhost:27017/projectdb', { useNewUrlParser: true, useUnifiedTopology: true }, (err) => {
err && console.log(err);
});
client.connect((err) => {
assert.equal(null, err);
client.close();
});
const db = client.db();
class Items extends MongoDataSource {
getItem(id) {
return this.findOneById(id);
}
}
const typeDefs = gql`
type Item {
id: Int!
title: String!
}
type Query {
item(id: Int!): Item
}
`;
const resolvers = {
Query: {
item: (_, { id }, { dataSources }) => dataSources.items.getItem(id),
}
}
const server = new ApolloServer({
typeDefs,
resolvers,
dataSources: () => ({
items: new Items(db.collection('items')),
}),
});
server.listen().then(({ url }) => {
console.log(`Server ready at ${ url }`);
});
