import * as _ from "lodash"; import { StorageService } from './StorageService'; import { Parser, safeParse } from './Parsers'; import { Marshaller } from './Marshallers'; export const Prefix = "ovo"; export class LocalStorageService implements StorageService { constructor(private $window: ng.IWindowService) { } get(key: string, parse: Parser): T; get(key: string): T; get(key: string, parser?: Parser) { let value = this.$window.localStorage.getItem(`${Prefix}.${key}`); // Check null/undefined explicitly, because the parse function may not cope if (!value) return undefined; return (parser) ? safeParse(parser, value) : value; } set(key: string, value: T, marshal: Marshaller): void; set(key: string, value: T): void; set(key: string, value: T, marshal?: Marshaller) { if (_.isNil(value)) this.$window.localStorage.removeItem(`${Prefix}.${key}`); else this.$window.localStorage.setItem(`${Prefix}.${key}`, marshal ? marshal(value) : value as any); } contains(key: string): boolean { return `${Prefix}.${key}` in this.$window.localStorage; } }