Created
October 27, 2023 01:02
-
-
Save pelly-ryu/e37274cd7482257de69492b147715984 to your computer and use it in GitHub Desktop.
adapters/indexedDB/visitLocation.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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