0

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,

1
  • ES Modules in Node.js are still experimental. So no, it is not good practice (yet?). Commented Aug 2, 2019 at 15:21

1 Answer 1

1

In Typescript, import can only be used if there is a types declaration file (*.d.ts). The require keyword ignores those types and completely removes the use of types for that particular library.

This is a fine way of achieveing your goal to use the same database connection in different files.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.