Created
February 8, 2022 14:11
-
-
Save llambeau/4c708991fecb3332167693f197f9beb4 to your computer and use it in GitHub Desktop.
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 factorEndpoint = (baseUrl) => { | |
const endpoint = (id) => { | |
return createApi(`${baseUrl}/${id}`); | |
} | |
Object.assign(endpoint, { | |
get(id){ | |
const url = id ? `${baseUrl}/${id}` : baseUrl; | |
console.log('GET on', url); | |
}, | |
delete(){}, | |
post(id) { | |
const url = id ? `${baseUrl}/${id}` : baseUrl; | |
console.log('POST on', url); | |
}, | |
put() {}, | |
patch() {} | |
}); | |
return endpoint; | |
} | |
const createApi = (baseUrl) => { | |
const endpoint = factorEndpoint(baseUrl); | |
return new Proxy(endpoint, { | |
get(target, key) { | |
if (target[key]) { | |
return target[key]; | |
} | |
return createApi(`${baseUrl}/${key}`); | |
} | |
}); | |
}; | |
const api = createApi('http://localhost'); | |
// GET /people | |
api.people.get(); | |
// GET /people/12 | |
api.people.get(12); | |
// GET /people/14/hobbies | |
api.people(14).hobbies.get(); | |
// POST /entities/companies/14/assets/11/actions/sell | |
api.entities.companies(14).assets(11).actions.sell.post(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment