/
UseCase.js
113 lines (107 loc) · 2.9 KB
/
UseCase.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
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
113
// LICENSE : MIT
"use strict";
import Dispatcher from "./Dispatcher";
import UseCaseContext from "./UseCaseContext";
import {ActionTypes} from "./Context";
import DispatcherPayloadMeta from "./DispatcherPayloadMeta";
/**
* @type {string}
* @private
*/
export let defaultUseCaseName = "<Anonymous-UseCase>";
/**
* UseCase class is inherited Dispatcher.
* The user implement own user-case that is inherited UseCase class
* @example
import {UseCase} from "almin";
class AwesomeUseCase extends UseCase {
execute(){
// implementation own use-case
}
}
*
* @public
*/
export default class UseCase extends Dispatcher {
/**
* return true if the `v` is a UseCase.
* @param {*} v
* @returns {boolean}
* @public
*/
static isUseCase(v) {
if (v instanceof UseCase) {
return true;
} else if (typeof v === "object" && typeof v.execute === "function") {
return true;
}
return false
}
constructor() {
super();
/**
* @type {string} default: UseCase name
*/
this.name = this.displayName || this.constructor.name || defaultUseCaseName;
/**
* @type {string} UseCase name
*/
this.useCaseName = this.constructor.name;
}
/**
* `execute()` method should be overwrite by subclass.
* @public
*/
execute() {
throw new TypeError(`should be overwrite ${this.constructor.name}#execute()`);
}
/**
* getter to get context of UseCase
* @returns {UseCaseContext} the UseCaseContext has `execute()` method
* @public
*/
get context() {
return new UseCaseContext(this);
}
/**
* called the `errorHandler` with error when error is occurred.
* @param {function(error: Error)} errorHandler
* @returns {function(this:Dispatcher)}
* @public
*/
onError(errorHandler) {
return this.onDispatch(payload => {
if (payload.type === ActionTypes.ON_ERROR) {
errorHandler(payload.error);
}
});
}
/**
* payload object that is dispatched when UseCase is failing or `throwError`.
* @typedef {Object} UseCaseErrorPayload
* @property {string} type The event type of error.
* @property {UseCase} useCase useCase instance
* @property {error} error error object that is thrown from UseCase
* @public
*/
/**
* throw error event
* you can use it instead of `throw new Error()`
* this error event is caught by dispatcher.
* @param {Error} error
* @public
*/
throwError(error) {
const meta = new DispatcherPayloadMeta({
useCase: this
});
/**
* @type {UseCaseErrorPayload}
*/
const payload = {
type: ActionTypes.ON_ERROR,
error: error
};
this.dispatch(payload, meta);
}
}