import { AxiosResponse } from "axios"; import { useContext } from "@nuxtjs/composition-api"; import { NuxtAxiosInstance } from "@nuxtjs/axios"; import { Api } from "~/api"; import { ApiRequestInstance } from "~/types/api"; interface RequestResponse { response: AxiosResponse | null; data: T | null; error: any; } const request = { async safe(funcCall: any, url: string, data: object = {}): Promise> { const response = await funcCall(url, data).catch(function (error: object) { console.log(error); // Insert Generic Error Handling Here return { response: null, error, data: null }; }); return { response, error: null, data: response.data }; }, }; function getRequests(axoisInstance: NuxtAxiosInstance): ApiRequestInstance { const requests = { async get(url: string, queryParams = {}): Promise> { let error = null; const response = await axoisInstance.get(url, { params: { queryParams } }).catch((e) => { error = e; }); if (response != null) { return { response, error, data: response?.data }; } return { response: null, error, data: null }; }, async post(url: string, data: object) { return await request.safe(axoisInstance.post, url, data); }, async put(url: string, data: object) { return await request.safe(axoisInstance.put, url, data); }, async patch(url: string, data: object) { return await request.safe(axoisInstance.patch, url, data); }, async delete(url: string) { return await request.safe(axoisInstance.delete, url); }, }; return requests; } export const useApiSingleton = function (): Api { const { $axios } = useContext(); const requests = getRequests($axios); return new Api(requests) };