Skip to content

Instantly share code, notes, and snippets.

@llambeau
Created February 8, 2022 14:11
Show Gist options
  • Save llambeau/4c708991fecb3332167693f197f9beb4 to your computer and use it in GitHub Desktop.
Save llambeau/4c708991fecb3332167693f197f9beb4 to your computer and use it in GitHub Desktop.
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