Forked from DavidWells/javascript-proxy-as-rest-client.js
Created
February 8, 2022 16:34
-
-
Save karlguillotte/d41e7baa93f0fbae1914a7ea310205a2 to your computer and use it in GitHub Desktop.
Using a javascript proxy as low code REST client
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
/* Using a JavaScript proxy for a super low code REST client */ | |
// via https://dev.to/dipsaus9/javascript-lets-create-aproxy-19hg | |
// also see https://towardsdatascience.com/why-to-use-javascript-proxy-5cdc69d943e3 | |
const createApi = (url) => { | |
return new Proxy({}, { | |
get(target, key) { | |
return async function(id = "") { | |
const response = await fetch(`${url}/${key}/${id}`) | |
if (response.ok) { | |
return response.json(); | |
} | |
return Promise.resolve({ error: "Malformed Request" }) | |
} | |
} | |
}) | |
} | |
let api = createApi("https://swapi.co/api") | |
// 'get' request to https://swapi.co/api/people | |
let people = await api.people()/api/people/1 | |
// 'get' request to https://swapi.co/api/people/1 | |
let person = await api.people(1) | |
// ... any https://swapi.dev/ endpoint |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment