Skip to content
File

Blob: src/worker/db/d1/sessions.ts

typescript27 lines
1import { createD1Db, type D1Db } from "@/worker/db/d1/client";
2 
3export const D1_BOOKMARK_HEADER = "x-anvil-d1-bookmark";
4 
5export interface D1SessionContext {
6 session: D1DatabaseSession;
7 db: D1Db;
8 getBookmark: () => string | null;
9}
10 
11export 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 
21export 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 
26export const openPrimarySession = (request: Request, env: Env): D1SessionContext => openSession(env, "first-primary");