DEV Community

Warayus Poosaweang
Warayus Poosaweang

Posted on

API Handling: Utilizing the Facade Pattern with Axios in Frontend Development

Facade Pattern

Hello everyone! Today, I'd like to share a code pattern for interacting with APIs from the frontend. I recently came across this pattern and found it quite interesting.

Typically, there are various ways to choose an HTTP client, and for this example, I've chosen axios.

api.ts

import axios from 'axios';

const PUBLIC_API_URL="localhost:3000"

const METHOD: Record<string, string> = {
    GET: 'get',
    DELETE: 'delete',
    POST: 'post',
    PUT: 'put',
    PATCH: 'patch'
};

const axiosAPI = axios.create({
    baseURL: PUBLIC_API_URL
});

const apiRequest = async (
    method: string,
    url: string,
    request?: Record<string, any> | undefined
): Promise<ApiResponse> => {
    const headers = {
        Authorization: 'Bearer some_token',
        };

    return await axiosAPI({
        method,
        url,
        data: request,
        headers
    }).then((response) => {
        // handle a loading or something like that
        return response?.data;
    });
};

const get = (url: string, request?: Record<string, any> | undefined) =>
    apiRequest(METHOD.GET, url, request);

const post = async (
    url: string,
    request?: Record<string, any> | undefined,
) => {
    const response = await apiRequest(METHOD.POST, url, request);
        // show modal or something like that

    return response;
};

const patch = async (
    url: string,
    request?: Record<string, any> | undefined,
) => {
    const response = await apiRequest(METHOD.PATCH, url, request);
        // show modal or something like that

    return response;
};

const deleteRequest = async (url: string, request?: Record<string, any> | undefined) => {
    const response = await apiRequest(METHOD.DELETE, url, request);
        // show modal or something like that

    return response;
};

const put = (url: string, request?: Record<string, any> | undefined) => {
        const response = apiRequest(METHOD.PUT, url, request);
        // show modal or something like that

    return response;
}

const API = {
    get,
    delete: deleteRequest,
    post,
    put,
    patch
};

export default API;
Enter fullscreen mode Exit fullscreen mode

From the code snippet, you can see that we encapsulate concerns like authorization, endpoint URLs, and modal display within a single file.

How to use this class is

example.ts

import Api from './api'; // import api class

const responses = await Api.get(`/warranty/${serialNumber}`);
// handle data or something like that
console.log(response)
Enter fullscreen mode Exit fullscreen mode

The usage of this class is straightforward. You can see from the example.ts file how easy it is to call API methods without worrying about authorization, endpoint URLs, or modal displays, as these complexities have been abstracted away into the api.ts file.

This approach aligns well with the Facade Pattern.

The benefits of adopting this coding style include making the code easy to understand and efficient, allowing everyone on the team to grasp it quickly and use it without needing to spend time studying or modifying the code.

Additionally, splitting the code into smaller parts also improves testing efficiency.

Finally, utilizing the Facade Pattern helps maintain a structured and convenient maintenance process for the project.

Next time, I'll share how to handle cases where we call the same GET endpoint but need to handle different data. Stay tuned!

Top comments (0)