fix: custom got response type
This commit is contained in:
+28
-11
@@ -1,10 +1,30 @@
|
||||
import logger from '@/utils/logger';
|
||||
import { config } from '@/config';
|
||||
import got, { type Response, type NormalizedOptions, type Options } from 'got';
|
||||
import got, { CancelableRequest, Response as GotResponse, NormalizedOptions, Options } from 'got';
|
||||
|
||||
const custom: typeof got & {
|
||||
type Response<T> = GotResponse<unknown> & {
|
||||
data: T;
|
||||
status: number;
|
||||
};
|
||||
|
||||
type GotRequestFunction = {
|
||||
(url: string | URL, options?: Options): CancelableRequest<Response<Record<string, any>>>;
|
||||
<T>(url: string | URL, options?: Options): CancelableRequest<Response<T>>;
|
||||
(options: Options): CancelableRequest<Response<Record<string, any>>>;
|
||||
<T>(options: Options): CancelableRequest<Response<T>>;
|
||||
};
|
||||
|
||||
// @ts-expect-error got instance with custom response type
|
||||
const custom: {
|
||||
all?: <T>(list: Array<Promise<T>>) => Promise<Array<T>>;
|
||||
} = got.extend({
|
||||
get: GotRequestFunction;
|
||||
post: GotRequestFunction;
|
||||
put: GotRequestFunction;
|
||||
patch: GotRequestFunction;
|
||||
head: GotRequestFunction;
|
||||
delete: GotRequestFunction;
|
||||
} & GotRequestFunction = got.extend({
|
||||
get: got.get,
|
||||
retry: {
|
||||
limit: config.requestRetry,
|
||||
statusCodes: [400, 401, 402, 403, 404, 405, 406, 407, 408, 409, 410, 411, 412, 413, 414, 415, 416, 417, 421, 422, 423, 424, 426, 428, 429, 431, 451, 500, 501, 502, 503, 504, 505, 506, 507, 508, 510, 511, 521, 522, 524],
|
||||
@@ -28,16 +48,13 @@ const custom: typeof got & {
|
||||
},
|
||||
],
|
||||
afterResponse: [
|
||||
(
|
||||
response: Response & {
|
||||
data?: Record<string, any> | string;
|
||||
status?: number;
|
||||
}
|
||||
) => {
|
||||
// @ts-expect-error custom response type
|
||||
(response: Response<Record<string, any>>) => {
|
||||
try {
|
||||
response.data = JSON.parse(response.body as string);
|
||||
response.data = typeof response.body === 'string' ? JSON.parse(response.body) : response.body;
|
||||
} catch {
|
||||
response.data = response.body as string;
|
||||
// @ts-expect-error for compatibility
|
||||
response.data = response.body;
|
||||
}
|
||||
response.status = response.statusCode;
|
||||
return response;
|
||||
|
||||
Reference in New Issue
Block a user