-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathhttp.ts
More file actions
219 lines (183 loc) · 5.75 KB
/
Copy pathhttp.ts
File metadata and controls
219 lines (183 loc) · 5.75 KB
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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
export type FetchConfig = Omit<RequestInit, 'headers'> & {
headers?: Record<string, string>;
};
export type HttpBody = BodyInit | object;
export class BaseHttpClientError extends Error {
response: Response;
constructor(response: Response) {
super(`HTTP request failed: ${response.statusText} (${response.url})`)
this.response = response
}
}
function nonEmptyString(value: unknown): string | null {
return typeof value === 'string' && value.trim() ? value.trim() : null;
}
function resolveJsonErrorMessage(body: unknown): string | null {
if (!body || typeof body !== 'object') {
return nonEmptyString(body);
}
const record = body as Record<string, unknown>;
const detail = record.detail;
if (Array.isArray(detail)) {
const messages = detail
.map((item) => {
if (!item || typeof item !== 'object') {
return nonEmptyString(item);
}
const itemRecord = item as Record<string, unknown>;
return nonEmptyString(itemRecord.msg) ?? nonEmptyString(itemRecord.message);
})
.filter((message): message is string => Boolean(message));
if (messages.length > 0) {
return messages.join(' ');
}
}
const detailMessage = nonEmptyString(detail)
?? resolveJsonErrorMessage(detail);
const message = detailMessage
?? nonEmptyString(record.message)
?? nonEmptyString(record.error);
if (!message) {
return null;
}
const detailRecord = detail && typeof detail === 'object' && !Array.isArray(detail)
? detail as Record<string, unknown>
: null;
const existingLock = detailRecord?.existing_lock;
const lockRecord = existingLock && typeof existingLock === 'object' && !Array.isArray(existingLock)
? existingLock as Record<string, unknown>
: null;
const taskNumber = lockRecord?.task_number;
if (
typeof taskNumber === 'number'
|| (typeof taskNumber === 'string' && taskNumber.trim())
) {
const normalizedMessage = /[.!?]$/.test(message) ? message : `${message}.`;
return `${normalizedMessage} Existing lock: Task #${String(taskNumber).trim()}.`;
}
return message;
}
export async function resolveHttpErrorMessage(
error: unknown,
fallbackMessage: string
): Promise<string> {
const response = error instanceof Error && 'response' in error
? (error as { response?: Response }).response
: undefined;
if (response) {
try {
const message = resolveJsonErrorMessage(await response.clone().json());
if (message) {
return message;
}
}
catch {
try {
const contentType = response.headers.get('Content-Type') ?? '';
const message = contentType.includes('application/json')
? ''
: (await response.clone().text()).trim();
if (message) {
return message;
}
}
catch {
// Use the caller's concise fallback when the response body cannot be read.
}
}
return fallbackMessage;
}
return error instanceof Error && error.message.trim()
? error.message
: fallbackMessage;
}
export abstract class BaseHttpClient {
_baseUrl: string;
_requestHeaders = {
'Accept': 'application/json',
'Authorization': '',
'Content-Type': 'application/json'
};
_abortSignal?: AbortSignal;
constructor(baseUrl: string, signal?: AbortSignal) {
this._baseUrl = baseUrl;
this._abortSignal = signal;
}
url(rest: string) {
return this._baseUrl + rest
}
_get(url: string, config?: FetchConfig): Promise<Response> {
return this._send(url, 'GET', undefined, config);
}
_post(url: string, body?: HttpBody, config?: FetchConfig): Promise<Response> {
return this._send(url, 'POST', body, config);
}
_put(url: string, body?: HttpBody, config?: FetchConfig): Promise<Response> {
return this._send(url, 'PUT', body, config);
}
_patch(url: string, body?: HttpBody, config?: FetchConfig): Promise<Response> {
return this._send(url, 'PATCH', body, config);
}
_delete(url: string, config?: FetchConfig): Promise<Response> {
return this._send(url, 'DELETE', undefined, config);
}
async _sendTest(url: string, method: string, body?: any): Promise<Response> {
const response = await fetch(this.url(url), {
method,
body,
headers: {
Accept: 'application/text',
Authorization: this._requestHeaders.Authorization
}
});
if (!response.ok) {
throw new BaseHttpClientError(response);
}
return response;
}
async _send(
url: string,
method: string,
body?: HttpBody,
config?: FetchConfig,
): Promise<Response> {
const { headers: configHeaders, ...restConfig } = config ?? {};
const mergedHeaders: Record<string, string> = {
...this._requestHeaders,
...configHeaders,
};
const requestOptions = {
method,
body: undefined as BodyInit | undefined,
headers: mergedHeaders,
signal: this._abortSignal,
...restConfig,
};
// Let the browser set Content-Type (and multipart boundary) for FormData:
if (body instanceof FormData) {
delete mergedHeaders['Content-Type'];
requestOptions.body = body;
}
else if (body !== null && body !== undefined && (
mergedHeaders['Content-Type'] === 'application/json'
|| (
typeof body === 'object'
&& !(body instanceof Blob)
&& !(body instanceof ArrayBuffer)
&& !ArrayBuffer.isView(body)
&& !(body instanceof URLSearchParams)
&& !(body instanceof ReadableStream)
)
)) {
requestOptions.body = JSON.stringify(body);
}
else {
requestOptions.body = body as BodyInit;
}
const response = await fetch(this.url(url), requestOptions);
if (!response.ok) {
throw new BaseHttpClientError(response);
}
return response;
}
}