api.js
48 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 ) => API.get( endpoint ).then( ( res ) => { |
| 18 | const { data, ...rest } = res.data; |
| 19 | return { |
| 20 | data, |
| 21 | response: rest, |
| 22 | }; |
| 23 | } ); |
| 24 | |
| 25 | export const useMigrationFetcher = ( endpoint, params = {} ) => { |
| 26 | const { data, error, mutate } = useSWR( endpoint, Fetcher, params ); |
| 27 | return { |
| 28 | data: data ? data.data : undefined, |
| 29 | isLoading: ! error && ! data, |
| 30 | isError: error, |
| 31 | response: data ? data.response : undefined, |
| 32 | mutate, |
| 33 | }; |
| 34 | }; |
| 35 | |
| 36 | // GET endpoint with additional parameters |
| 37 | export const getEndpoint = ( endpoint, data ) => { |
| 38 | if ( data ) { |
| 39 | const queryString = new URLSearchParams( data ); |
| 40 | // pretty url? |
| 41 | const separator = ( window.GiveMigrations.apiRoot.indexOf( '?' ) === -1 ) ? '?' : '&'; |
| 42 | |
| 43 | return endpoint + separator + queryString.toString(); |
| 44 | } |
| 45 | |
| 46 | return endpoint; |
| 47 | }; |
| 48 |