Skip to content

Instantly share code, notes, and snippets.

@blrobin2
Created July 7, 2017 14:42
Show Gist options
  • Select an option

  • Save blrobin2/cb7c1c5efa1b3613d7af14b92b4be1fc to your computer and use it in GitHub Desktop.

Select an option

Save blrobin2/cb7c1c5efa1b3613d7af14b92b4be1fc to your computer and use it in GitHub Desktop.
Extending Dr. Axel Rauschmayer's RESTful web service example
// Source http://exploringjs.com/es6/ch_proxies.html#_accessing-a-restful-web-service-method-calls
const gitHubService = createWebService('http://api.github.com');
gitHubService.feeds.get().then(data => {
console.log(data.timeline_url);
});
gitHubService.users.blrobin2.get().then(data => {
console.log(data.avatar_url);
});
gitHubService.search.issues.params({q: 'test'}).get().then(data => {
console.log(data.items);
});
function createWebService(baseUrl) {
const proxy = new Proxy({
endpoint: '',
params(obj) {
Object.keys(obj).forEach(prop => {
if (this.endpoint.includes('?')) {
this.endpoint += '&';
} else {
this.endpoint += '?';
}
this.endpoint += `${prop}=${obj[prop]}`;
});
return proxy;
},
get() {
const endpoint = this.endpoint;
this.endpoint = '';
return httpGet(`${baseUrl}/${endpoint}`);
}
}, {
get(target, property) {
if (target.hasOwnProperty(property)) {
return target[property];
}
if (target.endpoint) {
target.endpoint += `/${property}`;
} else {
target.endpoint = property;
}
return proxy;
}
});
return proxy;
}
function httpGet(url) {
return fetch(url).then(data => data.json());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment