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
getInstanceto get an instance in the code rather than use already created instance from it.