SolidJSS
SolidJSโ€ข2y agoโ€ข
5 replies
sh1man

Can anyone tell me how best to do it? Store API

import axios from "axios";
import {ErrorApi} from "~/utils/tryCallApi";
import {IBaseResponse, UserProfileEntity} from "~/types";
import {getCookieValue} from "~/utils";
import {type Navigator} from "@solidjs/router";
import {paths} from "~/utils/paths";

export type HttpClientActions = {
    user: HttpClientActionsProfile
}

type HttpClientActionsProfile = {
    profile: () => Promise<IBaseResponse<UserProfileEntity>>;
}

export default function createHttpClient(navigate: Navigator) {

    const api = axios.create({
        baseURL: import.meta.env.VITE_API_URL,
        withCredentials: true,
        headers: {
            Accept: 'application/json',
        }
    })

    api.interceptors.request.use((config) => {
        const csrfToken = getCookieValue('csrftoken');
        if (csrfToken !== null) {
            config.headers['X-CSRFToken'] = csrfToken;
        }
        return config;
    })

    api.interceptors.response.use(
        async (response) => response,
        async (error) => {
            if(error?.response?.status === 401){
                /// This normal practice ????????????????????
                setTimeout(() => {
                  navigate(paths.logIn);
                }, 0);
            }
            const apiError: ErrorApi = {
                message: error?.response?.data?.detail,
                data: error?.response?.data,
                status: error?.response?.status,
                result: false
            }
            return Promise.reject(apiError);
        }
    )

    const httpClient: HttpClientActions = {
        user: {
           profile: async () => api.post('/user/profile/'),
        }
    }

    return httpClient;
}
Was this page helpful?