Skip to content
File

Blob: tests/worker/lib/d1-session.test.ts

typescript40 lines
1import { describe, expect, it, vi } from "vitest";
2 
3import { createSessionDb, selectHttpSessionConstraint } from "@/worker/db/d1/client";
4 
5describe("D1 session helpers", () => {
6 it("selects latency-focused reads when no bookmark is provided", () => {
7 expect(selectHttpSessionConstraint("GET")).toBe("first-unconstrained");
8 expect(selectHttpSessionConstraint("HEAD")).toBe("first-unconstrained");
9 expect(selectHttpSessionConstraint("GET", " ")).toBe("first-unconstrained");
10 });
11 
12 it("selects the caller bookmark for read requests when present", () => {
13 expect(selectHttpSessionConstraint("GET", "bookmark-123")).toBe("bookmark-123");
14 expect(selectHttpSessionConstraint("HEAD", " bookmark-123 ")).toBe("bookmark-123");
15 });
16 
17 it("selects primary for mutating requests even when a bookmark is present", () => {
18 for (const method of ["POST", "PATCH", "PUT", "DELETE"]) {
19 expect(selectHttpSessionConstraint(method, "bookmark-123")).toBe("first-primary");
20 }
21 });
22 
23 it("creates a Drizzle DB from a D1 session", () => {
24 const session = {
25 prepare: vi.fn(),
26 batch: vi.fn(),
27 getBookmark: vi.fn(),
28 } as unknown as D1DatabaseSession;
29 const d1 = {
30 withSession: vi.fn(() => session),
31 } as unknown as D1Database;
32 
33 const result = createSessionDb(d1, "first-unconstrained");
34 
35 expect(d1.withSession).toHaveBeenCalledWith("first-unconstrained");
36 expect(result.session).toBe(session);
37 expect(result.db.$client).toBe(session);
38 });
39});