getDb.ts 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import { openDB, DBSchema, StoreNames } from "idb";
  2. export interface NovelDb extends DBSchema {
  3. history: {
  4. value: HistoryItem;
  5. key: string;
  6. indexes: {
  7. uri: string;
  8. historyUpdateTime: Date;
  9. historyIsReading: number;
  10. historyIsFavorite: number;
  11. };
  12. };
  13. }
  14. export default function getDb() {
  15. return openDB<NovelDb>("NovelDit", 2, {
  16. upgrade(db, oldVersion, newVersion) {
  17. console.log(oldVersion, newVersion);
  18. if (oldVersion === 0) {
  19. const historyStore = db.createObjectStore("history", {
  20. keyPath: "uri",
  21. });
  22. historyStore.createIndex("historyUpdateTime", "readTime", {
  23. unique: false,
  24. });
  25. historyStore.createIndex(
  26. "historyIsReading",
  27. ["isReading", "readTime"],
  28. {
  29. unique: false,
  30. }
  31. );
  32. historyStore.createIndex("historyIsFavorite", "isFavorite", {
  33. unique: false,
  34. });
  35. } else if (oldVersion === 1) {
  36. const historyStore = db.transaction("history", "versionchange");
  37. const store = historyStore.store;
  38. store.deleteIndex("historyIsFavorite");
  39. store.createIndex("historyIsFavorite", "isFavorite", {
  40. unique: false,
  41. });
  42. }
  43. },
  44. });
  45. }