-
Notifications
You must be signed in to change notification settings - Fork 6
/
YamlDataSource.js
73 lines (53 loc) · 1.61 KB
/
YamlDataSource.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
'use strict';
const fs = require('fs');
const yaml = require('js-yaml');
const FileDataSource = require('./FileDataSource');
/**
* Data source when you have all entities in a single yaml file
*
* Config:
* path: string: relative path to .yml file from project root
*/
class YamlDataSource 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 YamlDataSource`);
}
return new Promise((resolve, reject) => {
const contents = fs.readFileSync(fs.realpathSync(filepath)).toString('utf8');
resolve(yaml.load(contents));
});
}
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, yaml.dump(data), 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 = YamlDataSource;