Suppose the following scenario:
We have a class that handles a Mongoose connection as below:
export interface IInstance {
name: string;
instance: Mongoose.Mongoose;
}
export default class MongoHandler {
public static instances: IInstance[] = [{
name: 'default',
instance: null,
}];
// Connect to mongo instance and add it to the instances array
public static async connect(name: string, uri: string, options?: object): Promise<void> {
const instance: Mongoose.Mongoose = await Mongoose.connect(uri, options);
const newInstance: IInstance = {
name,
instance,
};
MongoHandler.instances.push(newInstance);
}
// Returns the instance based on the name of instance
public static getInstance(name: string = 'default'): Mongoose.Mongoose {
return this.instances.find(instance => instance.name === name).instance;
}
}
The other module called CarModel is using getInstance() method for creating a model:
export interface ICar {
name: string;
}
const carSchema = new Mongoose.Schema<ICar>(
{
name: {
type: String,
required: true,
},
}
);
const carModel = MongoHandler.getInstance('default').model<ICar>('Car', carSchema, 'Cars');
export default carModel;
We are using carModel in a module called CarController.
In index.ts we are calling these two modules as below:
import
const app = new App(
[
MongoHandler.connect('default', process.env.MONGO_URI),
],
[
new CarController(),
]
);
App is a class for handling express bootstrapping (can be ignored).
While running this code MongoHandler.getInstance('default') is undefined because of the order of dependency resolution (I think)! And resolving MongoHandler.getInstance('default') is followed by MongoHandler.connect() which should be reversed.
How can I solve this?
Best regards
I think there are 2 issues at play here, neither of them having to do with module resolution (which will work just fine as you don't have any circular dependencies).
array.prototype.find returns the FIRST match found, you instantiate instances array with an object that matches the name default, but has no instance. When you connect, you add another object with the name default, but this will be second in the list, thus find will return the original object, which has its instance object set as null. I would advice removing this default empty instance object for error and code clarity.
your connect function makes use of async-await. But you never await your connect function, thus not guaranteeing that your new connection instance has been made before you are calling getInstance inside of your carController. You should catch the Promise returned by the connect function and await it. If you do not want to delay your CarController instantiation, you can use save this Promise in the MongoHandler and return it with some init function that you call inside of the CarController to make sure the connect has been resolved.