Skip to content

Instantly share code, notes, and snippets.

@pelly-ryu
Created October 27, 2023 01:02
Show Gist options
  • Save pelly-ryu/e37274cd7482257de69492b147715984 to your computer and use it in GitHub Desktop.
Save pelly-ryu/e37274cd7482257de69492b147715984 to your computer and use it in GitHub Desktop.
adapters/indexedDB/visitLocation.ts
import { type StoreKey } from "idb";
import {
type DefaultDB,
type LocationWithTimestamp,
StoreName,
getDb,
} from "@/adapters/indexedDB/core";
type Store = {
first(): Promise<LocationWithTimestamp | undefined>;
add(
location: Location,
): Promise<StoreKey<DefaultDB, StoreName.VisitLocation>>;
};
export function useVisitLocationStore(): Store {
return {
first: async () => {
const cursor = await (await getDb())
.transaction(StoreName.VisitLocation, "readonly")
.objectStore(StoreName.VisitLocation)
.openCursor();
if (cursor) {
return cursor.value;
}
return undefined;
},
add: async (location: Location) => {
const toSave: Partial<Location> = JSON.parse(JSON.stringify(location));
return await (
await getDb()
)
.transaction(StoreName.VisitLocation, "readwrite")
.objectStore(StoreName.VisitLocation)
.add({
location: toSave,
timestamp: new Date(),
} satisfies LocationWithTimestamp);
},
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment