diff --git a/lib/utils/got.ts b/lib/utils/got.ts index 5fb000c5e..d707308d6 100644 --- a/lib/utils/got.ts +++ b/lib/utils/got.ts @@ -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 = GotResponse & { + data: T; + status: number; +}; + +type GotRequestFunction = { + (url: string | URL, options?: Options): CancelableRequest>>; + (url: string | URL, options?: Options): CancelableRequest>; + (options: Options): CancelableRequest>>; + (options: Options): CancelableRequest>; +}; + +// @ts-expect-error got instance with custom response type +const custom: { all?: (list: Array>) => Promise>; -} = 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; - status?: number; - } - ) => { + // @ts-expect-error custom response type + (response: Response>) => { 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;