56 lines
1.2 KiB
TypeScript
56 lines
1.2 KiB
TypeScript
import { openDB, DBSchema, IDBPDatabase } from "idb";
|
|
import { type CalendarEvent } from "./types";
|
|
|
|
interface ICalDB extends DBSchema {
|
|
events: {
|
|
key: string;
|
|
value: CalendarEvent;
|
|
};
|
|
}
|
|
|
|
let dbPromise: Promise<IDBPDatabase<ICalDB>> | null = null;
|
|
|
|
async function initDB() {
|
|
return openDB<ICalDB>("icalPWA", 1, {
|
|
upgrade(db) {
|
|
if (!db.objectStoreNames.contains("events")) {
|
|
db.createObjectStore("events", { keyPath: "id" });
|
|
}
|
|
},
|
|
});
|
|
}
|
|
|
|
// Get the database in a browser-safe way
|
|
export async function getDB() {
|
|
if (typeof window === "undefined") return null;
|
|
if (!dbPromise) {
|
|
dbPromise = initDB();
|
|
}
|
|
return dbPromise;
|
|
}
|
|
|
|
// CRUD operations — all SSR-safe
|
|
export async function getAllEvents() {
|
|
const db = await getDB();
|
|
if (!db) return [];
|
|
return db.getAll("events");
|
|
}
|
|
|
|
export async function addEvent(event: ICalDB["events"]["value"]) {
|
|
const db = await getDB();
|
|
if (!db) return;
|
|
return db.put("events", event);
|
|
}
|
|
|
|
export async function deleteEvent(id: string) {
|
|
const db = await getDB();
|
|
if (!db) return;
|
|
return db.delete("events", id);
|
|
}
|
|
|
|
export async function clearEvents() {
|
|
const db = await getDB();
|
|
if (!db) return;
|
|
return db.clear("events");
|
|
}
|