-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathJsonDataSource.js
71 lines (50 loc) · 1.51 KB
/
JsonDataSource.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
'use strict';
const fs = require('fs');
const FileDataSource = require('./FileDataSource');
/**
* Data source when you have all entities in a single json file
*
* Config:
* path: string: relative path to .json file from project root
*/
class JsonDataSource extends FileDataSource {
hasData(config = {}) {
const filepath = this.resolvePath(config);
return Promise.resolve(fs.existsSync(filepath));
}
fetchAll(config = {}) {
const filepath = this.resolvePath(config);
if (!this.hasData(config)) {
throw new Error(`Invalid path [${filepath}] for JsonDataSource`);
}
delete require.cache[filepath];
return Promise.resolve(require(filepath));
}
async fetch(config = {}, id) {
const data = await this.fetchAll(config);
if (!data.hasOwnProperty(id)) {
throw new ReferenceError(`Record with id [${id}] not found.`);
}
return data[id];
}
replace(config = {}, data) {
const filepath = this.resolvePath(config);
return new Promise((resolve, reject) => {
fs.writeFile(filepath, JSON.stringify(data, null, 2), err => {
if (err) {
return reject(err);
}
resolve();
})
})
}
async update(config = {}, id, data) {
const currentData = await this.fetchAll(config);
if (Array.isArray(currentData)) {
throw new TypeError('Yaml data stored as array, cannot update by id');
}
currentData[id] = data;
return this.replace(config, currentData);
}
}
module.exports = JsonDataSource;