fetchcustom-vsm
v3.0.1
Published
Simple fetch custom
Downloads
5
Readme
FetchCustom README
Introduction
FetchCustom is a lightweight wrapper for the native fetch API in Node.js, providing additional functionality for handling HTTP requests and responses. It is designed to simplify the request process, especially when dealing with JSON, text, or blob data. This utility leverages the resolve pattern and requires Node.js 18 due to the native fetch support introduced in this version.
Features
- JSON Serialization: Automatically serializes request bodies if they are plain objects or arrays.
- Custom Error Handling: Provides a
ResponseErrorclass for detailed error messages, including HTTP status codes and status text. - Data Parsing: Supports methods for parsing responses as JSON, text, or blobs.
- Resolve Pattern: Uses the resolve pattern to handle success and error states more gracefully.
Requirements
- Node.js 18+: This library relies on the native
fetchAPI, which is available from Node.js 18.
Usage
npm i fetchcustom-vsmImport and Setup
import { FetchCustom } from './fetchcustom-vsm';Example Request
const fetcher = new FetchCustom();
async function makeRequest() {
const response = await fetcher.fetchCustom('https://api.example.com/data', {
method: 'POST',
body: { key: 'value' },
});
const result = await response.toJson();
if (result.error) {
console.error('Error:', result.error);
} else {
console.log('Data:', result.data);
}
}
makeRequest();toJson<T>(): Promise<{ data: T | undefined; error: Error | undefined }>
This method parses the response as JSON and returns the data or error.
Example:
const result = await fetcher.toJson();
if (result.error) {
console.error('Error:', result.error);
} else {
console.log('Data:', result.data);
}toText<T>(): Promise<{ data: T | undefined; error: Error | undefined }>
This method parses the response as plain text.
Example:
const result = await fetcher.toText();
if (result.error) {
console.error('Error:', result.error);
} else {
console.log('Text:', result.data);
}toBlob<T>(): Promise<{ data: T | undefined; error: Error | undefined }>
This method parses the response as a blob.
Example:
const result = await fetcher.toBlob();
if (result.error) {
console.error('Error:', result.error);
} else {
console.log('Blob:', result.data);
}Error Handling
If the fetch request returns a non-OK status (HTTP status code outside the 2xx range), the library throws a `ResponseError` with details such as `statusText` and `statusCode`.
🌐 Important Links
-Homepage: https://github.com/Smejia11/FetchCustom
-Repository: git+https://github.com/Smejia11/FetchCustom.git
-Issues: https://github.com/Smejia11/FetchCustom/issues
🤝 Contributing
Contributions are welcome.
Fork the project
Create your feature branch (git checkout -b feature/AmazingFeature)
Execute
npm run formator
pnpm run formatCommit your changes (git commit -m 'Add some AmazingFeature')
Push to the branch (git push origin feature/AmazingFeature)
Open a Pull Request
License
MIT
