Last active
October 1, 2018 22:02
-
-
Save Jeremboo/70b028ee3fe10a9a8dfd65d8a0230a44 to your computer and use it in GitHub Desktop.
Api.js to manage the communication between an api and the javascript project. With token.
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
export default class Api { | |
constuctor(serverUrl, sessionName = '__apiToken') { | |
if (typeof serverUrl === 'undefined') { | |
throw new Error('ERROR: the url of the server should exist'); | |
} | |
this._token = ''; | |
this.serverUrl = serverUrl; | |
this.sessionName = sessionName; | |
} | |
/** | |
* ****************** | |
* TOKEN | |
* ****************** | |
*/ | |
set token(tokenValue) { | |
this._token = tokenValue; | |
sessionStorage.setItem(this.sessionName, this._token); | |
} | |
get token() { | |
if (this._token && this._token.length > 0) return this._token; | |
this._token = sessionStorage.getItem(this.sessionName) || ''; | |
return this._token; | |
} | |
deleteToken() { | |
this._token = ''; | |
sessionStorage.removeItem(this.sessionName); | |
} | |
isTokenExist() { | |
return this.getToken() && this._token.length > 0; | |
} | |
/** | |
* ****************** | |
* CALL API | |
* https://stackoverflow.com/questions/29775797/fetch-post-json-data | |
* ****************** | |
*/ | |
async call(address, props = { method = 'get', params = {}, headers = {} }) => { | |
const { method, params } = props; | |
// Build the URL | |
const url = new URL(this.serverUrl + address); | |
url.search = new URLSearchParams(params); | |
// Build the options | |
const headersOptions = { ...headers }; | |
if (this.isTokenExist()) { | |
headersOptions['Authorization'] = this._token; | |
} | |
// FETCH | |
const rawResponse = await fetch(url, { | |
method, | |
headers: new Headers(headersOptions), | |
}); | |
// Check request status | |
if (rawResponse.status !== 200) { | |
throw new Error(`Server error ${rawResponse.status}`); | |
} | |
// Check request response | |
// TODO custom that according to the api | |
const response = await rawResponse.json(); | |
if (response.return === 'nok') { | |
throw new Error(response.result); | |
} | |
return response.result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment