File size: 2,986 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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
type BoundValue = bigint | boolean | null | number | string;

const databases = new Map<string, D1Database>();

function jsonValue(value: BoundValue) {
  if (typeof value === "bigint") {
    if (!Number.isSafeInteger(Number(value))) throw new TypeError("D1 integer is outside the safe range.");
    return Number(value);
  }
  return value;
}

class HttpD1Statement {
  private readonly endpoint: string;
  private readonly query: string;
  private readonly values: BoundValue[];

  constructor(endpoint: string, query: string, values: BoundValue[] = []) {
    this.endpoint = endpoint;
    this.query = query;
    this.values = values;
  }

  bind(...values: BoundValue[]) {
    return new HttpD1Statement(this.endpoint, this.query, values);
  }

  private async execute(operation: "all" | "first" | "raw" | "run", column?: string) {
    const response = await fetch(this.endpoint, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        protocol: "linkedin.d1.v1",
        operation,
        query: this.query,
        values: this.values.map(jsonValue),
        ...(column ? { column } : {}),
      }),
    });
    const payload = await response.json().catch(() => null) as { error?: string; result?: unknown } | null;
    if (!response.ok || !payload || !("result" in payload)) {
      throw new Error(`LinkedIn D1 proxy refused ${operation}: ${payload?.error || response.status}`);
    }
    return payload.result;
  }

  async first(column?: string) {
    return this.execute("first", column);
  }

  async run() {
    return this.execute("run");
  }

  async all() {
    return this.execute("all");
  }

  async raw() {
    return this.execute("raw");
  }

  envelope() {
    return { query: this.query, values: this.values.map(jsonValue) };
  }
}

class HttpD1Database {
  constructor(private readonly endpoint: string) {}

  prepare(query: string) {
    return new HttpD1Statement(this.endpoint, query);
  }

  async batch(statements: HttpD1Statement[]) {
    const response = await fetch(this.endpoint, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        protocol: "linkedin.d1.v1",
        operation: "batch",
        statements: statements.map((statement) => statement.envelope()),
      }),
    });
    const payload = await response.json().catch(() => null) as { error?: string; result?: unknown } | null;
    if (!response.ok || !payload || !("result" in payload)) {
      throw new Error(`LinkedIn D1 proxy refused batch: ${payload?.error || response.status}`);
    }
    return payload.result;
  }

  async exec(query: string) {
    return new HttpD1Statement(this.endpoint, query).run();
  }
}

export function getHttpD1Database(endpoint: string) {
  let database = databases.get(endpoint);
  if (!database) {
    database = new HttpD1Database(endpoint) as unknown as D1Database;
    databases.set(endpoint, database);
  }
  return database;
}