-
-
Notifications
You must be signed in to change notification settings - Fork 391
/
Copy pathky-http-client.ejs
220 lines (198 loc) · 5.98 KB
/
ky-http-client.ejs
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
220
<%
const { apiConfig, generateResponses, config } = it;
%>
import type {
BeforeRequestHook,
Hooks,
KyInstance,
Options as KyOptions,
NormalizedOptions,
SearchParamsOption,
} from "ky";
import ky from "ky";
type KyResponse<Data> = Response & {
json<T extends Data = Data>(): Promise<T>;
}
export type ResponsePromise<Data> = {
arrayBuffer: () => Promise<ArrayBuffer>;
blob: () => Promise<Blob>;
formData: () => Promise<FormData>;
json<T extends Data = Data>(): Promise<T>;
text: () => Promise<string>;
} & Promise<KyResponse<Data>>;
export type ResponseFormat = keyof Omit<Body, "body" | "bodyUsed">;
export interface FullRequestParams
extends Omit<KyOptions, "json" | "body" | "searchParams"> {
/** set parameter to `true` for call `securityWorker` for this request */
secure?: boolean;
/** request path */
path: string;
/** content type of request body */
type?: ContentType;
/** query params */
query?: SearchParamsOption;
/** format of response (i.e. response.json() -> format: "json") */
format?: ResponseFormat;
/** request body */
body?: unknown;
}
export type RequestParams = Omit<
FullRequestParams,
"body" | "method" | "query" | "path"
>;
export interface ApiConfig<SecurityDataType = unknown>
extends Omit<KyOptions, "data" | "cancelToken"> {
securityWorker?: (
securityData: SecurityDataType | null,
) => Promise<NormalizedOptions | void> | NormalizedOptions | void;
secure?: boolean;
format?: ResponseType;
}
export enum ContentType {
Json = "application/json",
FormData = "multipart/form-data",
UrlEncoded = "application/x-www-form-urlencoded",
Text = "text/plain",
}
export class HttpClient<SecurityDataType = unknown> {
public ky: KyInstance;
private securityData: SecurityDataType | null = null;
private securityWorker?: ApiConfig<SecurityDataType>["securityWorker"];
private secure?: boolean;
private format?: ResponseType;
constructor({
securityWorker,
secure,
format,
...options
}: ApiConfig<SecurityDataType> = {}) {
this.ky = ky.create({ ...options, prefixUrl: options.prefixUrl || "" });
this.secure = secure;
this.format = format;
this.securityWorker = securityWorker;
}
public setSecurityData = (data: SecurityDataType | null) => {
this.securityData = data;
};
protected mergeRequestParams(
params1: KyOptions,
params2?: KyOptions,
): KyOptions {
return {
...params1,
...params2,
headers: {
...params1.headers,
...(params2 && params2.headers),
},
};
}
protected stringifyFormItem(formItem: unknown) {
if (typeof formItem === "object" && formItem !== null) {
return JSON.stringify(formItem);
} else {
return `${formItem}`;
}
}
protected createFormData(input: Record<string, unknown>): FormData {
return Object.keys(input || {}).reduce((formData, key) => {
const property = input[key];
const propertyContent: any[] =
property instanceof Array ? property : [property];
for (const formItem of propertyContent) {
const isFileType = formItem instanceof Blob || formItem instanceof File;
formData.append(
key,
isFileType ? formItem : this.stringifyFormItem(formItem),
);
}
return formData;
}, new FormData());
}
public request = <T = any, _E = any>({
secure = this.secure,
path,
type,
query,
format,
body,
...options
<% if (config.unwrapResponseData) { %>
}: FullRequestParams): Promise<T> => {
<% } else { %>
}: FullRequestParams): ResponsePromise<T> => {
<% } %>
if (body) {
if (type === ContentType.FormData) {
body =
typeof body === "object"
? this.createFormData(body as Record<string, unknown>)
: body;
} else if (type === ContentType.Text) {
body = typeof body !== "string" ? JSON.stringify(body) : body;
}
}
let headers: Headers | Record<string, string | undefined> | undefined;
if (options.headers instanceof Headers) {
headers = new Headers(options.headers);
if (type && type !== ContentType.FormData) {
headers.set("Content-Type", type);
}
} else {
headers = { ...options.headers } as Record<string, string | undefined>;
if (type && type !== ContentType.FormData) {
headers["Content-Type"] = type;
}
}
let hooks: Hooks | undefined;
if (secure && this.securityWorker) {
const securityWorker: BeforeRequestHook = async (request, options) => {
const secureOptions = await this.securityWorker!(this.securityData);
if (secureOptions && typeof secureOptions === "object") {
let { headers } = options;
if (secureOptions.headers) {
const mergedHeaders = new Headers(headers);
const secureHeaders = new Headers(secureOptions.headers);
secureHeaders.forEach((value, key) => {
mergedHeaders.set(key, value);
});
headers = mergedHeaders;
}
return new Request(request.url, {
...options,
...secureOptions,
headers,
});
}
};
hooks = {
...options.hooks,
beforeRequest:
options.hooks && options.hooks.beforeRequest
? [securityWorker, ...options.hooks.beforeRequest]
: [securityWorker],
};
}
const request = this.ky(path.replace(/^\//, ""), {
...options,
headers,
searchParams: query,
body: body as any,
hooks,
});
<% if (config.unwrapResponseData) { %>
const responseFormat = format || this.format || undefined;
return (responseFormat === "json"
? request.json()
: responseFormat === "arrayBuffer"
? request.arrayBuffer()
: responseFormat === "blob"
? request.blob()
: responseFormat === "formData"
? request.formData()
: request.text()) as Promise<T>;
<% } else { %>
return request;
<% } %>
};
}