0

this is bit of a loaded quesiton but thought i may give it a go. We have similar db code for diff projects so we decided to wrap Sequelize into its own module. basically, i have this format

const instance = require('./instance');
const modelDefinitions = require('./models');
const queries = require('./queries');
const sequelize = require('sequelize');

module.exports = {
  ...queries,
  ...modelDefinitions,
  instance,
  sequelize,
};

so basically, ./instance will create connection and load up all models and etc then export it via

const getInstance = () => {
  let instance = null;
  
  .... INSTANCE CODE

  try {

    return instance;
  } catch (error) {}
};

module.exports = getInstance();

so then when you import the module, the instance is created.

to add more,

const queries = require('./queries');

this is the actual queries using the models. Now, in here we also need the instance to make these calls so we import it like such (example based on one of the files)

const instance = require('../instance');

const testQuery = async id => {
    return instance.models.fakeModel.findAll();
};

so my question is, is there a bad practice? to load and return instance like that? and pass it into files within the module? We may getting closed connections and/or mem leaks and trying to figure out if maybe it is due to the way the code is above

here is an example of how our service uses it, which should load the instance, and multiple files will be importing it

const { testQuery, instance, <ETC> } = require('@something/db');

thanks in advance

3
  • If it's a separate module it would be better to use getInstance to get an instance in the code rather than use already created instance from it. Commented May 20, 2023 at 16:08
  • @Anatoly hello. I heard this is like a factory method that kinda simulates a singleton but I can be wrong, else what makes the way you suggested better vs what I have? Commented May 21, 2023 at 19:57
  • It's better to have an opportunity to create an instance on the fly rather that always have on the first module import. Commented May 21, 2023 at 20:56

0

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.