UNPKG

phx-react

Version:

PHX REACT

43 lines 1.83 kB
import { PHXAxiosInstance } from '../../axiosInstance'; export class ApiError extends Error { constructor(status, message, raw) { super(message); this.name = 'ApiError'; this.status = status; this.raw = raw; Object.setPrototypeOf(this, ApiError.prototype); } } export async function apiFetch(endpoint, options = {}) { var _a, _b; const { body, method = 'GET', params } = options; const finalMethod = method.toLowerCase(); const url = `${process.env.NEXT_PUBLIC_API_GATEWAY}${endpoint}`; const config = { headers: { ...options.headers, }, }; // truyền params cho method GET if (finalMethod === 'get' && params) { config.params = params; } const methodMap = { get: () => PHXAxiosInstance.get(url, config), delete: () => PHXAxiosInstance.delete(url, config), post: () => PHXAxiosInstance.post(url, body, config), put: () => PHXAxiosInstance.put(url, body, config), patch: () => PHXAxiosInstance.patch(url, body, config), }; try { const res = await methodMap[finalMethod](); return res.data; } catch (error) { const status = ((_a = error === null || error === void 0 ? void 0 : error.response) === null || _a === void 0 ? void 0 : _a.status) || 500; const data = ((_b = error === null || error === void 0 ? void 0 : error.response) === null || _b === void 0 ? void 0 : _b.data) || null; const message = (data === null || data === void 0 ? void 0 : data.message) || (data === null || data === void 0 ? void 0 : data.error) || (error === null || error === void 0 ? void 0 : error.message) || 'Unexpected error occurred'; throw new ApiError(status, message, data); } } //# sourceMappingURL=apiClient.js.map