Reputation: 250
I have an npm dependency that I import into a file of my server node. I wish it was not a singleton because it should not be shared between each request.
The file who import the dependency :
const dependency = require('dependency');
export class dependencyFactory {
public static getDependency() {
return dependency;
}
}
index.js of dependency in node_modules :
const path = require('path');
const createApi = require('./createApi');
module.exports = createApi(path.join(__dirname, './lib/providers'));
How can i do that ? thank you.
Upvotes: 1
Views: 874
Reputation: 222875
Modules result in singletons in Node. If this is undesirable, a workaround always depends on specific package.
A preferable way is to export factory function or constructor class from a package that can create new instances when needed.
If this is not possible, possible workarounds may include:
All of them can be considered hacks and should be avoided when possible. E.g. relying on internal package structure may introduce breaking changes with new package version, even if package changelog doesn't assume breaking changes. And a pitfall for cache invalidation is that a package may consist of numerous modules that should or should not be re-imported.
The first workaround seems to be applicable here.
const createApi = require('dependency/createApi');
const instance = createApi(require.resolve('dependency/lib/providers'));
A cleaner solution is to fork a package and add a capability to create multiple instances.
Upvotes: 1