-
-
Notifications
You must be signed in to change notification settings - Fork 347
Expand file tree
/
Copy pathclient.gen.ts
More file actions
254 lines (216 loc) · 6.76 KB
/
client.gen.ts
File metadata and controls
254 lines (216 loc) · 6.76 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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
// This file is auto-generated by @hey-api/openapi-ts
import type { HttpResponse } from '@angular/common/http';
import { HttpClient, HttpErrorResponse, HttpEventType, HttpRequest } from '@angular/common/http';
import {
assertInInjectionContext,
inject,
provideAppInitializer,
runInInjectionContext,
} from '@angular/core';
import { firstValueFrom } from 'rxjs';
import { filter } from 'rxjs/operators';
import { createSseClient } from '../core/serverSentEvents.gen';
import type { HttpMethod } from '../core/types.gen';
import { getValidRequestBody } from '../core/utils.gen';
import type {
Client,
Config,
RequestOptions,
ResolvedRequestOptions,
ResponseStyle,
} from './types.gen';
import {
buildUrl,
createConfig,
createInterceptors,
mergeConfigs,
mergeHeaders,
setAuthParams,
} from './utils.gen';
export function provideHeyApiClient(client: Client) {
return provideAppInitializer(() => {
const httpClient = inject(HttpClient);
client.setConfig({ httpClient });
});
}
export const createClient = (config: Config = {}): Client => {
let _config = mergeConfigs(createConfig(), config);
const getConfig = (): Config => ({ ..._config });
const setConfig = (config: Config): Config => {
_config = mergeConfigs(_config, config);
return getConfig();
};
const interceptors = createInterceptors<
HttpRequest<unknown>,
HttpResponse<unknown>,
unknown,
ResolvedRequestOptions
>();
const requestOptions = <
TData = unknown,
ThrowOnError extends boolean = false,
TResponseStyle extends ResponseStyle = 'fields',
>(
options: RequestOptions<TData, TResponseStyle, ThrowOnError>,
) => {
const opts = {
..._config,
...options,
headers: mergeHeaders(_config.headers, options.headers),
httpClient: options.httpClient ?? _config.httpClient,
serializedBody: undefined as string | undefined,
};
if (!opts.httpClient) {
if (opts.injector) {
opts.httpClient = runInInjectionContext(opts.injector, () => inject(HttpClient));
} else {
assertInInjectionContext(requestOptions);
opts.httpClient = inject(HttpClient);
}
}
if (opts.body !== undefined && opts.bodySerializer) {
opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined;
}
// remove Content-Type header if body is empty to avoid sending invalid requests
if (opts.body === undefined || opts.serializedBody === '') {
opts.headers.delete('Content-Type');
}
const url = buildUrl(opts as any);
const req = new HttpRequest<unknown>(opts.method ?? 'GET', url, getValidRequestBody(opts), {
redirect: 'follow',
...opts,
});
return { opts, req, url };
};
const beforeRequest = async <
TData = unknown,
TResponseStyle extends ResponseStyle = 'fields',
ThrowOnError extends boolean = boolean,
Url extends string = string,
>(
options: RequestOptions<TData, TResponseStyle, ThrowOnError, Url>,
) => {
const { opts, req, url } = requestOptions(options);
if (opts.security) {
await setAuthParams({
...opts,
security: opts.security,
});
}
if (opts.requestValidator) {
await opts.requestValidator(opts);
}
return { opts, req, url };
};
const request: Client['request'] = async (options) => {
const { opts, req: initialReq } = await beforeRequest(options);
let req = initialReq;
for (const fn of interceptors.request.fns) {
if (fn) {
req = await fn(req, opts as any);
}
}
const result: {
request: HttpRequest<unknown>;
response: any;
} = {
request: req,
response: null,
};
try {
result.response = (await firstValueFrom(
opts
.httpClient!.request(req)
.pipe(filter((event) => event.type === HttpEventType.Response)),
)) as HttpResponse<unknown>;
for (const fn of interceptors.response.fns) {
if (fn) {
result.response = await fn(result.response, req, opts as any);
}
}
let bodyResponse = result.response.body;
if (opts.responseValidator) {
await opts.responseValidator(bodyResponse);
}
if (opts.responseTransformer) {
bodyResponse = await opts.responseTransformer(bodyResponse);
}
return opts.responseStyle === 'data' ? bodyResponse : { data: bodyResponse, ...result };
} catch (error) {
if (error instanceof HttpErrorResponse) {
result.response = error;
}
let finalError = error instanceof HttpErrorResponse ? error.error : error;
for (const fn of interceptors.error.fns) {
if (fn) {
finalError = (await fn(finalError, result.response as any, req, opts as any)) as string;
}
}
if (opts.throwOnError) {
if (opts.responseStyle === 'fields') {
throw {
error: finalError,
...result,
};
}
throw finalError;
}
return opts.responseStyle === 'data'
? undefined
: {
error: finalError,
...result,
};
}
};
const makeMethodFn = (method: Uppercase<HttpMethod>) => (options: RequestOptions) =>
request({ ...options, method });
const makeSseFn = (method: Uppercase<HttpMethod>) => async (options: RequestOptions) => {
const { opts, url } = await beforeRequest(options);
return createSseClient({
...opts,
body: opts.body as BodyInit | null | undefined,
headers: opts.headers as unknown as Record<string, string>,
method,
serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined,
url,
});
};
const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options });
return {
buildUrl: _buildUrl,
connect: makeMethodFn('CONNECT'),
delete: makeMethodFn('DELETE'),
get: makeMethodFn('GET'),
getConfig,
head: makeMethodFn('HEAD'),
interceptors,
options: makeMethodFn('OPTIONS'),
patch: makeMethodFn('PATCH'),
post: makeMethodFn('POST'),
put: makeMethodFn('PUT'),
request,
requestOptions: (options) => {
if (options.security) {
throw new Error('Security is not supported in requestOptions');
}
if (options.requestValidator) {
throw new Error('Request validation is not supported in requestOptions');
}
return requestOptions(options).req;
},
setConfig,
sse: {
connect: makeSseFn('CONNECT'),
delete: makeSseFn('DELETE'),
get: makeSseFn('GET'),
head: makeSseFn('HEAD'),
options: makeSseFn('OPTIONS'),
patch: makeSseFn('PATCH'),
post: makeSseFn('POST'),
put: makeSseFn('PUT'),
trace: makeSseFn('TRACE'),
},
trace: makeMethodFn('TRACE'),
} as Client;
};