Repository navigation
Expand file tree
/
Copy pathJsonDirectoryDataSource.js
More file actions
78 lines (61 loc) · 1.93 KB
/
Copy pathJsonDirectoryDataSource.js
File metadata and controls
78 lines (61 loc) · 1.93 KB
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
'use strict';
const fs = require('fs');
const path = require('path');
const FileDataSource = require('./FileDataSource');
const JsonDataSource = require('./JsonDataSource');
/**
* Data source when you have a directory of json files and each entity is stored in
* its own json file, e.g.,
*
* foo/
* a.json
* b.json
* c.json
*
* Config:
* path: string: relative path to directory containing .json files from project root
*
* @extends DataSource
*/
class JsonDirectoryDataSource extends FileDataSource {
hasData(config = {}) {
const filepath = this.resolvePath(config);
return Promise.resolve(fs.existsSync(filepath));
}
fetchAll(config = {}) {
const dirPath = this.resolvePath(config);
if (!this.hasData(config)) {
throw new Error(`Invalid path [${dirPath}] specified for JsonDirectoryDataSource`);
}
return new Promise((resolve, reject) => {
const data = {};
fs.readdir(fs.realpathSync(dirPath), async (err, files) => {
for (const file of files) {
if (path.extname(file) !== '.json') {
continue;
}
const id = path.basename(file, '.json');
data[id] = await this.fetch(config, id);
}
resolve(data);
});
});
}
fetch(config = {}, id) {
const dirPath = this.resolvePath(config);
if (!fs.existsSync(dirPath)) {
throw new Error(`Invalid path [${dirPath}] specified for JsonDirectoryDataSource`);
}
const source = new JsonDataSource({}, dirPath);
return source.fetchAll({ path: `${id}.json` });
}
async update(config = {}, id, data) {
const dirPath = this.resolvePath(config);
if (!fs.existsSync(dirPath)) {
throw new Error(`Invalid path [${dirPath}] specified for JsonDirectoryDataSource`);
}
const source = new JsonDataSource({}, dirPath);
return await source.replace({ path: `${id}.json` }, data);
}
}
module.exports = JsonDirectoryDataSource;