working idb example
This commit is contained in:
@@ -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
7
src/lib/types.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
export type CalendarEvent = {
|
||||
id: string;
|
||||
title: string;
|
||||
start: string; // ISO date string (YYYY-MM-DD)
|
||||
end?: string;
|
||||
description?: string;
|
||||
};
|
||||
Reference in New Issue
Block a user