-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmigration-set.js
135 lines (119 loc) · 2.8 KB
/
migration-set.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
'use strict'
const Migration = require('./migration')
module.exports = function MigrationSet (_migrations, sortFnc) {
let sorted = true
let lastRun = null
let migrations = []
add(_migrations)
// Add to migrations
function add (mig) {
if (!mig) {
return
}
// Add an array of migrations
if (Array.isArray(mig)) {
return mig.map(add)
}
// Adding single migration
let migration = mig
if (!(migration instanceof Migration)) {
migration = new Migration(migration)
}
migrations.push(migration)
sorted = false
return migration
}
// Sort by sort function if dirty
function sort () {
if (sorted) {
return
}
migrations.sort(sortFnc)
sorted = true
return p
}
function indexOf (title) {
sort()
for (let i = 0; i < migrations.length; ++i) {
if (migrations[i].title === title) {
return i
}
}
return -1
}
function filter (fnc) {
sort()
return migrations.filter(fnc)
}
const p = new Proxy({}, {
get: (target, prop) => {
// Accessable fields
switch (prop) {
case 'lastRun':
return lastRun
case 'add':
return add
case 'indexOf':
return indexOf
case 'sort':
return sort
case 'filter':
return filter
case 'size':
return migrations.length
case Symbol.iterator:
return () => {
return {
_i: -1,
next: function () {
sort()
this._i++
if (migrations[this._i]) {
return { value: migrations[this._i], done: false }
} else {
return { done: true }
}
}
}
}
}
if (typeof prop === 'string') {
// Get by index
const i = parseInt(prop, 10)
if (!isNaN(i)) {
return migrations[i]
}
// Get by title
return migrations.find((m) => m.title === prop)
}
return undefined
},
has: (target, prop) => {
if (typeof prop === 'string') {
// Get by index
const i = parseInt(prop, 10)
if (!isNaN(i)) {
return !!migrations[i]
}
// Get by title
return !!migrations.find((m) => m.title === prop)
}
return false
},
set: (target, prop, value) => {
if (prop === 'lastRun') {
if (!migrations.find((m) => m.title === value)) {
throw new Error(`lastRun does not exist in MigrationSet: ${value}`)
}
lastRun = value
return true
}
// dont allow calling set on other keys
return false
},
ownKeys: () => {
return migrations.map((m) => m.title)
}
})
return p
}