Created
March 4, 2018 00:51
-
-
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
This file contains hidden or 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
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