Created
March 19, 2016 20:21
-
-
Save codejets/d4604d6d6df7409ab1cd to your computer and use it in GitHub Desktop.
module pattern
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
// Module Pattern | |
/* | |
In Simple terms, Module pattern is a collection of functions in a object literal. | |
*/ | |
/* | |
We will make a simple service to store and retrive data from localStorage. | |
*/ | |
(function() { | |
'use strict'; | |
function authtoken() { | |
var storage = $window.localStorage; | |
var token = 'token'; | |
var cachedToken; | |
// Works like a menu for all the APIs in this module | |
var service = { | |
setToken: setToken, | |
getToken: getToken, | |
removeToken: removeToken, | |
removeAll: removeAll, | |
authUser: authUser, | |
isAuthenticated: isAuthenticated, | |
}; | |
return service; | |
function authUser(data) { | |
setToken('username', data.name); | |
setToken('token', data.token); | |
} | |
function setToken(key, token) { | |
cachedToken = token; | |
storage.setItem(key, token); | |
} | |
function removeToken(key) { | |
cachedToken = null; | |
storage.removeItem(key); | |
} | |
function removeAll () { | |
storage.clear(); | |
} | |
function getToken(key) { | |
cachedToken = storage.getItem(key); | |
return cachedToken; | |
} | |
function isAuthenticated() { | |
return !!this.getToken(token); | |
} | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment