import type { Collection, CollectionOptions, Db, Document, MongoClient } from "mongodb"; import { mongo } from "./client.ts"; export function getDatabaseAccessor>( database: string, ): DatabaseAccessor { let instance: Db | undefined; return { get db(): Db { if (instance === undefined) { instance = this.client.db(database); } return instance; }, get client(): MongoClient { return mongo; }, collection( name: TSchema, options?: CollectionOptions, ): Collection { return this.db.collection(name.toString(), options); }, }; } export type DatabaseAccessor> = { /** * Database for given accessor. */ db: Db; /** * Lazy loaded mongo client. */ client: MongoClient; /** * Returns a reference to a MongoDB Collection. If it does not exist it will be created implicitly. * * Collection namespace validation is performed server-side. * * @param name - Collection name we wish to access. * @param options - Optional settings for the command. */ collection(name: TSchema, options?: CollectionOptions): Collection; };