问题描述
我想在 Node JS Express 4 中使用 node-mssql 作为 MSSQL 数据库连接器Web应用程序.路由处理程序逻辑在单独的文件中处理.
I want to use node-mssql as a MSSQL database connector in a Node JS Express 4 web application. Route handler logic is handled in separate files.
如何创建单个/全局连接池并在处理路由逻辑的多个文件中使用它?我不想在每个路由处理函数/文件中创建一个新的连接池.
How do I create a single/global connection pool and use it across several files where route logic is handled? I don't want to make a new connection pool in each route handler function/file.
推荐答案
自从我问和回答这个问题已经 3 年了.从那时起,一些事情发生了变化.这是我今天推荐的基于 ES6、mssql 4 和 Express 4 的新解决方案.
It's been 3 years since I asked and answered the question. Since then a few things have changed. Here's the new solution based on ES6, mssql 4 and Express 4 that I would suggest today.
这里有两个关键元素在起作用.
Two key elements are at play here.
- 模块在第一次加载后被缓存.这意味着每次调用 require('./db') 都将返回完全相同的对象.db.js 的第一个 require 将运行该文件并创建承诺并将其导出.db.js 的第二个要求将在不运行文件的情况下返回相同的承诺.正是这个承诺将与游泳池一起解决.
- 可以再次验证承诺.如果之前解决了,它会立即再次解决第一次解决的问题,也就是池.
- Modules are cached after the first time they are loaded. This means that every call to require('./db') will return exactly the same object. The first require of db.js will run that file and create the promise and export it. The second require of db.js will return THAT same promise without running the file. And it's that promise that will resolve with the pool.
- A promise can be thenified again. And if it resolved before, it will immediately resolve again with whatever it resolved with the first time, which is the pool.
在server.js
const express = require('express')
// require route handlers.
// they will all include the same connection pool
const set1Router = require('./routes/set1')
const set2Router = require('./routes/set2')
// generic express stuff
const app = express()
// ...
app.use('/set1', set1Router)
app.use('/set2', set2Router)
// No need to connect the pool
// Just start the web server
const server = app.listen(process.env.PORT || 3000, () => {
const host = server.address().address
const port = server.address().port
console.log(`Example app listening at http://${host}:${port}`)
})
在db.js
const sql = require('mssql')
const config = {/*...*