@unireq/presets
Pre-configured clients and helpers that assemble transports + policies for common scenarios.
Installation
bash
pnpm add @unireq/presetsExport overview
| Helper | Description |
|---|---|
httpClient(baseUrl?, options?) | Simple HTTP client with sensible defaults (JSON, redirects, timeout, headers). |
httpsJsonAuthSmart(uri, options) | HTTPS client with content negotiation, redirect hardening, HTTP-aware retry/backoff, optional OAuth. |
httpUploadGeneric(uri?, options?) | Thin wrapper that returns client(http(uri), ...policies) for uploads. |
createMultipartUpload(files, fields?, options?) | Convenience helper over body.multipart (validation included). |
httpDownloadResume(uri, resumeStateOrOptions?) | HTTP client pre-wired with range/resume for partial downloads. |
gmailImap(tokenSupplier) | Policy that selects INBOX over IMAP with XOAUTH2. |
resume, multipart, MultipartFile, ... | Re-exports from @unireq/http for consumers who only import presets. |
httpClient (Simple HTTP Client)
The simplest way to create an HTTP client with sensible defaults:
ts
import { httpClient } from '@unireq/presets';
// Minimal usage
const api = httpClient('https://api.example.com');
const user = await api.get('/users/42');
// With options
const api = httpClient('https://api.example.com', {
timeout: 10000,
headers: { 'X-API-Key': 'secret' },
query: { api_key: 'secret123', format: 'json' }, // default query params
json: true, // default: true
followRedirects: true, // default: true
policies: [customLogging()],
});
// Safe methods (returns Result instead of throwing)
const result = await api.safe.get('/users/42');
if (result.isOk()) {
console.log(result.value.data);
}Options
| Option | Type | Default | Description |
|---|---|---|---|
timeout | number | - | Request timeout in milliseconds |
headers | Record<string, string> | - | Default headers for all requests |
query | Record<string, string | number | boolean | undefined> | - | Default query parameters appended to all requests |
json | boolean | true | Auto-parse JSON responses |
followRedirects | boolean | true | Follow 307/308 redirects |
policies | Policy[] | [] | Additional policies to apply |
When to use
- httpClient: Quick prototyping, simple API calls, when you want sensible defaults
- httpsJsonAuthSmart: Production apps needing OAuth, retry, rate limiting
- Custom client: Full control over policy composition
httpsJsonAuthSmart
ts
import { httpsJsonAuthSmart } from '@unireq/presets';
const api = await httpsJsonAuthSmart('https://api.example.com', {
tokenSupplier: () => getAccessToken(),
jwks: { type: 'url', url: 'https://accounts.example.com/jwks.json' },
allowUnsafeMode: false,
policies: [customMetrics()],
});
const res = await api.get('/users/me');- Accepts JSON/XML, follows only
307/308, retries (408/429/5xx) withrateLimitDelay+backoffstrategies. - Optional
oauthBearerlayer (only iftokenSupplierprovided). Ordering matches the guidance from composition. - You may append extra policies via
options.policies(they run closest to the transport).
httpUploadGeneric + createMultipartUpload
ts
import { httpUploadGeneric, createMultipartUpload } from '@unireq/presets';
const uploader = httpUploadGeneric('https://uploads.example.com');
await uploader.post('/files', createMultipartUpload([
{ name: 'file', filename: 'doc.pdf', part: body.binary(fileBuffer, 'application/pdf') },
]));httpUploadGenericjust returns aclientso you can compose your own policies (auth, logging, etc.).createMultipartUploadenforces size/type limits viaMultipartValidationOptionsbefore serializing the body.
httpDownloadResume
ts
import { httpDownloadResume } from '@unireq/presets';
const downloader = httpDownloadResume('https://cdn.example.com', { resumeState: { downloaded: 5_000 } });
const chunk = await downloader.get('/video.mp4');- Detects whether the server supports
Accept-Rangesand, if so, resumes fromresumeState.downloadedvia therangepolicy. - Pass
options.policiesto add logging or checksum verification.
gmailImap
ts
import { gmailImap } from '@unireq/presets';
import { client } from '@unireq/core';
import { imap } from '@unireq/imap';
const gmail = client(imap({ host: 'imap.gmail.com', port: 993 }), gmailImap(() => getGmailToken()));
const inbox = await gmail.list();- Wraps the XOAUTH2 policy from
@unireq/imapand issues aSELECT INBOXcommand automatically. - Replace
gmailImapwith your own policy if you need a different mailbox or capability negotiation.
Choosing a preset
| Helper | Transport | OAuth | Retry/backoff | Rate-limit aware | Content negotiation |
|---|---|---|---|---|---|
httpsJsonAuthSmart | HTTP/HTTPS | Optional | ✅ | ✅ (Retry-After) | JSON ↔ XML via either() |
httpUploadGeneric | HTTP/HTTPS | Bring-your-own | ❌ | ❌ | Depends on added policies |
httpDownloadResume | HTTP/HTTPS | N/A | ❌ | ❌ | Binary chunks |
gmailImap | IMAP (imapflow) | ✅ (XOAUTH2) | ❌ | ❌ | IMAP responses |
Need a different combo? These helpers are short wrappers around client(http(...), ...policies), so inspect packages/presets/src and copy the pattern into your app.