My MonoRepo structure
Intent: I want to bring out database from app1 and app2 level and put it to common's database folder. So app1 and app2 or appN will pass on the connection string and the class from shared repo will establish the connection to DB.
Problem: If I bring out this db connecting to common it's not loading models in app1 and app2. I can see the value of readyState: 1
, which means mongo is connected but, I'm not sure why it's not loading models.
I'm not using Lerna or NX. it's simple TS project. Every project has tsConfig and package.json but all common codes/services are in common folder. This mono repo contains only backend code.
Now the simple way I'm connecting to DB from individual app level is like below,
const dbConnectionConfig = { url: MONGO_URI ?? '', options: { dbName: MASTER_DATABASE_NAME, },};export class Database { private static instance: Database; private isConnected: boolean = false; private constructor() {} public static async getInstance(): Promise<Database> { if (!Database.instance) { Database.instance = new Database(); await Database.instance.establishConnection(); } return Database.instance; } private async establishConnection(): Promise<void> { if (this.isConnected) return; try { if (NODE_ENV !== 'production') { set('debug', true) } await connect(dbConnectionConfig.url, dbConnectionConfig.options); this.isConnected = true; } catch (err) { throw err; } }}
and in app.ts in app1 and app2 folder I'm doing like this
public static getInstance({ routes = [] }: { routes?: IRoute[] } = {}): App { if (!App.instance) { App.instance = new App(routes); Database.getInstance().catch((err) => { logger.error('Database connection failed', err); process.exit(1); }); } return App.instance; }
I'm following repository pattern, in common I'm keeping base repository and base models like below,
export class BaseRepository<T> implements IBaseRepository<T> { private model: Model<T>; constructor(model: Model<T>) { this.model = model } async findAll(query: any): Promise<T[]> { return this.model.find(query) };}
and
export class BaseSchema<T extends { [key: string]: any } = any> extends Schema { constructor(schema: Record<string, any> = {}) { const baseFields = { isDeleted: { type: SchemaTypes.Boolean, required: true, default: false }, createdBy: { type: SchemaTypes.String, required: false }, updatedBy: { type: SchemaTypes.String, required: false }, }; const combinedSchema = { ...baseFields, ...schema }; super(combinedSchema, { timestamps: true, discriminatorKey: 'kind' }); }}
this is how I'm extending these classes to app1, app2
interface XRepositoryInterface {}export class XRepository extends BaseRepository<IX> implements XRepositoryInterface { constructor() { super(XModel); }}
and
const XSchema = new BaseSchema<IX>({ userId: { type: SchemaTypes.String, ref: 'user', required: true }, version: { type: SchemaTypes.String, required: false },});export const XModel = model<IX>(COLLECTION_NAME.X, XSchema);
Can anyone please help me with this?