working idb example

This commit is contained in:
2025-08-14 23:09:34 -04:00
parent ad600a896c
commit b1dad2f6ba
3 changed files with 99 additions and 21 deletions

View File

@@ -1,7 +1,55 @@
import { openDB } from "idb";
import { openDB, DBSchema, IDBPDatabase } from "idb";
import { type CalendarEvent } from "./types";
export const dbPromise = openDB("icalPWA", 1, {
upgrade(db) {
db.createObjectStore("events", { keyPath: "id" });
},
});
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");
}

7
src/lib/types.ts Normal file
View File

@@ -0,0 +1,7 @@
export type CalendarEvent = {
id: string;
title: string;
start: string; // ISO date string (YYYY-MM-DD)
end?: string;
description?: string;
};