-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathsample-store.js
79 lines (66 loc) · 1.88 KB
/
sample-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
67
68
69
70
71
72
73
74
75
76
77
78
79
'use strict';
const fs = require('fs');
function FileStore2(path) {
this.path = path;
}
/**
* Save the migration data.
*
* @api public
*/
FileStore2.prototype.save = function (set, fn) {
console.log('custom saver...');
fs.writeFile(this.path, JSON.stringify({
lastRun: set.lastRun,
migrations: set.migrations,
}, null, ' '), fn);
};
/**
* Load the migration data and call `fn(err, obj)`.
*
* @param {Function} fn
* @return {Type}
* @api public
*/
FileStore2.prototype.load = function (fn) {
console.log('custom loader...');
fs.readFile(this.path, 'utf8', (err, json) => {
if (err && err.code !== 'ENOENT') return fn(err);
if (!json || json === '') {
return fn(null, {});
}
let store;
try {
store = JSON.parse(json);
// eslint-disable-next-line no-shadow
} catch (err) {
return fn(err);
}
// Check if old format and convert if needed
// eslint-disable-next-line no-prototype-builtins
if (!store.hasOwnProperty('lastRun') && store.hasOwnProperty('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) {
// eslint-disable-next-line no-param-reassign
migration.timestamp = Date.now();
}
});
}
// Check if does not have required properties
// eslint-disable-next-line no-prototype-builtins
if (!store.hasOwnProperty('lastRun') || !store.hasOwnProperty('migrations')) {
return fn(new Error('Invalid store file'));
}
return fn(null, store);
});
};
module.exports = FileStore2;