UNPKG

ngz-cache-platform-server

Version:
102 lines (98 loc) 2.77 kB
import { isPlatformServer } from '@angular/common'; import { Injectable, Inject, PLATFORM_ID, Injector, NgModule, Optional, SkipSelf } from '@angular/core'; import { STORAGE } from 'ngz-cache-core'; class FsCacheService { constructor(platformId, injector) { this.platformId = platformId; this.injector = injector; if (!isPlatformServer(platformId)) { throw new Error('FsCacheService is not supported outside `server` platform!'); } this.fsStorage = injector.get(STORAGE); } get isEnabled() { if (!isPlatformServer(this.platformId)) { return false; } try { this.fsStorage.setItem('test', 'test'); this.fsStorage.removeItem('test'); return true; } catch (e) { return false; } } get keys() { if (!this.isEnabled) { return undefined; } return this.fsStorage.keys; } setItem(key, value) { if (!this.isEnabled) { return false; } try { this.fsStorage.setItem(key, JSON.stringify(value)); return true; } catch (e) { return false; } } getItem(key) { if (!this.isEnabled) { return undefined; } const value = this.fsStorage.getItem(key); return value ? JSON.parse(value) : undefined; } removeItem(key, wild = false) { if (!this.isEnabled) { return; } this.fsStorage.removeItem(key); if (wild) { for (const item of this.keys) { if (item.indexOf(key) === 0) { this.fsStorage.removeItem(item); } } } } clear() { if (!this.isEnabled) { return; } this.fsStorage.clear(); } } FsCacheService.decorators = [ { type: Injectable } ]; FsCacheService.ctorParameters = () => [ { type: undefined, decorators: [{ type: Inject, args: [PLATFORM_ID,] }] }, { type: Injector } ]; class ServerCacheModule { constructor(parentModule) { if (parentModule) { throw new Error('ServerCacheModule already loaded; import in SERVER module only.'); } } static forRoot(configuredProviders) { return { ngModule: ServerCacheModule, providers: configuredProviders }; } } ServerCacheModule.decorators = [ { type: NgModule } ]; ServerCacheModule.ctorParameters = () => [ { type: ServerCacheModule, decorators: [{ type: Optional }, { type: SkipSelf }] } ]; export { FsCacheService, ServerCacheModule }; //# sourceMappingURL=ngz-cache-platform-server.js.map