| 1 |
import apiFetch from '@wordpress/api-fetch'; |
| 2 |
import useSWR from 'swr'; |
| 3 |
|
| 4 |
const NAMESPACE = '/give-api/v2/logs'; |
| 5 |
|
| 6 |
/** |
| 7 |
* @since 4.16.8 Replaced axios with @wordpress/api-fetch, which resolves with the parsed |
| 8 |
* response body and supplies the REST root and nonce from WordPress core. |
| 9 |
*/ |
| 10 |
const API = { |
| 11 |
get: (endpoint) => apiFetch({path: NAMESPACE + endpoint}), |
| 12 |
post: (endpoint, data) => apiFetch({path: NAMESPACE + endpoint, method: 'POST', data}), |
| 13 |
delete: (endpoint) => apiFetch({path: NAMESPACE + endpoint, method: 'DELETE'}), |
| 14 |
}; |
| 15 |
|
| 16 |
export default API; |
| 17 |
|
| 18 |
// SWR Fetcher |
| 19 |
export const Fetcher = (endpoint) => |
| 20 |
API.get(endpoint).then(({data, ...rest}) => { |
| 21 |
return { |
| 22 |
data, |
| 23 |
response: rest, |
| 24 |
}; |
| 25 |
}); |
| 26 |
|
| 27 |
export const useLogFetcher = (endpoint, params = {}) => { |
| 28 |
const {data, error} = useSWR(endpoint, Fetcher, params); |
| 29 |
return { |
| 30 |
data: data ? data.data : undefined, |
| 31 |
isLoading: !error && !data, |
| 32 |
isError: error, |
| 33 |
response: data ? data.response : undefined, |
| 34 |
}; |
| 35 |
}; |
| 36 |
|
| 37 |
/** |
| 38 |
* GET endpoint with additional parameters. |
| 39 |
* |
| 40 |
* @since 4.16.8 apiFetch's root URL middleware rewrites the separator on sites without |
| 41 |
* pretty permalinks, so the endpoint always uses '?' here. |
| 42 |
*/ |
| 43 |
export const getEndpoint = (endpoint, data) => { |
| 44 |
if (data) { |
| 45 |
return endpoint + '?' + new URLSearchParams(data).toString(); |
| 46 |
} |
| 47 |
|
| 48 |
return endpoint; |
| 49 |
}; |
| 50 |
|