-
-
Notifications
You must be signed in to change notification settings - Fork 159
/
mongodb.ts
65 lines (51 loc) · 2.03 KB
/
mongodb.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
import type {UmzugStorage} from './contract'
type AnyObject = Record<string, any>
export type MongoDBConnectionOptions = {
/**
A connection to target database established with MongoDB Driver
*/
readonly connection: AnyObject
/**
The name of the migration collection in MongoDB
@default 'migrations'
*/
readonly collectionName?: string
}
export type MongoDBCollectionOptions = {
/**
A reference to a MongoDB Driver collection
*/
readonly collection: AnyObject
}
export type MongoDBStorageConstructorOptions = MongoDBConnectionOptions | MongoDBCollectionOptions
function isMongoDBCollectionOptions(arg: any): arg is MongoDBCollectionOptions {
return Boolean(arg.collection)
}
export class MongoDBStorage implements UmzugStorage {
public readonly collection: AnyObject
public readonly connection: any // TODO remove this
public readonly collectionName: string // TODO remove this
constructor(options: MongoDBStorageConstructorOptions) {
if (!options || (!(options as any).collection && !(options as any).connection)) {
throw new Error('MongoDB Connection or Collection required')
}
this.collection = isMongoDBCollectionOptions(options)
? options.collection
: options.connection.collection(options.collectionName ?? 'migrations')
this.connection = (options as any).connection // TODO remove this
this.collectionName = (options as any).collectionName ?? 'migrations' // TODO remove this
}
async logMigration({name: migrationName}: {name: string}): Promise<void> {
await this.collection.insertOne({migrationName})
}
async unlogMigration({name: migrationName}: {name: string}): Promise<void> {
await this.collection.deleteOne({migrationName})
}
async executed(): Promise<string[]> {
type Record = {migrationName: string}
const records: Record[] = await this.collection.find({}).sort({migrationName: 1}).toArray()
return records.map(r => r.migrationName)
}
}