-
Notifications
You must be signed in to change notification settings - Fork 1
/
client.ts
115 lines (97 loc) · 2.35 KB
/
client.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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
import axios from 'axios';
/*
rules : {
}
*/
function apiHandler(rules = {ERROR_CODE_CHECK: ""}) {
return function (target, property, descriptor) {
let originMethod = descriptor.value
descriptor.value = async function (...args) {
let res = {
status: 200,
data: {},
errorCode: false
}
try {
let { status, data } = await originMethod.apply(target, args)
res = {
status, data,
errorCode: data[rules.ERROR_CODE_CHECK]
}
// 정상응답은 여기서 반환
// errorCode가 있는 응답은 try ~ catch 밖에서 반환 => exception 발생
// 여기서 throw 호출할 경우 아래의 catch에서 받음
if (!res.errorCode) return res
} catch (err) { // 4xx, 5xx는 exception 처리된다.
let { status, data } = err.response
res = {
status, data,
errorCode: data[rules.ERROR_CODE_CHECK]
}
throw {
...res,
error: new Error('Error Force Raise By StatusCode')
};
}
if (res.errorCode) {
throw {
...res,
error: new Error('Error Force Raise By ErrorCode')
};
}
}
}
};
class ApiCall {
static URL: string = 'http://127.0.0.1:3000'
@apiHandler()
static async call(path, data) {
return await axios.get(`${ApiCall.URL}${path}`)
}
@apiHandler({
ERROR_CODE_CHECK: "errorCode1"
})
static async callRule(path, data) {
return await axios.get(`${ApiCall.URL}${path}`)
}
}
; (async () => {
console.log('===== No Rules =====')
try {
let res = await ApiCall.call('/a', {})
console.log(res)
} catch (err) {
console.log(err)
}
try {
let res = await ApiCall.call('/b', {})
console.log(res)
} catch (err) {
console.log(err)
}
try {
let res = await ApiCall.call('/c', {})
console.log(res)
} catch (err) {
console.log(err)
}
console.log('===== Rules =====')
try {
let res = await ApiCall.callRule('/a', {})
console.log(res)
} catch (err) {
console.log(err)
}
try {
let res = await ApiCall.callRule('/b', {})
console.log(res)
} catch (err) {
console.log(err)
}
try {
let res = await ApiCall.callRule('/c', {})
console.log(res)
} catch (err) {
console.log(err)
}
})()