javascript - 在通过 mergeResolvers 导入的外部解析器文件中使用 MongoDB 集合变量时的 ReferenceError
问题描述
这是一个完全简化的示例,可以更好地解释这个问题!所以当我使用解析器查询 getAllUsers
时,MongoDB 集合 Users
在外部解析器文件中不可用user.js
。因此,当我发送该查询时,我得到:
ReferenceError:未定义用户
这是正确的行为。但我不想在我的 index.js 中包含所有解析器,因为我以这种方式有更好的模块化。所以我在这样的外部文件中有我所有的类型定义和解析器。
当前文件结构
index.js
/graphql
/typdef
user.graphql
/resolver
user.js
user.graphql
架构正常工作。user.js
正如已经说过的那样,当我使用不可用的Users
变量执行查询时,这正是产生错误的原因。
这里index.js
和user.js
。
index.js
import express from 'express'
import cors from 'cors'
const app = express()
app.use(cors())
import bodyParser from 'body-parser'
import {graphqlExpress, graphiqlExpress} from 'graphql-server-express'
import {makeExecutableSchema} from 'graphql-tools'
import {fileLoader, mergeTypes, mergeResolvers} from 'merge-graphql-schemas';
import {writeFileSync} from 'fs'
const typeDefs = mergeTypes(fileLoader(`${__dirname}/graphql/typedef/*.graphql`), { all: true })
writeFileSync(`${__dirname}/graphql/typedef.graphql`, typeDefs)
export const start = async () => {
try {
const MONGO_URL = 'mongodb://localhost:27017'
const MongoClient = require('mongodb').MongoClient;
MongoClient.connect(MONGO_URL, function(err, client) {
console.log("Connected successfully to server");
const db = client.db('project');
const Users = db.collection('user')
});
const URL = 'http://localhost'
const homePath = '/graphql'
const PORT = 3001
app.use(
homePath,
bodyParser.json(),
graphqlExpress({schema})
)
app.use(homePath,
graphiqlExpress({
endpointURL: homePath
})
)
app.listen(PORT, () => {
console.log(`Visit ${URL}:${PORT}${homePath}`)
})
} catch (e) {
console.log(e)
}
}
用户.js
export default {
Query: {
getAllUsers: async () => {
return (await Users.find({}).toArray()).map(prepare)
}
}
}
将 MongoDB 或Users
集合传递给解析器文件的最佳方法是什么。或者这个问题有更好的解决方案吗?
解决方案
首先,这不是一个合适的解决方案,因为在外包模式时声明全局变量是一个糟糕的设计。但它成功了,也许这样有人会知道如何改进这个修复。
因此,要解决这个问题,我所要做的就是将变量从 local const 更改为 global。
所以在index.js const Users = db.collection('user')
中被global.Users = db.collection('user')
.
user.js也一样。这里return (await Users.find({}).toArray()).map(prepare)
由 重写return (await global.Users.find({}).toArray()).map(prepare)
。
推荐阅读
- python - 矢量化 softmax 梯度
- python - Tkinter - 将小部件放入框架大小
- python - 语音识别:麦克风在软件中工作,但不在 Python 代码中
- javascript - “超出最大调用堆栈大小”正确的方法但效率不够?Codewars Kata “阻止僵尸启示录!”
- mysql - MySQL:如何基于 SELECT Query UPDATE 查询
- php - PHP 流包装器和带有代理的 Windows 证书存储
- json - Leaflet 中的数据库映射(JSON、AJAX)
- c# - 如何为具有带参数的运行方法的天蓝色函数编写单元测试?
- service-accounts - 调用 Google IAM generateAccessToken API 总是返回错误
- amazon-web-services - AWS IAM - 撤销服务相关角色临时凭证的最佳方式-ec2 服务相关角色