Last active
May 12, 2024 14:24
-
-
Save DavidWells/53518b3c12344952641dc81cc7599939 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 | |
// also see https://github.com/fastify/manifetch | |
// also see https://github.com/flash-oss/allserver | |
// and https://gist.github.com/v1vendi/75d5e5dad7a2d1ef3fcb48234e4528cb | |
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() | |
// '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
Thank you very much.. Updated Typescript Playground
I actually modified it a little after re-looking at the code yesterday with fresh eyes..
I made it so the headers are merged.. so rather than one or the other.
I also removed the possibility of responseType cobbling, since it was originally calculated after the fetch was returned.
Just small cleanups, nothing major..
I just noticed in your code, that you had
arrayBuffer
which was a responseType I missed.. so thank you for that.