'Load subsequent modules after a DB Call (TypeScript, NodeJs, Inversify)
I am working on a project in which we were using a TypeScript Enum to maintain a list of currencies data that we are using in our Project but problem is whenever we introduce a new Currency, We will have to hardcode that Currency Enum to add currency. I was assigned a task to remove local currency enum and used a db call to get that currency list. Here is the enum :-
export enum Currencies {
USD = 'USD'
}
I have added migration to add currencies data to db and also added an injectable class which contains db call to get that list here is the code for it:-
@injectable()
export class CurrencyService {
@inject(SERVICE_IDENTIFIER.CurrencyRepository) private currencyRepository: ICurrencyRepository;
public async getCurrencies(): Promise<any> {
let currencies = {};
const currencyList = await this.currencyRepository.distinct("currency_label");
currencyList.forEach(currency => currencies[currency] = currency);
return currencies;
}}
This is working fine. My next task is to get this DB Currencies available to different modules that were using Currency file which is as follows:-
import { Currencies } from './enum';
export const paymentQuery = Joi.object().keys({
currency: Joi.string().valid(Object.values(Currencies)).required(),
});
export type NewCardPaymentQuery = Joi.extractType<typeof paymentQuery>;
So i rewrite the Currencies enum file as follows :-
import { container } from './inversifyContainer';
let currencies = container.get(CurrencyService).getCurrencies();
export const Currencies = currencies;
It has two problems:-
First:- container.get is undefined (That's is container is undefined, unintialized)(when enum file is compiled container is unavailable).
Second:- getCurrencies returns a promise which means if i use async function call to initialize the data, all the subsequent files that are using the Currencies recieves an empty Object which can't be changed later.
So, I want to load these files after application has initialized. Can someone guide how it can be possible ?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|