API Client
A fetch-based HTTP client with automatic JSON handling, configurable timeouts, retry logic with exponential backoff, request/response interceptors, file uploads with progress tracking, and abort controller support.
Quick Start
Configure a base URL, set default headers, then make requests using the standard HTTP method helpers.
import Aura from 'aurajs'; // Configure the API client Aura.api.configure({ baseURL: 'https://api.example.com', headers: { 'Authorization': 'Bearer my-token' }, timeout: 10000, retry: 2 }); // GET request const users = await Aura.api.get('/users'); // POST request const newUser = await Aura.api.post('/users', { name: 'Alice', email: 'alice@example.com' });
Types
ApiConfig
Configuration object accepted by configure(). All fields are optional (partial).
| Property | Type | Description |
|---|---|---|
| baseURL | string | Base URL prepended to all request paths. Default: ''. |
| headers | Record<string, string> | Default headers sent with every request. Default: { 'Content-Type': 'application/json' }. |
| timeout | number | Request timeout in milliseconds. Default: 30000. |
| retry | number | Number of retry attempts on failure. Default: 0. |
| retryDelay | number | Base delay between retries in ms (multiplied by attempt number). Default: 1000. |
RequestOptions
Per-request options passed as the last argument to HTTP method helpers.
| Property | Type | Description |
|---|---|---|
| params | Record<string, string | number> | Query string parameters appended to the URL. |
| headers | Record<string, string> | Extra headers merged with the defaults for this request. |
| interceptors | string[] | Names of specific request interceptors to run (default: all). |
| timeout | number | Override the global timeout for this request. |
| retry | number | Override the global retry count for this request. |
| signal | AbortSignal | An AbortSignal to cancel the request. |
configure() core
Merge partial configuration into the current API client settings. Any provided fields override the existing values.
| Param | Type | Description |
|---|---|---|
| config | Partial<ApiConfig> | Object with optional baseURL, headers, timeout, retry, and retryDelay fields. |
Aura.api.configure({ baseURL: 'https://api.example.com/v2', timeout: 15000, retry: 3, retryDelay: 500 });
get() core
Send a GET request. Automatically parses JSON responses when the Content-Type header is application/json.
| Param | Type | Description |
|---|---|---|
| url | string | Request path appended to baseURL. |
| opts | RequestOptions | Optional per-request settings (query params, headers, timeout, etc.). |
// Simple GET const users = await Aura.api.get('/users'); // With query parameters const results = await Aura.api.get('/search', { params: { q: 'aura', page: 1, limit: 20 } }); // With custom timeout const data = await Aura.api.get('/slow-endpoint', { timeout: 60000 });
post() core
Send a POST request with a JSON body. The body is automatically serialized with JSON.stringify().
| Param | Type | Description |
|---|---|---|
| url | string | Request path appended to baseURL. |
| body | unknown | Optional request body, serialized as JSON. |
| opts | RequestOptions | Optional per-request settings. |
const user = await Aura.api.post('/users', { name: 'Alice', email: 'alice@example.com', role: 'admin' }); console.log('Created user:', user.id);
put() core
Send a PUT request with a JSON body. Typically used for full resource replacement.
| Param | Type | Description |
|---|---|---|
| url | string | Request path appended to baseURL. |
| body | unknown | Optional request body, serialized as JSON. |
| opts | RequestOptions | Optional per-request settings. |
await Aura.api.put('/users/42', { name: 'Alice Updated', email: 'alice.new@example.com', role: 'superadmin' });
patch() core
Send a PATCH request with a JSON body. Typically used for partial resource updates.
| Param | Type | Description |
|---|---|---|
| url | string | Request path appended to baseURL. |
| body | unknown | Optional request body, serialized as JSON. |
| opts | RequestOptions | Optional per-request settings. |
// Update only specific fields await Aura.api.patch('/users/42', { role: 'moderator' });
delete() destructive
Send a DELETE request. No body is sent by default.
| Param | Type | Description |
|---|---|---|
| url | string | Request path appended to baseURL. |
| opts | RequestOptions | Optional per-request settings. |
await Aura.api.delete('/users/42'); // With custom headers await Aura.api.delete('/posts/99', { headers: { 'X-Confirm': 'true' } });
upload() file
Upload a file using FormData. The Content-Type header is automatically removed so the browser can set the correct multipart boundary. Supports optional progress tracking via XMLHttpRequest.
| Param | Type | Description |
|---|---|---|
| url | string | Upload endpoint path appended to baseURL. |
| formData | FormData | A FormData object containing the file(s) and any additional fields. |
| opts | RequestOptions & { onProgress? } | Optional settings. onProgress receives a percentage (0–100) during upload. |
const form = new FormData(); form.append('avatar', fileInput.files[0]); form.append('userId', '42'); const result = await Aura.api.upload('/upload/avatar', form, { onProgress(pct) { progressBar.style.width = pct + '%'; console.log(`Uploading: ${pct}%`); } }); console.log('Uploaded:', result.url);
createAbortController() utility
Create a new AbortController instance. Pass its signal to any request's opts.signal to enable cancellation.
This method takes no parameters.
const ctrl = Aura.api.createAbortController(); // Start a request with the signal const promise = Aura.api.get('/long-running', { signal: ctrl.signal }); // Cancel the request after 5 seconds setTimeout(() => ctrl.abort(), 5000); try { const data = await promise; } catch (e) { console.log('Request cancelled'); }
addInterceptor() interceptor
Register a named request interceptor. Interceptors run before every request (unless overridden by opts.interceptors). They receive the request config and can modify it, or return false to block the request entirely.
| Param | Type | Description |
|---|---|---|
| name | string | Unique name for the interceptor (used with removeInterceptor() and opts.interceptors). |
| interceptor | Function | Receives ReqConfig ({ url, method, headers, body, params }). Return modified config or false to block. |
// Auth interceptor: attach token to every request Aura.api.addInterceptor('auth', (config) => { const token = localStorage.getItem('token'); if (token) { config.headers['Authorization'] = `Bearer ${token}`; } return config; }); // Rate-limit interceptor: block if too many requests Aura.api.addInterceptor('rateLimit', (config) => { if (requestCount > 100) return false; // blocks the request return config; }); // Run only specific interceptors for one request await Aura.api.get('/public', { interceptors: ['rateLimit'] // skip 'auth' });
removeInterceptor() interceptor
Remove a previously registered request interceptor by name.
| Param | Type | Description |
|---|---|---|
| name | string | The name of the interceptor to remove. |
Aura.api.removeInterceptor('auth');
addResponseInterceptor() interceptor
Register a named response interceptor. Response interceptors run after every successful fetch, before the response is parsed. They receive the raw Response object and the original request config, and must return a Response.
| Param | Type | Description |
|---|---|---|
| name | string | Unique name for the response interceptor. |
| interceptor | Function | Receives the raw Response and ReqConfig. Must return a Response (can be the same or a new one). |
// Log all response statuses Aura.api.addResponseInterceptor('logger', (response, config) => { console.log(`[${config.method}]`, config.url, response.status); return response; }); // Handle token refresh on 401 Aura.api.addResponseInterceptor('tokenRefresh', async (response, config) => { if (response.status === 401) { await refreshToken(); // The retry logic will handle re-sending } return response; });
removeResponseInterceptor() interceptor
Remove a previously registered response interceptor by name.
| Param | Type | Description |
|---|---|---|
| name | string | The name of the response interceptor to remove. |
Aura.api.removeResponseInterceptor('logger');