70 lines
1.8 KiB
JavaScript
70 lines
1.8 KiB
JavaScript
import Service, { service } from '@ember/service';
|
|
import { tracked } from '@glimmer/tracking';
|
|
import { CALENDAR_EVENTS_NAMESPACE } from '../config/calendar';
|
|
|
|
// Persistent store of fetched calendar events, keyed by source calendar. The
|
|
// dashboard widget reads this so opening a tab shows events immediately instead
|
|
// of refetching; the calendar service refreshes entries in the background.
|
|
export default class CalendarCacheService extends Service {
|
|
@service storage;
|
|
|
|
@tracked entries = new Map();
|
|
|
|
ready = null;
|
|
|
|
constructor() {
|
|
super(...arguments);
|
|
this.ready = this.load();
|
|
}
|
|
|
|
async load() {
|
|
const keys = await this.storage.keys(CALENDAR_EVENTS_NAMESPACE);
|
|
const entries = await Promise.all(
|
|
keys.map((key) => this.storage.get(CALENDAR_EVENTS_NAMESPACE, key))
|
|
);
|
|
|
|
this.entries = new Map(
|
|
entries.filter(Boolean).map((entry) => [entry.key, entry])
|
|
);
|
|
}
|
|
|
|
all() {
|
|
return [...this.entries.values()];
|
|
}
|
|
|
|
get(key) {
|
|
return this.entries.get(key) ?? null;
|
|
}
|
|
|
|
forSource(type, instanceKey) {
|
|
return this.all().filter(
|
|
(entry) =>
|
|
entry.source.type === type && entry.source.instanceKey === instanceKey
|
|
);
|
|
}
|
|
|
|
async put(entry) {
|
|
await this.storage.set(CALENDAR_EVENTS_NAMESPACE, entry.key, entry);
|
|
this.entries = new Map(this.entries).set(entry.key, entry);
|
|
}
|
|
|
|
async remove(key) {
|
|
await this.storage.remove(CALENDAR_EVENTS_NAMESPACE, key);
|
|
|
|
const next = new Map(this.entries);
|
|
next.delete(key);
|
|
this.entries = next;
|
|
}
|
|
|
|
async removeSource(type, instanceKey) {
|
|
await Promise.all(
|
|
this.forSource(type, instanceKey).map((entry) => this.remove(entry.key))
|
|
);
|
|
}
|
|
|
|
async clear() {
|
|
await this.storage.clear(CALENDAR_EVENTS_NAMESPACE);
|
|
this.entries = new Map();
|
|
}
|
|
}
|