Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

200
Visualizações
NodeJS: How to delay a module's resolution due to the dependencies on that module

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

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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).

  1. 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.

  2. 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.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda