|
| 1 | +import { openDB, IDBPDatabase } from "idb"; |
| 2 | +import { FileResponse } from "@design-sdk/figma-remote-api"; |
| 3 | + |
| 4 | +// #region global db initialization |
| 5 | +const __db_pref = { name: "fimga-file-store", version: 1 }; |
| 6 | +const __pk = "key"; |
| 7 | +const __table = "files"; |
| 8 | +export type FileResponseRecord = FileResponse & { |
| 9 | + [__pk]: string; |
| 10 | +}; |
| 11 | + |
| 12 | +const db: Promise<IDBPDatabase<FileResponseRecord>> = new Promise((resolve) => { |
| 13 | + openDB<FileResponseRecord>(__db_pref.name, __db_pref.version, { |
| 14 | + upgrade(db) { |
| 15 | + db.createObjectStore(__table, { |
| 16 | + keyPath: __pk, |
| 17 | + }); |
| 18 | + }, |
| 19 | + }).then((_db) => { |
| 20 | + resolve(_db); |
| 21 | + }); |
| 22 | +}); |
| 23 | +// #endregion |
| 24 | + |
| 25 | +export class FigmaFilesStore { |
| 26 | + static of = (key: string): FigmaFileStore => { |
| 27 | + return new FigmaFileStore(key); |
| 28 | + }; |
| 29 | + |
| 30 | + static async all() { |
| 31 | + const files = await (await db).getAll(__table); |
| 32 | + return files.map((file) => file as FileResponseRecord); |
| 33 | + } |
| 34 | + |
| 35 | + static async add(key: string, file: FileResponse) { |
| 36 | + return new FigmaFileStore(key).upsert(file); |
| 37 | + } |
| 38 | +} |
| 39 | + |
| 40 | +export class FigmaFileStore { |
| 41 | + constructor(readonly filekey: string) {} |
| 42 | + |
| 43 | + async upsert(file: FileResponse) { |
| 44 | + try { |
| 45 | + await ( |
| 46 | + await db |
| 47 | + ).put(__table, <FileResponseRecord>{ ...file, [__pk]: this.filekey }); |
| 48 | + } catch (e) { |
| 49 | + if (process.env.NODE_ENV === "development") { |
| 50 | + console.error(e); |
| 51 | + } |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + async get() { |
| 56 | + const rec = await (await db).get(__table, this.filekey); |
| 57 | + return rec; |
| 58 | + } |
| 59 | +} |
0 commit comments