|
| 1 | +/* eslint-disable no-console, prefer-rest-params */ |
| 2 | +import Service, { inject as service } from '@ember/service'; |
| 3 | +import DS from 'ember-data'; |
| 4 | + |
| 5 | +function pushToStore(store: DS.Store, data: any): any[] | any { |
| 6 | + const parsed = data?.value; |
| 7 | + if (Array.isArray(parsed)) { |
| 8 | + const items = [] |
| 9 | + for (const item of parsed) { |
| 10 | + store.pushPayload(item); |
| 11 | + items.push(store.peekRecord(item.data.type, item.data.id)); |
| 12 | + } |
| 13 | + return items; |
| 14 | + } else { |
| 15 | + store.pushPayload(parsed); |
| 16 | + |
| 17 | + return store.peekRecord(parsed.data.type, parsed.data.id); |
| 18 | + } |
| 19 | +} |
| 20 | + |
| 21 | +function saveToStorage(key: string, value: any | null) { |
| 22 | + if (!value) {return} |
| 23 | + let serialized = null; |
| 24 | + if (Array.isArray(value.content)) { |
| 25 | + serialized = value.map((v: any) => v.serialize({ includeId: true })); |
| 26 | + } else { |
| 27 | + serialized = value.serialize({ includeId: true }); |
| 28 | + } |
| 29 | + |
| 30 | + localStorage.setItem(key, JSON.stringify({ |
| 31 | + time : Date.now(), |
| 32 | + value : serialized |
| 33 | + })); |
| 34 | +} |
| 35 | + |
| 36 | +export default class Cache extends Service.extend({ |
| 37 | + // anything which *must* be merged to prototype here |
| 38 | +}) { |
| 39 | + version = 'v1'; |
| 40 | + |
| 41 | + @service store!: DS.Store; |
| 42 | + |
| 43 | + get prefix(): string { |
| 44 | + return 'cache:' + this.version + ':'; |
| 45 | + } |
| 46 | + |
| 47 | + isExpired(data: { time: number, value: any} | null): boolean { |
| 48 | + // Item expired after 15 seconds |
| 49 | + return Boolean(data?.time && (Date.now() - data?.time) > 60 * 1000) |
| 50 | + } |
| 51 | + |
| 52 | + async passThrough(key: string, callable: () => any): Promise<any> { |
| 53 | + const value = await callable(); |
| 54 | + saveToStorage(key, value); |
| 55 | + |
| 56 | + return value; |
| 57 | + } |
| 58 | + |
| 59 | + async cacheData(key: string, callable: () => any): Promise<any | null> { |
| 60 | + key = this.prefix + key; |
| 61 | + const stored = localStorage.getItem(key); |
| 62 | + try { |
| 63 | + if (stored) { |
| 64 | + const data = JSON.parse(stored); |
| 65 | + |
| 66 | + if (!data.time) { |
| 67 | + // Invalid data structure |
| 68 | + return this.passThrough(key, callable); |
| 69 | + } |
| 70 | + |
| 71 | + const expired = this.isExpired(data); |
| 72 | + const item = pushToStore(this.store, data); |
| 73 | + |
| 74 | + if (expired) { |
| 75 | + // Revalidate resource while serving stale |
| 76 | + console.info('Item expired. Revalidating...', key); |
| 77 | + this.passThrough(key, callable); |
| 78 | + } |
| 79 | + |
| 80 | + return item; |
| 81 | + } else { |
| 82 | + return this.passThrough(key, callable); |
| 83 | + } |
| 84 | + } catch (e) { |
| 85 | + console.error('Error while loading value from cache using key: ' + key, e); |
| 86 | + |
| 87 | + return callable(); |
| 88 | + } |
| 89 | + } |
| 90 | + |
| 91 | + async findAll(model: string, options: any | null): Promise<any> { |
| 92 | + const saved = await this.cacheData(model, () => this.store.findAll(model, options)); |
| 93 | + if (saved) {return saved;} |
| 94 | + return this.store.peekAll(model); |
| 95 | + } |
| 96 | + |
| 97 | + async queryRecord(key: string, model: string, options: any | null): Promise<any> { |
| 98 | + const saved = await this.cacheData(key, () => this.store.queryRecord(model, options)); |
| 99 | + if (saved) {return saved;} |
| 100 | + return this.store.peekRecord(model, 1); |
| 101 | + } |
| 102 | + |
| 103 | + clear(): void { |
| 104 | + for (const key of Object.keys(localStorage)) { |
| 105 | + if (key.startsWith(this.prefix)) { |
| 106 | + console.info('Clearing cache entry:', key); |
| 107 | + localStorage.removeItem(key); |
| 108 | + } |
| 109 | + } |
| 110 | + } |
| 111 | + |
| 112 | + constructor() { |
| 113 | + super(...arguments); |
| 114 | + for (const key of Object.keys(localStorage)) { |
| 115 | + if (key.startsWith('cache:')) { |
| 116 | + if (!key.startsWith(this.prefix)) { |
| 117 | + console.info('Removing previous cache entry:', key); |
| 118 | + localStorage.removeItem(key); |
| 119 | + } |
| 120 | + } |
| 121 | + } |
| 122 | + } |
| 123 | +} |
| 124 | + |
| 125 | +// DO NOT DELETE: this is how TypeScript knows how to look up your services. |
| 126 | +declare module '@ember/service' { |
| 127 | + interface Registry { |
| 128 | + 'cache': Cache; |
| 129 | + } |
| 130 | +} |
0 commit comments