diff --git a/src/packages/emmett-mongodb/src/eventStore/mongoDBEventStore.ts b/src/packages/emmett-mongodb/src/eventStore/mongoDBEventStore.ts index 14b9211..9d22f07 100644 --- a/src/packages/emmett-mongodb/src/eventStore/mongoDBEventStore.ts +++ b/src/packages/emmett-mongodb/src/eventStore/mongoDBEventStore.ts @@ -14,13 +14,7 @@ import { type ReadEventMetadata, type ExpectedStreamVersion, } from '@event-driven-io/emmett'; -import { - type WithId, - type Collection, - type Db, - MongoClient, - ObjectId, -} from 'mongodb'; +import { type Collection, MongoClient, ObjectId } from 'mongodb'; export const MongoDBEventStoreDefaultStreamVersion = -1; export const MongoDBDefaultCollectionName = 'eventstreams'; @@ -61,17 +55,10 @@ export interface MongoDBConnectionOptions { } class EventStoreClass implements EventStore { - private readonly client: MongoClient; - private readonly db: Db; private readonly collection: Collection; - constructor(options: MongoDBConnectionOptions) { - this.client = new MongoClient(options.connectionString); - this.db = this.client.db(options.database); - this.collection = this.db.collection( - options.collection ?? MongoDBDefaultCollectionName, - ); - this.collection.createIndex({ streamName: 1 }, { unique: true }); + constructor(collection: typeof this.collection) { + this.collection = collection; } async readStream( @@ -142,7 +129,7 @@ class EventStoreClass implements EventStore { ): Promise> { const eventCreateInputs = events.map(this.stringifyEvent); - let stream: WithId | null = await this.collection.findOne({ + let stream = await this.collection.findOne({ streamName: { $eq: streamName }, }); let createdNewStream = false; @@ -271,8 +258,16 @@ class EventStoreClass implements EventStore { } } -export const getMongoDBEventStore = (options: MongoDBConnectionOptions) => { - const eventStore = new EventStoreClass(options); +export const getMongoDBEventStore = async ( + options: MongoDBConnectionOptions, +) => { + const client = new MongoClient(options.connectionString); + const db = client.db(options.database); + const collection = db.collection( + options.collection ?? MongoDBDefaultCollectionName, + ); + await collection.createIndex({ streamName: 1 }, { unique: true }); + const eventStore = new EventStoreClass(collection); return eventStore; };