( {
apiUrl = apiBaseUrl,
fetchMethod = defaultFetchMethod
} = {} )
| 44 | |
| 45 | |
| 46 | export function generateAPI ( { |
| 47 | apiUrl = apiBaseUrl, |
| 48 | fetchMethod = defaultFetchMethod |
| 49 | } = {} ) { |
| 50 | |
| 51 | // console.log( 'apiUrl', apiUrl ) |
| 52 | |
| 53 | // a hack, so we can use field either as property or a method |
| 54 | const callable = () => {} |
| 55 | callable.url = apiUrl |
| 56 | |
| 57 | return new Proxy(callable, { |
| 58 | get({ url }, propKey) { |
| 59 | // If we're just getting the url, return it |
| 60 | if ( propKey === 'url' ) return `${ url }.json` |
| 61 | |
| 62 | // If we're using an HTTP method |
| 63 | // then do a request to the url |
| 64 | if ( HTTP_METHODS.includes(propKey.toUpperCase()) ) { |
| 65 | return (data) => fetchMethod({ |
| 66 | url: `${ url }.json`, |
| 67 | method: propKey.toUpperCase(), |
| 68 | data |
| 69 | }) |
| 70 | } |
| 71 | |
| 72 | // Otherwise drill down to the next property |
| 73 | // Example: |
| 74 | // From DoesItAPI.kind... |
| 75 | // To DoesItAPI.kind.apps... |
| 76 | return generateAPI({ apiUrl: `${url}/${propKey}` }) |
| 77 | |
| 78 | }, |
| 79 | // Handles when () goes after a property key |
| 80 | // Example: DoesItAPI() or DoesItAPI.app() |
| 81 | // Proxy.handler.apply - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/apply |
| 82 | apply({ url }, thisArg, [arg] = []) { |
| 83 | const apiUrl = arg ? `${url}/${arg}` : url |
| 84 | return generateAPI({ apiUrl: apiUrl }) |
| 85 | } |
| 86 | }) |
| 87 | |
| 88 | } |
| 89 | |
| 90 | export const DoesItAPI = generateAPI() |
no outgoing calls
no test coverage detected