This repository was archived by the owner on Dec 15, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 402
/
Copy pathaction-pipeline.js
76 lines (63 loc) · 1.87 KB
/
action-pipeline.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
74
75
76
function partial(fn, ...args) {
return function wrapped() {
return fn(...args);
};
}
export class ActionPipeline {
constructor(actionKey) {
this.actionKey = actionKey;
this.middleware = [];
}
run(fn, repository, ...args) {
const pipelineFn = this.middleware
.map(middleware => middleware.fn)
.reduceRight((acc, nextFn) => partial(nextFn, acc, repository, ...args), partial(fn, ...args));
return pipelineFn(...args);
}
addMiddleware(name, fn) {
if (!name) {
throw new Error('Middleware must be registered with a unique middleware name');
}
if (this.middleware.find(middleware => middleware.name === name)) {
throw new Error(`A middleware with the name ${name} is already registered`);
}
this.middleware.push({name, fn});
}
}
export default class ActionPipelineManager {
constructor({actionNames} = {actionNames: []}) {
this.pipelines = new Map();
this.actionKeys = {};
actionNames.forEach(actionName => {
const actionKey = Symbol(actionName);
this.actionKeys[actionName] = actionKey;
this.pipelines.set(actionKey, new ActionPipeline(actionKey));
});
}
getPipeline(actionKey) {
const pipeline = this.pipelines.get(actionKey);
if (actionKey && pipeline) {
return pipeline;
} else {
throw new Error(`${actionKey} is not a known action`);
}
}
}
class NullActionPipeline extends ActionPipeline {
run(fn, repository, ...args) {
return fn(...args);
}
addMiddleware() {
throw new Error('Cannot add middleware to a null pipeline');
}
}
const nullPipeline = new NullActionPipeline();
class NullActionPipelineManager extends ActionPipelineManager {
getPipeline() {
return nullPipeline;
}
}
const nullActionPipelineManager = new NullActionPipelineManager();
export function getNullActionPipelineManager() {
return nullActionPipelineManager;
}