├── .gitignore ├── .npmignore ├── .travis.yml ├── README.md ├── dist ├── ng2-cache-service.d.ts ├── ng2-cache-service.js └── src │ ├── enums │ ├── cache-storages.enum.d.ts │ └── cache-storages.enum.js │ ├── interfaces │ ├── cache-options.interface.d.ts │ ├── cache-options.interface.js │ ├── storage-value.interface.d.ts │ └── storage-value.interface.js │ └── services │ ├── cache.service.d.ts │ ├── cache.service.js │ └── storage │ ├── cache-storage-abstract.service.d.ts │ ├── cache-storage-abstract.service.js │ ├── local-storage │ ├── cache-local-storage.service.d.ts │ └── cache-local-storage.service.js │ ├── memory │ ├── cache-memory.service.d.ts │ └── cache-memory.service.js │ └── session-storage │ ├── cache-session-storage.service.d.ts │ └── cache-session-storage.service.js ├── index.d.ts ├── index.js ├── ng2-cache-service.ts ├── package.json ├── src ├── enums │ └── cache-storages.enum.ts ├── interfaces │ ├── cache-options.interface.ts │ └── storage-value.interface.ts └── services │ ├── cache.service.ts │ └── storage │ ├── cache-storage-abstract.service.ts │ ├── local-storage │ └── cache-local-storage.service.ts │ ├── memory │ └── cache-memory.service.ts │ └── session-storage │ └── cache-session-storage.service.ts └── tsconfig.json /.gitignore: -------------------------------------------------------------------------------- 1 | # Node generated files 2 | node_modules 3 | npm-debug.log 4 | 5 | # OS generated files 6 | .DS_Store 7 | .idea 8 | 9 | # Ignored files 10 | /typings 11 | *.map -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | # Node 2 | node_modules/* 3 | npm-debug.log 4 | /src 5 | /typing 6 | 7 | # Typescript 8 | *.ts 9 | !*.d.ts 10 | 11 | # JetBrains 12 | .idea 13 | .project 14 | .settings 15 | .idea/* 16 | *.iml 17 | 18 | # Windows 19 | Thumbs.db 20 | Desktop.ini 21 | 22 | # Mac 23 | .DS_Store 24 | **/.DS_Store -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | sudo: false 3 | node_js: 4 | - '6.9.1 -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ng2-cache-service 2 | 3 | Client side caching service for Angular2 4 | 5 | ## Installation 6 | 7 | To install this library, run: 8 | 9 | ```bash 10 | $ npm install ng2-cache-service --save 11 | ``` 12 | 13 | Usage: 14 | 15 | ```typescript 16 | 17 | import { Component } from '@angular/core'; 18 | import { CacheService } from 'ng2-cache-service'; 19 | 20 | declare var BUILD_VERSION: string; 21 | 22 | @Component({ 23 | selector: 'some-selector', 24 | template: '
Template
', 25 | providers: [ CacheService ] 26 | }) 27 | export class ExampleComponent { 28 | 29 | constructor(private _cacheService: CacheService) {} 30 | 31 | public func() { 32 | 33 | //set global prefix as build version 34 | this._cacheService.setGlobalPrefix(BUILD_VERSION); 35 | 36 | //put some data to cache "forever" 37 | //returns true is data was cached successfully, otherwise - false 38 | let result: boolean = this._cacheService.set('key', ['some data']); 39 | 40 | //put some data to cache for 5 minutes (maxAge - in seconds) 41 | this._cacheService.set('key', ['some data'], {maxAge: 5 * 60}); 42 | 43 | //put some data to cache for 1 hour (expires - timestamp with milliseconds) 44 | this._cacheService.set('key', {'some': 'data'}, {expires: Date.now() + 1000 * 60 * 60}); 45 | 46 | //put some data to cache with tag "tag" 47 | this._cacheService.set('key', 'some data', {tag: 'tag'}); 48 | 49 | //get some data by key, null - if there is no data or data has expired 50 | let data: any|null = this._cacheService.get('key'); 51 | 52 | //check if data exists in cache 53 | let exists: boolean = this._cacheService.exists('key'); 54 | 55 | //remove all data from cache with tag "tag" 56 | this._cacheService.removeTag('tag'); 57 | 58 | //remove all from cache 59 | this._cacheService.removeAll(); 60 | 61 | //get all data related to tag "tag" : 62 | // {'key' => 'key data', ...} 63 | this._cacheService.getTagData('tag'); 64 | 65 | } 66 | } 67 | 68 | ``` 69 | 70 | By default service store data in session storage, you could select local storage 71 | 72 | To change storage to local storage: 73 | 74 | ```typescript 75 | 76 | import { NgModule } from 'angular2/core'; 77 | import { LocalStorageServiceModule } from 'ng2-cache-service'; 78 | 79 | @NgModule({ 80 | imports: [ 81 | LocalStorageServiceModule 82 | ] 83 | }) 84 | 85 | ``` 86 | 87 | ## License 88 | ISC © [Evgeny Popodyanets](https://github.com/DarthKurt) 89 | 90 | Originally forked from © [Romanov Evgeny](https://github.com/Jackson88) 91 | 92 | -------------------------------------------------------------------------------- /dist/ng2-cache-service.d.ts: -------------------------------------------------------------------------------- 1 | export { CacheService } from './src/services/cache.service'; 2 | export declare class LocalStorageServiceModule { 3 | } 4 | -------------------------------------------------------------------------------- /dist/ng2-cache-service.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { 3 | var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; 4 | if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); 5 | else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; 6 | return c > 3 && r && Object.defineProperty(target, key, r), r; 7 | }; 8 | Object.defineProperty(exports, "__esModule", { value: true }); 9 | var core_1 = require("@angular/core"); 10 | var cache_local_storage_service_1 = require("./src/services/storage/local-storage/cache-local-storage.service"); 11 | var cache_service_1 = require("./src/services/cache.service"); 12 | var cache_storage_abstract_service_1 = require("./src/services/storage/cache-storage-abstract.service"); 13 | var cache_service_2 = require("./src/services/cache.service"); 14 | exports.CacheService = cache_service_2.CacheService; 15 | var LocalStorageServiceModule = (function () { 16 | function LocalStorageServiceModule() { 17 | } 18 | return LocalStorageServiceModule; 19 | }()); 20 | LocalStorageServiceModule = __decorate([ 21 | core_1.NgModule({ 22 | providers: [cache_service_1.CacheService, { provide: cache_storage_abstract_service_1.CacheStorageAbstract, useClass: cache_local_storage_service_1.CacheLocalStorage }] 23 | }) 24 | ], LocalStorageServiceModule); 25 | exports.LocalStorageServiceModule = LocalStorageServiceModule; 26 | -------------------------------------------------------------------------------- /dist/src/enums/cache-storages.enum.d.ts: -------------------------------------------------------------------------------- 1 | export declare const enum CacheStoragesEnum { 2 | LOCAL_STORAGE = 0, 3 | SESSION_STORAGE = 1, 4 | MEMORY = 2, 5 | } 6 | -------------------------------------------------------------------------------- /dist/src/enums/cache-storages.enum.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | Object.defineProperty(exports, "__esModule", { value: true }); 3 | -------------------------------------------------------------------------------- /dist/src/interfaces/cache-options.interface.d.ts: -------------------------------------------------------------------------------- 1 | export interface CacheOptionsInterface { 2 | /** 3 | * Expires timestamp 4 | */ 5 | expires?: number; 6 | /** 7 | * Max age in seconds 8 | */ 9 | maxAge?: number; 10 | /** 11 | * Tag for this key 12 | */ 13 | tag?: string; 14 | } 15 | -------------------------------------------------------------------------------- /dist/src/interfaces/cache-options.interface.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | Object.defineProperty(exports, "__esModule", { value: true }); 3 | -------------------------------------------------------------------------------- /dist/src/interfaces/storage-value.interface.d.ts: -------------------------------------------------------------------------------- 1 | import { CacheOptionsInterface } from './cache-options.interface'; 2 | export interface StorageValueInterface { 3 | /** 4 | * Cached data 5 | */ 6 | value: any; 7 | /** 8 | * Cached options 9 | */ 10 | options: CacheOptionsInterface; 11 | } 12 | -------------------------------------------------------------------------------- /dist/src/interfaces/storage-value.interface.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | Object.defineProperty(exports, "__esModule", { value: true }); 3 | -------------------------------------------------------------------------------- /dist/src/services/cache.service.d.ts: -------------------------------------------------------------------------------- 1 | import { CacheOptionsInterface } from '../interfaces/cache-options.interface'; 2 | import { CacheStoragesEnum } from '../enums/cache-storages.enum'; 3 | import { CacheStorageAbstract } from './storage/cache-storage-abstract.service'; 4 | export declare class CacheService { 5 | private _storage; 6 | /** 7 | * Default cache options 8 | * @type CacheOptionsInterface 9 | * @private 10 | */ 11 | private _defaultOptions; 12 | /** 13 | * Cache prefix 14 | */ 15 | private _prefix; 16 | constructor(_storage: CacheStorageAbstract); 17 | /** 18 | * Set data to cache 19 | * @param key 20 | * @param value 21 | * @param options 22 | */ 23 | set(key: string, value: any, options?: CacheOptionsInterface): boolean; 24 | /** 25 | * Get data from cache 26 | * @param key 27 | * @returns {any} 28 | */ 29 | get(key: string): any; 30 | /** 31 | * Check if value exists 32 | * @param key 33 | * @returns {boolean} 34 | */ 35 | exists(key: string): boolean; 36 | /** 37 | * Remove item from cache 38 | * @param key 39 | */ 40 | remove(key: string): void; 41 | /** 42 | * Remove all from cache 43 | */ 44 | removeAll(): void; 45 | /** 46 | * Get all tag data 47 | * @param tag 48 | * @returns {Array} 49 | */ 50 | getTagData(tag: string): { 51 | [key: string]: any; 52 | }; 53 | /** 54 | * Create a new instance of cache with needed storage 55 | * @param type 56 | * @returns {CacheService} 57 | */ 58 | useStorage(type: CacheStoragesEnum): CacheService; 59 | /** 60 | * Remove all by tag 61 | * @param tag 62 | */ 63 | removeTag(tag: string): void; 64 | /** 65 | * Set global cache key prefix 66 | * @param prefix 67 | */ 68 | setGlobalPrefix(prefix: string): void; 69 | /** 70 | * Validate cache storage 71 | * @private 72 | */ 73 | private _validateStorage(); 74 | /** 75 | * Remove key from tags keys list 76 | * @param key 77 | * @private 78 | */ 79 | private _removeFromTag(key); 80 | /** 81 | * Init storage by type 82 | * @param type 83 | * @returns {CacheStorageAbstract} 84 | */ 85 | private _initStorage(type); 86 | private _toStorageKey(key); 87 | private _fromStorageKey(key); 88 | /** 89 | * Prepare value to set to storage 90 | * @param value 91 | * @param options 92 | * @returns {{value: any, options: CacheOptionsInterface}} 93 | * @private 94 | */ 95 | private _toStorageValue(value, options); 96 | /** 97 | * Prepare options to set to storage 98 | * @param options 99 | * @returns {CacheOptionsInterface} 100 | * @private 101 | */ 102 | private _toStorageOptions(options); 103 | /** 104 | * Validate storage value 105 | * @param value 106 | * @returns {boolean} 107 | * @private 108 | */ 109 | private _validateStorageValue(value); 110 | /** 111 | * check if its system cache key 112 | * @param key 113 | * @returns {boolean} 114 | * @private 115 | */ 116 | private _isSystemKey(key); 117 | /** 118 | * Save tag to list of tags 119 | * @param tag 120 | * @param key 121 | * @private 122 | */ 123 | private _saveTag(tag, key); 124 | /** 125 | * Get global cache prefix 126 | * @returns {string} 127 | * @private 128 | */ 129 | private _getCachePrefix(); 130 | private _tagsStorageKey(); 131 | } 132 | -------------------------------------------------------------------------------- /dist/src/services/cache.service.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { 3 | var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; 4 | if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); 5 | else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; 6 | return c > 3 && r && Object.defineProperty(target, key, r), r; 7 | }; 8 | var __metadata = (this && this.__metadata) || function (k, v) { 9 | if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); 10 | }; 11 | var __param = (this && this.__param) || function (paramIndex, decorator) { 12 | return function (target, key) { decorator(target, key, paramIndex); } 13 | }; 14 | Object.defineProperty(exports, "__esModule", { value: true }); 15 | var core_1 = require("@angular/core"); 16 | var cache_storage_abstract_service_1 = require("./storage/cache-storage-abstract.service"); 17 | var cache_session_storage_service_1 = require("./storage/session-storage/cache-session-storage.service"); 18 | var cache_local_storage_service_1 = require("./storage/local-storage/cache-local-storage.service"); 19 | var cache_memory_service_1 = require("./storage/memory/cache-memory.service"); 20 | var CACHE_PREFIX = 'CacheService'; 21 | var DEFAULT_STORAGE = 1 /* SESSION_STORAGE */; 22 | var DEFAULT_ENABLED_STORAGE = 2 /* MEMORY */; 23 | var CacheService = CacheService_1 = (function () { 24 | function CacheService(_storage) { 25 | this._storage = _storage; 26 | /** 27 | * Default cache options 28 | * @type CacheOptionsInterface 29 | * @private 30 | */ 31 | this._defaultOptions = { 32 | expires: Number.MAX_VALUE, 33 | maxAge: Number.MAX_VALUE 34 | }; 35 | /** 36 | * Cache prefix 37 | */ 38 | this._prefix = CACHE_PREFIX; 39 | this._validateStorage(); 40 | } 41 | /** 42 | * Set data to cache 43 | * @param key 44 | * @param value 45 | * @param options 46 | */ 47 | CacheService.prototype.set = function (key, value, options) { 48 | var storageKey = this._toStorageKey(key); 49 | options = options ? options : this._defaultOptions; 50 | if (this._storage.setItem(storageKey, this._toStorageValue(value, options))) { 51 | if (!this._isSystemKey(key) && options.tag) { 52 | this._saveTag(options.tag, storageKey); 53 | } 54 | return true; 55 | } 56 | return false; 57 | }; 58 | /** 59 | * Get data from cache 60 | * @param key 61 | * @returns {any} 62 | */ 63 | CacheService.prototype.get = function (key) { 64 | var storageValue = this._storage.getItem(this._toStorageKey(key)), value = null; 65 | if (storageValue) { 66 | if (this._validateStorageValue(storageValue)) { 67 | value = storageValue.value; 68 | } 69 | else { 70 | this.remove(key); 71 | } 72 | } 73 | return value; 74 | }; 75 | /** 76 | * Check if value exists 77 | * @param key 78 | * @returns {boolean} 79 | */ 80 | CacheService.prototype.exists = function (key) { 81 | return !!this.get(key); 82 | }; 83 | /** 84 | * Remove item from cache 85 | * @param key 86 | */ 87 | CacheService.prototype.remove = function (key) { 88 | this._storage.removeItem(this._toStorageKey(key)); 89 | this._removeFromTag(this._toStorageKey(key)); 90 | }; 91 | /** 92 | * Remove all from cache 93 | */ 94 | CacheService.prototype.removeAll = function () { 95 | this._storage.clear(); 96 | }; 97 | /** 98 | * Get all tag data 99 | * @param tag 100 | * @returns {Array} 101 | */ 102 | CacheService.prototype.getTagData = function (tag) { 103 | var _this = this; 104 | var tags = this.get(this._tagsStorageKey()) || {}, result = {}; 105 | if (tags[tag]) { 106 | tags[tag].forEach(function (key) { 107 | var data = _this.get(_this._fromStorageKey(key)); 108 | if (data) { 109 | result[_this._fromStorageKey(key)] = data; 110 | } 111 | }); 112 | } 113 | return result; 114 | }; 115 | /** 116 | * Create a new instance of cache with needed storage 117 | * @param type 118 | * @returns {CacheService} 119 | */ 120 | CacheService.prototype.useStorage = function (type) { 121 | var service = new CacheService_1(this._initStorage(type)); 122 | service.setGlobalPrefix(this._getCachePrefix()); 123 | return service; 124 | }; 125 | /** 126 | * Remove all by tag 127 | * @param tag 128 | */ 129 | CacheService.prototype.removeTag = function (tag) { 130 | var _this = this; 131 | var tags = this.get(this._tagsStorageKey()) || {}; 132 | if (tags[tag]) { 133 | tags[tag].forEach(function (key) { 134 | _this._storage.removeItem(key); 135 | }); 136 | delete tags[tag]; 137 | this.set(this._tagsStorageKey(), tags); 138 | } 139 | }; 140 | /** 141 | * Set global cache key prefix 142 | * @param prefix 143 | */ 144 | CacheService.prototype.setGlobalPrefix = function (prefix) { 145 | this._prefix = prefix; 146 | }; 147 | /** 148 | * Validate cache storage 149 | * @private 150 | */ 151 | CacheService.prototype._validateStorage = function () { 152 | if (!this._storage) { 153 | this._storage = this._initStorage(DEFAULT_STORAGE); 154 | } 155 | if (!this._storage.isEnabled()) { 156 | this._storage = this._initStorage(DEFAULT_ENABLED_STORAGE); 157 | } 158 | }; 159 | /** 160 | * Remove key from tags keys list 161 | * @param key 162 | * @private 163 | */ 164 | CacheService.prototype._removeFromTag = function (key) { 165 | var tags = this.get(this._tagsStorageKey()) || {}, index; 166 | for (var tag in tags) { 167 | index = tags[tag].indexOf(key); 168 | if (index !== -1) { 169 | tags[tag].splice(index, 1); 170 | this.set(this._tagsStorageKey(), tags); 171 | break; 172 | } 173 | } 174 | }; 175 | /** 176 | * Init storage by type 177 | * @param type 178 | * @returns {CacheStorageAbstract} 179 | */ 180 | CacheService.prototype._initStorage = function (type) { 181 | var storage; 182 | switch (type) { 183 | case 1 /* SESSION_STORAGE */: 184 | storage = new cache_session_storage_service_1.CacheSessionStorage(); 185 | break; 186 | case 0 /* LOCAL_STORAGE */: 187 | storage = new cache_local_storage_service_1.CacheLocalStorage(); 188 | break; 189 | default: storage = new cache_memory_service_1.CacheMemoryStorage(); 190 | } 191 | return storage; 192 | }; 193 | CacheService.prototype._toStorageKey = function (key) { 194 | return this._getCachePrefix() + key; 195 | }; 196 | CacheService.prototype._fromStorageKey = function (key) { 197 | return key.replace(this._getCachePrefix(), ''); 198 | }; 199 | /** 200 | * Prepare value to set to storage 201 | * @param value 202 | * @param options 203 | * @returns {{value: any, options: CacheOptionsInterface}} 204 | * @private 205 | */ 206 | CacheService.prototype._toStorageValue = function (value, options) { 207 | return { 208 | value: value, 209 | options: this._toStorageOptions(options) 210 | }; 211 | }; 212 | /** 213 | * Prepare options to set to storage 214 | * @param options 215 | * @returns {CacheOptionsInterface} 216 | * @private 217 | */ 218 | CacheService.prototype._toStorageOptions = function (options) { 219 | var storageOptions = {}; 220 | storageOptions.expires = options.expires ? options.expires : 221 | (options.maxAge ? Date.now() + (options.maxAge * 1000) : this._defaultOptions.expires); 222 | storageOptions.maxAge = options.maxAge ? options.maxAge : this._defaultOptions.maxAge; 223 | return storageOptions; 224 | }; 225 | /** 226 | * Validate storage value 227 | * @param value 228 | * @returns {boolean} 229 | * @private 230 | */ 231 | CacheService.prototype._validateStorageValue = function (value) { 232 | return !!value.options.expires && value.options.expires > Date.now(); 233 | }; 234 | /** 235 | * check if its system cache key 236 | * @param key 237 | * @returns {boolean} 238 | * @private 239 | */ 240 | CacheService.prototype._isSystemKey = function (key) { 241 | return [this._tagsStorageKey()].indexOf(key) !== -1; 242 | }; 243 | /** 244 | * Save tag to list of tags 245 | * @param tag 246 | * @param key 247 | * @private 248 | */ 249 | CacheService.prototype._saveTag = function (tag, key) { 250 | var tags = this.get(this._tagsStorageKey()) || {}; 251 | if (!tags[tag]) { 252 | tags[tag] = [key]; 253 | } 254 | else { 255 | tags[tag].push(key); 256 | } 257 | this.set(this._tagsStorageKey(), tags); 258 | }; 259 | /** 260 | * Get global cache prefix 261 | * @returns {string} 262 | * @private 263 | */ 264 | CacheService.prototype._getCachePrefix = function () { 265 | return this._prefix; 266 | }; 267 | CacheService.prototype._tagsStorageKey = function () { 268 | return 'CacheService_tags'; 269 | }; 270 | return CacheService; 271 | }()); 272 | CacheService = CacheService_1 = __decorate([ 273 | core_1.Injectable(), 274 | __param(0, core_1.Optional()), 275 | __metadata("design:paramtypes", [cache_storage_abstract_service_1.CacheStorageAbstract]) 276 | ], CacheService); 277 | exports.CacheService = CacheService; 278 | var CacheService_1; 279 | -------------------------------------------------------------------------------- /dist/src/services/storage/cache-storage-abstract.service.d.ts: -------------------------------------------------------------------------------- 1 | import { CacheStoragesEnum } from '../../enums/cache-storages.enum'; 2 | import { StorageValueInterface } from '../../interfaces/storage-value.interface'; 3 | /** 4 | * Abstract cache storage 5 | */ 6 | export declare abstract class CacheStorageAbstract { 7 | /** 8 | * Get item from storage 9 | * @param key 10 | */ 11 | abstract getItem(key: string): StorageValueInterface; 12 | /** 13 | * Set item to storage 14 | * @param key 15 | * @param value 16 | */ 17 | abstract setItem(key: string, value: StorageValueInterface): boolean; 18 | /** 19 | * Remove item from storage 20 | * @param key 21 | */ 22 | abstract removeItem(key: string): void; 23 | /** 24 | * Clear item in storage 25 | */ 26 | abstract clear(): void; 27 | /** 28 | * Get current storage type 29 | */ 30 | abstract type(): CacheStoragesEnum; 31 | /** 32 | * Check if storage is enabled 33 | */ 34 | abstract isEnabled(): boolean; 35 | } 36 | -------------------------------------------------------------------------------- /dist/src/services/storage/cache-storage-abstract.service.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | Object.defineProperty(exports, "__esModule", { value: true }); 3 | /** 4 | * Abstract cache storage 5 | */ 6 | var CacheStorageAbstract = (function () { 7 | function CacheStorageAbstract() { 8 | } 9 | return CacheStorageAbstract; 10 | }()); 11 | exports.CacheStorageAbstract = CacheStorageAbstract; 12 | -------------------------------------------------------------------------------- /dist/src/services/storage/local-storage/cache-local-storage.service.d.ts: -------------------------------------------------------------------------------- 1 | import { CacheStorageAbstract } from '../cache-storage-abstract.service'; 2 | import { CacheStoragesEnum } from '../../../enums/cache-storages.enum'; 3 | import { StorageValueInterface } from '../../../interfaces/storage-value.interface'; 4 | /** 5 | * Service for storing data in local storage 6 | */ 7 | export declare class CacheLocalStorage extends CacheStorageAbstract { 8 | getItem(key: string): any; 9 | setItem(key: string, value: StorageValueInterface): boolean; 10 | removeItem(key: string): void; 11 | clear(): void; 12 | type(): CacheStoragesEnum; 13 | isEnabled(): boolean; 14 | } 15 | -------------------------------------------------------------------------------- /dist/src/services/storage/local-storage/cache-local-storage.service.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | var __extends = (this && this.__extends) || (function () { 3 | var extendStatics = Object.setPrototypeOf || 4 | ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || 5 | function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; 6 | return function (d, b) { 7 | extendStatics(d, b); 8 | function __() { this.constructor = d; } 9 | d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); 10 | }; 11 | })(); 12 | var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { 13 | var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; 14 | if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); 15 | else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; 16 | return c > 3 && r && Object.defineProperty(target, key, r), r; 17 | }; 18 | Object.defineProperty(exports, "__esModule", { value: true }); 19 | var core_1 = require("@angular/core"); 20 | var cache_storage_abstract_service_1 = require("../cache-storage-abstract.service"); 21 | /** 22 | * Service for storing data in local storage 23 | */ 24 | var CacheLocalStorage = (function (_super) { 25 | __extends(CacheLocalStorage, _super); 26 | function CacheLocalStorage() { 27 | return _super !== null && _super.apply(this, arguments) || this; 28 | } 29 | CacheLocalStorage.prototype.getItem = function (key) { 30 | var value = localStorage.getItem(key); 31 | return value ? JSON.parse(value) : null; 32 | }; 33 | CacheLocalStorage.prototype.setItem = function (key, value) { 34 | try { 35 | localStorage.setItem(key, JSON.stringify(value)); 36 | return true; 37 | } 38 | catch (e) { 39 | return false; 40 | } 41 | }; 42 | CacheLocalStorage.prototype.removeItem = function (key) { 43 | localStorage.removeItem(key); 44 | }; 45 | CacheLocalStorage.prototype.clear = function () { 46 | localStorage.clear(); 47 | }; 48 | CacheLocalStorage.prototype.type = function () { 49 | return 0 /* LOCAL_STORAGE */; 50 | }; 51 | CacheLocalStorage.prototype.isEnabled = function () { 52 | try { 53 | localStorage.setItem('test', 'test'); 54 | localStorage.removeItem('test'); 55 | return true; 56 | } 57 | catch (e) { 58 | return false; 59 | } 60 | }; 61 | return CacheLocalStorage; 62 | }(cache_storage_abstract_service_1.CacheStorageAbstract)); 63 | CacheLocalStorage = __decorate([ 64 | core_1.Injectable() 65 | ], CacheLocalStorage); 66 | exports.CacheLocalStorage = CacheLocalStorage; 67 | -------------------------------------------------------------------------------- /dist/src/services/storage/memory/cache-memory.service.d.ts: -------------------------------------------------------------------------------- 1 | import { CacheStorageAbstract } from '../cache-storage-abstract.service'; 2 | import { CacheStoragesEnum } from '../../../enums/cache-storages.enum'; 3 | import { StorageValueInterface } from '../../../interfaces/storage-value.interface'; 4 | /** 5 | * Service for storing data in local storage 6 | */ 7 | export declare class CacheMemoryStorage extends CacheStorageAbstract { 8 | private _data; 9 | getItem(key: string): any; 10 | setItem(key: string, value: StorageValueInterface): boolean; 11 | removeItem(key: string): void; 12 | clear(): void; 13 | type(): CacheStoragesEnum; 14 | isEnabled(): boolean; 15 | } 16 | -------------------------------------------------------------------------------- /dist/src/services/storage/memory/cache-memory.service.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | var __extends = (this && this.__extends) || (function () { 3 | var extendStatics = Object.setPrototypeOf || 4 | ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || 5 | function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; 6 | return function (d, b) { 7 | extendStatics(d, b); 8 | function __() { this.constructor = d; } 9 | d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); 10 | }; 11 | })(); 12 | var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { 13 | var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; 14 | if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); 15 | else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; 16 | return c > 3 && r && Object.defineProperty(target, key, r), r; 17 | }; 18 | Object.defineProperty(exports, "__esModule", { value: true }); 19 | var core_1 = require("@angular/core"); 20 | var cache_storage_abstract_service_1 = require("../cache-storage-abstract.service"); 21 | /** 22 | * Service for storing data in local storage 23 | */ 24 | var CacheMemoryStorage = (function (_super) { 25 | __extends(CacheMemoryStorage, _super); 26 | function CacheMemoryStorage() { 27 | var _this = _super !== null && _super.apply(this, arguments) || this; 28 | _this._data = {}; 29 | return _this; 30 | } 31 | CacheMemoryStorage.prototype.getItem = function (key) { 32 | return this._data[key] ? this._data[key] : null; 33 | }; 34 | CacheMemoryStorage.prototype.setItem = function (key, value) { 35 | this._data[key] = value; 36 | return true; 37 | }; 38 | CacheMemoryStorage.prototype.removeItem = function (key) { 39 | delete this._data[key]; 40 | }; 41 | CacheMemoryStorage.prototype.clear = function () { 42 | this._data = []; 43 | }; 44 | CacheMemoryStorage.prototype.type = function () { 45 | return 2 /* MEMORY */; 46 | }; 47 | CacheMemoryStorage.prototype.isEnabled = function () { 48 | return true; 49 | }; 50 | return CacheMemoryStorage; 51 | }(cache_storage_abstract_service_1.CacheStorageAbstract)); 52 | CacheMemoryStorage = __decorate([ 53 | core_1.Injectable() 54 | ], CacheMemoryStorage); 55 | exports.CacheMemoryStorage = CacheMemoryStorage; 56 | -------------------------------------------------------------------------------- /dist/src/services/storage/session-storage/cache-session-storage.service.d.ts: -------------------------------------------------------------------------------- 1 | import { CacheStorageAbstract } from '../cache-storage-abstract.service'; 2 | import { CacheStoragesEnum } from '../../../enums/cache-storages.enum'; 3 | import { StorageValueInterface } from '../../../interfaces/storage-value.interface'; 4 | /** 5 | * Service for storing data in session storage 6 | */ 7 | export declare class CacheSessionStorage extends CacheStorageAbstract { 8 | getItem(key: string): any; 9 | setItem(key: string, value: StorageValueInterface): boolean; 10 | removeItem(key: string): void; 11 | clear(): void; 12 | type(): CacheStoragesEnum; 13 | isEnabled(): boolean; 14 | } 15 | -------------------------------------------------------------------------------- /dist/src/services/storage/session-storage/cache-session-storage.service.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | var __extends = (this && this.__extends) || (function () { 3 | var extendStatics = Object.setPrototypeOf || 4 | ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || 5 | function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; 6 | return function (d, b) { 7 | extendStatics(d, b); 8 | function __() { this.constructor = d; } 9 | d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); 10 | }; 11 | })(); 12 | var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { 13 | var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; 14 | if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); 15 | else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; 16 | return c > 3 && r && Object.defineProperty(target, key, r), r; 17 | }; 18 | Object.defineProperty(exports, "__esModule", { value: true }); 19 | var core_1 = require("@angular/core"); 20 | var cache_storage_abstract_service_1 = require("../cache-storage-abstract.service"); 21 | /** 22 | * Service for storing data in session storage 23 | */ 24 | var CacheSessionStorage = (function (_super) { 25 | __extends(CacheSessionStorage, _super); 26 | function CacheSessionStorage() { 27 | return _super !== null && _super.apply(this, arguments) || this; 28 | } 29 | CacheSessionStorage.prototype.getItem = function (key) { 30 | var value = sessionStorage.getItem(key); 31 | return value ? JSON.parse(value) : null; 32 | }; 33 | CacheSessionStorage.prototype.setItem = function (key, value) { 34 | try { 35 | sessionStorage.setItem(key, JSON.stringify(value)); 36 | return true; 37 | } 38 | catch (e) { 39 | return false; 40 | } 41 | }; 42 | CacheSessionStorage.prototype.removeItem = function (key) { 43 | sessionStorage.removeItem(key); 44 | }; 45 | CacheSessionStorage.prototype.clear = function () { 46 | sessionStorage.clear(); 47 | }; 48 | CacheSessionStorage.prototype.type = function () { 49 | return 1 /* SESSION_STORAGE */; 50 | }; 51 | CacheSessionStorage.prototype.isEnabled = function () { 52 | try { 53 | sessionStorage.setItem('test', 'test'); 54 | sessionStorage.removeItem('test'); 55 | return true; 56 | } 57 | catch (e) { 58 | return false; 59 | } 60 | }; 61 | return CacheSessionStorage; 62 | }(cache_storage_abstract_service_1.CacheStorageAbstract)); 63 | CacheSessionStorage = __decorate([ 64 | core_1.Injectable() 65 | ], CacheSessionStorage); 66 | exports.CacheSessionStorage = CacheSessionStorage; 67 | -------------------------------------------------------------------------------- /index.d.ts: -------------------------------------------------------------------------------- 1 | export * from './dist/ng2-cache-service'; -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | function __export(m) { 2 | for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; 3 | } 4 | __export(require('./dist/ng2-cache-service')); -------------------------------------------------------------------------------- /ng2-cache-service.ts: -------------------------------------------------------------------------------- 1 | import {NgModule} from '@angular/core'; 2 | import {CacheLocalStorage} from './src/services/storage/local-storage/cache-local-storage.service'; 3 | import {CacheMemoryStorage} from './src/services/storage/memory/cache-memory.service'; 4 | import {CacheOptionsInterface} from './src/interfaces/cache-options.interface'; 5 | import {CacheService} from './src/services/cache.service'; 6 | import {CacheSessionStorage} from './src/services/storage/session-storage/cache-session-storage.service'; 7 | import {CacheStorageAbstract} from './src/services/storage/cache-storage-abstract.service'; 8 | import {CacheStoragesEnum} from './src/enums/cache-storages.enum'; 9 | 10 | export {CacheService} from './src/services/cache.service'; 11 | 12 | @NgModule({ 13 | providers: [ CacheService, {provide: CacheStorageAbstract, useClass: CacheLocalStorage} ] 14 | }) 15 | export class LocalStorageServiceModule {} -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "ng2-cache-service", 3 | "version": "1.1.1", 4 | "description": "Client side caching service for Angular2", 5 | "main": "index.js", 6 | "repository": { 7 | "type": "git", 8 | "url": "https://github.com/DarthKurt/ng2-cache-service.git" 9 | }, 10 | "scripts": { 11 | "prepublish": "tsc", 12 | "build": "tsc" 13 | }, 14 | "typings": "ng2-cache-service.d.ts", 15 | "keywords": [ 16 | "cache", 17 | "angular2", 18 | "client-side", 19 | "caching" 20 | ], 21 | "author": "Evgeny Popodyanets", 22 | "license": "ISC", 23 | "devDependencies": { 24 | "@angular/core": "^4.0.0", 25 | "@types/core-js": "0.9.34", 26 | "core-js": "^2.4.1", 27 | "reflect-metadata": "^0.1.10", 28 | "rxjs": "^5.3.0", 29 | "zone.js": "^0.8.0", 30 | "typescript": "^2.2.0" 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/enums/cache-storages.enum.ts: -------------------------------------------------------------------------------- 1 | export const enum CacheStoragesEnum { 2 | LOCAL_STORAGE, 3 | SESSION_STORAGE, 4 | MEMORY 5 | } -------------------------------------------------------------------------------- /src/interfaces/cache-options.interface.ts: -------------------------------------------------------------------------------- 1 | export interface CacheOptionsInterface { 2 | 3 | /** 4 | * Expires timestamp 5 | */ 6 | expires?: number 7 | 8 | /** 9 | * Max age in seconds 10 | */ 11 | maxAge?: number 12 | 13 | /** 14 | * Tag for this key 15 | */ 16 | tag?: string 17 | 18 | } -------------------------------------------------------------------------------- /src/interfaces/storage-value.interface.ts: -------------------------------------------------------------------------------- 1 | import {CacheOptionsInterface} from './cache-options.interface'; 2 | 3 | export interface StorageValueInterface { 4 | 5 | /** 6 | * Cached data 7 | */ 8 | value: any 9 | 10 | /** 11 | * Cached options 12 | */ 13 | options: CacheOptionsInterface 14 | } -------------------------------------------------------------------------------- /src/services/cache.service.ts: -------------------------------------------------------------------------------- 1 | import {Injectable, Optional} from '@angular/core'; 2 | import {CacheOptionsInterface} from '../interfaces/cache-options.interface'; 3 | import {CacheStoragesEnum} from '../enums/cache-storages.enum'; 4 | import {CacheStorageAbstract} from './storage/cache-storage-abstract.service'; 5 | import {CacheSessionStorage} from './storage/session-storage/cache-session-storage.service'; 6 | import {CacheLocalStorage} from './storage/local-storage/cache-local-storage.service'; 7 | import {CacheMemoryStorage} from './storage/memory/cache-memory.service'; 8 | import {StorageValueInterface} from '../interfaces/storage-value.interface'; 9 | 10 | const CACHE_PREFIX = 'CacheService'; 11 | 12 | const DEFAULT_STORAGE = CacheStoragesEnum.SESSION_STORAGE; 13 | const DEFAULT_ENABLED_STORAGE = CacheStoragesEnum.MEMORY; 14 | 15 | @Injectable() 16 | export class CacheService { 17 | 18 | /** 19 | * Default cache options 20 | * @type CacheOptionsInterface 21 | * @private 22 | */ 23 | private _defaultOptions: CacheOptionsInterface = { 24 | expires: Number.MAX_VALUE, 25 | maxAge : Number.MAX_VALUE 26 | }; 27 | 28 | /** 29 | * Cache prefix 30 | */ 31 | private _prefix: string = CACHE_PREFIX; 32 | 33 | public constructor(@Optional() private _storage: CacheStorageAbstract) { 34 | this._validateStorage(); 35 | } 36 | 37 | /** 38 | * Set data to cache 39 | * @param key 40 | * @param value 41 | * @param options 42 | */ 43 | public set(key: string, value: any, options?: CacheOptionsInterface) { 44 | let storageKey = this._toStorageKey(key); 45 | options = options ? options : this._defaultOptions; 46 | if (this._storage.setItem(storageKey, this._toStorageValue(value, options))) { 47 | if (!this._isSystemKey(key) && options.tag) { 48 | this._saveTag(options.tag, storageKey); 49 | } 50 | return true; 51 | } 52 | return false; 53 | } 54 | 55 | 56 | /** 57 | * Get data from cache 58 | * @param key 59 | * @returns {any} 60 | */ 61 | public get(key: string): any { 62 | let storageValue = this._storage.getItem(this._toStorageKey(key)), 63 | value: any = null; 64 | if (storageValue) { 65 | if (this._validateStorageValue(storageValue)) { 66 | value = storageValue.value; 67 | } else { 68 | this.remove(key); 69 | } 70 | } 71 | return value; 72 | } 73 | 74 | /** 75 | * Check if value exists 76 | * @param key 77 | * @returns {boolean} 78 | */ 79 | public exists(key: string): boolean { 80 | return !!this.get(key); 81 | } 82 | 83 | /** 84 | * Remove item from cache 85 | * @param key 86 | */ 87 | public remove(key: string) { 88 | this._storage.removeItem(this._toStorageKey(key)); 89 | this._removeFromTag(this._toStorageKey(key)); 90 | } 91 | 92 | /** 93 | * Remove all from cache 94 | */ 95 | public removeAll() { 96 | this._storage.clear(); 97 | } 98 | 99 | /** 100 | * Get all tag data 101 | * @param tag 102 | * @returns {Array} 103 | */ 104 | public getTagData(tag: string) { 105 | let tags = this.get(this._tagsStorageKey()) || {}, 106 | result : {[key: string]: any} = {}; 107 | if (tags[tag]) { 108 | tags[tag].forEach((key: string) => { 109 | let data = this.get(this._fromStorageKey(key)); 110 | if (data) { 111 | result[this._fromStorageKey(key)] = data; 112 | } 113 | }); 114 | } 115 | return result; 116 | } 117 | 118 | /** 119 | * Create a new instance of cache with needed storage 120 | * @param type 121 | * @returns {CacheService} 122 | */ 123 | public useStorage(type: CacheStoragesEnum) { 124 | let service = new CacheService(this._initStorage(type)); 125 | service.setGlobalPrefix(this._getCachePrefix()); 126 | return service; 127 | } 128 | 129 | /** 130 | * Remove all by tag 131 | * @param tag 132 | */ 133 | public removeTag(tag: string) { 134 | let tags = this.get(this._tagsStorageKey()) || {}; 135 | if (tags[tag]) { 136 | tags[tag].forEach((key: string) => { 137 | this._storage.removeItem(key); 138 | }); 139 | delete tags[tag]; 140 | this.set(this._tagsStorageKey(), tags); 141 | } 142 | } 143 | 144 | /** 145 | * Set global cache key prefix 146 | * @param prefix 147 | */ 148 | public setGlobalPrefix(prefix: string) { 149 | this._prefix = prefix; 150 | } 151 | 152 | /** 153 | * Validate cache storage 154 | * @private 155 | */ 156 | private _validateStorage() { 157 | if (!this._storage) { 158 | this._storage = this._initStorage(DEFAULT_STORAGE); 159 | } 160 | if (!this._storage.isEnabled()) { 161 | this._storage = this._initStorage(DEFAULT_ENABLED_STORAGE); 162 | } 163 | } 164 | 165 | /** 166 | * Remove key from tags keys list 167 | * @param key 168 | * @private 169 | */ 170 | private _removeFromTag(key: string) { 171 | let tags = this.get(this._tagsStorageKey()) || {}, 172 | index: number; 173 | for (let tag in tags) { 174 | index = tags[tag].indexOf(key); 175 | if (index !== -1) { 176 | tags[tag].splice(index, 1); 177 | this.set(this._tagsStorageKey(), tags); 178 | break; 179 | } 180 | } 181 | } 182 | 183 | /** 184 | * Init storage by type 185 | * @param type 186 | * @returns {CacheStorageAbstract} 187 | */ 188 | private _initStorage(type: CacheStoragesEnum) { 189 | let storage: CacheStorageAbstract; 190 | switch (type) { 191 | case CacheStoragesEnum.SESSION_STORAGE: 192 | storage = new CacheSessionStorage(); 193 | break; 194 | case CacheStoragesEnum.LOCAL_STORAGE: 195 | storage = new CacheLocalStorage(); 196 | break; 197 | default: storage = new CacheMemoryStorage(); 198 | } 199 | return storage; 200 | } 201 | 202 | private _toStorageKey(key: string) { 203 | return this._getCachePrefix() + key; 204 | } 205 | 206 | private _fromStorageKey(key: string) { 207 | return key.replace(this._getCachePrefix(), ''); 208 | } 209 | 210 | /** 211 | * Prepare value to set to storage 212 | * @param value 213 | * @param options 214 | * @returns {{value: any, options: CacheOptionsInterface}} 215 | * @private 216 | */ 217 | private _toStorageValue(value: any, options: CacheOptionsInterface): StorageValueInterface { 218 | return { 219 | value: value, 220 | options: this._toStorageOptions(options) 221 | }; 222 | } 223 | 224 | /** 225 | * Prepare options to set to storage 226 | * @param options 227 | * @returns {CacheOptionsInterface} 228 | * @private 229 | */ 230 | private _toStorageOptions(options: CacheOptionsInterface): CacheOptionsInterface { 231 | var storageOptions: CacheOptionsInterface = {}; 232 | storageOptions.expires = options.expires ? options.expires : 233 | (options.maxAge ? Date.now() + (options.maxAge * 1000) : this._defaultOptions.expires); 234 | storageOptions.maxAge = options.maxAge ? options.maxAge : this._defaultOptions.maxAge; 235 | return storageOptions; 236 | } 237 | 238 | /** 239 | * Validate storage value 240 | * @param value 241 | * @returns {boolean} 242 | * @private 243 | */ 244 | private _validateStorageValue(value: StorageValueInterface) { 245 | return !!value.options.expires && value.options.expires > Date.now(); 246 | } 247 | 248 | /** 249 | * check if its system cache key 250 | * @param key 251 | * @returns {boolean} 252 | * @private 253 | */ 254 | private _isSystemKey(key: string) { 255 | return [this._tagsStorageKey()].indexOf(key) !== -1; 256 | } 257 | 258 | /** 259 | * Save tag to list of tags 260 | * @param tag 261 | * @param key 262 | * @private 263 | */ 264 | private _saveTag(tag: string, key: string) { 265 | let tags = this.get(this._tagsStorageKey()) || {}; 266 | if (!tags[tag]) { 267 | tags[tag] = [key]; 268 | } else { 269 | tags[tag].push(key); 270 | } 271 | this.set(this._tagsStorageKey(), tags); 272 | } 273 | 274 | /** 275 | * Get global cache prefix 276 | * @returns {string} 277 | * @private 278 | */ 279 | private _getCachePrefix() { 280 | return this._prefix; 281 | } 282 | 283 | private _tagsStorageKey() { 284 | return 'CacheService_tags'; 285 | } 286 | 287 | } 288 | -------------------------------------------------------------------------------- /src/services/storage/cache-storage-abstract.service.ts: -------------------------------------------------------------------------------- 1 | import {CacheStoragesEnum} from '../../enums/cache-storages.enum'; 2 | import {StorageValueInterface} from '../../interfaces/storage-value.interface'; 3 | 4 | /** 5 | * Abstract cache storage 6 | */ 7 | export abstract class CacheStorageAbstract { 8 | 9 | /** 10 | * Get item from storage 11 | * @param key 12 | */ 13 | public abstract getItem(key: string): StorageValueInterface; 14 | 15 | /** 16 | * Set item to storage 17 | * @param key 18 | * @param value 19 | */ 20 | public abstract setItem(key: string, value: StorageValueInterface): boolean; 21 | 22 | /** 23 | * Remove item from storage 24 | * @param key 25 | */ 26 | public abstract removeItem(key: string): void; 27 | 28 | /** 29 | * Clear item in storage 30 | */ 31 | public abstract clear(): void; 32 | 33 | /** 34 | * Get current storage type 35 | */ 36 | public abstract type(): CacheStoragesEnum; 37 | 38 | /** 39 | * Check if storage is enabled 40 | */ 41 | public abstract isEnabled(): boolean; 42 | 43 | } 44 | -------------------------------------------------------------------------------- /src/services/storage/local-storage/cache-local-storage.service.ts: -------------------------------------------------------------------------------- 1 | import {Injectable} from '@angular/core'; 2 | import {CacheStorageAbstract} from '../cache-storage-abstract.service'; 3 | import {CacheStoragesEnum} from '../../../enums/cache-storages.enum'; 4 | import {StorageValueInterface} from '../../../interfaces/storage-value.interface'; 5 | 6 | /** 7 | * Service for storing data in local storage 8 | */ 9 | @Injectable() 10 | export class CacheLocalStorage extends CacheStorageAbstract { 11 | 12 | public getItem(key: string) { 13 | let value = localStorage.getItem(key); 14 | return value ? JSON.parse(value) : null; 15 | } 16 | 17 | public setItem(key: string, value: StorageValueInterface) { 18 | try { 19 | localStorage.setItem(key, JSON.stringify(value)); 20 | return true; 21 | } catch (e) { 22 | return false; 23 | } 24 | } 25 | 26 | public removeItem(key: string) { 27 | localStorage.removeItem(key); 28 | } 29 | 30 | public clear() { 31 | localStorage.clear(); 32 | } 33 | 34 | public type() { 35 | return CacheStoragesEnum.LOCAL_STORAGE; 36 | } 37 | 38 | public isEnabled() { 39 | try { 40 | localStorage.setItem('test', 'test'); 41 | localStorage.removeItem('test'); 42 | return true; 43 | } catch (e) { 44 | return false; 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/services/storage/memory/cache-memory.service.ts: -------------------------------------------------------------------------------- 1 | import {Injectable} from '@angular/core'; 2 | import {CacheStorageAbstract} from '../cache-storage-abstract.service'; 3 | import {CacheStoragesEnum} from '../../../enums/cache-storages.enum'; 4 | import {StorageValueInterface} from '../../../interfaces/storage-value.interface'; 5 | 6 | /** 7 | * Service for storing data in local storage 8 | */ 9 | @Injectable() 10 | export class CacheMemoryStorage extends CacheStorageAbstract { 11 | 12 | private _data: {[key: string]: any} = {}; 13 | 14 | public getItem(key: string) { 15 | return this._data[key] ? this._data[key] : null; 16 | } 17 | 18 | public setItem(key: string, value: StorageValueInterface) { 19 | this._data[key] = value; 20 | return true; 21 | } 22 | 23 | public removeItem(key: string) { 24 | delete this._data[key]; 25 | } 26 | 27 | public clear() { 28 | this._data = []; 29 | } 30 | 31 | public type() { 32 | return CacheStoragesEnum.MEMORY; 33 | } 34 | 35 | public isEnabled() { 36 | return true; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/services/storage/session-storage/cache-session-storage.service.ts: -------------------------------------------------------------------------------- 1 | import {Injectable} from '@angular/core'; 2 | import {CacheStorageAbstract} from '../cache-storage-abstract.service'; 3 | import {CacheStoragesEnum} from '../../../enums/cache-storages.enum'; 4 | import {StorageValueInterface} from '../../../interfaces/storage-value.interface'; 5 | 6 | /** 7 | * Service for storing data in session storage 8 | */ 9 | @Injectable() 10 | export class CacheSessionStorage extends CacheStorageAbstract { 11 | 12 | public getItem(key: string) { 13 | let value = sessionStorage.getItem(key); 14 | return value ? JSON.parse(value) : null; 15 | } 16 | 17 | public setItem(key: string, value: StorageValueInterface) { 18 | try { 19 | sessionStorage.setItem(key, JSON.stringify(value)); 20 | return true; 21 | } catch (e) { 22 | return false; 23 | } 24 | } 25 | 26 | public removeItem(key: string) { 27 | sessionStorage.removeItem(key); 28 | } 29 | 30 | public clear() { 31 | sessionStorage.clear(); 32 | } 33 | 34 | public type() { 35 | return CacheStoragesEnum.SESSION_STORAGE; 36 | } 37 | 38 | public isEnabled() { 39 | try { 40 | sessionStorage.setItem('test', 'test'); 41 | sessionStorage.removeItem('test'); 42 | return true; 43 | } catch (e) { 44 | return false; 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "module": "commonjs", 4 | "target": "es5", 5 | "emitDecoratorMetadata": true, 6 | "experimentalDecorators": true, 7 | "sourceMap": false, 8 | "moduleResolution": "node", 9 | "declaration": true, 10 | "outDir": "./dist" 11 | }, 12 | "exclude": [ 13 | "node_modules" 14 | ], 15 | "files": [ 16 | "ng2-cache-service.ts", 17 | "./src/services/cache.service.ts", 18 | "./src/services/storage/cache-storage-abstract.service.ts", 19 | "./src/enums/cache-storages.enum.ts", 20 | "./src/services/storage/local-storage/cache-local-storage.service.ts", 21 | "./src/services/storage/memory/cache-memory.service.ts", 22 | "./src/services/storage/session-storage/cache-session-storage.service.ts", 23 | "./src/interfaces/cache-options.interface.ts", 24 | "./src/interfaces/storage-value.interface.ts" 25 | ], 26 | "compileOnSave": false, 27 | "buildOnSave": false, 28 | "atom": { "rewriteTsconfig": false } 29 | } --------------------------------------------------------------------------------