Something went wrong. Try again.
Synapse is a study workspace. Organize courses read and annotate the material, train with generated exercises and watch your progress forked from denishovart.com/synapse
Something went wrong. Try again.
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061import { Global, Inject, Injectable, Module, type OnModuleDestroy } from '@nestjs/common';import { openDrizzle, type AppDatabase, type AppSchema, type DrizzleHandle } from './drizzle/db';
// DI tokens. Repositories inject the live Drizzle db + the (dialect-matched)// schema object; they never import a dialect directly, so one implementation// serves both SQLite and Postgres.export const DRIZZLE = Symbol('DRIZZLE');export const DRIZZLE_SCHEMA = Symbol('DRIZZLE_SCHEMA');// The transaction + locking surface of the handle, injected where a repository// or service needs to run several writes atomically or hold a doc-scoped lock.export const DRIZZLE_TX = Symbol('DRIZZLE_TX');
export type DrizzleTx = Pick<DrizzleHandle, 'runInTx' | 'withDocLock' | 'dialect'>;// The opened handle (db + schema + close()); kept internal so shutdown can// release connections.const DRIZZLE_HANDLE = Symbol('DRIZZLE_HANDLE');
export type { AppDatabase, AppSchema } from './drizzle/db';
// Closes the underlying connection pool on app shutdown (no-op for SQLite).@Injectable()class DrizzleLifecycle implements OnModuleDestroy { constructor(@Inject(DRIZZLE_HANDLE) private readonly handle: DrizzleHandle) {} async onModuleDestroy(): Promise<void> { await this.handle.close(); }}
@Global()@Module({ providers: [ { // Opens the DB (runs migrations + data fixups) exactly once, app-wide. provide: DRIZZLE_HANDLE, useFactory: (): Promise<DrizzleHandle> => openDrizzle(), }, { provide: DRIZZLE, inject: [DRIZZLE_HANDLE], useFactory: (handle: DrizzleHandle): AppDatabase => handle.db, }, { provide: DRIZZLE_SCHEMA, inject: [DRIZZLE_HANDLE], useFactory: (handle: DrizzleHandle): AppSchema => handle.schema, }, { provide: DRIZZLE_TX, inject: [DRIZZLE_HANDLE], useFactory: (handle: DrizzleHandle): DrizzleTx => ({ runInTx: handle.runInTx, withDocLock: handle.withDocLock, dialect: handle.dialect, }), }, DrizzleLifecycle, ], exports: [DRIZZLE, DRIZZLE_SCHEMA, DRIZZLE_TX],})export class DatabaseModule {}