-
Notifications
You must be signed in to change notification settings - Fork 0
/
02-Fluent-UseCase.ts
59 lines (54 loc) · 1.35 KB
/
02-Fluent-UseCase.ts
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
import { UseCase, Context, Dispatcher, Store } from "almin";
class MyUseCase extends UseCase {
execute(...args) {
return args;
}
}
class AsyncUseCase extends UseCase {
execute(value: string) {
return Promise.resolve(value);
}
}
class UseCaseExecutor<T extends UseCase> {
useCase: T;
constructor(useCase: T) {
this.useCase = useCase;
}
executor(executor: (useCase: T) => any) {
return new Promise((resolve, reject) => {
const proxyUseCase = proxify(this.useCase, resolve, reject);
executor(proxyUseCase);
});
}
}
const proxify = <T extends UseCase>(useCase: T, resolve: Function, reject: Function): T => {
let isExecuted = false;
return {
execute(...args){
console.info("[LOG]", ...args);
if (isExecuted) {
return reject(new Error("already executed"));
}
return resolve(useCase.execute(...args));
}
} as T;
};
/**
* Fluent UseCase style
*
* It could
*
* - type safe UseCase
* - hook
*
*/
new UseCaseExecutor(new MyUseCase())
.executor(useCase => useCase.execute("test"))
.then(value => {
console.log(value);
});
new UseCaseExecutor(new AsyncUseCase())
.executor(useCase => useCase.execute("async"))
.then(value => {
console.log(value);
});