@dakataa/requester
v2.0.3
Published
Fetch API Simplifying library
Downloads
35
Readme
Requester
The library is a utility designed to simplify HTTP requests using the Fetch API.
It provides a clean and flexible interface for making GET, POST, and other HTTP requests, with support for various request body types, authorization mechanisms, and interceptors.
Table of Contents
Installation
Install the library via your preferred package manager:
Using npm:
npm install @dakataa/requesterUsing yarn:
yarn add @dakataa/requesterConfiguration
Default Configuration (Config)
You can set default configuration values that apply to all instances. For example:
Requester.defaults = {
baseURL: 'https://example-api.com',
headers: {
Accept: 'application/json'
}
};Namespace Configuration
The namespace feature allows for custom configurations for different use cases or contexts.
Each namespace can have its own settings, such as authorization.
Example: Setting up a Namespace
Requester.namespace["secure_area"] = {
authorization: new BearerToken('Token')
};Example: Setting up a Namespace
(new Requester({}, 'secure_area')).post({
url: '/secure-endpoint',
body: {
key: 'value'
}
}).then(({status, data}) => {
console.log(data)
});
// or
// Using the `instance` static method
Requester.instance('secure_area').post({
url: '/path/to/endpoint',
body: {
key: 'value'
}
}).then((data: Response) => {
});Using Aliased Methods
The following saves on boilerplate with a single line:
Requester.post({
url: '/path/to/endpoint',
body: {
key: 'value'
},
bodyType: RequestBodyType.JSON,
namespace: 'secure_area'
}).then(({status, data}) => {
console.log(data)
});API Reference
Requester Class
Methods
fetch(config: Request): Promise<Response> Makes an HTTP request based on the provided configuration.
post(config: PostRequestConfig): Promise<Response> Makes a
POSTrequest.get(config: GetRequestConfig): Promise<Response> Makes a
GETrequest.static instance(config?: InstanceConfig): Requester Creates a new
Requesterinstance with the provided configuration.static on(event: InterceptEvent, callable: PreRequestCallback | PreResponseCallback | PostResponseCallback | ErrorCallback, namespace?: string): number Adds an interceptor for the specified event.
static off(interceptorId: number): void Removes an interceptor by its ID.
Request method aliases
For convenience, aliases have been provided for all common request methods.
- Requester.instance(InstanceConfig)
- Requester.post(PostRequestConfig & InstanceConfig
- Requester.get(GetRequestConfig & InstanceConfig)
Types
Config
| Key | Type | Default | Required | Description | |---------------|------------------------------------------------------------------------------------------------|---------|----------|-----------------------------| | baseURL | string | | No | Base URL to create Endpoint | | authorization | Authorization Object (BearerToken, BasicAuth, APIKey) | | No | Authorization Object. | | headers | array | | No | List of HTTP Headers. |
InstanceConfig
| Key | Type | Default | Required | Description | |-----------|---------|---------|----------|--------------------------------------------------| | config | Config | | No | Configuration | | namespace | string | | No | Which namespace to use for default configuration |
PostRequestConfig
| Key | Type | Required | Description | |----------|------------------------------------------------------------------------------------------------------|------------------------------------|----------------------| | url | string | Yes | Full URL or Pathname | | body | FormData, string, Object ([key: value]) | No | Request Body | | bodyType | RequestBodyType | No (Default: RequestBodyType.JSON) | Type of Request Body | | signal | AbortSignal | no | |
GetRequestConfig
| Key | Type | Required | Description | |----------|------------------------------------------------------------------------------------------------------------|----------|----------------------| | url | string | Yes | Full URL or Pathname | | query | URLSearchParams, Object ([key: value]) | No | URL Query Parameters | | signal | AbortSignal | no | |
Request
| Key | Type | Description | |----------|-------------------------------------|----------------------------| | url | number, URL | | | method | Method | Request METHOD | | body | Any | Request BODY | | query | Object, URLSearchParams, FormData | URL Query Parameters | | signal | AbortSignal | Fetch Request Abort Signal | | headers | Object | Request Headers | | timeout | number | Request Timeout |
Response
| Key | Type | Description | |--------|--------|--------------------------------------------------------| | status | number | Response Status Code (200, 400, etc...) | | data | any | Response Data (JSON, Text) depends on response headers |
PreRequestCallback
This type represents a function that is used for callback functions that are invoked before HTTP request to be executed.
- Parameters:
requestId: anumberrepresenting the unique identifier for the request.url: either a URL object or astring, indicating the URL associated with the request.
- Return Type:
void— the function does not return any value.
PreResponseCallback
This type represents a function that is used for callback functions that are invoked before processing HTTP response, providing raw Fetch API response details.
Parameters:
requestId: anumberrepresenting the unique identifier for the request.response: a Response object from the Fetch API, representing the HTTP response.url: either a URL object or astring, indicating the URL associated with the request.options: of typeany, allowing any additional options or data to be passed.
Return Type:
void— the function does not return any value.
PostResponseCallback
This type represents a function that is used for callback functions that are invoked on response.
Parameters:
Return Type:
void— the function does not return any value.
ErrorCallback
This type represents a function that is used for callback functions that are invoked on error.
Parameters:
requestId: anumberrepresenting the unique identifier for the request.reason: astringorErrorobject, representing the error.url: either a URL object or astring, indicating the URL associated with the request.options: of typeany, allowing any additional options or data to be passed.
Return Type:
void— the function does not return any value.
Enums
InterceptEvent
| Case | Description | |---------------|---------------------------| | PRE_REQUEST | FormData | | PRE_RESPONSE | Before Response resolving | | POST_RESPONSE | After Response resolving | | ERROR | On Error |
RequestBodyType
Every RequestBodyType send the body with corresponding request headers.
| Case | Type | Description | |------------|-----------------------|-----------------------| | FormData | form-data | FormData | | Urlencoded | x-www-form-urlencoded | Request Body | | JSON | raw (JSON) | Send Body as raw JSON | | Text | raw (Text) | Send Body as raw Text | | Xml | raw (XML) | Send Body | | Html | raw (Html) | Request Body | | Javascript | raw (Javascript) | Request Body | | Binary | raw (binary) | Request Body |
Authorization
This classes helps you to authorize. We have some basic implementation. You can implement yours.
BearerToken
This class apply Bearer token to headers in your request.
| Argument | Type | Description | |----------|--------|--------------| | token | string | Access Token |
BasicAuth
This class apply basic Authorization header with base64 encoded combination of username and password.
| Argument | Type | Description | |----------|--------|-------------| | username | string | | | password | string | |
APIKey
This class apply custom Header with key and value you have set.
| Argument | Type | Description | |----------|--------|-------------| | key | string | X-API-Key | | value | string | Token |
Example:
new BearerToken('token')Examples
Making a GET Request
Requester.get({
url: '/search?id=2',
query: {
search: 'term'
}
}).then(({data, status}) => {
console.log(status, data);
})Making a POST Request
Requester.post({
url: '/post/endpoint-path',
body: {
form: {
key1: 'value',
key2: {name: 'Yordan'},
key3: ['example', 'array']
}
},
}).then(({data, status}) => {
console.log(status, data);
});Cancel Request
const abortController = new AbortController();
Requester.get({
url: '/search?id=2',
query: {
search: 'term'
},
signal: abortController.signal
}).then(({data, status}) => {
console.log(status, data);
})
// Cancel
abortController.abort();Using Authorization
import BearerToken from "./BearerToken";
Requester.get({
url: '/profile/me',
config: {
authorization: new BearerToken('token')
}
}).then(({data, status}) => {
console.log(status, data);
})Changelog
For a detailed list of changes, see the CHANGELOG file.
FAQ
How do I set a custom base URL?
You can set a custom base URL using the defaults configuration:
Requester.defaults = {
baseURL: 'https://my-custom-api.com'
};Can I use this library in Node.js?
This library is designed for use in browser environments. For Node.js, consider using libraries like axios or node-fetch.
