Published at
Updated at
Reading time

I just found a super smart gist from David Wells that's worth bookmarking.

David uses a JavaScript Proxy to map object properties to fetch calls.

This approach works quite nice for querying RESTful APIs. maps to /cars/ and'123') maps to /cars/123/. 👏

// Found at
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("")

// 'get' request to
let people = await api.people()

// 'get' request to
let person = await api.people(1)

What a great little trick! 💯

Was this snippet helpful?
Yes? Cool! You might want to check out Web Weekly for more snippets. The last edition went out 12 days ago.

Related Topics

Related Articles

About the author

Stefan standing in the park in front of a green background

Frontend nerd with over ten years of experience, "Today I Learned" blogger, conference speaker, Tiny helpers maintainer, and DevRel at Checkly.