| // Copyright 2018 The Chromium Authors. All rights reserved. |
| // Use of this source code is governed by a BSD-style license that can be |
| // found in the LICENSE file. |
| const localStorage = window.localStorage; |
| |
| /** A localStorage-backed cached JSON object. */ |
| export class CacheObject { |
| key: string; |
| |
| /** |
| * Creates a new CacheObject instance. |
| * |
| * @param key localStorage key name for storage. |
| */ |
| constructor(key: string) { |
| this.key = key; |
| } |
| |
| private checkObj(obj: any) { |
| if (typeof obj !== 'object' || Array.isArray(obj)) { |
| throw Error('obj parameter value is not an Object'); |
| } |
| return obj; |
| } |
| |
| /** |
| * Reads the cached object. |
| * |
| * @return The object from storage. |
| * On failure, clears the storage and returns {}. |
| */ |
| read(): any { |
| try { |
| const storeItem = localStorage.getItem(this.key); |
| if (storeItem == null) { |
| return {}; |
| } |
| return this.checkObj(JSON.parse(storeItem)); |
| } catch (ex) { |
| console.warn( |
| `error while reading cache at localStorage key "${this.key}`, |
| ex |
| ); |
| localStorage.removeItem(this.key); |
| return {}; |
| } |
| } |
| |
| /** Writes the cache value. */ |
| write(obj: any) { |
| localStorage.setItem(this.key, JSON.stringify(this.checkObj(obj))); |
| } |
| |
| /** Clears the cache value. */ |
| clear() { |
| localStorage.removeItem(this.key); |
| } |
| } |