@avidian/http
v1.0.5
Published
Just another http library.
Readme
@avidian/http
A lightweight, flexible HTTP client for browsers and Node.js.
Features
- Promise-based API
- Supports GET, POST, PUT, PATCH, DELETE
- Custom headers, query parameters, and response types
- Emulate PUT/PATCH with POST for legacy backends
- Works in Node.js and browsers
- TypeScript support
Installation
npm install @avidian/httpUsage
Basic Example
import Http from '@avidian/http';
const http = new Http();
async function fetchData() {
const response = await http.get('https://api.example.com/data');
console.log(response.data);
}With Custom Options
import Http from '@avidian/http';
const http = new Http({
baseUrl: 'https://api.example.com',
headers: { Authorization: 'Bearer token' },
});
http.post('/users', { name: 'Alice' }).then(res => {
console.log(res.data);
});Emulate PUT/PATCH
const http = new Http({ emulatePutPatch: true });
http.put('/resource/1', { name: 'Bob' });API
Http(options?: HttpOptions)
Creates a new HTTP client instance.
options (HttpOptions)
baseUrl?: string– Base URL for requestsheaders?: Record<string, string>– Default headersparams?: Record<string, string | number>– Default query parametersfetch?: Fetch– Custom fetch implementationemulatePutPatch?: 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: string, options?: Options)post<T>(url: string, data?: any, options?: Options)put<T>(url: string, data?: any, options?: Options)patch<T>(url: string, data?: any, options?: Options)delete<T>(url: string, options?: Options)
Options (Options)
headers?: Record<string, string>params?: Record<string, string | number>responseType?: 'json' | 'text' | 'blob' | 'arrayBuffer'(default:'json')signal?: AbortSignal
Response<T> (Response)
headers: Record<string, string>statusCode: numberdata: T
Error Handling
Errors with status code >= 400 throw an Exception containing the response.
import Http, { isException } from '@avidian/http';
const http = new Http();
try {
await http.get('/not-found');
} catch (err) {
if (isException(err)) {
console.error(err.response.statusCode, err.response.data);
}
}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
