@pgxsinkit/server 0.1.7 → 0.1.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +200 -337
- package/dist/index.js.map +7 -6
- package/package.json +2 -6
- package/src/electric-proxy.ts +203 -0
- package/src/index.ts +79 -445
- package/src/mutations/bulk/route.ts +8 -3
- package/dist/experimental/index.js +0 -195
- package/dist/experimental/index.js.map +0 -11
- package/src/experimental/index.ts +0 -6
- package/src/experimental/mutations/bulk/dynamic-strategy.ts +0 -91
- package/src/experimental/mutations/bulk/pregenerated-strategy.ts +0 -136
- package/src/experimental/mutations/bulk/types.ts +0 -5
package/src/index.ts
CHANGED
|
@@ -1,5 +1,3 @@
|
|
|
1
|
-
import { eq, sql } from "drizzle-orm";
|
|
2
|
-
import type { AnyPgTable } from "drizzle-orm/pg-core";
|
|
3
1
|
import type { PostgresJsDatabase } from "drizzle-orm/postgres-js";
|
|
4
2
|
import { drizzle } from "drizzle-orm/postgres-js";
|
|
5
3
|
import { defineRelations } from "drizzle-orm/relations";
|
|
@@ -10,18 +8,15 @@ import postgres from "postgres";
|
|
|
10
8
|
import type {
|
|
11
9
|
RegistryRelations,
|
|
12
10
|
RegistryTables,
|
|
13
|
-
ServerRouteSpec,
|
|
14
11
|
SyncRuntimeStatus,
|
|
15
12
|
SyncServerAddress,
|
|
16
|
-
SyncTableEntry,
|
|
17
13
|
SyncTableRegistry,
|
|
18
14
|
} from "@pgxsinkit/contracts";
|
|
19
15
|
|
|
20
16
|
import { registerBulkMutationRoute } from "./mutations/bulk/route";
|
|
21
17
|
import type { BulkMutationBackend } from "./mutations/bulk/types";
|
|
22
18
|
import { ensureOperationsLogSchema } from "./operations-log/ddl";
|
|
23
|
-
import type {
|
|
24
|
-
import { logOperation, logOperationSafely } from "./operations-log/writer";
|
|
19
|
+
import type { OperationsLogConfig } from "./operations-log/types";
|
|
25
20
|
|
|
26
21
|
const defaultAllowedOrigins = ["http://localhost:5173", "http://localhost:5174"];
|
|
27
22
|
|
|
@@ -40,12 +35,19 @@ interface BunNamespace {
|
|
|
40
35
|
|
|
41
36
|
export interface CreateSyncServerOptions<TRegistry extends SyncTableRegistry> {
|
|
42
37
|
registry: TRegistry;
|
|
43
|
-
databaseUrl
|
|
38
|
+
/** Existing Drizzle database instance. Mutually exclusive with databaseUrl. */
|
|
39
|
+
db?: PostgresJsDatabase<RegistryRelations<TRegistry>>;
|
|
40
|
+
/** PostgreSQL connection URL. Mutually exclusive with db. */
|
|
41
|
+
databaseUrl?: string;
|
|
42
|
+
/** Existing Hono app to register routes on. If omitted, a new Hono app is created. */
|
|
43
|
+
app?: Hono;
|
|
44
44
|
backend?: BulkMutationBackend;
|
|
45
45
|
resolveAuthClaims?: (request: Request) => Promise<Record<string, unknown> | null> | Record<string, unknown> | null;
|
|
46
46
|
operationsLog?: {
|
|
47
47
|
enabled?: boolean;
|
|
48
48
|
};
|
|
49
|
+
/** Health check endpoint. Only applies when pgxsinkit owns the Hono app. */
|
|
50
|
+
healthCheck?: boolean | { path: string };
|
|
49
51
|
port?: number;
|
|
50
52
|
host?: string;
|
|
51
53
|
idleTimeoutSeconds?: number;
|
|
@@ -56,7 +58,6 @@ export interface CreateSyncServerOptions<TRegistry extends SyncTableRegistry> {
|
|
|
56
58
|
export interface ServerDiagnostics<TRegistry extends SyncTableRegistry> {
|
|
57
59
|
tables: Array<keyof TRegistry & string>;
|
|
58
60
|
modes: Record<string, TRegistry[keyof TRegistry]["mode"]>;
|
|
59
|
-
routes: Record<string, ServerRouteSpec | undefined>;
|
|
60
61
|
}
|
|
61
62
|
|
|
62
63
|
export interface SyncServer<TRegistry extends SyncTableRegistry> {
|
|
@@ -73,10 +74,26 @@ export interface SyncServer<TRegistry extends SyncTableRegistry> {
|
|
|
73
74
|
export function createSyncServer<TRegistry extends SyncTableRegistry>(
|
|
74
75
|
options: CreateSyncServerOptions<TRegistry>,
|
|
75
76
|
): SyncServer<TRegistry> {
|
|
76
|
-
const
|
|
77
|
-
const
|
|
78
|
-
|
|
79
|
-
|
|
77
|
+
const ownsApp = !options.app;
|
|
78
|
+
const ownsDb = !options.db;
|
|
79
|
+
|
|
80
|
+
if (!ownsDb && !options.databaseUrl) {
|
|
81
|
+
throw new Error("createSyncServer requires either db or databaseUrl");
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
let pgClient: ReturnType<typeof postgres> | undefined;
|
|
85
|
+
let db: PostgresJsDatabase<RegistryRelations<TRegistry>>;
|
|
86
|
+
|
|
87
|
+
if (options.db) {
|
|
88
|
+
db = options.db;
|
|
89
|
+
} else {
|
|
90
|
+
pgClient = createPostgresClient(options.databaseUrl!);
|
|
91
|
+
const schema = buildSchema(options.registry);
|
|
92
|
+
const relations = defineRelations(schema) as RegistryRelations<TRegistry>;
|
|
93
|
+
db = drizzle({ client: pgClient, relations }) as unknown as PostgresJsDatabase<RegistryRelations<TRegistry>>;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
const app = options.app ?? new Hono();
|
|
80
97
|
let bunServer: BunServerHandle | undefined;
|
|
81
98
|
|
|
82
99
|
const status: SyncRuntimeStatus = {
|
|
@@ -89,50 +106,49 @@ export function createSyncServer<TRegistry extends SyncTableRegistry>(
|
|
|
89
106
|
const operationsLogReady = ensureOperationsLogSchema(db, operationsLogConfig);
|
|
90
107
|
const backend = options.backend ?? "bulk-plpgsql-artifact";
|
|
91
108
|
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
109
|
+
if (ownsApp) {
|
|
110
|
+
app.use(
|
|
111
|
+
"/api/*",
|
|
112
|
+
cors({
|
|
113
|
+
origin: options.allowedOrigins ?? defaultAllowedOrigins,
|
|
114
|
+
allowMethods: ["GET", "POST", "OPTIONS"],
|
|
115
|
+
allowHeaders: ["Content-Type", "Authorization"],
|
|
116
|
+
}),
|
|
117
|
+
);
|
|
118
|
+
|
|
119
|
+
app.onError((error, context) => {
|
|
120
|
+
status.phase = "degraded";
|
|
121
|
+
status.lastError = error instanceof Error ? error.message : "Unexpected error";
|
|
122
|
+
options.onStatusChange?.(status);
|
|
100
123
|
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
124
|
+
if (isValidationError(error)) {
|
|
125
|
+
return context.json(
|
|
126
|
+
{
|
|
127
|
+
message: "Validation failed",
|
|
128
|
+
issues: error.issues,
|
|
129
|
+
},
|
|
130
|
+
400,
|
|
131
|
+
);
|
|
132
|
+
}
|
|
105
133
|
|
|
106
|
-
if (isValidationError(error)) {
|
|
107
134
|
return context.json(
|
|
108
135
|
{
|
|
109
|
-
message: "
|
|
110
|
-
issues: error.issues,
|
|
136
|
+
message: error instanceof Error ? error.message : "Unexpected error",
|
|
111
137
|
},
|
|
112
|
-
|
|
138
|
+
500,
|
|
113
139
|
);
|
|
114
|
-
}
|
|
140
|
+
});
|
|
115
141
|
|
|
116
|
-
|
|
117
|
-
{
|
|
118
|
-
message: error instanceof Error ? error.message : "Unexpected error",
|
|
119
|
-
},
|
|
120
|
-
500,
|
|
121
|
-
);
|
|
122
|
-
});
|
|
142
|
+
const healthCheckPath = resolveHealthCheckPath(options.healthCheck, true);
|
|
123
143
|
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
registerTableRoutes(app, db, tableKey, entry, {
|
|
130
|
-
backend,
|
|
131
|
-
operationsLogConfig,
|
|
132
|
-
operationsLogReady,
|
|
133
|
-
});
|
|
144
|
+
if (healthCheckPath) {
|
|
145
|
+
app.get(healthCheckPath, (context) => {
|
|
146
|
+
return context.json({ ok: true });
|
|
147
|
+
});
|
|
148
|
+
}
|
|
134
149
|
}
|
|
135
150
|
|
|
151
|
+
// The single mutation ingress point — all writes go through POST /api/mutations
|
|
136
152
|
registerBulkMutationRoute(
|
|
137
153
|
app,
|
|
138
154
|
db,
|
|
@@ -157,6 +173,10 @@ export function createSyncServer<TRegistry extends SyncTableRegistry>(
|
|
|
157
173
|
return;
|
|
158
174
|
}
|
|
159
175
|
|
|
176
|
+
if (!ownsApp) {
|
|
177
|
+
throw new Error("createSyncServer.start() requires pgxsinkit to own the Hono app (no external app provided)");
|
|
178
|
+
}
|
|
179
|
+
|
|
160
180
|
const bun = getBunNamespace();
|
|
161
181
|
if (!bun) {
|
|
162
182
|
throw new Error("createSyncServer.start() requires the Bun runtime");
|
|
@@ -183,7 +203,7 @@ export function createSyncServer<TRegistry extends SyncTableRegistry>(
|
|
|
183
203
|
bunServer?.stop();
|
|
184
204
|
bunServer = undefined;
|
|
185
205
|
status.isRunning = false;
|
|
186
|
-
await
|
|
206
|
+
await pgClient?.end();
|
|
187
207
|
options.onStatusChange?.(status);
|
|
188
208
|
},
|
|
189
209
|
status,
|
|
@@ -193,7 +213,6 @@ export function createSyncServer<TRegistry extends SyncTableRegistry>(
|
|
|
193
213
|
diagnostics: () => ({
|
|
194
214
|
tables: Object.keys(options.registry) as Array<keyof TRegistry & string>,
|
|
195
215
|
modes: Object.fromEntries(Object.entries(options.registry).map(([key, entry]) => [key, entry.mode])),
|
|
196
|
-
routes: Object.fromEntries(Object.entries(options.registry).map(([key, entry]) => [key, entry.routes])),
|
|
197
216
|
}),
|
|
198
217
|
};
|
|
199
218
|
}
|
|
@@ -219,379 +238,20 @@ function buildSchema<TRegistry extends SyncTableRegistry>(registry: TRegistry) {
|
|
|
219
238
|
) as RegistryTables<TRegistry>;
|
|
220
239
|
}
|
|
221
240
|
|
|
222
|
-
function
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
) {
|
|
226
|
-
const relations = defineRelations(schema) as RegistryRelations<TRegistry>;
|
|
227
|
-
|
|
228
|
-
const createDatabase = drizzle as unknown as (config: {
|
|
229
|
-
client: ReturnType<typeof createPostgresClient>;
|
|
230
|
-
relations: RegistryRelations<TRegistry>;
|
|
231
|
-
}) => PostgresJsDatabase<RegistryRelations<TRegistry>>;
|
|
232
|
-
|
|
233
|
-
return createDatabase({ client, relations });
|
|
234
|
-
}
|
|
235
|
-
|
|
236
|
-
function registerTableRoutes<TRegistry extends SyncTableRegistry>(
|
|
237
|
-
app: Hono,
|
|
238
|
-
db: PostgresJsDatabase<RegistryRelations<TRegistry>>,
|
|
239
|
-
tableKey: string,
|
|
240
|
-
entry: SyncTableEntry<AnyPgTable>,
|
|
241
|
-
options: {
|
|
242
|
-
backend: OpsLogBackend;
|
|
243
|
-
operationsLogConfig: OperationsLogConfig;
|
|
244
|
-
operationsLogReady: Promise<void>;
|
|
245
|
-
},
|
|
246
|
-
) {
|
|
247
|
-
const basePath = entry.routes?.basePath;
|
|
248
|
-
|
|
249
|
-
if (!basePath) {
|
|
250
|
-
return;
|
|
251
|
-
}
|
|
252
|
-
|
|
253
|
-
const primaryKeyColumnName = getSinglePrimaryKeyColumnName(entry, tableKey);
|
|
254
|
-
const primaryKeyColumn = getTableColumn(entry.table, primaryKeyColumnName, tableKey);
|
|
255
|
-
const crudWritesAllowed = options.backend !== "bulk-plpgsql-artifact";
|
|
256
|
-
|
|
257
|
-
if (entry.mode !== "writeonly") {
|
|
258
|
-
app.get(basePath, async (context) => {
|
|
259
|
-
const rows = await db.select().from(entry.table);
|
|
260
|
-
return context.json(parseRows(entry, rows));
|
|
261
|
-
});
|
|
262
|
-
}
|
|
263
|
-
|
|
264
|
-
if (entry.mode !== "readonly") {
|
|
265
|
-
if (!crudWritesAllowed) {
|
|
266
|
-
registerMethodNotAllowed(app, basePath, ["POST", "PATCH", "DELETE"], tableKey);
|
|
267
|
-
registerMethodNotAllowed(app, `${basePath}/:id`, ["PATCH", "DELETE"], tableKey);
|
|
268
|
-
return;
|
|
269
|
-
}
|
|
270
|
-
|
|
271
|
-
app.post(basePath, async (context) => {
|
|
272
|
-
await options.operationsLogReady;
|
|
273
|
-
|
|
274
|
-
const requestBody = await context.req.json();
|
|
275
|
-
let payload: unknown;
|
|
276
|
-
|
|
277
|
-
try {
|
|
278
|
-
payload = parseCreatePayload(entry, requestBody);
|
|
279
|
-
} catch (error) {
|
|
280
|
-
await logOperationSafely(db, options.operationsLogConfig, {
|
|
281
|
-
source: "crud",
|
|
282
|
-
backend: options.backend,
|
|
283
|
-
tableName: tableKey,
|
|
284
|
-
operationKind: "create",
|
|
285
|
-
entityKey: extractEntityKeyFromRecord(entry, requestBody),
|
|
286
|
-
payload: requestBody,
|
|
287
|
-
status: "validation_failed",
|
|
288
|
-
errorMessage: error instanceof Error ? error.message : "Validation failed",
|
|
289
|
-
httpStatus: 400,
|
|
290
|
-
requestPath: context.req.path,
|
|
291
|
-
});
|
|
292
|
-
|
|
293
|
-
return context.json(
|
|
294
|
-
{
|
|
295
|
-
message: "Validation failed",
|
|
296
|
-
issues: isValidationError(error) ? error.issues : [],
|
|
297
|
-
},
|
|
298
|
-
400,
|
|
299
|
-
);
|
|
300
|
-
}
|
|
301
|
-
|
|
302
|
-
try {
|
|
303
|
-
const insertedRow = await db.transaction(async (tx) => {
|
|
304
|
-
const inserted = await tx
|
|
305
|
-
.insert(entry.table)
|
|
306
|
-
.values(payload as never)
|
|
307
|
-
.returning();
|
|
308
|
-
|
|
309
|
-
const row = inserted[0];
|
|
310
|
-
if (!row) {
|
|
311
|
-
throw new Error(`Failed to insert ${tableKey}`);
|
|
312
|
-
}
|
|
313
|
-
|
|
314
|
-
await logOperation(tx, options.operationsLogConfig, {
|
|
315
|
-
source: "crud",
|
|
316
|
-
backend: options.backend,
|
|
317
|
-
tableName: tableKey,
|
|
318
|
-
operationKind: "create",
|
|
319
|
-
entityKey: extractEntityKeyFromRecord(entry, row),
|
|
320
|
-
payload,
|
|
321
|
-
status: "succeeded",
|
|
322
|
-
httpStatus: 201,
|
|
323
|
-
requestPath: context.req.path,
|
|
324
|
-
});
|
|
325
|
-
|
|
326
|
-
return row;
|
|
327
|
-
});
|
|
328
|
-
|
|
329
|
-
return context.json(parseRow(entry, insertedRow), 201);
|
|
330
|
-
} catch (error) {
|
|
331
|
-
await logOperationSafely(db, options.operationsLogConfig, {
|
|
332
|
-
source: "crud",
|
|
333
|
-
backend: options.backend,
|
|
334
|
-
tableName: tableKey,
|
|
335
|
-
operationKind: "create",
|
|
336
|
-
entityKey: extractEntityKeyFromRecord(entry, payload),
|
|
337
|
-
payload,
|
|
338
|
-
status: "execution_failed",
|
|
339
|
-
errorMessage: error instanceof Error ? error.message : "Execution failed",
|
|
340
|
-
httpStatus: 500,
|
|
341
|
-
requestPath: context.req.path,
|
|
342
|
-
});
|
|
343
|
-
|
|
344
|
-
throw error;
|
|
345
|
-
}
|
|
346
|
-
});
|
|
347
|
-
|
|
348
|
-
app.patch(`${basePath}/:id`, async (context) => {
|
|
349
|
-
await options.operationsLogReady;
|
|
350
|
-
|
|
351
|
-
const id = context.req.param("id");
|
|
352
|
-
const entityKey = {
|
|
353
|
-
[primaryKeyColumnName]: id,
|
|
354
|
-
};
|
|
355
|
-
const requestBody = await context.req.json();
|
|
356
|
-
let payload: unknown;
|
|
357
|
-
|
|
358
|
-
try {
|
|
359
|
-
payload = parseUpdatePayload(entry, requestBody);
|
|
360
|
-
} catch (error) {
|
|
361
|
-
await logOperationSafely(db, options.operationsLogConfig, {
|
|
362
|
-
source: "crud",
|
|
363
|
-
backend: options.backend,
|
|
364
|
-
tableName: tableKey,
|
|
365
|
-
operationKind: "update",
|
|
366
|
-
entityKey,
|
|
367
|
-
payload: requestBody,
|
|
368
|
-
status: "validation_failed",
|
|
369
|
-
errorMessage: error instanceof Error ? error.message : "Validation failed",
|
|
370
|
-
httpStatus: 400,
|
|
371
|
-
requestPath: context.req.path,
|
|
372
|
-
});
|
|
373
|
-
|
|
374
|
-
return context.json(
|
|
375
|
-
{
|
|
376
|
-
message: "Validation failed",
|
|
377
|
-
issues: isValidationError(error) ? error.issues : [],
|
|
378
|
-
},
|
|
379
|
-
400,
|
|
380
|
-
);
|
|
381
|
-
}
|
|
382
|
-
|
|
383
|
-
try {
|
|
384
|
-
const updatedRow = await db.transaction(async (tx) => {
|
|
385
|
-
const updated = await tx
|
|
386
|
-
.update(entry.table)
|
|
387
|
-
.set(withUpdatedAtUs(entry.table, payload))
|
|
388
|
-
.where(eq(primaryKeyColumn, id))
|
|
389
|
-
.returning();
|
|
390
|
-
|
|
391
|
-
if (updated.length === 0) {
|
|
392
|
-
await logOperation(tx, options.operationsLogConfig, {
|
|
393
|
-
source: "crud",
|
|
394
|
-
backend: options.backend,
|
|
395
|
-
tableName: tableKey,
|
|
396
|
-
operationKind: "update",
|
|
397
|
-
entityKey,
|
|
398
|
-
payload,
|
|
399
|
-
status: "not_found",
|
|
400
|
-
httpStatus: 404,
|
|
401
|
-
requestPath: context.req.path,
|
|
402
|
-
});
|
|
403
|
-
|
|
404
|
-
return null;
|
|
405
|
-
}
|
|
406
|
-
|
|
407
|
-
const row = updated[0]!;
|
|
408
|
-
|
|
409
|
-
await logOperation(tx, options.operationsLogConfig, {
|
|
410
|
-
source: "crud",
|
|
411
|
-
backend: options.backend,
|
|
412
|
-
tableName: tableKey,
|
|
413
|
-
operationKind: "update",
|
|
414
|
-
entityKey: extractEntityKeyFromRecord(entry, row) ?? entityKey,
|
|
415
|
-
payload,
|
|
416
|
-
status: "succeeded",
|
|
417
|
-
httpStatus: 200,
|
|
418
|
-
requestPath: context.req.path,
|
|
419
|
-
});
|
|
420
|
-
|
|
421
|
-
return row;
|
|
422
|
-
});
|
|
423
|
-
|
|
424
|
-
if (updatedRow === null) {
|
|
425
|
-
return context.json({ message: `${tableKey} record not found` }, 404);
|
|
426
|
-
}
|
|
427
|
-
|
|
428
|
-
return context.json(parseRow(entry, updatedRow));
|
|
429
|
-
} catch (error) {
|
|
430
|
-
await logOperationSafely(db, options.operationsLogConfig, {
|
|
431
|
-
source: "crud",
|
|
432
|
-
backend: options.backend,
|
|
433
|
-
tableName: tableKey,
|
|
434
|
-
operationKind: "update",
|
|
435
|
-
entityKey,
|
|
436
|
-
payload,
|
|
437
|
-
status: "execution_failed",
|
|
438
|
-
errorMessage: error instanceof Error ? error.message : "Execution failed",
|
|
439
|
-
httpStatus: 500,
|
|
440
|
-
requestPath: context.req.path,
|
|
441
|
-
});
|
|
442
|
-
|
|
443
|
-
throw error;
|
|
444
|
-
}
|
|
445
|
-
});
|
|
446
|
-
|
|
447
|
-
app.delete(`${basePath}/:id`, async (context) => {
|
|
448
|
-
await options.operationsLogReady;
|
|
449
|
-
|
|
450
|
-
const id = context.req.param("id");
|
|
451
|
-
const entityKey = {
|
|
452
|
-
[primaryKeyColumnName]: id,
|
|
453
|
-
};
|
|
454
|
-
|
|
455
|
-
try {
|
|
456
|
-
const deleted = await db.transaction(async (tx) => {
|
|
457
|
-
const deletedRows = await tx.delete(entry.table).where(eq(primaryKeyColumn, id)).returning();
|
|
458
|
-
|
|
459
|
-
if (deletedRows.length === 0) {
|
|
460
|
-
await logOperation(tx, options.operationsLogConfig, {
|
|
461
|
-
source: "crud",
|
|
462
|
-
backend: options.backend,
|
|
463
|
-
tableName: tableKey,
|
|
464
|
-
operationKind: "delete",
|
|
465
|
-
entityKey,
|
|
466
|
-
payload: entityKey,
|
|
467
|
-
status: "not_found",
|
|
468
|
-
httpStatus: 404,
|
|
469
|
-
requestPath: context.req.path,
|
|
470
|
-
});
|
|
471
|
-
|
|
472
|
-
return false;
|
|
473
|
-
}
|
|
474
|
-
|
|
475
|
-
await logOperation(tx, options.operationsLogConfig, {
|
|
476
|
-
source: "crud",
|
|
477
|
-
backend: options.backend,
|
|
478
|
-
tableName: tableKey,
|
|
479
|
-
operationKind: "delete",
|
|
480
|
-
entityKey,
|
|
481
|
-
payload: entityKey,
|
|
482
|
-
status: "succeeded",
|
|
483
|
-
httpStatus: 204,
|
|
484
|
-
requestPath: context.req.path,
|
|
485
|
-
});
|
|
486
|
-
|
|
487
|
-
return true;
|
|
488
|
-
});
|
|
489
|
-
|
|
490
|
-
if (!deleted) {
|
|
491
|
-
return context.json({ message: `${tableKey} record not found` }, 404);
|
|
492
|
-
}
|
|
493
|
-
|
|
494
|
-
return context.body(null, 204);
|
|
495
|
-
} catch (error) {
|
|
496
|
-
await logOperationSafely(db, options.operationsLogConfig, {
|
|
497
|
-
source: "crud",
|
|
498
|
-
backend: options.backend,
|
|
499
|
-
tableName: tableKey,
|
|
500
|
-
operationKind: "delete",
|
|
501
|
-
entityKey,
|
|
502
|
-
payload: entityKey,
|
|
503
|
-
status: "execution_failed",
|
|
504
|
-
errorMessage: error instanceof Error ? error.message : "Execution failed",
|
|
505
|
-
httpStatus: 500,
|
|
506
|
-
requestPath: context.req.path,
|
|
507
|
-
});
|
|
508
|
-
|
|
509
|
-
throw error;
|
|
510
|
-
}
|
|
511
|
-
});
|
|
512
|
-
}
|
|
513
|
-
}
|
|
514
|
-
|
|
515
|
-
function getSinglePrimaryKeyColumnName(entry: SyncTableEntry, tableKey: string) {
|
|
516
|
-
if (entry.primaryKey.columns.length !== 1) {
|
|
517
|
-
throw new Error(`@pgxsinkit/server currently supports single-column primary keys only: ${tableKey}`);
|
|
518
|
-
}
|
|
519
|
-
|
|
520
|
-
return entry.primaryKey.columns[0]!;
|
|
521
|
-
}
|
|
522
|
-
|
|
523
|
-
function getTableColumn(table: AnyPgTable, columnName: string, tableKey: string) {
|
|
524
|
-
const column = (table as unknown as Record<string, unknown>)[columnName];
|
|
525
|
-
|
|
526
|
-
if (!column) {
|
|
527
|
-
throw new Error(`Primary key column ${columnName} was not found on table ${tableKey}`);
|
|
528
|
-
}
|
|
529
|
-
|
|
530
|
-
return column as never;
|
|
531
|
-
}
|
|
532
|
-
|
|
533
|
-
function parseCreatePayload(entry: SyncTableEntry, input: unknown) {
|
|
534
|
-
return entry.schemas?.createSchema ? entry.schemas.createSchema.parse(input) : input;
|
|
535
|
-
}
|
|
536
|
-
|
|
537
|
-
function parseUpdatePayload(entry: SyncTableEntry, input: unknown) {
|
|
538
|
-
return entry.schemas?.updateSchema ? entry.schemas.updateSchema.parse(input) : input;
|
|
539
|
-
}
|
|
540
|
-
|
|
541
|
-
function registerMethodNotAllowed(app: Hono, path: string, methods: string[], tableKey: string) {
|
|
542
|
-
for (const method of methods) {
|
|
543
|
-
app.on(method as "POST" | "PATCH" | "DELETE", path, (context) => {
|
|
544
|
-
context.header("Allow", "GET, OPTIONS");
|
|
545
|
-
|
|
546
|
-
return context.json(
|
|
547
|
-
{
|
|
548
|
-
message: `CRUD ${method} routes are disabled for ${tableKey} when WRITE_API_BACKEND=bulk-plpgsql-artifact. Use POST /api/mutations instead.`,
|
|
549
|
-
},
|
|
550
|
-
405,
|
|
551
|
-
);
|
|
552
|
-
});
|
|
553
|
-
}
|
|
554
|
-
}
|
|
555
|
-
|
|
556
|
-
function parseRows(entry: SyncTableEntry, rows: unknown[]) {
|
|
557
|
-
return rows.map((row) => parseRow(entry, row));
|
|
558
|
-
}
|
|
559
|
-
|
|
560
|
-
function parseRow(entry: SyncTableEntry, row: unknown) {
|
|
561
|
-
const normalized = normalizeBigInts(row);
|
|
562
|
-
return entry.schemas?.recordSchema ? entry.schemas.recordSchema.parse(normalized) : normalized;
|
|
563
|
-
}
|
|
564
|
-
|
|
565
|
-
function withUpdatedAtUs(table: AnyPgTable, payload: unknown) {
|
|
566
|
-
const values = {
|
|
567
|
-
...(isRecord(payload) ? payload : {}),
|
|
568
|
-
};
|
|
569
|
-
|
|
570
|
-
if ("updatedAtUs" in table) {
|
|
571
|
-
values.updatedAtUs = sql`CAST(FLOOR(EXTRACT(EPOCH FROM clock_timestamp()) * 1000000) AS BIGINT)`;
|
|
572
|
-
}
|
|
573
|
-
|
|
574
|
-
return values as never;
|
|
575
|
-
}
|
|
576
|
-
|
|
577
|
-
function normalizeBigInts(value: unknown): unknown {
|
|
578
|
-
if (typeof value === "bigint") {
|
|
579
|
-
return value.toString();
|
|
241
|
+
function resolveHealthCheckPath(config?: boolean | { path: string }, defaultEnabled = false): string | null {
|
|
242
|
+
if (config === false) {
|
|
243
|
+
return null;
|
|
580
244
|
}
|
|
581
245
|
|
|
582
|
-
if (
|
|
583
|
-
return
|
|
246
|
+
if (config === undefined && !defaultEnabled) {
|
|
247
|
+
return null;
|
|
584
248
|
}
|
|
585
249
|
|
|
586
|
-
if (
|
|
587
|
-
return
|
|
250
|
+
if (typeof config === "object" && "path" in config) {
|
|
251
|
+
return config.path;
|
|
588
252
|
}
|
|
589
253
|
|
|
590
|
-
return
|
|
591
|
-
}
|
|
592
|
-
|
|
593
|
-
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
594
|
-
return typeof value === "object" && value !== null;
|
|
254
|
+
return "/health";
|
|
595
255
|
}
|
|
596
256
|
|
|
597
257
|
function getBunNamespace(): BunNamespace | undefined {
|
|
@@ -609,34 +269,8 @@ function resolveOperationsLogConfig(options?: { enabled?: boolean }): Operations
|
|
|
609
269
|
};
|
|
610
270
|
}
|
|
611
271
|
|
|
612
|
-
|
|
613
|
-
if (!isRecord(value)) {
|
|
614
|
-
return null;
|
|
615
|
-
}
|
|
616
|
-
|
|
617
|
-
const entityKey: Record<string, string> = {};
|
|
618
|
-
|
|
619
|
-
for (const primaryKeyColumn of entry.primaryKey.columns) {
|
|
620
|
-
const rawValue = value[primaryKeyColumn];
|
|
621
|
-
|
|
622
|
-
if (rawValue === undefined || rawValue === null) {
|
|
623
|
-
return null;
|
|
624
|
-
}
|
|
625
|
-
|
|
626
|
-
if (
|
|
627
|
-
typeof rawValue === "string" ||
|
|
628
|
-
typeof rawValue === "number" ||
|
|
629
|
-
typeof rawValue === "bigint" ||
|
|
630
|
-
typeof rawValue === "boolean"
|
|
631
|
-
) {
|
|
632
|
-
entityKey[primaryKeyColumn] = String(rawValue);
|
|
633
|
-
continue;
|
|
634
|
-
}
|
|
635
|
-
|
|
636
|
-
return null;
|
|
637
|
-
}
|
|
638
|
-
|
|
639
|
-
return entityKey;
|
|
640
|
-
}
|
|
641
|
-
|
|
272
|
+
export { registerBulkMutationRoute } from "./mutations/bulk/route";
|
|
642
273
|
export { buildPlpgsqlBatchFunctionDdl } from "./mutations/bulk/plpgsql-strategy";
|
|
274
|
+
export { ensureOperationsLogSchema } from "./operations-log/ddl";
|
|
275
|
+
export { proxyElectricShapeRequest } from "./electric-proxy";
|
|
276
|
+
export type { ElectricProxyOptions } from "./electric-proxy";
|
|
@@ -2,7 +2,7 @@ import { getTableName, sql } from "drizzle-orm";
|
|
|
2
2
|
import type { AnyPgTable } from "drizzle-orm/pg-core";
|
|
3
3
|
import type { PostgresJsDatabase } from "drizzle-orm/postgres-js";
|
|
4
4
|
import { getColumns } from "drizzle-orm/utils";
|
|
5
|
-
import type { Hono } from "hono";
|
|
5
|
+
import type { Context, Hono } from "hono";
|
|
6
6
|
|
|
7
7
|
import type {
|
|
8
8
|
BatchMutationRequest,
|
|
@@ -31,6 +31,7 @@ export function registerBulkMutationRoute<TRegistry extends SyncTableRegistry>(
|
|
|
31
31
|
resolveAuthClaims?: (request: Request) => Promise<Record<string, unknown> | null> | Record<string, unknown> | null,
|
|
32
32
|
) {
|
|
33
33
|
let startupReadyPromise: Promise<void> | undefined;
|
|
34
|
+
const batchMutationPaths = ["/api/mutations", "/mutations"] as const;
|
|
34
35
|
|
|
35
36
|
const startupReady = () => {
|
|
36
37
|
if (!startupReadyPromise) {
|
|
@@ -40,7 +41,7 @@ export function registerBulkMutationRoute<TRegistry extends SyncTableRegistry>(
|
|
|
40
41
|
return startupReadyPromise;
|
|
41
42
|
};
|
|
42
43
|
|
|
43
|
-
|
|
44
|
+
const handleBatchMutation = async (context: Context) => {
|
|
44
45
|
await Promise.all([startupReady(), operationsLogReady]);
|
|
45
46
|
|
|
46
47
|
let rawBody: unknown;
|
|
@@ -284,7 +285,11 @@ export function registerBulkMutationRoute<TRegistry extends SyncTableRegistry>(
|
|
|
284
285
|
}
|
|
285
286
|
|
|
286
287
|
return context.json({ acks });
|
|
287
|
-
}
|
|
288
|
+
};
|
|
289
|
+
|
|
290
|
+
for (const path of batchMutationPaths) {
|
|
291
|
+
app.post(path, handleBatchMutation);
|
|
292
|
+
}
|
|
288
293
|
}
|
|
289
294
|
|
|
290
295
|
function isValidationError(error: unknown): error is { issues: unknown[] } {
|