-
-
Notifications
You must be signed in to change notification settings - Fork 196
/
jsonStore.js
75 lines (67 loc) · 1.93 KB
/
jsonStore.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
'use strict'
// eslint-disable-next-line one-var
var jsonfile = require('jsonfile'),
reqlib = require('app-root-path').require,
storeDir = reqlib('config/app.js').storeDir,
Promise = require('bluebird'),
debug = reqlib('/lib/debug')('Store'),
utils = reqlib('lib/utils.js')
debug.color = 3
function getFile (config) {
return new Promise((resolve, reject) => {
jsonfile.readFile(utils.joinPath(true, storeDir, config.file), function (err, data) {
if (err && err.code !== 'ENOENT') {
reject(err)
} else {
if (err && err.code === 'ENOENT') {
debug(config.file, 'not found')
}
if (!data) {
data = config.default
}
resolve({ file: config.file, data: data })
}
})
})
}
/**
Constructor
**/
function StorageHelper () {
this.store = {}
}
StorageHelper.prototype.init = function (config) {
return new Promise((resolve, reject) => {
storage_helper.config = config
Promise.map(Object.keys(config), function (model) {
return getFile(config[model])
}).then(results => {
for (var i = 0; i < results.length; i++) {
storage_helper.store[results[i].file] = results[i].data
}
resolve(storage_helper.store)
})
.catch(err => reject(err))
})
}
StorageHelper.prototype.get = function (model) {
if (storage_helper.store[model.file]) {
return storage_helper.store[model.file]
} else {
throw Error('Requested file not present in store: ' + model.file)
}
}
StorageHelper.prototype.put = function (model, data) {
return new Promise((resolve, reject) => {
jsonfile.writeFile(utils.joinPath(true, storeDir, model.file), data, function (err) {
if (err) {
reject(err)
} else {
storage_helper.store[model.file] = data
resolve(storage_helper.store[model.file])
}
})
})
}
// eslint-disable-next-line camelcase
var storage_helper = module.exports = new StorageHelper()