-
Notifications
You must be signed in to change notification settings - Fork 0
/
mod.ts
96 lines (82 loc) · 2.09 KB
/
mod.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
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
export type TResult<DataType, ErrorType> =
| ResultOK<DataType>
| ResultFAIL<ErrorType>;
export type TResultAsync<DataType, ErrorType> = Promise<
TResult<DataType, ErrorType>
>;
export class Result<DataType, ErrorType> {
protected readonly data: DataType;
protected readonly error: ErrorType;
constructor(data: DataType, error: ErrorType) {
this.data = data;
this.error = error;
}
}
export class ResultOK<DataType> extends Result<DataType, undefined> {
constructor(data: DataType) {
super(data, void 0);
}
unwrap(): DataType {
return this.data;
}
isOk(): boolean {
return true;
}
isFail(): boolean {
return false;
}
}
export class ResultFAIL<ErrorType> extends Result<undefined, ErrorType> {
constructor(error: ErrorType) {
super(void 0, error);
}
unwrap(): never {
throw this.error;
}
isOk(): boolean {
return false;
}
isFail(): boolean {
return true;
}
}
export const ok = <DataType>(data: DataType) => new ResultOK(data);
export const fail = <ErrorType>(error: ErrorType) => new ResultFAIL(error);
export function tryCatch<TargetType, DataType, ErrorType>(
target: TargetType,
property: string,
descriptor: PropertyDescriptor,
): PropertyDescriptor {
const self = descriptor.value;
descriptor.value = function (...args: any[]) {
try {
if (self instanceof Function) {
return self.call(this, ...args);
} else {
return fail(new TypeError("Descriptor value is not a function."));
}
} catch (error) {
return fail(error);
}
};
return descriptor;
}
export function tryCatchAsync<TargetType, DataType, ErrorType>(
target: TargetType,
property: string,
descriptor: PropertyDescriptor,
): PropertyDescriptor {
const self = descriptor.value;
descriptor.value = async function (...args: any[]) {
try {
if (self instanceof Function) {
return await self.call(this, ...args);
} else {
return fail(new TypeError("Descriptor value is not a function."));
}
} catch (error) {
return fail(error);
}
};
return descriptor;
}