-
Notifications
You must be signed in to change notification settings - Fork 0
/
01-Revealing-Constructor-Pattern-UseCase.ts
55 lines (50 loc) · 1.47 KB
/
01-Revealing-Constructor-Pattern-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
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> {
promise: Promise<any>;
constructor(useCase: T, executor: (useCase: T) => any) {
this.promise = new Promise((resolve, reject) => {
const proxyUseCase = proxify(useCase, resolve, reject);
executor(proxyUseCase);
});
}
then(onFull, onReject?) {
return this.promise.then(onFull, onReject);
}
catch(onReject) {
return this.promise.catch(onReject);
}
}
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;
};
/**
* Revealing Constructor Pattern
* Reference: https://blog.domenic.me/the-revealing-constructor-pattern/
*/
new UseCaseExecutor(new MyUseCase(), (useCase) => useCase.execute('arg', 'arg2')).then(value => {
console.log(value);
});
new UseCaseExecutor(new AsyncUseCase(), (useCase) => {
return useCase.execute("test");
}).then(value => {
console.log(value);
});