| 1 |
import axios from 'axios' |
| 2 |
import type { AxiosRequestConfig, AxiosResponse } from 'axios' |
| 3 |
|
| 4 |
export const useApiClient = () => { |
| 5 |
const { root, nonce, namespace } = window.wpIvyApiSettings || {} |
| 6 |
|
| 7 |
const apiClient = axios.create({ |
| 8 |
baseURL: root || '', |
| 9 |
}) |
| 10 |
|
| 11 |
apiClient.interceptors.request.use( |
| 12 |
(config) => { |
| 13 |
if (nonce) { |
| 14 |
if (typeof config.headers?.set === 'function') { |
| 15 |
config.headers.set('X-WP-Nonce', nonce) |
| 16 |
} else { |
| 17 |
;(config.headers as Record<string, string>)['X-WP-Nonce'] = nonce |
| 18 |
} |
| 19 |
} |
| 20 |
return config |
| 21 |
}, |
| 22 |
(error) => Promise.reject(error), |
| 23 |
) |
| 24 |
|
| 25 |
const handleResponse = async <T = unknown>(promise: Promise<AxiosResponse<T>>) => { |
| 26 |
try { |
| 27 |
const response = await promise |
| 28 |
return { data: response.data, error: null, status: response.status } |
| 29 |
} catch (error: unknown) { |
| 30 |
const status = |
| 31 |
typeof error === 'object' && |
| 32 |
error !== null && |
| 33 |
'response' in error && |
| 34 |
typeof (error as { response?: { status?: number } }).response?.status === 'number' |
| 35 |
? (error as { response: { status: number } }).response.status |
| 36 |
: 500 |
| 37 |
return { |
| 38 |
data: null, |
| 39 |
error, |
| 40 |
status, |
| 41 |
} |
| 42 |
} |
| 43 |
} |
| 44 |
|
| 45 |
const request = async <T = unknown>( |
| 46 |
endpoint: string, |
| 47 |
options: AxiosRequestConfig = {}, |
| 48 |
config: { useNamespace?: boolean; namespace?: string } = {}, |
| 49 |
) => { |
| 50 |
let url = root || '' |
| 51 |
const ns = config.namespace || namespace |
| 52 |
const useNs = config.useNamespace !== undefined ? config.useNamespace : true |
| 53 |
if (useNs && ns) { |
| 54 |
url += ns.endsWith('/') ? ns : ns + '/' |
| 55 |
} |
| 56 |
url += endpoint.startsWith('/') ? endpoint.slice(1) : endpoint |
| 57 |
return handleResponse<T>(apiClient.request({ url, ...options })) |
| 58 |
} |
| 59 |
|
| 60 |
return { |
| 61 |
request, |
| 62 |
apiClient, |
| 63 |
root, |
| 64 |
namespace, |
| 65 |
nonce, |
| 66 |
} |
| 67 |
} |
| 68 |
|