UNPKG

nyro

Version:

A simple and effective promise-based HTTP & HTTP/2 request library that supports all HTTP methods.

584 lines (583 loc) 26.5 kB
import * as http from 'http'; import ErrorHandler from '../helpers/errorHandler'; import PluginManager, { Plugin } from './pluginManager'; import { PassThrough } from 'stream'; import { EventEmitter } from 'events'; import { Headers } from '../helpers/types'; interface ProxyOptions { host: string; port: number; auth?: { username: string; password: string; }; protocol?: ('http' | 'https' | 'socks' | 'socks4' | 'socks5' | 'socks4a' | 'socks5h' & string); } interface AuthOptions { username: string; password: string; } interface PaginationOptions { pageParam: string; limitParam: string; maxPages?: number; } interface QueueOptions { delay?: number; } type InferBodySchema<T> = T extends Record<string, infer U> ? { [K in keyof T]: T[K] extends NumberConstructor ? number : T[K] extends StringConstructor ? string : any; } : any; interface RequestOptions<B = any> { requestId?: string; method?: ('GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'HEAD' | 'OPTIONS' | 'CONNECT' | 'TRACE' | 'get' | 'post' | 'put' | 'delete' | 'patch' | 'head' | 'options' | 'connect' | 'trace' & string); port?: number; url?: string; path?: string; headers?: (Headers & Record<string, string>); body?: any; timeout?: number; params?: Record<string, string>; baseURL?: string; query?: Record<string, string | number | boolean>; responseType?: ('json' | 'text' | 'blob' | 'stream' | 'arrayBuffer' | 'document' & string); responseEncoding?: BufferEncoding; timeoutErrorMessage?: string; onTimeout?: () => void; isStream?: boolean; useHttp2?: boolean; validateStatus?: (status: number) => boolean; decompress?: boolean; proxy?: ProxyOptions; maxRedirects?: number; auth?: AuthOptions; maxBodyLength?: number; maxContentLength?: number; maxRate?: number; signal?: AbortSignal; bodySchema?: B; cache?: boolean; cacheTTL?: number; retries?: number; retryDelay?: number; onRetry?: (req: http.RequestOptions, error: Error) => boolean; onDownloadProgress?: (progress: { percent: number; transferredBytes: number; totalBytes: number; }) => void; onRequest?: (options: RequestOptions<B>) => RequestOptions<B> | void; onResponse?: (response: HttpResponse<any, BodyFromSchema<B, RequestOptions>>) => HttpResponse<any, BodyFromSchema<B, RequestOptions>> | void; onChunk?: (chunk: Buffer) => Buffer | void; onRedirect?: (response: http.IncomingMessage) => void; sslOptions?: { key?: Buffer; cert?: Buffer; ca?: Buffer; rejectUnauthorized?: boolean; secureProtocol?: ('SSLv2_method' | 'SSLv3_method' | 'TLSv1_method' | 'TLSv1_1_method' | 'TLSv1_2_method' | 'TLSv1_3_method' & string); ciphers?: string; passphrase?: string; }; defaultMode?: boolean; } interface RequestInfo { requestId: string; method?: string; url?: string; fullUrl: string; headers: (Headers & Record<string, string>); body?: BodyFromSchema<any, RequestOptions>; httpVersion?: string; startTimestamp: number; timeout?: number; contentLength?: number; } type BodyFromSchema<B, Options> = Options extends { responseType: 'stream'; } | { isStream: true; } ? PassThrough : B extends typeof Number ? number : B extends typeof String ? string : B extends Record<string, unknown> ? { [K in keyof B]: B[K] extends typeof Number ? number : B[K] extends typeof String ? string : B[K] extends typeof Array ? any[] : B[K]; } : B extends ArrayConstructor ? any[] : B; interface HttpResponse<T, B = any> { requestId: string; body: (BodyFromSchema<B, RequestOptions>); statusCode: number; statusText: string; headers: (Headers & Record<string, string | string[]>); config: RequestOptions<B>; request: http.ClientRequest; requestInfo: RequestInfo; response: http.IncomingMessage; timestamp: { startTimestamp: number; endTimestamp: number; }; responseTime: number; responseSize: number; serverIp?: string; connectionReused: boolean; isStream?: boolean; isCached?: boolean; } type OmitedCreate = Omit<Core, 'create'>; type OmitedExtend = Omit<Core, 'create'>; interface Events { ['beforeRequest']: (requestOptions: RequestOptions<any>) => void; ['afterResponse']: (res: HttpResponse<any, any>) => void; ['error']: (error: ErrorHandler) => void; } declare class Core extends EventEmitter { baseRequestOptions: RequestOptions; pluginManager: PluginManager; constructor(baseRequestOptions?: RequestOptions); use(plugin: Plugin): void; on<K extends keyof Events>(event: K, listener: Events[K]): this; once<K extends keyof Events>(event: K, listener: Events[K]): this; off<K extends keyof Events>(event: K, listener: Events[K]): this; emit<K extends keyof Events>(event: K, ...args: Parameters<Events[K]>): boolean; /** * The version of the Nyro library. */ static version: string; /** * The package.json file for the Nyro library. */ static pkg: { name: string; version: string; main: string; module: string; types: string; exports: { require: string; import: string; }; description: string; scripts: { test: string; "build:cjs": string; "build:esm": string; build: string; }; keywords: string[]; author: { name: string; url: string; }; homepage: string; repository: { type: string; url: string; }; bugs: { url: string; }; funding: { type: string; url: string; }; license: string; devDependencies: { "ts-node": string; tsup: string; }; dependencies: { fastgate: string; http: string; "http-proxy-agent": string; "http2-wrapper": string; https: string; "https-proxy-agent": string; "socks-proxy-agent": string; }; }; /** * @param url * @returns this * @example Nyro.setURL('https://jsonplaceholder.typicode.com/posts'); * @description This function sets the URL for the request. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers|MDN web docs} */ setURL(url: string): this; /** * @param baseURL * @returns this * @example Nyro.setBaseURL('https://jsonplaceholder.typicode.com'); * @description This function sets the base URL for the request. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers|MDN web docs} */ setBaseURL(baseURL: string): this; /** * @param path * @returns this * @example Nyro.setPath('/posts'); * @description This function sets the path for the request. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers|MDN web docs} */ setPath(path: string): this; /** * @param bodySchema * @returns this * @example Nyro.setBodySchema({ title: String, body: String }); * @description This function sets the body schema for the request. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers|MDN web docs} */ setBodySchema(bodySchema: any): this; /** * @param auth * @returns this * @example Nyro.setAuth({ username: 'user', password: 'pass' }); * @description This function sets the authentication credentials for the request. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers|MDN web docs} */ setAuth(auth: AuthOptions): this; /** * @param proxy * @returns this * @example Nyro.setProxy({ host: 'localhost', port: 8080, protocol: 'http' }); * @description This function sets the proxy for the request. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers|MDN web docs} */ setProxy(proxy: ProxyOptions): this; /** * @param method * @returns this * @example Nyro.setMethod('GET'); * @description This function sets the method for the request. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers|MDN web docs} */ setMethod(method: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'HEAD' | 'OPTIONS' | 'CONNECT' | 'TRACE'): this; /** * @param headers * @returns this * @example Nyro.setHeaders({ 'Content-Type': 'application/json' }); * @description This function sets the headers for the request. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers|MDN web docs} */ setHeaders(headers: (Headers & Record<string, string>)): this; /** * @param params * @returns this * @example Nyro.setParams({ id: '1' }); * @description This function sets the query parameters for the request. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers|MDN web docs} */ setParams(params: Record<string, string>): this; /** * @param query * @returns this * @example Nyro.setQuery({ id: '1' }); * @description This function sets the query parameters for the request. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers|MDN web docs} */ setQuery(query: Record<string, string | number | boolean>): this; /** * @param body * @returns this * @example Nyro.setBody({ title: 'foo', body: 'bar', userId: 1 }); * @description This function sets the body for the request. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers|MDN web docs} */ setBody(body: any): this; /** * @param timeout * @returns this * @example Nyro.setTimeout(5000); * @description This function sets the timeout for the request. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers|MDN web docs} */ setTimeout(timeout: number): this; /** * @param retryOn * @returns this * @example Nyro.setRetryOn((req, error) => error.code === 'ETIMEDOUT'); * @description This function sets the retry condition for the request. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers|MDN web docs} */ setRetryOn(retryOn: (req: http.RequestOptions, error: Error) => boolean): this; /** * @param retries * @returns this * @example Nyro.setRetries(3); * @description This function sets the number of retries for the request. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers|MDN web docs} */ setRetries(retries: number): this; /** * @param validateStatus * @returns this * @example Nyro.setValidateStatus((status) => status >= 200 && status < 300); * @description This function sets the status validation for the request. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers|MDN web docs} */ setValidateStatus(validateStatus: (status: number) => boolean): this; /** * @param maxBodyLength * @returns this * @example Nyro.setMaxBodyLength(1000); * @description This function sets the maximum body length for the request. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers|MDN web docs} */ setMaxBodyLength(maxBodyLength: number): this; /** * @param maxContentLength * @returns this * @example Nyro.setMaxContentLength(1000); * @description This function sets the maximum content length for the request. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers|MDN web docs} */ setMaxContentLength(maxContentLength: number): this; /** * @param maxRate * @returns this * @example Nyro.setMaxRate(1000); * @description This function sets the maximum rate for the request. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers|MDN web docs} */ setMaxRate(maxRate: number): this; /** * @param signal * @returns this * @example Nyro.setSignal(signal); * @description This function sets the signal for the request. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers|MDN web docs} */ setSignal(signal: AbortSignal): this; /** * @param onDownloadProgress * @returns this * @example Nyro.setOnDownloadProgress((progress) => console.log(progress)); * @description This function sets the download progress for the request. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers|MDN web docs} */ setOnDownloadProgress(onDownloadProgress: (progress: { percent: number; transferredBytes: number; totalBytes: number; }) => void): this; /** * @param timeoutErrorMessage * @returns this * @example Nyro.setTimeoutErrorMessage('Request timed out'); * @description This function sets the timeout error message for the request. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers|MDN web docs} */ setTimeoutErrorMessage(timeoutErrorMessage: string): this; /** * @param responseType * @returns this * @example Nyro.setResponseType('json'); * @description This function sets the response type for the request. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers|MDN web docs} */ setResponseType(responseType: ('json' | 'text' | 'blob' | 'stream' | 'arrayBuffer' | 'document' & string)): this; /** * @param responseEncoding * @returns this * @example Nyro.setResponseEncoding('utf8'); * @description This function sets the response encoding for the request. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers|MDN web docs} */ setResponseEncoding(responseEncoding: BufferEncoding): this; /** * @param maxRedirects * @returns this * @example Nyro.setMaxRedirects(3); * @description This function sets the maximum number of redirects for the request. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers|MDN web docs} */ setMaxRedirects(maxRedirects: number): this; /** * @param retryDelay * @returns this * @example Nyro.setRetryDelay(1000); * @description This function sets the retry delay for the request. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers|MDN web docs} */ setRetryDelay(retryDelay: number): this; /** * @param decompress * @returns this * @example Nyro.setDecompress(true); * @description This function sets the decompress option for the request. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers|MDN web docs} */ setDecompress(decompress: boolean): this; /** * Sends a GET request to the specified URL. * @param url - The URL to send the request to. * @param options - The request options. * @returns A promise that resolves with the HTTP response. * @example Nyro.get('https://jsonplaceholder.typicode.com/posts'); * @description This function sends a GET request to the specified URL and returns a promise that resolves with the HTTP response. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/GET|MDN web docs} */ get<T, B>(url?: string, options?: RequestOptions<B>): Promise<HttpResponse<T, BodyFromSchema<B, RequestOptions>>>; /** * Sends a POST request to the specified URL. * @param url - The URL to send the request to. * @param options - The request options. * @returns A promise that resolves with the HTTP response. * @example Nyro.post('https://jsonplaceholder.typicode.com/posts'); * @description This function sends a POST request to the specified URL and returns a promise that resolves with the HTTP response. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST|MDN web docs} */ post<T, B>(url?: string, options?: RequestOptions<B>): Promise<HttpResponse<T, BodyFromSchema<B, RequestOptions>>>; /** * Sends a PUT request to the specified URL. * @param url - The URL to send the request to. * @param options - The request options. * @returns A promise that resolves with the HTTP response. * @example Nyro.put('https://jsonplaceholder.typicode.com/posts'); * @description This function sends a PUT request to the specified URL and returns a promise that resolves with the HTTP response. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PUT|MDN web docs} */ put<T, B>(url?: string, options?: RequestOptions<B>): Promise<HttpResponse<T, BodyFromSchema<B, RequestOptions>>>; /** * Sends a DELETE request to the specified URL. * @param url - The URL to send the request to. * @param options - The request options. * @returns A promise that resolves with the HTTP response. * @example Nyro.delete('https://jsonplaceholder.typicode.com/posts'); * @description This function sends a DELETE request to the specified URL and returns a promise that resolves with the HTTP response. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/DELETE|MDN web docs} */ delete<T, B>(url?: string, options?: RequestOptions<B>): Promise<HttpResponse<T, BodyFromSchema<B, RequestOptions>>>; /** * Sends a PATCH request to the specified URL. * @param url - The URL to send the request to. * @param options - The request options. * @returns A promise that resolves with the HTTP response. * @example Nyro.patch('https://jsonplaceholder.typicode.com/posts'); * @description This function sends a PATCH request to the specified URL and returns a promise that resolves with the HTTP response. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PATCH|MDN web docs} */ patch<T, B>(url?: string, options?: RequestOptions<B>): Promise<HttpResponse<T, BodyFromSchema<B, RequestOptions>>>; /** * Sends a HEAD request to the specified URL. * @param url - The URL to send the request to. * @param options - The request options. * @returns A promise that resolves with the HTTP response. * @example Nyro.head('https://jsonplaceholder.typicode.com/posts'); * @description This function sends a HEAD request to the specified URL and returns a promise that resolves with the HTTP response. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/HEAD|MDN web docs} */ head<T, B>(url?: string, options?: RequestOptions<B>): Promise<HttpResponse<T, BodyFromSchema<B, RequestOptions>>>; /** * Sends an OPTIONS request to the specified URL. * @param url - The URL to send the request to. * @param options - The request options. * @returns A promise that resolves with the HTTP response. * @example Nyro.options('https://jsonplaceholder.typicode.com/posts'); * @description This function sends an OPTIONS request to the specified URL and returns a promise that resolves with the HTTP response. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/OPTIONS|MDN web docs} */ options<T, B>(url?: string, options?: RequestOptions<B>): Promise<HttpResponse<T, BodyFromSchema<B, RequestOptions>>>; /** * Sends a CONNECT request to the specified URL. * @param url - The URL to send the request to. * @param options - The request options. * @returns A promise that resolves with the HTTP response. * @example Nyro.connect('https://jsonplaceholder.typicode.com/posts'); * @description This function sends a CONNECT request to the specified URL and returns a promise that resolves with the HTTP response. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/CONNECT|MDN web docs} */ connect<T, B>(url?: string, options?: RequestOptions<B>): Promise<HttpResponse<T, BodyFromSchema<B, RequestOptions>>>; /** * Sends a TRACE request to the specified URL. * @param url - The URL to send the request to. * @param options - The request options. * @returns A promise that resolves with the HTTP response. * @example Nyro.trace('https://jsonplaceholder.typicode.com/posts'); * @description This function sends a TRACE request to the specified URL and returns a promise that resolves with the HTTP response. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/TRACE|MDN web docs} */ trace<T, B>(url?: string, options?: RequestOptions<B>): Promise<HttpResponse<T, BodyFromSchema<B, RequestOptions>>>; /** * Downloads a file from the specified URL. * @param url - The URL to download the file from. * @param options - The request options. * @returns A promise that resolves with the HTTP response. * @example Nyro.download('https://jsonplaceholder.typicode.com/posts'); * @description This function downloads a file from the specified URL and returns a promise that resolves with the HTTP response. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/GET|MDN web docs} * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition|MDN web docs} * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type|MDN web docs} */ download<T, B>(url?: string, options?: RequestOptions<B>): Promise<HttpResponse<T, BodyFromSchema<B, RequestOptions>>>; /** * Sends a request to the specified URL with pagination. * @param options - The request options. * @param paginationOptions - The pagination options. * @returns A promise that resolves with an array of HTTP responses. * @example Nyro.pagination({ url: 'https://jsonplaceholder.typicode.com/posts', method: 'GET' }, { pageParam: 'page', limitParam: 'limit', maxPages: 3 }); * @description This function sends a request to the specified URL with pagination and returns a promise that resolves with an array of HTTP responses. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods|MDN web docs} * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers|MDN web docs} * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Status|MDN web docs} * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Response_headers|MDN web docs} * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Link|MDN web docs} */ pagination<T, B>(options?: RequestOptions<B>, paginationOptions?: PaginationOptions): Promise<Array<HttpResponse<T, BodyFromSchema<B, RequestOptions>>>>; /** * Sends multiple requests to the specified URLs. * @param requests - The request options. * @returns A promise that resolves with an array of HTTP responses. * @example Nyro.queue([ * { url: 'https://jsonplaceholder.typicode.com/posts/1', method: 'GET' }, * { url: 'https://jsonplaceholder.typicode.com/posts/2', method: 'POST' } * ]); * @description This function sends multiple requests to the specified URLs and returns a promise that resolves with an array of HTTP responses. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods|MDN web docs} * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers|MDN web docs} * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Status|MDN web docs} * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Response_headers|MDN web docs} */ queue<T, B>(requests: Array<RequestOptions<B>>, queueOptions?: QueueOptions): Promise<Array<HttpResponse<T, BodyFromSchema<B, RequestOptions>>>>; /** * Extends the default request options with the provided options. * * @param extendOptions - The options to extend the default request options with. * @returns An object with the execute function to make the request and the options used for the request. * @example Nyro.extend({ * url: 'https://jsonplaceholder.typicode.com/posts', * method: 'GET', * headers: { * 'Content-Type': 'application/json' * } * }); * @description This function allows you to create a new request with the provided options, while keeping the default options for future requests. */ extend<T, B>(extendOptions: RequestOptions<B>): Promise<OmitedExtend>; /** * Creates a new instance of the Nyro library with the provided options. * * @param options - The request options. * @returns A new instance of the Nyro library with the provided options. * @example Nyro.create({ * url: 'https://jsonplaceholder.typicode.com/posts', * method: 'GET', * headers: { * 'Content-Type': 'application/json' * } * }); * @description This function creates a new instance of the Nyro library with the provided options. * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods|MDN web docs} * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers|MDN web docs} * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Status|MDN web docs} * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Response_headers|MDN web docs} */ create<T, B>(options: RequestOptions<B>): Promise<OmitedCreate>; /** * Core function for handling HTTP requests. * * @param options - The request options. * @param currentRedirects - The number of redirects that have occurred. * @returns A promise that resolves with the HTTP response. */ request<T, B>(options?: RequestOptions<B>, currentRedirects?: number, attempt?: number, visitedUrls?: Set<string>): Promise<HttpResponse<T, BodyFromSchema<B, RequestOptions>>>; } export default Core; export { RequestInfo, RequestOptions, HttpResponse, Headers, ProxyOptions, AuthOptions, InferBodySchema, BodyFromSchema, Events, QueueOptions, PaginationOptions };