UNPKG

create-request

Version:

A modern, chainable wrapper for fetch with automatic retries, timeouts, comprehensive error handling, and first-class TypeScript support

171 lines (170 loc) 6.17 kB
import type { GraphQLOptions } from "./types.js"; /** * Wrapper for HTTP responses with methods to transform the response data. * Provides convenient methods to parse the response body in different formats. * Response bodies are cached after the first read, so you can call multiple methods * (e.g., `getJson()` and `getText()`) on the same response. * * @example * ```typescript * const response = await create.get('/api/users').getResponse(); * console.log(response.status); // 200 * console.log(response.ok); // true * const data = await response.getJson(); * ``` */ export declare class ResponseWrapper { /** The URL that was requested (if available) */ readonly url?: string; /** The HTTP method that was used (if available) */ readonly method?: string; private readonly response; private graphQLOptions?; private cachedBlob?; private cachedText?; private cachedJson?; private cachedArrayBuffer?; constructor(response: Response, url?: string, method?: string, graphQLOptions?: GraphQLOptions); /** * HTTP status code (e.g., 200, 404, 500) */ get status(): number; /** * HTTP status text (e.g., "OK", "Not Found", "Internal Server Error") */ get statusText(): string; /** * Response headers as a Headers object */ get headers(): Headers; /** * Whether the response status is in the 200-299 range (successful) */ get ok(): boolean; /** * The raw Response object from the fetch API. * Use this if you need direct access to the underlying Response. */ get raw(): Response; /** * Check if the response body has already been consumed and throw an error if so * @throws RequestError if the body has already been consumed */ private checkBodyNotConsumed; /** * Check for GraphQL errors and throw if throwOnError is enabled * @param data - The parsed JSON data * @throws RequestError if GraphQL response contains errors and throwOnError is enabled */ private checkGraphQLErrors; /** * Parse the response body as JSON * If GraphQL options are set with throwOnError=true, will check for GraphQL errors and throw. * * @returns The parsed JSON data * @throws {RequestError} When the request fails, JSON parsing fails, or GraphQL errors occur (if throwOnError enabled). * * @example * const data = await response.getJson(); * console.log(data.items); * * @example * // Error handling - errors are always RequestError * try { * const data = await response.getJson(); * } catch (error) { * if (error instanceof RequestError) { * console.log(error.status, error.url, error.method); * } * } */ getJson<T = unknown>(): Promise<T>; /** * Get the response body as text. * The result is cached, so subsequent calls return the same value without re-reading the body. * * @returns A promise that resolves to the response body as a string * @throws {RequestError} When the body has already been consumed or reading fails * * @example * ```typescript * const text = await response.getText(); * console.log(text); // "Hello, world!" * ``` */ getText(): Promise<string>; /** * Get the response body as a Blob. * Useful for downloading files or handling binary data. * The result is cached, so subsequent calls return the same value without re-reading the body. * * @returns A promise that resolves to the response body as a Blob * @throws {RequestError} When the body has already been consumed or reading fails * * @example * ```typescript * const blob = await response.getBlob(); * const url = URL.createObjectURL(blob); * // Use the blob URL for downloading or displaying * ``` */ getBlob(): Promise<Blob>; /** * Get the response body as an ArrayBuffer. * Useful for processing binary data at a low level. * The result is cached, so subsequent calls return the same value without re-reading the body. * * @returns A promise that resolves to the response body as an ArrayBuffer * @throws {RequestError} When the body has already been consumed or reading fails * * @example * ```typescript * const buffer = await response.getArrayBuffer(); * const uint8Array = new Uint8Array(buffer); * // Process the binary data * ``` */ getArrayBuffer(): Promise<ArrayBuffer>; /** * Get the raw response body as a ReadableStream * Note: This consumes the response body and should only be called once. * Unlike other methods, streams cannot be cached, so this will throw if the body is already consumed. * * @returns The response body as a ReadableStream or null * @throws {RequestError} When the response body has already been consumed * * @example * const stream = response.getBody(); * if (stream) { * const reader = stream.getReader(); * // Process the stream * } */ getBody(): ReadableStream<Uint8Array> | null; /** * Extract specific data using a selector function * If no selector is provided, returns the full JSON response. * * @param selector - Optional function to extract and transform data * @returns A promise that resolves to the selected data * @throws {RequestError} When the request fails, JSON parsing fails, or the selector throws an error * * @example * // Get full response * const data = await response.getData(); * * // Extract specific data * const users = await response.getData(data => data.results.users); * * @example * // Error handling - errors are always RequestError * try { * const data = await response.getData(); * } catch (error) { * if (error instanceof RequestError) { * console.log(error.status, error.url, error.method); * } * } */ getData<T = unknown, R = T>(selector?: (data: T) => R): Promise<T | R>; }