import { __ } from '@wordpress/i18n'; import axios, { AxiosInstance } from 'axios'; import { AjaxResponse } from './ajax.service.types'; interface AjaxServiceInitParams { ajaxUrl: string; nonce: string; } class AjaxService { private axiosInstance: AxiosInstance; private ajaxUrl!: string; private nonce!: string; constructor() { this.axiosInstance = axios.create({ headers: { 'Content-Type': 'multipart/form-data', }, }); } init(params: AjaxServiceInitParams) { this.ajaxUrl = params.ajaxUrl; this.nonce = params.nonce; } /** * Send POST AJAX request with JSON payload converted to FormData */ async post(action: string, payload: Record): Promise { if (!this.ajaxUrl) { throw new Error(__('AjaxService not initialized', 'timetailor-salon-booking')); } try { const ajaxPayload = { action, security: this.nonce, ...payload, }; const formData = this.jsonToFormData(ajaxPayload); const response = await this.axiosInstance.post>(this.ajaxUrl, formData); // If success is true, return the data object if (response.data.success) { return response.data.data; } // If success is false, throw the data as error throw response.data.data || new Error(__('Request failed', 'timetailor-salon-booking')); } catch (error) { // If it's already the data object we threw, re-throw it if (error && typeof error === 'object' && !(error instanceof Error)) { throw error; } if (axios.isAxiosError(error) && error.response) { // If server returned an error response, try to parse it const responseData = error.response.data; if (responseData && typeof responseData === 'object' && 'data' in responseData) { throw responseData.data || new Error(__('Request failed', 'timetailor-salon-booking')); } throw new Error(responseData?.message || __('Request failed', 'timetailor-salon-booking')); } throw new Error(__('Network error or request failed', 'timetailor-salon-booking')); } } private jsonToFormData(payload: Record): FormData { const formData = new FormData(); Object.keys(payload).forEach((key) => { const value = payload[key]; if (value !== null && value !== undefined) { formData.append(key, value); } }); return formData; } } export const ajaxService = new AjaxService();