Created
December 14, 2016 06:28
-
-
Save allex/32752939b4f882b50085918274f6a3b6 to your computer and use it in GitHub Desktop.
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
| /** | |
| * Helper module for angular http extends with localStorage cache enabled. | |
| * | |
| * @author Allex Wang <http://iallex.com> | |
| * | |
| * Last Modified: Wed Dec 14, 2016 14:26 | |
| * GistID: 32752939b4f882b50085918274f6a3b6 | |
| * GistURL: https://gist.github.com/32752939b4f882b50085918274f6a3b6 | |
| * | |
| * @example | |
| * | |
| * ```js | |
| * $http2({ | |
| * method: 'GET', | |
| * url: '<API_URL_WITH_PARAMS>', | |
| * data: '', | |
| * responseType: "json", | |
| * headers: { 'Content-Type': 'application/x-www-form-urlencoded' } | |
| * }) | |
| * .success(function(res, status, headers, config) { | |
| * $rootScope.treedatas = res.data; | |
| * callback($rootScope.treedatas); | |
| * }) | |
| * .error(function(data, status, headers, config) { | |
| * console.error(data, status); | |
| * }); | |
| * ``` | |
| */ | |
| angular.module('allex-ng.helpers', []) | |
| .factory('$localStorage', [ '$window', function($window) { | |
| var $store = $window.localStorage || {} | |
| return { | |
| set: function(key, value) { | |
| $store[key] = value; | |
| }, | |
| get: function(key, defaultValue) { | |
| return $store[key] || defaultValue; | |
| }, | |
| has: function(key) { | |
| return !!$store[key]; | |
| }, | |
| setObject: function(key, value) { | |
| $store[key] = JSON.stringify(value); | |
| }, | |
| getObject: function(key) { | |
| var v = $store[key] | |
| if (!v) { | |
| return null; | |
| } | |
| return JSON.parse(v); | |
| } | |
| } | |
| }]) | |
| .factory('$http2', [ '$q', '$localStorage', '$http', function($q, $localStorage, io) { | |
| return function(config) { | |
| var key = config.url, cache = $localStorage.getObject(key); | |
| if (cache) { | |
| var headers = cache.headers; | |
| cache.headers = function() { return headers; } | |
| var deferred = $q.defer(); | |
| var promise = deferred.promise; | |
| promise.success = function(fn) { | |
| promise.then(function(response) { | |
| fn(response.data, response.status, response.headers, config); | |
| }); | |
| return promise; | |
| }; | |
| promise.error = function(fn) { | |
| promise.then(null, function(response) { | |
| fn(response.data, response.status, response.headers, config); | |
| }); | |
| return promise; | |
| }; | |
| deferred.resolve(cache); | |
| return promise; | |
| } | |
| else { | |
| return io(config).success(function(res, status, headers, config) { | |
| $localStorage.setObject(key, {data: res, status: status, headers: headers()}) | |
| }); | |
| } | |
| }; | |
| }]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment