dimanche 5 avril 2020

Is it safe to rely on module caching by Nodejs for single instances

I use the following pattern when I need to make sure that I have a single instance of a class:

class DB {    
    constructor() {
        // create db connection
    }
}

const myDB = new DB();
export default myDB;

So that even if I import it multiple other modules, I get the same instance. Is this a reliable pattern? I know that module caching comes with the file case sensitivity caveat. But are there any edge cases that could cause my multiple imports to create multiple db objects?

I know that I can alternatively create a concrete singleton, with a getInstance() method but this pattern looks simpler.

Aucun commentaire:

Enregistrer un commentaire