Skip to content

Commit 8ef1098

Browse files
committed
FP Refactor
Thx to @clemos
1 parent 0d580dc commit 8ef1098

File tree

2 files changed

+44
-48
lines changed

2 files changed

+44
-48
lines changed

lib/index.js

Lines changed: 11 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -102,7 +102,12 @@ function isAuthentifiedFunction(methodName) {
102102
'stat', 'batch'].includes(methodName);
103103
}
104104

105-
const HOOKS = ['onRead', 'onWrite'];
105+
const HOOKS = {
106+
ON_READ: 'onRead',
107+
ON_WRITE: 'onWrite'
108+
};
109+
110+
const applyPlugins = (plugins, content) => plugins.reduce((data, action) => action(data), content);
106111

107112
const connectors = Symbol('connectors');
108113

@@ -121,8 +126,8 @@ class Unifile {
121126
*/
122127
constructor() {
123128
this[connectors] = new Map();
124-
this.plugins = HOOKS.reduce((memo, hook) => {
125-
memo[hook] = [];
129+
this.plugins = Object.keys(HOOKS).reduce((memo, key) => {
130+
memo[HOOKS[key]] = [];
126131
return memo;
127132
}, {});
128133
}
@@ -144,7 +149,7 @@ class Unifile {
144149
* @param {Plugin} plugin - A plugin with at least one hook implemented
145150
*/
146151
ext(plugin) {
147-
HOOKS.forEach((hook) => {
152+
Object.keys(HOOKS).map((key) => HOOKS[key]).forEach((hook) => {
148153
if(plugin.hasOwnProperty(hook)) this.plugins[hook].push(plugin[hook]);
149154
});
150155
}
@@ -267,10 +272,7 @@ class Unifile {
267272
* @return {external:Promise<null>} an empty promise.
268273
*/
269274
writeFile(session, connectorName, path, content) {
270-
let input = content;
271-
this.plugins.onWrite.forEach((action) => {
272-
input = action(input);
273-
});
275+
const input = applyPlugins(this.plugins[HOOKS.ON_WRITE], content);
274276
return this.callMethod(connectorName, session, 'writeFile', path, input);
275277
}
276278

@@ -294,13 +296,7 @@ class Unifile {
294296
*/
295297
readFile(session, connectorName, path) {
296298
return this.callMethod(connectorName, session, 'readFile', path)
297-
.then((content) => {
298-
let output = content;
299-
this.plugins.onRead.forEach((action) => {
300-
output = action(output);
301-
});
302-
return output;
303-
});
299+
.then((content) => applyPlugins(this.plugins[HOOKS.ON_READ], content));
304300
}
305301

306302
/**

package-lock.json

Lines changed: 33 additions & 33 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)