This repository was archived by the owner on Oct 14, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathindex.js
More file actions
112 lines (96 loc) · 2.71 KB
/
index.js
File metadata and controls
112 lines (96 loc) · 2.71 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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
// const makeDebug = require('debug');
// const debug = makeDebug('feathers-fs');
const p = require('path');
const fs = require('fs');
const defaults = {
root: undefined,
cache: false,
type: 'json'
};
class Service {
constructor (options) {
if (!options.root) {
throw new Error('You must provide a `root` path to the feathers-json adapter');
}
this.options = Object.assign({}, defaults, options);
}
create ({path, data}) {
if (!path) {
return Promise.reject(new Error('You must pass a `path` to the feathers-json adapter\'s create method.'));
}
let filePath = this.makeFilePath(path);
return this.toFileString(data)
.then(dataString => {
return new Promise((resolve, reject) => {
fs.writeFile(filePath, dataString, 'utf8', function (err) {
if (err) {
reject(err);
} else {
resolve(data);
}
});
});
});
}
get (path, params = {}) {
const { cache } = params;
if (!path) {
return Promise.reject(new Error('You must pass a `path` to the feathers-json adapter\'s get method.'));
}
path = this.makeFilePath(path);
return this.readFromFile(path, { cache });
}
/**
* Reads a file at `path` and returns a Promise that resolves with an object literal.
* @param {String} path - The location of the file to be read.
* @return Promise
*/
readFromFile (path, params = {}) {
const { cache } = params;
return new Promise((resolve, reject) => {
let data;
try {
const shouldCache = cache === undefined ? this.options.cache : cache;
shouldCache || this.clearCache(path);
data = require(path);
shouldCache || this.clearCache(path);
resolve(data);
} catch (error) {
reject(error);
}
});
}
/**
* Clears a module from the require cache.
* @param {String} path - The module path to be cleared from the require cache
*/
clearCache (path) {
delete require.cache[require.resolve(path)];
}
// Input an object literal and output a string.
toFileString (data) {
return new Promise((resolve, reject) => {
let formatted;
try {
formatted = JSON.stringify(data, null, 2);
resolve(formatted);
} catch (error) {
reject(error);
}
});
}
makeFilePath (path) {
let fullPath = p.join(this.options.root, path);
let extension = '.' + this.options.type;
if (!fullPath.includes(extension)) {
fullPath += extension;
}
return fullPath;
}
}
function init (options) {
options = Object.assign({}, defaults, options);
return new Service(options);
}
init.Service = Service;
module.exports = init;