Documentation for fetch_helper.ts
This file provides helper functions for making HTTP requests with enhanced error handling and default configurations.
It uses the native fetch API in JavaScript and introduces abstractions for streamlined usage in applications.
Below is a breakdown of the provided functionality and how to use it.
Overview
Functions and Types
Types:
WrappedFetchRequest: Defines the structure of the request object.WrappedFetchResponse: Defines the structure of the response object.
Functions:
-
wrappedFetch(request: WrappedFetchRequest): Promise<WrappedFetchResponse>- A generic wrapper around
fetchto make HTTP requests with error handling and default configurations.
- A generic wrapper around
-
wrappedAuthFetch(request: WrappedFetchRequest, auth_token: Nullable<string>): Promise<WrappedFetchResponse>- Extends
wrappedFetchto include a JSON Web Token (JWT) as anAuthorizationheader in the request.
- Extends
Usage
Setup
- Ensure your project has access to the following dependencies:
@fnz/types@fnz/types/errors
- The environment variable
BACKEND_URLshould be set to your application's base API URL (optional ifbaseURLis provided).
Examples
Basic Request Using wrappedFetch
import { wrappedFetch } from './fetch_helper';
const makeGetRequest = async () => {
const request = {
method: 'GET',
endpoint: '/api/example',
};
const response = await wrappedFetch(request);
if (response.error) {
console.error('Error:', response.error);
} else {
console.log('Response Body:', response.body);
}
};
makeGetRequest();
Authenticated Request Using wrappedAuthFetch
import { wrappedAuthFetch } from './fetch_helper';
const makeAuthenticatedRequest = async () => {
const authToken = 'your-auth-token-here';
const request = {
method: 'POST',
endpoint: '/api/secure-resource',
body: { key: 'value' },
};
const response = await wrappedAuthFetch(request, authToken);
if (response.error) {
console.error('Authentication Error:', response.error);
} else {
console.log('Secure Response:', response.body);
}
};
makeAuthenticatedRequest();
Advanced Usage
Custom Base URL
import { wrappedFetch } from './fetch_helper';
const makeCustomBaseUrlRequest = async () => {
const request = {
method: 'PUT',
endpoint: '/api/custom-endpoint',
baseURL: 'https://custom.api.server.com',
body: { data: 'example' },
};
const response = await wrappedFetch(request);
if (response.error) {
console.error('Custom Base URL Error:', response.error);
} else {
console.log('Custom Response:', response.body);
}
};
makeCustomBaseUrlRequest();
Adding Additional Headers
import { wrappedFetch } from './fetch_helper';
const makeRequestWithHeaders = async () => {
const headers = new Headers();
headers.append('X-Custom-Header', 'CustomValue');
const request = {
method: 'GET',
endpoint: '/api/with-headers',
headers,
};
const response = await wrappedFetch(request);
if (response.error) {
console.error('Header Error:', response.error);
} else {
console.log('Header Response:', response.body);
}
};
makeRequestWithHeaders();
Error Handling
Errors are encapsulated in the error field of the WrappedFetchResponse object.
The ServerErrorV2 class provides structured error details:
failure_code: The error code returned by the server.error: The error message.
Example:
const response = await wrappedFetch(request);
if (response.error) {
console.error(`Error Code: ${response.error.failure_code}`);
console.error(`Error Message: ${response.error.message}`);
}