Created
August 20, 2019 19:19
-
-
Save v1vendi/75d5e5dad7a2d1ef3fcb48234e4528cb to your computer and use it in GitHub Desktop.
REST API functional generator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const fetch = (...args) => console.log(...args) // mock | |
function httpRequest(url, method, data) { | |
const init = { method } | |
switch (method) { | |
case 'GET': | |
if (data) url = `${url}?${new URLSearchParams(data)}` | |
break | |
case 'POST': | |
case 'PUT': | |
case 'PATCH': | |
init.body = JSON.stringify(data) | |
} | |
return fetch(url, init) | |
} | |
function generateAPI(url) { | |
// a hack, so we can use field either as property or a method | |
const callable = () => {} | |
callable.url = url | |
return new Proxy(callable, { | |
get({ url }, propKey) { | |
return (['GET', 'POST', 'PUT', 'DELETE', 'PATCH'].includes(propKey.toUpperCase())) ? | |
(data) => httpRequest(url, propKey.toUpperCase(), data) : | |
generateAPI(`${url}/${propKey}`) | |
}, | |
apply({ url }, thisArg, [arg] = []) { | |
return generateAPI( arg ? `${url}/${arg}` : url) | |
} | |
}) | |
} | |
// example usage | |
const GameAPI = generateAPI('game_api') | |
GameAPI.get() // GET /game_api | |
GameAPI.clans.get() // GET /game_api/clans | |
GameAPI.clans(7).get() // GET /game_api/clans/7 | |
GameAPI.clans(7).whatever.delete() // DELETE /game_api/clans/7/whatever | |
GameAPI.clans.put({ whatever: 1 }) | |
// GET game_api/tiles/public/static/3/4/2.json?turn=37038&games=wot | |
GameAPI.tiles.public.static(3)(4)(`${2}.json`).get({ turn: 37, games: 'wot' }) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment