@avidian/http
v2.0.0
Published
Just another http library.
Readme
@avidian/http
A lightweight, axios-like HTTP client built on the fetch API. Works in browsers and Node.js.
Features
- Promise-based API with axios-style ergonomics, fetch under the hood
GET,POST,PUT,PATCH,DELETE,HEAD, plus a genericrequest()- Request and response interceptors, including error interceptors with recovery
- Timeouts via
AbortController, merged with your ownAbortSignal - Custom headers, query parameters, and response types
fetchOptionspass-through forcredentials,mode,cache, and any otherRequestInitfield- Configurable
validateStatus - Emulate PUT/PATCH with POST for legacy backends (
FormData-safe) - TypeScript-first, ships ESM, CJS, and UMD builds
Installation
npm install @avidian/httpUsage
Basic Example
import createHttp from '@avidian/http';
const http = createHttp();
const response = await http.get('https://api.example.com/data');
console.log(response.data);You can also construct the class directly:
import { Http } from '@avidian/http';
const http = new Http({
baseUrl: 'https://api.example.com',
headers: { Authorization: 'Bearer token' },
timeout: 10000,
});
const res = await http.post('/users', { name: 'Alice' });In browsers, relative URLs without a baseUrl resolve against the current page, just like fetch.
Interceptors
// Request interceptors receive the RequestInit about to be sent.
const removeAuth = http.addRequestInterceptor((request) => {
request.headers = { ...request.headers, 'X-Trace': 'abc' };
return request;
});
// Response interceptors chain like promise handlers (axios-style).
http.addResponseInterceptor(
(response) => response,
(error) => {
// Return a Response to recover, or rethrow to propagate.
throw error;
}
);
removeAuth(); // every add* method returns an unsubscribe functionError interceptors receive an Exception for HTTP status failures (code: 'ERR_BAD_RESPONSE'), an Exception with code: 'ETIMEDOUT' for timeouts, or the original error for network failures.
Timeouts and Cancellation
const controller = new AbortController();
await http.get('/slow', {
timeout: 5000, // rejects with Exception code ETIMEDOUT
signal: controller.signal, // user aborts keep their AbortError
});Cookies / CORS
const http = new Http({
baseUrl: 'https://api.example.com',
fetchOptions: { credentials: 'include' },
});Emulate PUT/PATCH
const http = new Http({ emulatePutPatch: true });
// Plain objects gain a `_method` field; FormData/URLSearchParams get
// `_method` appended; opaque bodies carry `_method` in the query string.
await http.put('/resource/1', { name: 'Bob' });API
createHttp(options?: HttpOptions) / new Http(options?: HttpOptions)
HttpOptions (src/types.ts)
baseUrl?: string- base URL for requestsheaders?: Record<string, string> | Headers- default headersparams?: QueryParams- default query parametersfetch?: Fetch- custom fetch implementationtimeout?: number- default timeout in millisecondsfetchOptions?: RequestInit- extra fetch options for every requestvalidateStatus?: (status: number) => boolean- default:status < 400emulatePutPatch?: boolean- emulate PUT/PATCH with POSTemulateMethodKey?: string- key for emulated method (default:_method)emulateMethod?: 'GET' | 'POST'- HTTP method to use (default:POST)emulateMethodValue?: string- value for emulated method
Methods
All methods return a Promise<Response<T>>.
get<T>(url, options?)head<T>(url, options?)post<T, D>(url, data?, options?)put<T, D>(url, data?, options?)patch<T, D>(url, data?, options?)delete<T, D>(url, options?)- acceptsdatainsideoptionsrequest<T, D>(config)- generic dispatch with fullRequestConfigaddRequestInterceptor(fn)- returns an unsubscribe functionaddResponseInterceptor(onFulfilled?, onRejected?)- returns an unsubscribe function
Options (src/types.ts)
headers?: Record<string, string> | Headersparams?: QueryParamsresponseType?: 'json' | 'text' | 'blob' | 'arrayBuffer'(default:'json')signal?: AbortSignaltimeout?: numberfetchOptions?: RequestInitvalidateStatus?: (status: number) => boolean
Response<T> (src/types.ts)
headers: Record<string, string>statusCode: numberstatusText: stringdata: T
Error Handling
Requests failing validateStatus reject with an Exception.
import createHttp, { isException } from '@avidian/http';
const http = createHttp();
try {
await http.get('/not-found');
} catch (err) {
if (isException(err)) {
console.error(err.code, err.response?.statusCode, err.response?.data);
}
}Exception fields:
message: stringresponse?: Response<any>- present for HTTP status failurescode?: string-ERR_BAD_RESPONSE,ETIMEDOUT, ...
Testing
npm testBuilding
npm run buildContributing
- Fork the repo and create your branch.
- Run
npm install. - Add tests for your feature or bugfix.
- Run
npm testandnpm run build. - Submit a pull request.
License
MIT © John Michael Manlupig
