Rezo Class
The main HTTP client class. Create instances with custom defaults, adapters, cookie jars, caching, and proxy managers.
Constructor
new Rezo(config?: RezoDefaultOptions, adapter?: AdapterFunction) Parameters
| Parameter | Type | Description |
|---|---|---|
config | RezoDefaultOptions | Optional default configuration applied to every request. |
adapter | AdapterFunction | Optional HTTP adapter function. If omitted, the global adapter set by the platform entry point is used. |
Example
import { Rezo } from 'rezo';
// Basic instance
const rezo = new Rezo();
// With defaults
const api = new Rezo({
baseURL: 'https://api.example.com',
timeout: 10000,
headers: { 'Authorization': 'Bearer token123' }
});
// With cookie persistence
const client = new Rezo({
cookieFile: './cookies.json'
});
// With caching
const cached = new Rezo({
cache: { response: { enable: true, ttl: 60000 }, dns: true }
});
// With a queue
const queued = new Rezo({
queue: { concurrency: 5, domainConcurrency: 2 }
});
// With proxy rotation
import { ProxyManager } from 'rezo';
const proxied = new Rezo({
proxyManager: new ProxyManager({
rotation: 'random',
proxies: ['http://proxy1:8080', 'socks5://proxy2:1080']
})
}); HTTP Methods (No Body)
These methods send requests without a request body. They all share the same signature.
get / head / options / trace / delete
rezo.get<T = any>(url: string | URL, options?: RezoHttpRequest): Promise<RezoResponse<T>>
rezo.head<T = any>(url: string | URL, options?: RezoHttpRequest): Promise<RezoResponse<T>>
rezo.options<T = any>(url: string | URL, options?: RezoHttpRequest): Promise<RezoResponse<T>>
rezo.trace<T = any>(url: string | URL, options?: RezoHttpRequest): Promise<RezoResponse<T>>
rezo.delete<T = any>(url: string | URL, options?: RezoHttpRequest): Promise<RezoResponse<T>> | Parameter | Type | Description |
|---|---|---|
url | string \| URL | The request URL. Resolved against baseURL if relative. |
options | RezoHttpRequest | Optional per-request configuration (headers, timeout, params, etc.). |
Example
// Simple GET
const { data } = await rezo.get('https://api.example.com/users');
// GET with query params and typed response
interface User { id: number; name: string; }
const { data: users } = await rezo.get<User[]>('/users', {
params: { page: 1, limit: 10 }
});
// HEAD request to check resource
const headResp = await rezo.head('/file.zip');
console.log('Content-Length:', headResp.headers.get('content-length'));
// DELETE with auth
await rezo.delete('/users/123', {
headers: { 'Authorization': 'Bearer token' }
}); HTTP Methods (With Body)
post / put / patch
rezo.post<T = any>(url: string | URL, data?: any, options?: RezoHttpRequest): Promise<RezoResponse<T>>
rezo.put<T = any>(url: string | URL, data?: any, options?: RezoHttpRequest): Promise<RezoResponse<T>>
rezo.patch<T = any>(url: string | URL, data?: any, options?: RezoHttpRequest): Promise<RezoResponse<T>> | Parameter | Type | Description |
|---|---|---|
url | string \| URL | The request URL. |
data | RezoFormData \| FormData \| Record<string, any> | Request body. |
options | RezoHttpRequest | Optional per-request configuration. |
Example
// POST with object body
const { data } = await rezo.post('/users', {
name: 'Alice',
email: 'alice@example.com'
});
// PUT update
await rezo.put('/users/1', { name: 'Alice Updated' });
// PATCH partial update
await rezo.patch('/users/1', { email: 'new@example.com' }); postJson / putJson / patchJson
Convenience methods that automatically set Content-Type: application/json and JSON-stringify the body.
rezo.postJson<T = any>(url: string | URL, data?: Record<any, any> | string | Array<any> | null, options?: RezoHttpRequest): Promise<RezoResponse<T>>
rezo.putJson<T = any>(url: string | URL, data?: Record<any, any> | string | Array<any> | null, options?: RezoHttpRequest): Promise<RezoResponse<T>>
rezo.patchJson<T = any>(url: string | URL, data?: Record<any, any> | string | Array<any> | null, options?: RezoHttpRequest): Promise<RezoResponse<T>> Example
const { data } = await rezo.postJson('/api/data', { key: 'value' });
// Array body
await rezo.postJson('/api/batch', [{ id: 1 }, { id: 2 }]); postForm / putForm / patchForm
Convenience methods that set Content-Type: application/x-www-form-urlencoded and encode the body.
rezo.postForm<T = any>(url: string | URL, data?: URLSearchParams | Record<string, any> | string | null, options?: RezoHttpRequest): Promise<RezoResponse<T>>
rezo.putForm<T = any>(url: string | URL, data?: URLSearchParams | Record<string, any> | string | null, options?: RezoHttpRequest): Promise<RezoResponse<T>>
rezo.patchForm<T = any>(url: string | URL, data?: URLSearchParams | Record<string, any> | string | null, options?: RezoHttpRequest): Promise<RezoResponse<T>> Example
// Login form
const { data } = await rezo.postForm('/login', {
username: 'alice',
password: 'secret'
});
// From URLSearchParams
const params = new URLSearchParams({ grant_type: 'client_credentials' });
await rezo.postForm('/oauth/token', params); postMultipart / putMultipart / patchMultipart
Convenience methods for multipart/form-data uploads. Accepts RezoFormData, native FormData, or plain objects.
rezo.postMultipart<T = any>(url: string | URL, data: RezoFormData | FormData | Record<string, any>, options?: RezoHttpRequest): Promise<RezoResponse<T>>
rezo.putMultipart<T = any>(url: string | URL, data: RezoFormData | FormData | Record<string, any>, options?: RezoHttpRequest): Promise<RezoResponse<T>>
rezo.patchMultipart<T = any>(url: string | URL, data: RezoFormData | FormData | Record<string, any>, options?: RezoHttpRequest): Promise<RezoResponse<T>> Example
import { RezoFormData } from 'rezo';
const form = new RezoFormData();
form.append('file', new Blob(['hello']), 'hello.txt');
form.append('description', 'A test file');
const { data } = await rezo.postMultipart('/upload', form);
// From plain object
await rezo.postMultipart('/upload', {
file: new Blob(['content']),
name: 'document.txt'
}); Streaming
stream(url, options?)
Returns a RezoStreamResponse immediately. Data is delivered via events.
rezo.stream(url: string | URL, options?: RezoHttpRequest): RezoStreamResponse | Parameter | Type | Description |
|---|---|---|
url | string \| URL | URL to stream from. |
options | RezoHttpRequest | Optional request configuration. |
Example
const stream = rezo.stream('https://example.com/large-file');
stream.on('data', (chunk) => {
console.log('Received:', chunk.length, 'bytes');
});
stream.on('headers', (info) => {
console.log('Status:', info.status);
});
stream.on('finish', (info) => {
console.log('Total bytes:', info.totalBytes);
});
stream.on('error', (err) => {
console.error('Stream failed:', err.message);
}); download(url, saveTo, options?)
Downloads a resource to a file path. Returns a RezoDownloadResponse immediately with progress events.
rezo.download(url: string | URL, saveTo: string, options?: RezoHttpRequest): RezoDownloadResponse | Parameter | Type | Description |
|---|---|---|
url | string \| URL | URL to download from. |
saveTo | string | Local file path to save the download to. |
options | RezoHttpRequest | Optional request configuration. |
Example
const download = rezo.download('https://example.com/file.zip', './downloads/file.zip');
download.on('progress', (p) => {
console.log(`${p.percent}% complete (${p.transferred}/${p.total} bytes)`);
});
download.on('finish', (info) => {
console.log('Saved to:', info.filePath);
});
download.on('error', (err) => {
console.error('Download failed:', err.message);
}); upload(url, data, options?)
Uploads data with progress tracking. Returns a RezoUploadResponse immediately.
rezo.upload(url: string | URL, data: Buffer | FormData | RezoFormData | string | Record<string, any>, options?: RezoHttpRequest): RezoUploadResponse | Parameter | Type | Description |
|---|---|---|
url | string \| URL | URL to upload to. |
data | Buffer \| FormData \| RezoFormData \| string \| Record<string, any> | Data to upload. |
options | RezoHttpRequest | Optional request configuration. |
Example
import { readFileSync } from 'node:fs';
const fileBuffer = readFileSync('./image.png');
const upload = rezo.upload('https://example.com/upload', fileBuffer);
upload.on('progress', (p) => {
console.log(`${p.percent}% uploaded`);
});
upload.on('finish', (response) => {
console.log('Upload complete:', response.data);
}); Pagination
paginate(url, options?)
Async generator for paginated APIs. Auto-detects pagination via Link headers or accepts custom logic.
rezo.paginate<T = any>(url: string, options?: RezoHttpRequest & {
pagination?: {
getNextUrl?: (response: RezoResponse<T>) => string | null | undefined;
transform?: (response: RezoResponse<T>) => any;
countLimit?: number;
requestLimit?: number;
}
}): AsyncGenerator<T, void, undefined> | Option | Type | Description |
|---|---|---|
pagination.getNextUrl | (response) => string \| null | Extract the next page URL from the response. Return null to stop. |
pagination.transform | (response) => any | Transform each response before yielding. Defaults to response.data. |
pagination.countLimit | number | Maximum number of pages to fetch. Default: Infinity. |
pagination.requestLimit | number | Alias for countLimit. |
Example
// Auto-detect via Link header
for await (const page of rezo.paginate('/users')) {
console.log(page); // response.data for each page
}
// Cursor-based pagination
for await (const page of rezo.paginate('/items', {
pagination: {
getNextUrl: (resp) => resp.data.next_cursor
? `/items?cursor=${resp.data.next_cursor}`
: null
}
})) {
console.log(page);
}
// Collect all with transform and limit
const allUsers = [];
for await (const users of rezo.paginate('/users', {
pagination: {
transform: (resp) => resp.data.results,
requestLimit: 10
}
})) {
allUsers.push(...users);
} URL Building
buildUri(config)
Builds a full, safely-encoded URL from parts or a request config.
rezo.buildUri(config: string | URL | BuildUriOptions): RezoUri BuildUriOptions includes all URL API properties plus:
| Property | Type | Description |
|---|---|---|
url | string \| URL | Full or relative URL. |
baseURL | string | Base URL to resolve relative paths against. |
params | Record<string, any> | Query parameters merged into the URL. |
paramsSerializer | (params) => string \| Record<string, string> | Custom params serializer. |
auth | { username: string; password: string } | Basic auth encoded into the URL. |
protocol | string | URL protocol (e.g., 'https'). |
hostname | string | Hostname. |
port | number \| string | Port number. |
pathname | string | URL path. |
search | string | Query string. |
hash | string | URL fragment. |
Example
// From request config
rezo.buildUri({ url: '/users', params: { page: 2 } });
// From individual parts
rezo.buildUri({
protocol: 'https',
hostname: 'api.example.com',
port: 8443,
pathname: '/v1/users',
params: { role: 'admin' },
hash: 'section-2',
auth: { username: 'user', password: 'pass' }
});
// => "https://user:pass@api.example.com:8443/v1/users?role=admin#section-2"
// Encode a string safely
rezo.buildUri('https://example.com/path with spaces?q=a&b'); Instance Management
extend(config)
Creates a child instance that inherits this instance’s defaults, merged with new options.
rezo.extend(config: RezoDefaultOptions): Rezo Example
const api = rezo.extend({ baseURL: 'https://api.example.com' });
const authed = api.extend({
headers: { Authorization: 'Bearer token123' }
});
const { data } = await authed.get('/users'); // Uses both baseURL and auth header destroy()
Releases internal resources such as ProxyManager cooldown timers. Call when the instance is no longer needed.
rezo.destroy(): void Cache Management
clearCache()
Clears both response and DNS caches.
rezo.clearCache(): void invalidateCache(url, method?)
Invalidates the cached response for a specific URL and optional HTTP method.
rezo.invalidateCache(url: string, method?: string): void getCacheStats()
Returns cache statistics for both response and DNS caches.
rezo.getCacheStats(): {
response?: { size: number; enabled: boolean; persistent: boolean };
dns?: { size: number; enabled: boolean };
} Example
const rezo = new Rezo({ cache: true });
await rezo.get('/data'); // Cached
console.log(rezo.getCacheStats());
// { response: { size: 1, enabled: true, persistent: false }, dns: { size: 1, enabled: true } }
rezo.invalidateCache('/data', 'GET');
rezo.clearCache(); // Clear everything Cookie Management
setCookies(cookies, url?, startNew?)
Sets cookies in the jar from multiple input formats.
rezo.setCookies(cookies: string): void
rezo.setCookies(cookies: string, url: string, startNew?: boolean): void
rezo.setCookies(cookies: string[]): void
rezo.setCookies(cookies: string[], url: string, startNew?: boolean): void
rezo.setCookies(cookies: SerializedCookie[]): void
rezo.setCookies(cookies: SerializedCookie[], url: string, startNew?: boolean): void
rezo.setCookies(cookies: Cookie[]): void
rezo.setCookies(cookies: Cookie[], url: string, startNew?: boolean): void | Parameter | Type | Description |
|---|---|---|
cookies | Various | Cookies in Netscape string, Set-Cookie array, serialized objects, or Cookie instances. |
url | string | Optional URL context for domain/path inference. |
startNew | boolean | If true, clears all existing cookies before setting. Default: false. |
getCookies(url?)
Returns cookies in multiple formats.
rezo.getCookies(): Cookies
rezo.getCookies(url: string): Cookies Returns a Cookies object with array, serialized, netscape, string, and setCookiesString properties.
clearCookies()
Removes all cookies from the jar.
rezo.clearCookies(): void Example
// Set from Set-Cookie headers
rezo.setCookies([
'session=abc123; Domain=example.com; Path=/; HttpOnly',
'user=john; Max-Age=3600'
], 'https://example.com');
// Get cookies for a URL
const cookies = rezo.getCookies('https://example.com');
console.log(cookies.string); // "session=abc123; user=john"
// Clear all
rezo.clearCookies(); Properties
jar
Get or set the RezoCookieJar instance.
get jar(): RezoCookieJar
set jar(jar: RezoCookieJar) sessionId
A unique session ID generated for each Rezo instance. Persists across all requests from this instance.
readonly sessionId: string // e.g., "ses_1234567890_abc123def" defaults
The instance-level default options applied to every request.
defaults: RezoDefaultOptions hooks
The hooks system for request/response lifecycle.
hooks: RezoHooks interceptors
Interceptor managers for request/response middleware.
interceptors: {
request: RequestInterceptorManager;
response: ResponseInterceptorManager;
} Example
// Add request interceptor
rezo.interceptors.request.use((config) => {
config.headers = config.headers || {};
config.headers['X-Request-ID'] = crypto.randomUUID();
return config;
});
// Add response interceptor
rezo.interceptors.response.use(
(response) => response,
(error) => {
if (error.status === 401) {
// Handle unauthorized
}
throw error;
}
); proxyManager
Returns the ProxyManager instance if configured, or null.
get proxyManager(): ProxyManager | null responseCache
The response cache instance (if caching is enabled).
readonly responseCache?: ResponseCache dnsCache
The DNS cache instance (if DNS caching is enabled).
readonly dnsCache?: DNSCache Static Methods
Rezo.mergeConfig(config1, config2)
Deep-merges two request configs. Headers and params are merged (not replaced). Properties from config2 take precedence.
static mergeConfig(config1: RezoDefaultOptions, config2: Partial<RezoDefaultOptions>): RezoDefaultOptions Example
const merged = Rezo.mergeConfig(
{ baseURL: 'https://api.example.com', headers: { 'Accept': 'application/json' } },
{ timeout: 5000, headers: { 'Authorization': 'Bearer token' } }
);
// Result: { baseURL: '...', timeout: 5000, headers: { Accept: '...', Authorization: '...' } } Rezo.toCurl(config)
Converts a Rezo request configuration to a cURL command string.
static toCurl(config: RezoRequestConfig): string Rezo.fromCurl(curlCommand)
Parses a cURL command string into a Rezo request configuration object.
static fromCurl(curlCommand: string): RezoRequestConfig Example
// Generate cURL
const curl = Rezo.toCurl({
url: 'https://api.example.com/users',
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'Alice' })
});
// => "curl -X POST -H 'Content-Type: application/json' -d '{"name":"Alice"}' 'https://api.example.com/users'"
// Parse cURL
const config = Rezo.fromCurl("curl -H 'Authorization: Bearer token' https://api.example.com");
const { data } = await rezo.get(config.url, config);