api.js
49 lines
| 1 | import axios from 'axios'; |
| 2 | import useSWR from 'swr'; |
| 3 | |
| 4 | const API = axios.create({ |
| 5 | baseURL: window.GiveMigrations.apiRoot, |
| 6 | headers: { |
| 7 | 'Content-Type': 'application/json', |
| 8 | 'X-WP-Nonce': window.GiveMigrations.apiNonce, |
| 9 | }, |
| 10 | }); |
| 11 | |
| 12 | export default API; |
| 13 | |
| 14 | export const CancelToken = axios.CancelToken.source(); |
| 15 | |
| 16 | // SWR Fetcher |
| 17 | export const Fetcher = (endpoint) => |
| 18 | API.get(endpoint).then((res) => { |
| 19 | const {data, ...rest} = res.data; |
| 20 | return { |
| 21 | data, |
| 22 | response: rest, |
| 23 | }; |
| 24 | }); |
| 25 | |
| 26 | export const useMigrationFetcher = (endpoint, params = {}) => { |
| 27 | const {data, error, mutate} = useSWR(endpoint, Fetcher, params); |
| 28 | return { |
| 29 | data: data ? data.data : undefined, |
| 30 | isLoading: !error && !data, |
| 31 | isError: error, |
| 32 | response: data ? data.response : undefined, |
| 33 | mutate, |
| 34 | }; |
| 35 | }; |
| 36 | |
| 37 | // GET endpoint with additional parameters |
| 38 | export const getEndpoint = (endpoint, data) => { |
| 39 | if (data) { |
| 40 | const queryString = new URLSearchParams(data); |
| 41 | // pretty url? |
| 42 | const separator = window.GiveMigrations.apiRoot.indexOf('?') === -1 ? '?' : '&'; |
| 43 | |
| 44 | return endpoint + separator + queryString.toString(); |
| 45 | } |
| 46 | |
| 47 | return endpoint; |
| 48 | }; |
| 49 |