@pgxsinkit/server 0.1.7 → 0.1.9
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/dist/index.js
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
2
|
// packages/server/src/index.ts
|
|
3
|
-
import { eq, sql as sql5 } from "drizzle-orm";
|
|
4
3
|
import { drizzle } from "drizzle-orm/postgres-js";
|
|
5
4
|
import { defineRelations } from "drizzle-orm/relations";
|
|
6
5
|
import { Hono } from "hono";
|
|
@@ -359,13 +358,14 @@ async function executePlpgsqlBatch(tx, batch, requestPath, logEnabled, rlsEnable
|
|
|
359
358
|
// packages/server/src/mutations/bulk/route.ts
|
|
360
359
|
function registerBulkMutationRoute(app, db, registry, backend, operationsLogConfig, operationsLogReady, resolveAuthClaims) {
|
|
361
360
|
let startupReadyPromise;
|
|
361
|
+
const batchMutationPaths = ["/api/mutations", "/mutations"];
|
|
362
362
|
const startupReady = () => {
|
|
363
363
|
if (!startupReadyPromise) {
|
|
364
364
|
startupReadyPromise = installBulkStartupDdl(db, registry, backend);
|
|
365
365
|
}
|
|
366
366
|
return startupReadyPromise;
|
|
367
367
|
};
|
|
368
|
-
|
|
368
|
+
const handleBatchMutation = async (context) => {
|
|
369
369
|
await Promise.all([startupReady(), operationsLogReady]);
|
|
370
370
|
let rawBody;
|
|
371
371
|
try {
|
|
@@ -555,7 +555,10 @@ function registerBulkMutationRoute(app, db, registry, backend, operationsLogConf
|
|
|
555
555
|
return context.json({ message: errorMessage }, 500);
|
|
556
556
|
}
|
|
557
557
|
return context.json({ acks });
|
|
558
|
-
}
|
|
558
|
+
};
|
|
559
|
+
for (const path of batchMutationPaths) {
|
|
560
|
+
app.post(path, handleBatchMutation);
|
|
561
|
+
}
|
|
559
562
|
}
|
|
560
563
|
function isValidationError(error) {
|
|
561
564
|
return typeof error === "object" && error !== null && "issues" in error && Array.isArray(error.issues);
|
|
@@ -745,14 +748,160 @@ async function ensureOperationsLogSchema(db, config) {
|
|
|
745
748
|
throw new Error("operations_log table is missing. Run bun run db:push before starting the write API.");
|
|
746
749
|
}
|
|
747
750
|
}
|
|
751
|
+
// packages/server/src/electric-proxy.ts
|
|
752
|
+
import { buildRowFilterWhere, getOmittedProjectedColumnNames } from "@pgxsinkit/contracts";
|
|
753
|
+
async function proxyElectricShapeRequest(request, claims, options) {
|
|
754
|
+
const targetUrl = buildProxyTargetUrl(request, claims, options);
|
|
755
|
+
const response = await fetch(targetUrl, {
|
|
756
|
+
method: "GET",
|
|
757
|
+
headers: buildForwardHeaders(request.headers),
|
|
758
|
+
signal: request.signal
|
|
759
|
+
});
|
|
760
|
+
const headers = new Headers(response.headers);
|
|
761
|
+
headers.set("Cache-Control", "private, no-store, no-cache, must-revalidate, max-age=0");
|
|
762
|
+
headers.set("Pragma", "no-cache");
|
|
763
|
+
headers.set("Expires", "0");
|
|
764
|
+
headers.set("Vary", appendVaryHeader(headers.get("Vary"), "Authorization"));
|
|
765
|
+
const table = new URL(request.url).searchParams.get("table");
|
|
766
|
+
const omittedColumns = table ? getOmittedProjectedColumnsForTable(options.registry, table) : [];
|
|
767
|
+
const contentType = headers.get("content-type") ?? "";
|
|
768
|
+
if (omittedColumns.length > 0 && contentType.includes("application/json")) {
|
|
769
|
+
const payload = await response.clone().json().catch(() => {
|
|
770
|
+
return;
|
|
771
|
+
});
|
|
772
|
+
if (Array.isArray(payload)) {
|
|
773
|
+
const stripped = stripOmittedColumnsFromShapeLogEntries(payload, omittedColumns);
|
|
774
|
+
return new Response(JSON.stringify(stripped), {
|
|
775
|
+
status: response.status,
|
|
776
|
+
statusText: response.statusText,
|
|
777
|
+
headers
|
|
778
|
+
});
|
|
779
|
+
}
|
|
780
|
+
}
|
|
781
|
+
return new Response(response.body, {
|
|
782
|
+
status: response.status,
|
|
783
|
+
statusText: response.statusText,
|
|
784
|
+
headers
|
|
785
|
+
});
|
|
786
|
+
}
|
|
787
|
+
function buildProxyTargetUrl(request, claims, options) {
|
|
788
|
+
const requestUrl = new URL(request.url);
|
|
789
|
+
const targetUrl = new URL(options.electricUrl);
|
|
790
|
+
targetUrl.search = requestUrl.search;
|
|
791
|
+
const table = targetUrl.searchParams.get("table");
|
|
792
|
+
if (!table) {
|
|
793
|
+
return targetUrl.toString();
|
|
794
|
+
}
|
|
795
|
+
const entry = getRegistryEntry(options.registry, table);
|
|
796
|
+
if (!entry) {
|
|
797
|
+
return targetUrl.toString();
|
|
798
|
+
}
|
|
799
|
+
const rowFilter = entry.shape?.rowFilter;
|
|
800
|
+
if (!rowFilter) {
|
|
801
|
+
return targetUrl.toString();
|
|
802
|
+
}
|
|
803
|
+
const whereClause = buildRowFilterWhere(rowFilter, claims, options.extraParams);
|
|
804
|
+
if (!whereClause) {
|
|
805
|
+
return targetUrl.toString();
|
|
806
|
+
}
|
|
807
|
+
const existingWhere = targetUrl.searchParams.get("where");
|
|
808
|
+
if (!existingWhere) {
|
|
809
|
+
targetUrl.searchParams.set("where", whereClause);
|
|
810
|
+
} else {
|
|
811
|
+
targetUrl.searchParams.set("where", `(${existingWhere}) AND (${whereClause})`);
|
|
812
|
+
}
|
|
813
|
+
if (rowFilter.columns && rowFilter.columns.length > 0) {
|
|
814
|
+
targetUrl.searchParams.set("columns", rowFilter.columns.join(","));
|
|
815
|
+
}
|
|
816
|
+
return targetUrl.toString();
|
|
817
|
+
}
|
|
818
|
+
function getRegistryEntry(registry, table) {
|
|
819
|
+
const parts = table.split(".");
|
|
820
|
+
const key = parts.at(-1) ?? table;
|
|
821
|
+
return registry[key];
|
|
822
|
+
}
|
|
823
|
+
function getOmittedProjectedColumnsForTable(registry, table) {
|
|
824
|
+
const entry = getRegistryEntry(registry, table);
|
|
825
|
+
return entry ? getOmittedProjectedColumnNames(entry) : [];
|
|
826
|
+
}
|
|
827
|
+
function buildForwardHeaders(headers) {
|
|
828
|
+
const next = new Headers;
|
|
829
|
+
for (const [name, value] of headers.entries()) {
|
|
830
|
+
const lower = name.toLowerCase();
|
|
831
|
+
if (lower === "host" || lower === "authorization") {
|
|
832
|
+
continue;
|
|
833
|
+
}
|
|
834
|
+
next.set(name, value);
|
|
835
|
+
}
|
|
836
|
+
return next;
|
|
837
|
+
}
|
|
838
|
+
function appendVaryHeader(existingValue, nextValue) {
|
|
839
|
+
if (!existingValue) {
|
|
840
|
+
return nextValue;
|
|
841
|
+
}
|
|
842
|
+
const values = existingValue.split(",").map((value) => value.trim()).filter((value) => value.length > 0);
|
|
843
|
+
if (values.includes(nextValue)) {
|
|
844
|
+
return values.join(", ");
|
|
845
|
+
}
|
|
846
|
+
values.push(nextValue);
|
|
847
|
+
return values.join(", ");
|
|
848
|
+
}
|
|
849
|
+
function isObjectRecord(value) {
|
|
850
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
851
|
+
}
|
|
852
|
+
function stripOmittedColumnsFromShapeLogEntries(payload, omittedColumns) {
|
|
853
|
+
return payload.map((entry) => {
|
|
854
|
+
if (!isObjectRecord(entry)) {
|
|
855
|
+
return entry;
|
|
856
|
+
}
|
|
857
|
+
let nextEntry = null;
|
|
858
|
+
if (isObjectRecord(entry.value)) {
|
|
859
|
+
const nextValue = omitColumnsFromRow(entry.value, omittedColumns);
|
|
860
|
+
if (nextValue !== entry.value) {
|
|
861
|
+
nextEntry = { ...entry, value: nextValue };
|
|
862
|
+
}
|
|
863
|
+
}
|
|
864
|
+
const currentEntry = nextEntry ?? entry;
|
|
865
|
+
if (isObjectRecord(currentEntry.old_value)) {
|
|
866
|
+
const nextOldValue = omitColumnsFromRow(currentEntry.old_value, omittedColumns);
|
|
867
|
+
if (nextOldValue !== currentEntry.old_value) {
|
|
868
|
+
return { ...currentEntry, old_value: nextOldValue };
|
|
869
|
+
}
|
|
870
|
+
}
|
|
871
|
+
return currentEntry;
|
|
872
|
+
});
|
|
873
|
+
}
|
|
874
|
+
function omitColumnsFromRow(row, omittedColumns) {
|
|
875
|
+
let changed = false;
|
|
876
|
+
const nextRow = { ...row };
|
|
877
|
+
for (const column of omittedColumns) {
|
|
878
|
+
if (Object.prototype.hasOwnProperty.call(nextRow, column)) {
|
|
879
|
+
delete nextRow[column];
|
|
880
|
+
changed = true;
|
|
881
|
+
}
|
|
882
|
+
}
|
|
883
|
+
return changed ? nextRow : row;
|
|
884
|
+
}
|
|
748
885
|
|
|
749
886
|
// packages/server/src/index.ts
|
|
750
887
|
var defaultAllowedOrigins = ["http://localhost:5173", "http://localhost:5174"];
|
|
751
888
|
function createSyncServer(options) {
|
|
752
|
-
const
|
|
753
|
-
const
|
|
754
|
-
|
|
755
|
-
|
|
889
|
+
const ownsApp = !options.app;
|
|
890
|
+
const ownsDb = !options.db;
|
|
891
|
+
if (!ownsDb && !options.databaseUrl) {
|
|
892
|
+
throw new Error("createSyncServer requires either db or databaseUrl");
|
|
893
|
+
}
|
|
894
|
+
let pgClient;
|
|
895
|
+
let db;
|
|
896
|
+
if (options.db) {
|
|
897
|
+
db = options.db;
|
|
898
|
+
} else {
|
|
899
|
+
pgClient = createPostgresClient(options.databaseUrl);
|
|
900
|
+
const schema = buildSchema(options.registry);
|
|
901
|
+
const relations = defineRelations(schema);
|
|
902
|
+
db = drizzle({ client: pgClient, relations });
|
|
903
|
+
}
|
|
904
|
+
const app = options.app ?? new Hono;
|
|
756
905
|
let bunServer;
|
|
757
906
|
const status = {
|
|
758
907
|
phase: "ready",
|
|
@@ -762,48 +911,49 @@ function createSyncServer(options) {
|
|
|
762
911
|
const operationsLogConfig = resolveOperationsLogConfig(options.operationsLog);
|
|
763
912
|
const operationsLogReady = ensureOperationsLogSchema(db, operationsLogConfig);
|
|
764
913
|
const backend = options.backend ?? "bulk-plpgsql-artifact";
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
914
|
+
if (ownsApp) {
|
|
915
|
+
app.use("/api/*", cors({
|
|
916
|
+
origin: options.allowedOrigins ?? defaultAllowedOrigins,
|
|
917
|
+
allowMethods: ["GET", "POST", "OPTIONS"],
|
|
918
|
+
allowHeaders: ["Content-Type", "Authorization"]
|
|
919
|
+
}));
|
|
920
|
+
app.onError((error, context) => {
|
|
921
|
+
status.phase = "degraded";
|
|
922
|
+
status.lastError = error instanceof Error ? error.message : "Unexpected error";
|
|
923
|
+
options.onStatusChange?.(status);
|
|
924
|
+
if (isValidationError2(error)) {
|
|
925
|
+
return context.json({
|
|
926
|
+
message: "Validation failed",
|
|
927
|
+
issues: error.issues
|
|
928
|
+
}, 400);
|
|
929
|
+
}
|
|
775
930
|
return context.json({
|
|
776
|
-
message: "
|
|
777
|
-
|
|
778
|
-
}, 400);
|
|
779
|
-
}
|
|
780
|
-
return context.json({
|
|
781
|
-
message: error instanceof Error ? error.message : "Unexpected error"
|
|
782
|
-
}, 500);
|
|
783
|
-
});
|
|
784
|
-
app.get("/health", (context) => {
|
|
785
|
-
return context.json({ ok: true });
|
|
786
|
-
});
|
|
787
|
-
for (const [tableKey, entry] of Object.entries(options.registry)) {
|
|
788
|
-
registerTableRoutes(app, db, tableKey, entry, {
|
|
789
|
-
backend,
|
|
790
|
-
operationsLogConfig,
|
|
791
|
-
operationsLogReady
|
|
931
|
+
message: error instanceof Error ? error.message : "Unexpected error"
|
|
932
|
+
}, 500);
|
|
792
933
|
});
|
|
934
|
+
const healthCheckPath = resolveHealthCheckPath(options.healthCheck, true);
|
|
935
|
+
if (healthCheckPath) {
|
|
936
|
+
app.get(healthCheckPath, (context) => {
|
|
937
|
+
return context.json({ ok: true });
|
|
938
|
+
});
|
|
939
|
+
}
|
|
793
940
|
}
|
|
794
941
|
registerBulkMutationRoute(app, db, options.registry, backend, operationsLogConfig, operationsLogReady, options.resolveAuthClaims);
|
|
795
|
-
const
|
|
942
|
+
const fetch2 = async (request) => app.fetch(request);
|
|
796
943
|
return {
|
|
797
944
|
drizzle: db,
|
|
798
|
-
fetch,
|
|
945
|
+
fetch: fetch2,
|
|
799
946
|
request: (path, init) => {
|
|
800
947
|
const baseUrl = address === null ? "http://localhost" : `http://${address.host}:${address.port}`;
|
|
801
|
-
return
|
|
948
|
+
return fetch2(new Request(new URL(path, baseUrl), init));
|
|
802
949
|
},
|
|
803
950
|
start: async () => {
|
|
804
951
|
if (bunServer) {
|
|
805
952
|
return;
|
|
806
953
|
}
|
|
954
|
+
if (!ownsApp) {
|
|
955
|
+
throw new Error("createSyncServer.start() requires pgxsinkit to own the Hono app (no external app provided)");
|
|
956
|
+
}
|
|
807
957
|
const bun = getBunNamespace();
|
|
808
958
|
if (!bun) {
|
|
809
959
|
throw new Error("createSyncServer.start() requires the Bun runtime");
|
|
@@ -827,7 +977,7 @@ function createSyncServer(options) {
|
|
|
827
977
|
bunServer?.stop();
|
|
828
978
|
bunServer = undefined;
|
|
829
979
|
status.isRunning = false;
|
|
830
|
-
await
|
|
980
|
+
await pgClient?.end();
|
|
831
981
|
options.onStatusChange?.(status);
|
|
832
982
|
},
|
|
833
983
|
status,
|
|
@@ -836,8 +986,7 @@ function createSyncServer(options) {
|
|
|
836
986
|
},
|
|
837
987
|
diagnostics: () => ({
|
|
838
988
|
tables: Object.keys(options.registry),
|
|
839
|
-
modes: Object.fromEntries(Object.entries(options.registry).map(([key, entry]) => [key, entry.mode]))
|
|
840
|
-
routes: Object.fromEntries(Object.entries(options.registry).map(([key, entry]) => [key, entry.routes]))
|
|
989
|
+
modes: Object.fromEntries(Object.entries(options.registry).map(([key, entry]) => [key, entry.mode]))
|
|
841
990
|
})
|
|
842
991
|
};
|
|
843
992
|
}
|
|
@@ -857,288 +1006,17 @@ function createPostgresClient(connectionString) {
|
|
|
857
1006
|
function buildSchema(registry) {
|
|
858
1007
|
return Object.fromEntries(Object.entries(registry).map(([key, entry]) => [key, entry.table]));
|
|
859
1008
|
}
|
|
860
|
-
function
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
return createDatabase({ client, relations });
|
|
864
|
-
}
|
|
865
|
-
function registerTableRoutes(app, db, tableKey, entry, options) {
|
|
866
|
-
const basePath = entry.routes?.basePath;
|
|
867
|
-
if (!basePath) {
|
|
868
|
-
return;
|
|
869
|
-
}
|
|
870
|
-
const primaryKeyColumnName = getSinglePrimaryKeyColumnName(entry, tableKey);
|
|
871
|
-
const primaryKeyColumn = getTableColumn(entry.table, primaryKeyColumnName, tableKey);
|
|
872
|
-
const crudWritesAllowed = options.backend !== "bulk-plpgsql-artifact";
|
|
873
|
-
if (entry.mode !== "writeonly") {
|
|
874
|
-
app.get(basePath, async (context) => {
|
|
875
|
-
const rows = await db.select().from(entry.table);
|
|
876
|
-
return context.json(parseRows(entry, rows));
|
|
877
|
-
});
|
|
878
|
-
}
|
|
879
|
-
if (entry.mode !== "readonly") {
|
|
880
|
-
if (!crudWritesAllowed) {
|
|
881
|
-
registerMethodNotAllowed(app, basePath, ["POST", "PATCH", "DELETE"], tableKey);
|
|
882
|
-
registerMethodNotAllowed(app, `${basePath}/:id`, ["PATCH", "DELETE"], tableKey);
|
|
883
|
-
return;
|
|
884
|
-
}
|
|
885
|
-
app.post(basePath, async (context) => {
|
|
886
|
-
await options.operationsLogReady;
|
|
887
|
-
const requestBody = await context.req.json();
|
|
888
|
-
let payload;
|
|
889
|
-
try {
|
|
890
|
-
payload = parseCreatePayload(entry, requestBody);
|
|
891
|
-
} catch (error) {
|
|
892
|
-
await logOperationSafely(db, options.operationsLogConfig, {
|
|
893
|
-
source: "crud",
|
|
894
|
-
backend: options.backend,
|
|
895
|
-
tableName: tableKey,
|
|
896
|
-
operationKind: "create",
|
|
897
|
-
entityKey: extractEntityKeyFromRecord(entry, requestBody),
|
|
898
|
-
payload: requestBody,
|
|
899
|
-
status: "validation_failed",
|
|
900
|
-
errorMessage: error instanceof Error ? error.message : "Validation failed",
|
|
901
|
-
httpStatus: 400,
|
|
902
|
-
requestPath: context.req.path
|
|
903
|
-
});
|
|
904
|
-
return context.json({
|
|
905
|
-
message: "Validation failed",
|
|
906
|
-
issues: isValidationError2(error) ? error.issues : []
|
|
907
|
-
}, 400);
|
|
908
|
-
}
|
|
909
|
-
try {
|
|
910
|
-
const insertedRow = await db.transaction(async (tx) => {
|
|
911
|
-
const inserted = await tx.insert(entry.table).values(payload).returning();
|
|
912
|
-
const row = inserted[0];
|
|
913
|
-
if (!row) {
|
|
914
|
-
throw new Error(`Failed to insert ${tableKey}`);
|
|
915
|
-
}
|
|
916
|
-
await logOperation(tx, options.operationsLogConfig, {
|
|
917
|
-
source: "crud",
|
|
918
|
-
backend: options.backend,
|
|
919
|
-
tableName: tableKey,
|
|
920
|
-
operationKind: "create",
|
|
921
|
-
entityKey: extractEntityKeyFromRecord(entry, row),
|
|
922
|
-
payload,
|
|
923
|
-
status: "succeeded",
|
|
924
|
-
httpStatus: 201,
|
|
925
|
-
requestPath: context.req.path
|
|
926
|
-
});
|
|
927
|
-
return row;
|
|
928
|
-
});
|
|
929
|
-
return context.json(parseRow(entry, insertedRow), 201);
|
|
930
|
-
} catch (error) {
|
|
931
|
-
await logOperationSafely(db, options.operationsLogConfig, {
|
|
932
|
-
source: "crud",
|
|
933
|
-
backend: options.backend,
|
|
934
|
-
tableName: tableKey,
|
|
935
|
-
operationKind: "create",
|
|
936
|
-
entityKey: extractEntityKeyFromRecord(entry, payload),
|
|
937
|
-
payload,
|
|
938
|
-
status: "execution_failed",
|
|
939
|
-
errorMessage: error instanceof Error ? error.message : "Execution failed",
|
|
940
|
-
httpStatus: 500,
|
|
941
|
-
requestPath: context.req.path
|
|
942
|
-
});
|
|
943
|
-
throw error;
|
|
944
|
-
}
|
|
945
|
-
});
|
|
946
|
-
app.patch(`${basePath}/:id`, async (context) => {
|
|
947
|
-
await options.operationsLogReady;
|
|
948
|
-
const id = context.req.param("id");
|
|
949
|
-
const entityKey = {
|
|
950
|
-
[primaryKeyColumnName]: id
|
|
951
|
-
};
|
|
952
|
-
const requestBody = await context.req.json();
|
|
953
|
-
let payload;
|
|
954
|
-
try {
|
|
955
|
-
payload = parseUpdatePayload(entry, requestBody);
|
|
956
|
-
} catch (error) {
|
|
957
|
-
await logOperationSafely(db, options.operationsLogConfig, {
|
|
958
|
-
source: "crud",
|
|
959
|
-
backend: options.backend,
|
|
960
|
-
tableName: tableKey,
|
|
961
|
-
operationKind: "update",
|
|
962
|
-
entityKey,
|
|
963
|
-
payload: requestBody,
|
|
964
|
-
status: "validation_failed",
|
|
965
|
-
errorMessage: error instanceof Error ? error.message : "Validation failed",
|
|
966
|
-
httpStatus: 400,
|
|
967
|
-
requestPath: context.req.path
|
|
968
|
-
});
|
|
969
|
-
return context.json({
|
|
970
|
-
message: "Validation failed",
|
|
971
|
-
issues: isValidationError2(error) ? error.issues : []
|
|
972
|
-
}, 400);
|
|
973
|
-
}
|
|
974
|
-
try {
|
|
975
|
-
const updatedRow = await db.transaction(async (tx) => {
|
|
976
|
-
const updated = await tx.update(entry.table).set(withUpdatedAtUs(entry.table, payload)).where(eq(primaryKeyColumn, id)).returning();
|
|
977
|
-
if (updated.length === 0) {
|
|
978
|
-
await logOperation(tx, options.operationsLogConfig, {
|
|
979
|
-
source: "crud",
|
|
980
|
-
backend: options.backend,
|
|
981
|
-
tableName: tableKey,
|
|
982
|
-
operationKind: "update",
|
|
983
|
-
entityKey,
|
|
984
|
-
payload,
|
|
985
|
-
status: "not_found",
|
|
986
|
-
httpStatus: 404,
|
|
987
|
-
requestPath: context.req.path
|
|
988
|
-
});
|
|
989
|
-
return null;
|
|
990
|
-
}
|
|
991
|
-
const row = updated[0];
|
|
992
|
-
await logOperation(tx, options.operationsLogConfig, {
|
|
993
|
-
source: "crud",
|
|
994
|
-
backend: options.backend,
|
|
995
|
-
tableName: tableKey,
|
|
996
|
-
operationKind: "update",
|
|
997
|
-
entityKey: extractEntityKeyFromRecord(entry, row) ?? entityKey,
|
|
998
|
-
payload,
|
|
999
|
-
status: "succeeded",
|
|
1000
|
-
httpStatus: 200,
|
|
1001
|
-
requestPath: context.req.path
|
|
1002
|
-
});
|
|
1003
|
-
return row;
|
|
1004
|
-
});
|
|
1005
|
-
if (updatedRow === null) {
|
|
1006
|
-
return context.json({ message: `${tableKey} record not found` }, 404);
|
|
1007
|
-
}
|
|
1008
|
-
return context.json(parseRow(entry, updatedRow));
|
|
1009
|
-
} catch (error) {
|
|
1010
|
-
await logOperationSafely(db, options.operationsLogConfig, {
|
|
1011
|
-
source: "crud",
|
|
1012
|
-
backend: options.backend,
|
|
1013
|
-
tableName: tableKey,
|
|
1014
|
-
operationKind: "update",
|
|
1015
|
-
entityKey,
|
|
1016
|
-
payload,
|
|
1017
|
-
status: "execution_failed",
|
|
1018
|
-
errorMessage: error instanceof Error ? error.message : "Execution failed",
|
|
1019
|
-
httpStatus: 500,
|
|
1020
|
-
requestPath: context.req.path
|
|
1021
|
-
});
|
|
1022
|
-
throw error;
|
|
1023
|
-
}
|
|
1024
|
-
});
|
|
1025
|
-
app.delete(`${basePath}/:id`, async (context) => {
|
|
1026
|
-
await options.operationsLogReady;
|
|
1027
|
-
const id = context.req.param("id");
|
|
1028
|
-
const entityKey = {
|
|
1029
|
-
[primaryKeyColumnName]: id
|
|
1030
|
-
};
|
|
1031
|
-
try {
|
|
1032
|
-
const deleted = await db.transaction(async (tx) => {
|
|
1033
|
-
const deletedRows = await tx.delete(entry.table).where(eq(primaryKeyColumn, id)).returning();
|
|
1034
|
-
if (deletedRows.length === 0) {
|
|
1035
|
-
await logOperation(tx, options.operationsLogConfig, {
|
|
1036
|
-
source: "crud",
|
|
1037
|
-
backend: options.backend,
|
|
1038
|
-
tableName: tableKey,
|
|
1039
|
-
operationKind: "delete",
|
|
1040
|
-
entityKey,
|
|
1041
|
-
payload: entityKey,
|
|
1042
|
-
status: "not_found",
|
|
1043
|
-
httpStatus: 404,
|
|
1044
|
-
requestPath: context.req.path
|
|
1045
|
-
});
|
|
1046
|
-
return false;
|
|
1047
|
-
}
|
|
1048
|
-
await logOperation(tx, options.operationsLogConfig, {
|
|
1049
|
-
source: "crud",
|
|
1050
|
-
backend: options.backend,
|
|
1051
|
-
tableName: tableKey,
|
|
1052
|
-
operationKind: "delete",
|
|
1053
|
-
entityKey,
|
|
1054
|
-
payload: entityKey,
|
|
1055
|
-
status: "succeeded",
|
|
1056
|
-
httpStatus: 204,
|
|
1057
|
-
requestPath: context.req.path
|
|
1058
|
-
});
|
|
1059
|
-
return true;
|
|
1060
|
-
});
|
|
1061
|
-
if (!deleted) {
|
|
1062
|
-
return context.json({ message: `${tableKey} record not found` }, 404);
|
|
1063
|
-
}
|
|
1064
|
-
return context.body(null, 204);
|
|
1065
|
-
} catch (error) {
|
|
1066
|
-
await logOperationSafely(db, options.operationsLogConfig, {
|
|
1067
|
-
source: "crud",
|
|
1068
|
-
backend: options.backend,
|
|
1069
|
-
tableName: tableKey,
|
|
1070
|
-
operationKind: "delete",
|
|
1071
|
-
entityKey,
|
|
1072
|
-
payload: entityKey,
|
|
1073
|
-
status: "execution_failed",
|
|
1074
|
-
errorMessage: error instanceof Error ? error.message : "Execution failed",
|
|
1075
|
-
httpStatus: 500,
|
|
1076
|
-
requestPath: context.req.path
|
|
1077
|
-
});
|
|
1078
|
-
throw error;
|
|
1079
|
-
}
|
|
1080
|
-
});
|
|
1081
|
-
}
|
|
1082
|
-
}
|
|
1083
|
-
function getSinglePrimaryKeyColumnName(entry, tableKey) {
|
|
1084
|
-
if (entry.primaryKey.columns.length !== 1) {
|
|
1085
|
-
throw new Error(`@pgxsinkit/server currently supports single-column primary keys only: ${tableKey}`);
|
|
1086
|
-
}
|
|
1087
|
-
return entry.primaryKey.columns[0];
|
|
1088
|
-
}
|
|
1089
|
-
function getTableColumn(table, columnName, tableKey) {
|
|
1090
|
-
const column = table[columnName];
|
|
1091
|
-
if (!column) {
|
|
1092
|
-
throw new Error(`Primary key column ${columnName} was not found on table ${tableKey}`);
|
|
1093
|
-
}
|
|
1094
|
-
return column;
|
|
1095
|
-
}
|
|
1096
|
-
function parseCreatePayload(entry, input) {
|
|
1097
|
-
return entry.schemas?.createSchema ? entry.schemas.createSchema.parse(input) : input;
|
|
1098
|
-
}
|
|
1099
|
-
function parseUpdatePayload(entry, input) {
|
|
1100
|
-
return entry.schemas?.updateSchema ? entry.schemas.updateSchema.parse(input) : input;
|
|
1101
|
-
}
|
|
1102
|
-
function registerMethodNotAllowed(app, path, methods, tableKey) {
|
|
1103
|
-
for (const method of methods) {
|
|
1104
|
-
app.on(method, path, (context) => {
|
|
1105
|
-
context.header("Allow", "GET, OPTIONS");
|
|
1106
|
-
return context.json({
|
|
1107
|
-
message: `CRUD ${method} routes are disabled for ${tableKey} when WRITE_API_BACKEND=bulk-plpgsql-artifact. Use POST /api/mutations instead.`
|
|
1108
|
-
}, 405);
|
|
1109
|
-
});
|
|
1110
|
-
}
|
|
1111
|
-
}
|
|
1112
|
-
function parseRows(entry, rows) {
|
|
1113
|
-
return rows.map((row) => parseRow(entry, row));
|
|
1114
|
-
}
|
|
1115
|
-
function parseRow(entry, row) {
|
|
1116
|
-
const normalized = normalizeBigInts(row);
|
|
1117
|
-
return entry.schemas?.recordSchema ? entry.schemas.recordSchema.parse(normalized) : normalized;
|
|
1118
|
-
}
|
|
1119
|
-
function withUpdatedAtUs(table, payload) {
|
|
1120
|
-
const values = {
|
|
1121
|
-
...isRecord(payload) ? payload : {}
|
|
1122
|
-
};
|
|
1123
|
-
if ("updatedAtUs" in table) {
|
|
1124
|
-
values.updatedAtUs = sql5`CAST(FLOOR(EXTRACT(EPOCH FROM clock_timestamp()) * 1000000) AS BIGINT)`;
|
|
1125
|
-
}
|
|
1126
|
-
return values;
|
|
1127
|
-
}
|
|
1128
|
-
function normalizeBigInts(value) {
|
|
1129
|
-
if (typeof value === "bigint") {
|
|
1130
|
-
return value.toString();
|
|
1009
|
+
function resolveHealthCheckPath(config, defaultEnabled = false) {
|
|
1010
|
+
if (config === false) {
|
|
1011
|
+
return null;
|
|
1131
1012
|
}
|
|
1132
|
-
if (
|
|
1133
|
-
return
|
|
1013
|
+
if (config === undefined && !defaultEnabled) {
|
|
1014
|
+
return null;
|
|
1134
1015
|
}
|
|
1135
|
-
if (
|
|
1136
|
-
return
|
|
1016
|
+
if (typeof config === "object" && "path" in config) {
|
|
1017
|
+
return config.path;
|
|
1137
1018
|
}
|
|
1138
|
-
return
|
|
1139
|
-
}
|
|
1140
|
-
function isRecord(value) {
|
|
1141
|
-
return typeof value === "object" && value !== null;
|
|
1019
|
+
return "/health";
|
|
1142
1020
|
}
|
|
1143
1021
|
function getBunNamespace() {
|
|
1144
1022
|
const maybeBun = globalThis.Bun;
|
|
@@ -1152,27 +1030,12 @@ function resolveOperationsLogConfig(options) {
|
|
|
1152
1030
|
enabled: options?.enabled ?? true
|
|
1153
1031
|
};
|
|
1154
1032
|
}
|
|
1155
|
-
function extractEntityKeyFromRecord(entry, value) {
|
|
1156
|
-
if (!isRecord(value)) {
|
|
1157
|
-
return null;
|
|
1158
|
-
}
|
|
1159
|
-
const entityKey = {};
|
|
1160
|
-
for (const primaryKeyColumn of entry.primaryKey.columns) {
|
|
1161
|
-
const rawValue = value[primaryKeyColumn];
|
|
1162
|
-
if (rawValue === undefined || rawValue === null) {
|
|
1163
|
-
return null;
|
|
1164
|
-
}
|
|
1165
|
-
if (typeof rawValue === "string" || typeof rawValue === "number" || typeof rawValue === "bigint" || typeof rawValue === "boolean") {
|
|
1166
|
-
entityKey[primaryKeyColumn] = String(rawValue);
|
|
1167
|
-
continue;
|
|
1168
|
-
}
|
|
1169
|
-
return null;
|
|
1170
|
-
}
|
|
1171
|
-
return entityKey;
|
|
1172
|
-
}
|
|
1173
1033
|
export {
|
|
1034
|
+
registerBulkMutationRoute,
|
|
1035
|
+
proxyElectricShapeRequest,
|
|
1036
|
+
ensureOperationsLogSchema,
|
|
1174
1037
|
createSyncServer,
|
|
1175
1038
|
buildPlpgsqlBatchFunctionDdl
|
|
1176
1039
|
};
|
|
1177
1040
|
|
|
1178
|
-
//# debugId=
|
|
1041
|
+
//# debugId=5FBD32E0C3AD739064756E2164756E21
|