| 12 | } |
| 13 | |
| 14 | export class MongoAdapter { |
| 15 | client?: MongoClient |
| 16 | db?: Db |
| 17 | options: MongoClientOptions |
| 18 | connectionString: string |
| 19 | |
| 20 | constructor(url: string | MongoConnectionlOptions, options: MongoClientOptions = {}) { |
| 21 | if (typeof url === 'object') { |
| 22 | const { user, password: pwd, dbName: db, host } = url |
| 23 | url = user ? `mongodb://${user}:${pwd}@${host}` : `mongodb://${host}` |
| 24 | url += db ? `/${db}` : '' |
| 25 | } |
| 26 | this.connectionString = url |
| 27 | this.options = options |
| 28 | } |
| 29 | |
| 30 | async connect() { |
| 31 | if (this.db) return this.db |
| 32 | const client = await MongoClient.connect(this.connectionString, this.options) |
| 33 | this.db = client.db() |
| 34 | return this.db |
| 35 | } |
| 36 | |
| 37 | async collection(name: string) { |
| 38 | const client = await this.connect() |
| 39 | return client.collection(name) |
| 40 | } |
| 41 | |
| 42 | async get<T extends MongoCommandOptions>(query: T) { |
| 43 | const doc = await this.collection(query.docName) |
| 44 | return doc.findOne(query) |
| 45 | } |
| 46 | |
| 47 | async put<T extends MongoCommandOptions>(query: T, values: object) { |
| 48 | const doc = await this.collection(query.docName) |
| 49 | const { value: document } = await doc.findOneAndUpdate( |
| 50 | query, |
| 51 | { $set: { ...query, ...values } }, |
| 52 | { upsert: true, returnDocument: 'after' }, |
| 53 | ) |
| 54 | return document |
| 55 | } |
| 56 | |
| 57 | async del<T extends MongoCommandOptions>(query: T) { |
| 58 | const doc = await this.collection(query.docName) |
| 59 | return doc.deleteMany(query) |
| 60 | } |
| 61 | |
| 62 | async readAsCursor<T extends MongoCommandOptions>( |
| 63 | query: T, |
| 64 | { limit, reverse }: { limit?: number; reverse?: boolean } = {}, |
| 65 | ) { |
| 66 | const doc = await this.collection(query.docName) |
| 67 | let curs = doc.find(query) |
| 68 | if (reverse) curs = curs.sort({ clock: -1 }) |
| 69 | if (limit) curs = curs.limit(limit) |
| 70 | return curs.toArray() |
| 71 | } |
nothing calls this directly
no outgoing calls
no test coverage detected
searching dependent graphs…