简体   繁体   中英

How to keep one instance of the database using express

I am using express along with sequelize to create a REST API. I want to keep just one instance of my database and use it in all the routes I may create. My first thought was to create the instance as soon as the app runs. Something like this.

const express = require('express')
const databaseService = require( './services/database')
const config = require( './config')

const userRoute = require( './routes/user')

const app = express()

databaseService.connect(config.db_options).then(
    connectionInstance => {
        app.use('user', userRoute(connectionInstance))
        app.listen(3000)
    }
)

I have not seen something like that so I believe it's not a good approach.

Any ideas ?

A strategy that I use extensively in several production applications to great success is to define the database connection logic in a single file similar to the following:

database.js

const dbClient = require('some-db-client')
let db

module.exports.connectDB = async () => {
  const client = await dbClient.connect(<DB_URL>)

  db = client.db()
}

module.exports.getDB = () => {
  return db
}

Obviously, the connection logic would need to be more complex then what I have defined above, but you can get the idea that you would connect to your database using whichever database client library that you choose and save a reference to that single instance of your database. Then, wherever you need to interface with your database, you can call the getDB function. But first, you would need to make a call to your connectDB function from your server application entry file.

server.js

async function run() {
  const db = require('./database')
  await db.connectDB()

  const app = require('express')()
  const routes = require('./routes')

  app.use('/', routes)

  app.listen(3000, () => {
    console.log('App server listening to port 3000')
  })
}

You would make the call to initialize your database connection in the server application entry file before initializing express . Afterwards, any place in your application that needs access to the database can simple call the getDB() function and use the returned database object as necessary from there. This does not require overly complicated connection open and close logic and saves on the overhead of constantly opening and closing connections whenever you want to access the database by maintaining just a single database connection that can be used anywhere.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM