UNPKG

frest

Version:

REST client for browser with Fetch

821 lines (813 loc) 29 kB
/// <reference types="node" /> /** * Default configuration if Frest instance is created without any configuration. * @public */ declare const DEFAULT_CONFIG: Config; /** * Frest constructor/class signature. * @remarks * This is only used for UMD build. * @public */ interface FrestConstructor { new (config?: ConfigType): Frest; } /** * The main Frest class. * @public */ declare class Frest { config: Config; interceptors: Interceptors; /** * Creates an instance of Frest. * @param config - Configuration for this instance. * Can be string or array of string (in which it'll be the `base` URL for * every requests), or a {@link Config} object. Defaults to `DEFAULT_CONFIG` */ constructor(config?: ConfigType); /** * Get base URL used in this instance. */ get base(): string; create(config?: ConfigType): Frest; /** * Merge this instance config with the one provided here. * @param config - Configuration to be merged into this instance's configuration. */ mergeConfig(config: ConfigMergeType): void; /** * Get `fetch` function used in this instance. * @remarks * This can be the native `fetch` API or any function with similar signature. */ get fetchFn(): typeof window.fetch; /** * Get full URL from the provided path and query object/string. * @remarks * This will use the instance's `base` URL configuration and construct full * URL to the provided arguments. * * @param path - Endpoint path * @param query - query object/string to include * @returns Full URL to the provided arguments. */ parsePath(path: string | string[], query?: any): string; /** * Utility function to parse a query object into string. * * @remarks * This is a shortcut to the `utils.parseQuery` function. * * @param query - The query to parse. It can be object/string * @returns Parsed query string */ parseQuery(query: any): string; /** * Make a request to an endpoint. * * @template T - The type of response's body, if any. Defaults to `any`. * @param init - A string, string array, or request configuration object. * @param request - request configuration if the first arg is string * or string array * @returns Response promise which will be resolved when the request is successful. * The promise will throws in case of error in any request life-cycle. */ request<T = any>(init: RequestType, request?: Partial<FrestRequest>): Promise<FrestResponse<T>>; private internalRequest; private requestConfig; private headers; private getFetch; private before; private req; private after; private onError; private toFrestError; } interface Frest { /** * Make a request to an endpoint with HTTP `POST` method. * * @template T - The type of response's body, if any. Defaults to `any`. * @param init - A string, string array, or request configuration object. * @param request - request configuration if the first arg is string * or string array * @returns Response promise which will be resolved when the request is successful. * The promise will throws in case of error in any request life-cycle. */ post<T = any>(init: RequestType, body?: any, request?: Partial<FrestRequest>): Promise<FrestResponse<T>>; /** * Make a request to an endpoint with HTTP `GET` method. * * @template T - The type of response's body, if any. Defaults to `any`. * @param init - A string, string array, or request configuration object. * @param request - request configuration if the first arg is string * or string array * @returns Response promise which will be resolved when the request is successful. * The promise will throws in case of error in any request life-cycle. */ get<T = any>(init: RequestType, request?: Partial<FrestRequest>): Promise<FrestResponse<T>>; /** * Make a request to an endpoint with HTTP `PUT` method. * * @template T - The type of response's body, if any. Defaults to `any`. * @param init - A string, string array, or request configuration object. * @param request - request configuration if the first arg is string * or string array * @returns Response promise which will be resolved when the request is successful. * The promise will throws in case of error in any request life-cycle. */ put<T = any>(init: RequestType, body?: any, request?: Partial<FrestRequest>): Promise<FrestResponse<T>>; /** * Make a request to an endpoint with HTTP `PATCH` method. * * @template T - The type of response's body, if any. Defaults to `any`. * @param init - A string, string array, or request configuration object. * @param request - request configuration if the first arg is string * or string array * @returns Response promise which will be resolved when the request is successful. * The promise will throws in case of error in any request life-cycle. */ patch<T = any>(init: RequestType, body?: any, request?: Partial<FrestRequest>): Promise<FrestResponse<T>>; /** * Make a request to an endpoint with HTTP `DELETE` method. * * @template T - The type of response's body, if any. Defaults to `any`. * @param init - A string, string array, or request configuration object. * @param request - request configuration if the first arg is string * or string array * @returns Response promise which will be resolved when the request is successful. * The promise will throws in case of error in any request life-cycle. */ delete<T = any>(init: RequestType, request?: Partial<FrestRequest>): Promise<FrestResponse<T>>; /** * Make a request to an endpoint with HTTP `OPTIONS` method. * * @template T - The type of response's body, if any. Defaults to `any`. * @param init - A string, string array, or request configuration object. * @param request - request configuration if the first arg is string * or string array * @returns Response promise which will be resolved when the request is successful. * The promise will throws in case of error in any request life-cycle. */ options<T = any>(init: RequestType, request?: Partial<FrestRequest>): Promise<FrestResponse<T>>; /** * Upload something to an endpoint. * @remarks * This is a special request function which will use `XMLHTTPRequest` to support * upload progress. By default the HTTP method used is `POST`. Currently only * support request body of `FormData` object. * * @template T - The type of response's body, if any. Defaults to `any`. * @param init - A string, string array, or request configuration object. * @param request - request configuration if the first arg is string * or string array * @returns Response promise which will be resolved when the request is successful. * The promise will throws in case of error in any request life-cycle. */ upload<T = any>(init: RequestType, body?: any, request?: Partial<FrestRequest>): Promise<FrestResponse<T>>; /** * Download something from an endpoint. * @remarks * This is a special request function which will use `XMLHTTPRequest` to support * download progress. By default the HTTP method used is `GET`. * * @template T - The type of response's body, if any. Defaults to `any`. * @param init - A string, string array, or request configuration object. * @param request - request configuration if the first arg is string * or string array * @returns Response promise which will be resolved when the request is successful. * The promise will throws in case of error in any request life-cycle. */ download<T = any>(init: RequestType, request?: Partial<FrestRequest>): Promise<FrestResponse<T>>; }//# sourceMappingURL=Frest.d.ts.map declare class InterceptorManager<T> { get handlers(): T[]; private _int; use(handler: T): number; eject(id: number): void; } //# sourceMappingURL=InterceptorManager.d.ts.map /** * Supported HTTP Method * @public */ declare type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'OPTIONS'; interface HeaderConfig { common: Headers; post: Headers; get: Headers; put: Headers; delete: Headers; patch: Headers; options: Headers; } declare type ResponseTransformer = (raw: Response, data: any) => any; declare type RequestTransformer = (req: FrestRequest, data?: any) => any; /** * Base config for Frest instance * @public */ interface ConfigBase { /** * The base url for this instance. Defaults to empty string. * @public */ base: string; transformResponse: ResponseTransformer[]; transformRequest: RequestTransformer[]; /** * {@link https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API | Fetch API} function implementation to use. * @remarks * Useful for example to provide custom `fetch` function or mocking in test. * By default use native browser `fetch` function and will fallback to {@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest | XMLHttpRequest} * if not available. * @public */ fetch: typeof fetch; /** * Default HTTP Method to use if not supplied in request. Defaults to `GET`. * @public */ method: HttpMethod; /** * Default cache mode you want to use for each request: `default`, `no-store`, `reload`, `no-cache`, `force-cache`, or `only-if-cached`. * @remarks * See {@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch | fetch} * request init for more. * @public */ cache?: RequestCache; /** * Default request credentials you want to use for each request: `omit`, `same-origin`, or `include`. * @remarks * See {@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch | fetch} * request init for more. * @public */ credentials?: RequestCredentials; /** * The `keepalive` option can be used to allow the request to outlive the page. * @remarks * See {@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch | fetch} * request init for more. * @public */ keepalive?: boolean; /** * Default mode you want to use for each request, e.g., `cors`, `no-cors`, or `same-origin`. * @remarks * See {@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch | fetch} * request init for more. * @public */ mode?: RequestMode; /** * Default redirect mode to use for each request. * @remarks * See {@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch | fetch} * request init for more. * @public */ redirect?: RequestRedirect; /** * A {@link https://developer.mozilla.org/en-US/docs/Web/API/USVString | USVString} specifying `no-referrer`, `client`, or a URL for each request * @remarks * See {@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch | fetch} * request init for more. * @public */ referrer?: string; /** * Specifies the value of the referer HTTP header for each request. * @remarks * See {@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch | fetch} * request init for more. * @public */ referrerPolicy?: ReferrerPolicy; /** * @remarks * See {@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch | fetch} * request init for more. * @public */ signal?: AbortSignal; } interface Config extends ConfigBase { /** * Default {@link https://developer.mozilla.org/en-US/docs/Web/API/Headers | Headers} to include in each request. * @remarks * If this Headers contain key which is supplied in request, it will get overridden. * In native `fetch` API, this can also be a key-value object, but for Frest * it's **required** to be an instance of `Headers` class. * @public */ headers: HeaderConfig; } /** * Frest configuration used in constructor and config merge. * @remarks * Frest instance contains some default configurations, so all * configuration properties are optional when used in constructor * and {@link Frest.mergeConfig}. They are basically * the same as {@link IConfig}. * @public */ declare type ConfigMergeType = Partial<ConfigBase> & { headers?: Partial<HeaderConfig>; }; /** * Frest configuration used in constructor. * @remarks * It can either be a string of `base` URL or a configuration object of {@link ConfigMergeType}. * @public */ declare type ConfigType = string | ConfigMergeType; /** * Request configuration object. * @remarks * The request configuration extends from native `fetch` request init options * and also accept any properties outside those. This can be useful for * debugging, interceptor, etc. to identify originating request. * * See {@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch | fetch} * request init for more. * @public */ interface FrestRequest { [key: string]: any; /** * Path relative to {@link IConfigBase.base}. * @remarks * The full endpoint URL to call is constructed from Frest instance's `base` * config and this `path` property. It can be a string, e.g. `/foo/bar` or * an array, e.g. `['foo', 'bar']` * @public */ path: string | string[]; /** * HTTP request method used in this request. * @remarks * Defaults to the instance's `method` configuration if not supplied. * This is ignored when calling instance's request shortcut methods, in * which the HTTP method is set according to the function name, e.g. `get` * will use `GET` HTTP method and setting this **won't** override it. * @public */ method: HttpMethod; /** * HTTP request headers used in this request. * @remarks * The request will include instance's `headers` configuration. Any existing * key defined in this request header will override the default headers. * @public */ headers: Headers; transformResponse: ResponseTransformer[]; transformRequest: RequestTransformer[]; /** * Specific action which this request called with. * @remarks * This is optional and mainly used for debugging purpose. You can provide * any value to this and use it in interceptor, logging, etc to identify * originating request. * Note that for `download` and `upload` method of Frest instance, this * is predetermined and can't be overridden * @public */ action?: string; /** * Specific base URL for this request. * @remarks * Override the instance's `base` configuration for this specific request. * @public */ base?: string; /** * Parameter for this request. * @remarks * Specify URL query with key-value object or string. This will be appended * to the final endpoint URL as query string. * @public */ query?: any; /** * `fetch` function used in this request. * @remarks * Override instance's `fetch` configuration for this request. Useful for * mocking in tests or when you want a customized native fetch function. * Note that for `download` and `upload` method of Frest instance, this will * be ignored and the request will use `XMLHTTPRequest` to support upload/download * progress. * @public */ fetch?: typeof fetch; /** * Skip processing interceptor by its id. * @remarks * This is mainly used internally by interceptors. By convention, interceptors * must honor this config and not modify request/response/error if defined * in `skip`. * @public */ skip?: string[]; /** * Body param for this request. * @remarks * Provide request body parameter which will be sent with this request. * This can be a `Blob`, `BufferSource`, `FormData`, `URLSearchParams`, * or `USVString` object, as per native `fetch` init. * * Note that a request using the GET or HEAD method cannot have a body. * Also for `upload` method of Frest instance, it's required to use * `FormData` as body. * * See {@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch | fetch} * request init for more. * @public */ body?: any; /** * Upload progress callback for Frest instance `upload` method. * @public */ onUploadProgress?: (ev: ProgressEvent) => any; /** * Download progress callback for Frest instance `download` method. * @public */ onDownloadProgress?: (ev: ProgressEvent) => any; /** * Response type in case of client is XMLHttpRequest. * * @remarks * If using `download`, this is default to `blob`. Otherwise by default * it's `text`. */ responseType?: 'arraybuffer' | 'blob' | 'document' | 'json' | 'text'; /** * The cache mode you want to use for the request: `default`, `no-store`, `reload`, `no-cache`, `force-cache`, or `only-if-cached`. * @remarks * See {@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch | fetch} * request init for more. * @public */ cache?: RequestCache; /** * The request credentials you want to use for the request: `omit`, `same-origin`, or `include`. * @remarks * See {@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch | fetch} * request init for more. * @public */ credentials?: RequestCredentials; /** * The `keepalive` option can be used to allow the request to outlive the page. * @remarks * See {@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch | fetch} * request init for more. * @public */ keepalive?: boolean; /** * The mode you want to use for the request, e.g., `cors`, `no-cors`, or `same-origin`. * @remarks * See {@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch | fetch} * request init for more. * @public */ mode?: RequestMode; /** * The redirect mode to use for the request. * @remarks * See {@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch | fetch} * request init for more. * @public */ redirect?: RequestRedirect; /** * A {@link https://developer.mozilla.org/en-US/docs/Web/API/USVString | USVString} specifying `no-referrer`, `client`, or a URL for the request * @remarks * See {@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch | fetch} * request init for more. * @public */ referrer?: string; /** * Specifies the value of the referer HTTP header for the request. * @remarks * See {@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch | fetch} * request init for more. * @public */ referrerPolicy?: ReferrerPolicy; /** * @remarks * See {@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch | fetch} * request init for more. * @public */ signal?: AbortSignal; } /** * Request configuration. * @remarks * This can be string, array of string as `path` of this request, or * a request configuration object of {@link IRequest} * @public */ declare type RequestType = string | string[] | Partial<FrestRequest>; /** * Response object as a result of successful endpoint call. * @remarks * Every successful request will return a promise of this object. `T` is * type parameter of the `body` property. * * @public * @template T - The type of `body` property. Defaults to `any` */ interface FrestResponse<T = any> { /** * Original `fetch` response. * @public */ raw: Response; /** * The body of this response, if any. * @public */ data: T; readonly headers: Headers; readonly ok: boolean; readonly redirected: boolean; readonly status: number; readonly statusText: string; readonly trailer: Promise<Headers>; readonly type: ResponseType; readonly url: string; } /** * Error object thrown in case of request failure. * @remarks * Any error happened during a request life-cycle, including non-ok HTTP status, * will have this signature. * @public */ interface FrestErrorType { /** * The message describing this error. * @public */ message: string; /** * Frest instance used when this error happened. * @public */ frest: Frest; /** * The request config used when this error happened. * @public */ request: FrestRequest; /** * The response when this error happened, if any. * @remarks * This can be `undefined` because an error may be thrown before the request * is made. * @public */ response?: FrestResponse; } /** * Argument object passed to a request interceptor function. * @public */ interface RequestInterceptorArg { /** * Frest instance which the request is made with. * @public */ frest: Frest; /** * The request configuration used in this request. * @public */ request: FrestRequest; } interface ResponseInterceptorArg { /** * Frest instance which the request is made with. * @public */ frest: Frest; /** * The request configuration used in this request. * @public */ request: FrestRequest; response: FrestResponse; } /** * Request interceptor function signature. * @public */ declare type RequestInterceptor = (input: RequestInterceptorArg) => Promise<FrestRequest>; /** * Response interceptor function signature. * @public */ declare type ResponseInterceptor = (input: ResponseInterceptorArg) => Promise<FrestResponse>; /** * Error interceptor function signature. * @public */ declare type ErrorInterceptor = (error: FrestErrorType) => Promise<FrestResponse | undefined | null>; /** * List of interceptors by its type. * @public */ interface Interceptors { /** * List of response interceptor; * @public */ response: InterceptorManager<ResponseInterceptor>; /** * List of request interceptor; * @public */ request: InterceptorManager<RequestInterceptor>; /** * List of error interceptor; * @public */ error: InterceptorManager<ErrorInterceptor>; } //# sourceMappingURL=types.d.ts.map /** * Remove multiple occurrence of **forward** slash in a string. * This doesn't remove leading and/or trailing slash. * * e.g. "http://example.com/a//b/" -> "http://example.com/a/b/" * * @public * @param input The string to clean. * @returns The `input` string without multiple occurrence of forward slash. */ declare const trimSlashes: (input: string) => string; /** * Utility function to parse a query object into string. * * @remarks * This will only do simple and dumb stringify according to `querystringify` * package. If you want more control use the package directly instead. * * @public * @param query The query to parse. It can be object/string * @returns Parsed query string */ declare const parseQuery: (query: any) => any; /** * A TypeScript utility to determine if a potential error is an instance of * `FrestError`. * * @public * @param e A potential error to check * @returns true if `e` is an instance of `FrestError`. TypeScript will then provide * completions of `FrestError` instance type. */ declare const isFrestError: (e: any) => e is FrestErrorType; /** * Determine if an object is a Buffer. * @remarks * Taken from `is-buffer` package by Feross Aboukhadijeh <https://feross.org>, * licensed under MIT and copied here to provide typings for Frest and * its users. * * {@link https://github.com/feross/is-buffer} * * @public * @param val Value to test. * @returns true if it's a Buffer. */ declare const isBuffer: (val?: any) => val is Buffer; /** * Determine if a value is an ArrayBuffer * * @param val The value to test * @returns True if value is an ArrayBuffer, otherwise false */ declare const isArrayBuffer: (val?: any) => val is ArrayBuffer; /** * Determine if a value is a FormData * * @param val The value to test * @returns True if value is an FormData, otherwise false */ declare const isFormData: (val?: any) => val is FormData; /** * Determine if a value is a view on an ArrayBuffer * * @param val The value to test * @returns True if value is a view on an ArrayBuffer, otherwise false */ declare const isArrayBufferView: (val?: any) => val is ArrayBufferView; /** * Determine if a value is an Object * * @param val The value to test * @returns True if value is an Object, otherwise false */ declare const isObject: (val?: any) => boolean; /** * Determine if a value is a File * * @param val The value to test * @returns True if value is a File, otherwise false */ declare const isFile: (val?: any) => val is File; /** * Determine if a value is a Blob * * @param val The value to test * @returns True if value is a Blob, otherwise false */ declare const isBlob: (val?: any) => val is Blob; /** * Determine if a value is a Function * * @param val The value to test * @returns True if value is a Function, otherwise false */ declare const isFunction: (val?: any) => val is (...args: any[]) => any; /** * Determine if a value is a Stream * * @param val The value to test * @returns True if value is a Stream, otherwise false */ declare const isStream: (val?: any) => boolean; /** * Determine if a value is a URLSearchParams object * * @param val The value to test * @returns True if value is a URLSearchParams object, otherwise false */ declare const isURLSearchParams: (val?: any) => val is URLSearchParams; //# sourceMappingURL=utils.d.ts.map declare const utils_d_trimSlashes: typeof trimSlashes; declare const utils_d_parseQuery: typeof parseQuery; declare const utils_d_isFrestError: typeof isFrestError; declare const utils_d_isBuffer: typeof isBuffer; declare const utils_d_isArrayBuffer: typeof isArrayBuffer; declare const utils_d_isFormData: typeof isFormData; declare const utils_d_isArrayBufferView: typeof isArrayBufferView; declare const utils_d_isObject: typeof isObject; declare const utils_d_isFile: typeof isFile; declare const utils_d_isBlob: typeof isBlob; declare const utils_d_isFunction: typeof isFunction; declare const utils_d_isStream: typeof isStream; declare const utils_d_isURLSearchParams: typeof isURLSearchParams; declare namespace utils_d { export { utils_d_trimSlashes as trimSlashes, utils_d_parseQuery as parseQuery, utils_d_isFrestError as isFrestError, utils_d_isBuffer as isBuffer, utils_d_isArrayBuffer as isArrayBuffer, utils_d_isFormData as isFormData, utils_d_isArrayBufferView as isArrayBufferView, utils_d_isObject as isObject, utils_d_isFile as isFile, utils_d_isBlob as isBlob, utils_d_isFunction as isFunction, utils_d_isStream as isStream, utils_d_isURLSearchParams as isURLSearchParams, }; } /** * FrestError constructor/class signature. * @remarks * This is only used for UMD build. * @public */ interface FrestErrorConstructor { new (message: string, frest: Frest, request: FrestRequest, response?: FrestResponse<any>): FrestError; } /** * Error representation class when there is any failure during request life-cycle. * @public */ declare class FrestError extends Error implements FrestErrorType { frest: Frest; request: FrestRequest; response?: FrestResponse<any> | undefined; constructor(message: string, frest: Frest, request: FrestRequest, response?: FrestResponse<any> | undefined); } //# sourceMappingURL=FrestError.d.ts.map declare const xhrFetch: typeof fetch; declare const frest: Frest;//# sourceMappingURL=index.d.ts.map export default frest; export { Config, ConfigBase, ConfigMergeType, ConfigType, DEFAULT_CONFIG, ErrorInterceptor, Frest, FrestConstructor, FrestError, FrestErrorConstructor, FrestErrorType, FrestRequest, FrestResponse, HeaderConfig, HttpMethod, Interceptors, RequestInterceptor, RequestInterceptorArg, RequestTransformer, RequestType, ResponseInterceptor, ResponseInterceptorArg, ResponseTransformer, utils_d as utils, xhrFetch };