Skip to content

Instantly share code, notes, and snippets.

@Maqsim
Created March 4, 2018 00:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Maqsim/18043ef6499588b4be9b22c4ce205937 to your computer and use it in GitHub Desktop.
Save Maqsim/18043ef6499588b4be9b22c4ce205937 to your computer and use it in GitHub Desktop.
Custom API wrapper (minimalistic concept) for any RESTful API to minimize and beautify your code
class WhateverAPI {
constructor(baseUrl, clientID, accessToken) {
this._baseUrl = baseUrl;
this._clientID = clientID;
this._accessToken = accessToken;
this._baseUrl += this._baseUrl.slice(-1) !== '/' ? '/' : '';
}
resolveUrl(path) {
return this._baseUrl + path + `?client_id=${this._clientID}&access_token=${this._accessToken}`;
}
get(path) {
return fetch(this.resolveUrl(path)).then(response => response.json());
}
post(path, data) {
return fetch(this.resolveUrl(path), {
method: 'POST',
body: JSON.stringify(data)
}).then(response => response.json());
}
...
}
const myContactBook = new WhateverAPI('https://googleapi.com/contactbook', 'xxx', 'yyy');
myContactBook.get('contacts');
myContactBook.post('contacts', { name: 'Max Diachenko', age: 26 });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment