File
Blob: src/worker/db/d1/sessions.ts
| 1 | import { createD1Db, type D1Db } from "@/worker/db/d1/client"; |
| 2 | |
| 3 | export const D1_BOOKMARK_HEADER = "x-anvil-d1-bookmark"; |
| 4 | |
| 5 | export interface D1SessionContext { |
| 6 | session: D1DatabaseSession; |
| 7 | db: D1Db; |
| 8 | getBookmark: () => string | null; |
| 9 | } |
| 10 | |
| 11 | export const openSession = (env: Env, bookmark: string): D1SessionContext => { |
| 12 | const session = env.DB.withSession(bookmark); |
| 13 | |
| 14 | return { |
| 15 | session, |
| 16 | db: createD1Db(session), |
| 17 | getBookmark: () => session.getBookmark() ?? null, |
| 18 | }; |
| 19 | }; |
| 20 | |
| 21 | export const openReadSession = (request: Request, env: Env): D1SessionContext => { |
| 22 | const bookmark = request.headers.get(D1_BOOKMARK_HEADER) ?? "first-unconstrained"; |
| 23 | return openSession(env, bookmark); |
| 24 | }; |
| 25 | |
| 26 | export const openPrimarySession = (request: Request, env: Env): D1SessionContext => openSession(env, "first-primary"); |