Last active
October 3, 2019 01:24
-
-
Save vandorjw/4f7b08c1f80ca7ba7f6119b498bb7bae to your computer and use it in GitHub Desktop.
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
/** | |
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes | |
* | |
* JavaScript classes, introduced in ECMAScript 2015, | |
* are primarily syntactical sugar over JavaScript's existing prototype-based inheritance. | |
* | |
* The class syntax does not introduce a new object-oriented inheritance model to JavaScript. | |
* | |
* I prefer to keep using the older style 'prototype' when writing code in JS. | |
*/ | |
let GoblinAPI = function () { | |
this.SERVER_URL = 'http://localhost:5000'; | |
} | |
GoblinAPI.prototype.login = function (username, password) { | |
const data = { | |
email: username, | |
password: password | |
}; | |
const response = fetch(this.SERVER_URL, { | |
method: 'POST', | |
mode: 'cors', | |
cache: 'no-cache', | |
headers: { | |
'Content-Type': 'application/x-www-form-urlencoded' | |
// 'Content-Type': 'application/json' | |
}, | |
body: data // JSON.stringify(data) -- the body needs to match the header.... | |
}); | |
response.then(data => { | |
// console.log(data); | |
this.setToken("Fake Token..."); | |
return true; | |
}).catch(error => { | |
// console.log(error); | |
return false | |
}); | |
}; | |
GoblinAPI.prototype.logout = function () { | |
// call server logout end-point. | |
this.clearToken(); | |
}; | |
GoblinAPI.prototype.getToken = function () { | |
// I am a fan of using localstorage. This when when a user hits refresh, or closes the browser, | |
// they don't have to login again. Token should be stored until they choose to logout. | |
// Drawback.. token doesn't expire, but we can do that on serverside. | |
// https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage#Browser_compatibility | |
return localStorage.getItem('token'); | |
} | |
GoblinAPI.prototype.setToken = function (token) { | |
localStorage.setItem('token', token); | |
}; | |
GoblinAPI.prototype.clearToken = function () { | |
localStorage.removeItem('token'); | |
}; | |
/** | |
The API stops here. You can add as many methods as needed. | |
You can have functions call eachother, (see line 35) | |
Anywhere inside your React/Vue/AngularIO ...whatever the framework of the day is, | |
you can use your API like this. | |
*/ | |
let g = new GoblinAPI(); // letter g is arbitrary. can be gAPI, gobs, etc | |
g.login("[email protected]", "password: Abcd1234!"); | |
g.getToken(); | |
g.logout(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment