diff --git a/src/services/mongodb.ts b/src/services/mongodb.ts new file mode 100644 index 0000000..10ff0de --- /dev/null +++ b/src/services/mongodb.ts @@ -0,0 +1,85 @@ +import _ from 'lodash'; + +import { singleton, container } from 'tsyringe'; +import { + MongoClientOptions, ObjectId, +} from 'mongodb'; + +import { AbstractMongoDB, AbstractMongoCollection, AbstractMongoCappedCollection } from 'civkit/abstract/mongo'; + + +import { LoggerInterface } from 'civkit/logger'; +import globalLogger, { GlobalLogger } from '../services/logger'; +import { Finalizer } from './finalizer'; +import { InjectProperty } from './registry'; +import { SecretExposer } from '../shared/services/secrets'; + +@singleton() +export class MongoDB extends AbstractMongoDB { + options?: MongoClientOptions; + url!: string; + logger = this.globalLogger.child({ service: this.constructor.name }); + + @InjectProperty() protected config!: SecretExposer; + + constructor( + protected globalLogger: GlobalLogger + ) { + super(...arguments); + + this.dependsOn(this.config); + } + + override async init() { + await this.dependencyReady(); + if (!this.options) { + this.options = { + minPoolSize: 2, + maxPoolSize: 10, + }; + } + if (!this.url) { + this.url = this.config.MONGO_URI; + } + + await super.init(); + + this.emit('ready'); + } + + @Finalizer() + override async standDown() { + if (this.serviceStatus !== 'ready') { + return; + } + await this.client.close(true); + super.standDown(); + } +} + +export abstract class MongoCollection extends AbstractMongoCollection { + @InjectProperty() + mongo!: MongoDB; + + logger: LoggerInterface = globalLogger.child({ service: this.constructor.name }); + + constructor(...whatever: any[]) { + super(...whatever); + + this.dependsOn(globalLogger); + } +} + +export abstract class MongoCappedCollection extends + AbstractMongoCappedCollection { + + logger: LoggerInterface = globalLogger.child({ service: this.constructor.name }); + + @InjectProperty() + mongo!: MongoDB; + +} + +export const mongoClient = container.resolve(MongoDB); + +export default mongoClient; diff --git a/thinapps-shared b/thinapps-shared index 95c88c0..4552b18 160000 --- a/thinapps-shared +++ b/thinapps-shared @@ -1 +1 @@ -Subproject commit 95c88c0da1058144a86b736fde6bec8a861c2800 +Subproject commit 4552b18a12f249a8413ba73700bbe0816e9fde0d