Skip to content

Instantly share code, notes, and snippets.

@hamzakaya
Created March 13, 2022 14:15
Show Gist options
  • Save hamzakaya/5e42ef3b486388d4ceea246e35474314 to your computer and use it in GitHub Desktop.
Save hamzakaya/5e42ef3b486388d4ceea246e35474314 to your computer and use it in GitHub Desktop.
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) {
const proxy = () => {}
proxy.url = url
return new Proxy(proxy, {
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('/v1/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.update.put({ whatever: 1 })
// GET game_api/tiles/public/static/3/4/2.json?turn=37038&games=wot
GameAPI.tiles.public.static(3)['asdf'](1)(2)(`${3}.json`).get({ turn: 37, games: 'wot' })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment