I'm starting a simple backend server using NodeJS and Typescript, to take advantage of its autocomplete/type detection features.
In previous applications, all the database logic was inside a db.js file, which is imported where needed using require. So far, it's been working good, but I'd like to give a try to importing modules using import, just to see its pros and cons, and I'd like some advice.
My plan is to create a class to handle all the database logic and keep the connection information. Something like:
db.ts
import { Sequelize } from 'sequelize';
export class AppDB {
// Will store the connection, note that it's STATIC
static sequelize: Sequelize;
constructor() {
// Connect to the DB and store the connection in the class property
AppDB.sequelize = this.connect(.....);
}
}
This way, I could access the database connection from all the routes or models using:
models/example_model.ts
import { AppDB } from 'db/db';
....
AppDB.sequelize.query(...);
....
My question is: Is this a good way of sharing an object through the application? Does it have any disadvantages over using require?
Thanks in advance,