UNPKG

@cardbrother/up-fetch

Version:

Advanced fetch client builder for typescript.

201 lines (194 loc) 9.95 kB
/** The Standard Schema interface. */ interface StandardSchemaV1<Input = unknown, Output = Input> { /** The Standard Schema properties. */ readonly "~standard": StandardSchemaV1.Props<Input, Output>; } declare namespace StandardSchemaV1 { /** The Standard Schema properties interface. */ export interface Props<Input = unknown, Output = Input> { /** The version number of the standard. */ readonly version: 1; /** The vendor name of the schema library. */ readonly vendor: string; /** Validates unknown input values. */ readonly validate: (value: unknown) => Result<Output> | Promise<Result<Output>>; /** Inferred types associated with the schema. */ readonly types?: Types<Input, Output> | undefined; } /** The result interface of the validate function. */ export type Result<Output> = SuccessResult<Output> | FailureResult; /** The result interface if validation succeeds. */ export interface SuccessResult<Output> { /** The typed output value. */ readonly value: Output; /** The non-existent issues. */ readonly issues?: undefined; } /** The result interface if validation fails. */ export interface FailureResult { /** The issues of failed validation. */ readonly issues: ReadonlyArray<Issue>; } /** The issue interface of the failure output. */ export interface Issue { /** The error message of the issue. */ readonly message: string; /** The path of the issue, if any. */ readonly path?: ReadonlyArray<PropertyKey | PathSegment> | undefined; } /** The path segment interface of the issue. */ export interface PathSegment { /** The key representing a path segment. */ readonly key: PropertyKey; } /** The Standard Schema types interface. */ export interface Types<Input = unknown, Output = Input> { /** The input type of the schema. */ readonly input: Input; /** The output type of the schema. */ readonly output: Output; } /** Infers the input type of a Standard Schema. */ export type InferInput<Schema extends StandardSchemaV1> = NonNullable<Schema["~standard"]["types"]>["input"]; /** Infers the output type of a Standard Schema. */ export type InferOutput<Schema extends StandardSchemaV1> = NonNullable<Schema["~standard"]["types"]>["output"]; export { }; } type KeyOf<O> = O extends unknown ? keyof O : never; type DistributiveOmit<TObject extends object, TKey extends KeyOf<TObject> | (string & {})> = TObject extends unknown ? Omit<TObject, TKey> : never; type MaybePromise<T> = T | Promise<T>; declare let isJsonifiable: (value: any) => value is JsonifiableObject | JsonifiableArray; type JsonPrimitive = string | number | boolean | null | undefined; type JsonifiableObject = Record<PropertyKey, any>; type JsonifiableArray = Array<JsonPrimitive | JsonifiableObject | JsonifiableArray> | ReadonlyArray<JsonPrimitive | JsonifiableObject | JsonifiableArray>; type BaseFetchFn = (input: any, options?: any, ctx?: any) => Promise<any>; type ParseResponse<TFetchFn extends BaseFetchFn, TParsedData> = (response: Response, options: ResolvedOptions<TFetchFn>) => MaybePromise<TParsedData>; type ParseRejected<TFetchFn extends BaseFetchFn> = (res: Response, options: ResolvedOptions<TFetchFn>) => any; type SerializeBody<TRawBody> = (body: TRawBody) => BodyInit | null | undefined; type SerializeParams = (params: Params) => string; type Params = Record<string, any>; type RawHeaders = HeadersInit | Record<string, string | number | null | undefined>; type Method = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'CONNECT' | 'OPTIONS' | 'TRACE' | 'HEAD' | (string & {}); type BaseOptions<TFetch extends BaseFetchFn> = DistributiveOmit<NonNullable<Parameters<TFetch>[1]>, 'body' | 'headers' | 'method'> & {}; type ResolvedOptions<TFetchFn extends BaseFetchFn, TSchema extends StandardSchemaV1 = any, TParsedData = any, TRawBody = any> = BaseOptions<TFetchFn> & { baseUrl?: string; readonly body?: BodyInit | null; headers: Record<string, string>; readonly input: Request | string; method?: Method; params: Params; parseRejected: ParseRejected<TFetchFn>; parseResponse: ParseResponse<TFetchFn, TParsedData>; rawBody?: TRawBody | null | undefined; reject: (response: Response) => MaybePromise<boolean>; schema?: TSchema; serializeBody: SerializeBody<TRawBody>; serializeParams: SerializeParams; signal?: AbortSignal; timeout?: number; }; type FallbackOptions<TFetchFn extends BaseFetchFn> = { parseRejected: ParseRejected<TFetchFn>; parseResponse: ParseResponse<TFetchFn, any>; reject: (response: Response) => MaybePromise<boolean>; serializeParams: SerializeParams; serializeBody: SerializeBody<BodyInit | JsonifiableObject | JsonifiableArray>; }; /** * Default configuration options for the fetch client */ type DefaultOptions<TFetchFn extends BaseFetchFn, TDefaultParsedData, TDefaultRawBody> = BaseOptions<TFetchFn> & { /** Base URL to prepend to all request URLs */ baseUrl?: string; /** Request headers to be sent with each request */ headers?: RawHeaders; /** HTTP method to use for the request */ method?: Method; /** Callback executed before the request is made */ onRequest?: (options: ResolvedOptions<TFetchFn>) => void | Promise<void>; /** Callback executed when the request fails */ onError?: (error: any, options: ResolvedOptions<TFetchFn>) => void; /** Callback executed when the request succeeds */ onSuccess?: (data: any, options: ResolvedOptions<TFetchFn>) => void; /** URL parameters to be serialized and appended to the URL */ params?: Params; /** Function to parse response errors */ parseRejected?: ParseRejected<TFetchFn>; /** Function to parse the response data */ parseResponse?: ParseResponse<TFetchFn, TDefaultParsedData>; /** * @deprecated Will be renamed `parseRejected` in v2.0 */ parseResponseError?: ParseRejected<TFetchFn>; /** Function to determine if a response should throw an error */ reject?: (response: Response) => MaybePromise<boolean>; /** Function to serialize request body. Restrict the valid `body` type by typing its first argument. */ serializeBody?: SerializeBody<TDefaultRawBody>; /** Function to serialize URL parameters */ serializeParams?: SerializeParams; /** AbortSignal to cancel the request */ signal?: AbortSignal; /** * @deprecated Will be renamed `reject` in v2.0 */ throwResponseError?: (response: Response) => MaybePromise<boolean>; /** Request timeout in milliseconds */ timeout?: number; }; /** * Options for individual fetch requests */ type FetcherOptions<TFetchFn extends BaseFetchFn, TSchema extends StandardSchemaV1, TParsedData, TRawBody> = BaseOptions<TFetchFn> & { /** Base URL to prepend to the request URL */ baseUrl?: string; /** Request body data */ body?: NoInfer<TRawBody> | null | undefined; /** Request headers */ headers?: RawHeaders; /** HTTP method */ method?: Method; /** URL parameters */ params?: Params; /** Function to parse response errors */ parseRejected?: ParseRejected<TFetchFn>; /** Function to parse the response data */ parseResponse?: ParseResponse<TFetchFn, TParsedData>; /** * @deprecated Will be renamed `parseRejected` in v2.0 */ parseResponseError?: ParseRejected<TFetchFn>; /** Function to determine if a response should throw an error */ reject?: (response: Response) => MaybePromise<boolean>; /** JSON Schema for request/response validation */ schema?: TSchema; /** Function to serialize request body. Restrict the valid `body` type by typing its first argument. */ serializeBody?: SerializeBody<TRawBody>; /** Function to serialize URL parameters */ serializeParams?: SerializeParams; /** AbortSignal to cancel the request */ signal?: AbortSignal; /** * @deprecated Will be renamed `reject` in v2.0 */ throwResponseError?: (response: Response) => MaybePromise<boolean>; /** Request timeout in milliseconds */ timeout?: number; }; declare function up<TFetchFn extends BaseFetchFn, TDefaultParsedData = any, TDefaultRawBody = Parameters<FallbackOptions<any>['serializeBody']>[0]>(fetchFn: TFetchFn, getDefaultOptions?: (input: Parameters<TFetchFn>[0], fetcherOpts: FetcherOptions<TFetchFn, any, any, any>, ctx?: Parameters<TFetchFn>[2]) => DefaultOptions<TFetchFn, TDefaultParsedData, TDefaultRawBody>): <TParsedData = TDefaultParsedData, TSchema extends StandardSchemaV1<TParsedData, any> = StandardSchemaV1<TParsedData, TParsedData>, TRawBody = TDefaultRawBody>(input: Parameters<TFetchFn>[0], fetcherOpts?: FetcherOptions<TFetchFn, TSchema, TParsedData, TRawBody>, ctx?: Parameters<TFetchFn>[2]) => Promise<StandardSchemaV1.InferOutput<TSchema>>; declare class ResponseError<TData = any, TFetchFn extends BaseFetchFn = typeof fetch> extends Error { name: 'ResponseError'; response: Response; options: ResolvedOptions<TFetchFn>; data: TData; status: number; constructor(res: Response, data: TData, options: ResolvedOptions<TFetchFn>); } declare let isResponseError: <TData = any, TFetchFn extends BaseFetchFn = typeof fetch>(error: any) => error is ResponseError<TData, TFetchFn>; declare class ValidationError<TData = any> extends Error { name: 'ValidationError'; issues: readonly StandardSchemaV1.Issue[]; data: TData; constructor(result: StandardSchemaV1.FailureResult, data: TData); } declare let isValidationError: (error: any) => error is ValidationError; export { type DefaultOptions, type FetcherOptions, type ResolvedOptions, ResponseError, ValidationError, isJsonifiable, isResponseError, isValidationError, up };