/
ky-http-client.ejs
137 lines (119 loc) · 4.17 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
<%
const { apiConfig, generateResponses, config } = it;
%>
import type { KyInstance, Options as KyOptions, 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"> {
/** 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"> {
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 format?: ResponseType;
constructor({ format, ...options }: ApiConfig<SecurityDataType> = {}) {
this.ky = ky.create({ ...options, prefixUrl: options.prefixUrl || "<%~ apiConfig.baseUrl %>" })
this.format = format;
}
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>({
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;
}
}
const request = this.ky(path, {
...options,
headers,
searchParams: query,
body: body as any,
});
<% 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();
<% } else { %>
return request;
<% } %>
};
}