File size: 1,155 Bytes
9d4a3b0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import { drizzle } from "drizzle-orm/d1";
import { getHttpD1Database } from "./http-d1";
import { getNodeD1Database } from "./node-d1";
import * as schema from "./schema";

const globalForDb = globalThis as typeof globalThis & {
  __linkedinTestDb?: D1Database;
};

/**
 * Resolve the clone database synchronously so existing route and library call
 * sites retain their current getDb() contract. Production containers use the
 * authenticated same-host D1 HTTP proxy; local development/tests use node:sqlite.
 */
export function getDb() {
  let binding: D1Database | undefined;

  if (process.env.LINKEDIN_TEST_RUNTIME === "1") {
    binding = globalForDb.__linkedinTestDb;
  }
  if (!binding && process.env.LINKEDIN_D1_PROXY_URL) {
    binding = getHttpD1Database(process.env.LINKEDIN_D1_PROXY_URL);
  }
  if (!binding && process.env.LINKEDIN_SQLITE_PATH) {
    binding = getNodeD1Database(process.env.LINKEDIN_SQLITE_PATH);
  }
  if (!binding) {
    throw new Error(
      "LinkedIn D1 storage is unavailable. Set LINKEDIN_D1_PROXY_URL in production or LINKEDIN_SQLITE_PATH for local development.",
    );
  }

  return drizzle(binding, { schema });
}