/** * API Client for WooNooW Customer SPA * Handles all HTTP requests to WordPress REST API */ // Get API base URL from WordPress const getApiBase = (): string => { // @ts-ignore - WordPress global return window.woonoowCustomer?.apiUrl || '/wp-json/woonoow/v1'; }; // Get nonce for authentication const getNonce = (): string => { // @ts-ignore - WordPress global return window.woonoowCustomer?.nonce || ''; }; interface RequestOptions { method?: 'GET' | 'POST' | 'PUT' | 'DELETE'; body?: any; headers?: Record; } class ApiClient { private baseUrl: string; constructor() { this.baseUrl = getApiBase(); } private async request(endpoint: string, options: RequestOptions = {}): Promise { const { method = 'GET', body, headers = {} } = options; const url = `${this.baseUrl}${endpoint}`; const config: RequestInit = { method, headers: { 'Content-Type': 'application/json', 'X-WP-Nonce': getNonce(), ...headers, }, credentials: 'same-origin', }; if (body) { config.body = JSON.stringify(body); } try { const response = await fetch(url, config); if (!response.ok) { const error = await response.json().catch(() => ({ message: response.statusText })); throw new Error(error.message || `HTTP ${response.status}`); } return await response.json(); } catch (error) { console.error('[API Error]', error); throw error; } } // GET request async get(endpoint: string, params?: Record): Promise { let url = endpoint; if (params) { const query = new URLSearchParams(params).toString(); url += `?${query}`; } return this.request(url, { method: 'GET' }); } // POST request async post(endpoint: string, body?: any): Promise { return this.request(endpoint, { method: 'POST', body }); } // PUT request async put(endpoint: string, body?: any): Promise { return this.request(endpoint, { method: 'PUT', body }); } // DELETE request async delete(endpoint: string): Promise { return this.request(endpoint, { method: 'DELETE' }); } } // Export singleton instance export const api = new ApiClient(); // Export API endpoints export const endpoints = { // Shop products: '/shop/products', product: (id: number) => `/shop/products/${id}`, categories: '/shop/categories', search: '/shop/search', // Cart cart: '/cart', cartAdd: '/cart/add', cartUpdate: '/cart/update', cartRemove: '/cart/remove', cartCoupon: '/cart/apply-coupon', // Checkout checkoutCalculate: '/checkout/calculate', checkoutCreate: '/checkout/create-order', paymentMethods: '/checkout/payment-methods', shippingMethods: '/checkout/shipping-methods', // Account orders: '/account/orders', order: (id: number) => `/account/orders/${id}`, downloads: '/account/downloads', profile: '/account/profile', password: '/account/password', addresses: '/account/addresses', };