I am using Typescript (2.5.3) in a backend Node.js application, and trying to figure out where my coding mistake is, in the following code. Briefly, I have one main class, and several other classes that use this main class :
DataBase ( main class ) :
- which is a singleton ( see
export let DB = DataBase.Instance;
below ) - whose role is simply to connect to a Mongo database, and set a flag if connection successful or not. This flag will be used by other classes to know whether connection was established.
ModelParametersDataBase ( one of the other classes ) :
- this class imports the main class ( see
import { DB } from './DataBase' ;
below ) - gets the connection status through the main class.
Here is my issue :
My issue is that even though the connection is established once and for all (DB.dataBaseStatus = true
is called), the ModelParametersDataBase gets false
when calling the singleton's getter.
Here is an snippet from the DataBase.ts
:
class DataBase {
private static _instance: DataBase = undefined;
private dataBaseStatus_ = false ;
public static get Instance() {
return this._instance || (this._instance = new this());
}
public get dataBaseStatus() {
return this.dataBaseStatus_ ;
}
public set dataBaseStatus(status :boolean) {
this.dataBaseStatus_ = status ;
}
public configDatabase() {
/* Connect to Mongo DB */
mongoose.connect(MONGODB_CONNECTION_ROOT + MONGODB_DB_NAME, options)
.then(() => {
DB.dataBaseStatus = true ;
debug('CONNECTED TO DATABASE ');
},
err => {
DB.dataBaseStatus = false ;
debug('ERROR - CANNOT CONNECT TO DATABASE');
}
);
}
}
/** Instantiate singleton */
export let DB = DataBase.Instance;
Ane here is how I use this singleton in the ModelParametersDataBase
class :
import { DB } from './DataBase' ;
export class ModelParametersDataBase {
public static getModelParameters(): Promise<IModelParameters> {
return new Promise((resolve, reject) => {
if (DB.dataBaseStatus) {
// do stuff
} else {
reject(Error(CANNOT_REACH_DB));
}
});
}
}
Can you please point out where my mistake is ? Thanks.