This repository has been archived by the owner on Nov 21, 2020. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 16
/
db-migrate-store.js
66 lines (52 loc) · 1.78 KB
/
db-migrate-store.js
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
66
const mongoose = require('mongoose');
const dotenv = require('dotenv');
dotenv.config();
class dbStore {
constructor() {
this.url = process.env.MONGO_URL
this.db = null
}
connect() {
return mongoose.createConnection(this.url, { useNewUrlParser: true }).then(client => {
return client.db;
})
}
load(fn) {
return this.connect()
.then(db => db.collection('migrations').find().toArray())
.then(data => {
if (!data.length) return fn(null, {})
const store = data[0]
// Check if old format and convert if needed
if (!Object.prototype.hasOwnProperty.call(store, 'lastRun') &&
Object.prototype.hasOwnProperty.call(store, 'pos')) {
if (store.pos === 0) {
store.lastRun = null
} else {
if (store.pos > store.migrations.length)
return fn(new Error('Store file contains invalid pos property'))
store.lastRun = store.migrations[store.pos - 1].title
}
// In-place mutate the migrations in the array
store.migrations.forEach((migration, index) => {
if (index < store.pos)
migration.timestamp = Date.now()
})
}
// Check if does not have required properties
if (!Object.prototype.hasOwnProperty.call(store, 'lastRun') || !Object.prototype.hasOwnProperty.call(store, 'migrations'))
return fn(new Error('Invalid store file'))
return fn(null, store)
})
.catch(fn)
}
save(set, fn) {
return this.connect()
.then(db => db.collection('migrations')
.replaceOne({}, { migrations: set.migrations, lastRun: set.lastRun }, { upsert: true })
.then(result => fn(null, result))
)
.catch(fn)
}
}
module.exports = dbStore;