Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

refactor(api): type database-error and args-envelope helpers

Raula5d22eaff4c6
diff --git a/apps/erp/app/routes/api+/v1+/lib/args-envelope.test.ts b/apps/erp/app/routes/api+/v1+/lib/args-envelope.test.ts
index 209944f860..6d157aa8b0 100644
--- a/apps/erp/app/routes/api+/v1+/lib/args-envelope.test.ts
+++ b/apps/erp/app/routes/api+/v1+/lib/args-envelope.test.ts
@@ -40,7 +40,7 @@ describe("unwrapArgsEnvelope", () => {
it("does not unwrap a non-object envelope", () => {
for (const value of [null, ["jo_1"], "jobId"]) {
- const body = { args: value } as Record<string, unknown>;
+ const body: Record<string, unknown> = { args: value };
expect(unwrapArgsEnvelope({ schema: flatSchema }, body)).toBe(body);
}
});
diff --git a/apps/erp/app/routes/api+/v1+/lib/args-envelope.ts b/apps/erp/app/routes/api+/v1+/lib/args-envelope.ts
index 51f0c6f274..bda2f01390 100644
--- a/apps/erp/app/routes/api+/v1+/lib/args-envelope.ts
+++ b/apps/erp/app/routes/api+/v1+/lib/args-envelope.ts
@@ -1,17 +1,17 @@
+import type { ManifestEntry } from "@carbon/api";
+
+function isPlainObject(value: unknown): value is Record<string, unknown> {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+
export function unwrapArgsEnvelope(
- meta: { schema?: unknown },
+ meta: Pick<ManifestEntry, "schema">,
args?: Record<string, unknown>
): Record<string, unknown> | undefined {
if (!args) return args;
- const declaresArgs = Boolean(
- (meta.schema as { properties?: Record<string, unknown> } | undefined)
- ?.properties?.args
- );
- if (declaresArgs) return args;
+ const properties = meta.schema.properties;
+ if (isPlainObject(properties) && "args" in properties) return args;
const keys = Object.keys(args);
if (keys.length !== 1 || keys[0] !== "args") return args;
- const envelope = args.args;
- return envelope && typeof envelope === "object" && !Array.isArray(envelope)
- ? (envelope as Record<string, unknown>)
- : args;
+ return isPlainObject(args.args) ? args.args : args;
}
diff --git a/apps/erp/app/routes/api+/v1+/lib/call.server.ts b/apps/erp/app/routes/api+/v1+/lib/call.server.ts
index dcd26bd6c2..a96c9aa2e1 100644
--- a/apps/erp/app/routes/api+/v1+/lib/call.server.ts
+++ b/apps/erp/app/routes/api+/v1+/lib/call.server.ts
@@ -12,7 +12,8 @@ import { unwrapArgsEnvelope } from "./args-envelope";
import type { AuthedContext } from "./base.server";
import {
classifyDatabaseFailure,
- publicDatabaseError
+ publicDatabaseError,
+ type SupabaseFailure
} from "./database-errors";
import {
operationId,
@@ -32,9 +33,14 @@ export type CallResult =
| { success: true; data: unknown; count?: number }
| { success: false; error: string; errorKind: "database" | "execution" };
-async function edgeFunctionMessage(error: unknown): Promise<string | null> {
- const candidate = error as { name?: unknown; context?: unknown };
- if (candidate?.name !== "FunctionsHttpError" || !candidate.context)
+async function edgeFunctionMessage(
+ error: SupabaseFailure
+): Promise<string | null> {
+ if (
+ error.name !== "FunctionsHttpError" ||
+ !("context" in error) ||
+ !error.context
+ )
return null;
const message = await getEdgeFunctionErrorMessage(error, "");
return message === "" ? null : message;
@@ -95,7 +101,7 @@ export async function callOperation(
} catch (err) {
const supabase =
err instanceof ORPCError
- ? (err.data as { supabase?: unknown } | undefined)?.supabase
+ ? (err.data as { supabase?: SupabaseFailure } | undefined)?.supabase
: undefined;
if (supabase) {
const edgeMessage = await edgeFunctionMessage(supabase);
diff --git a/apps/erp/app/routes/api+/v1+/lib/database-errors.test.ts b/apps/erp/app/routes/api+/v1+/lib/database-errors.test.ts
index 4a7252378e..18821b5d0f 100644
--- a/apps/erp/app/routes/api+/v1+/lib/database-errors.test.ts
+++ b/apps/erp/app/routes/api+/v1+/lib/database-errors.test.ts
@@ -1,3 +1,4 @@
+import { FunctionsHttpError, PostgrestError } from "@supabase/supabase-js";
import { describe, expect, it } from "vitest";
import {
classifyDatabaseFailure,
@@ -5,6 +6,20 @@ import {
publicDatabaseError
} from "./database-errors";
+function postgrestError(
+ fields: Partial<ConstructorParameters<typeof PostgrestError>[0]>
+) {
+ return new PostgrestError({
+ message: "",
+ details: "",
+ hint: "",
+ code: "",
+ ...fields
+ });
+}
+
+const edgeFunctionError = new FunctionsHttpError(new Response("{}"));
+
describe("classifyDatabaseFailure", () => {
it.each([
["23505", "conflict"],
@@ -13,26 +28,31 @@ describe("classifyDatabaseFailure", () => {
["42501", "permission"],
["PGRST116", "notFound"]
] as const)("maps SQLSTATE %s to %s", (code, kind) => {
- expect(classifyDatabaseFailure({ code, message: "boom" })).toBe(kind);
+ expect(
+ classifyDatabaseFailure(postgrestError({ code, message: "boom" }))
+ ).toBe(kind);
});
it("maps an edge-function failure by its constructor name", () => {
- expect(
- classifyDatabaseFailure({ name: "FunctionsHttpError", context: {} })
- ).toBe("rule");
+ expect(classifyDatabaseFailure(edgeFunctionError)).toBe("rule");
});
it("falls back to unknown for an unrecognized or absent code", () => {
- expect(classifyDatabaseFailure({ code: "XX000" })).toBe("unknown");
- expect(classifyDatabaseFailure({ message: "boom" })).toBe("unknown");
+ expect(classifyDatabaseFailure(postgrestError({ code: "XX000" }))).toBe(
+ "unknown"
+ );
+ expect(classifyDatabaseFailure(postgrestError({ message: "boom" }))).toBe(
+ "unknown"
+ );
expect(classifyDatabaseFailure(null)).toBe("unknown");
expect(classifyDatabaseFailure(undefined)).toBe("unknown");
- expect(classifyDatabaseFailure("boom")).toBe("unknown");
});
it("classifies on structured fields, never on message text", () => {
expect(
- classifyDatabaseFailure({ message: "duplicate key value violates 23505" })
+ classifyDatabaseFailure(
+ postgrestError({ message: "duplicate key value violates 23505" })
+ )
).toBe("unknown");
});
});
@@ -41,16 +61,16 @@ describe("publicDatabaseError", () => {
it("returns only strings from the closed set", () => {
const allowed = Object.values(DATABASE_ERROR_MESSAGES);
for (const error of [
- {
+ postgrestError({
code: "23505",
message: "duplicate key value violates unique constraint"
- },
- {
+ }),
+ postgrestError({
code: "42501",
details: "user 48e8db84 lacks privilege on table employee"
- },
- { name: "FunctionsHttpError", context: {} },
- { code: "XX000" },
+ }),
+ edgeFunctionError,
+ postgrestError({ code: "XX000" }),
null
]) {
expect(allowed).toContain(publicDatabaseError(error));
@@ -58,13 +78,13 @@ describe("publicDatabaseError", () => {
});
it("leaks nothing from the underlying error", () => {
- const error = {
+ const error = postgrestError({
code: "23505",
message:
'duplicate key value violates unique constraint "employee_email_key"',
details: "Key (email)=([email protected]) already exists.",
hint: "try another email"
- };
+ });
const publicMessage = publicDatabaseError(error);
expect(publicMessage).toBe(DATABASE_ERROR_MESSAGES.conflict);
diff --git a/apps/erp/app/routes/api+/v1+/lib/database-errors.ts b/apps/erp/app/routes/api+/v1+/lib/database-errors.ts
index fd21332a3f..41b4428bfa 100644
--- a/apps/erp/app/routes/api+/v1+/lib/database-errors.ts
+++ b/apps/erp/app/routes/api+/v1+/lib/database-errors.ts
@@ -1,3 +1,7 @@
+import type { FunctionsError, PostgrestError } from "@supabase/supabase-js";
+
+export type SupabaseFailure = PostgrestError | FunctionsError;
+
export type DatabaseFailureKind =
| "conflict"
| "reference"
@@ -19,12 +23,13 @@ export const DATABASE_ERROR_MESSAGES: Record<DatabaseFailureKind, string> = {
unknown: "Database error: the operation could not be completed."
};
-export function classifyDatabaseFailure(error: unknown): DatabaseFailureKind {
- const candidate = error as { code?: unknown; name?: unknown } | null;
- if (candidate?.name === "FunctionsHttpError") return "rule";
+export function classifyDatabaseFailure(
+ error: SupabaseFailure | null | undefined
+): DatabaseFailureKind {
+ if (!error) return "unknown";
+ if (error.name === "FunctionsHttpError") return "rule";
- const code = typeof candidate?.code === "string" ? candidate.code : "";
- switch (code) {
+ switch ("code" in error ? error.code : undefined) {
case "23505":
return "conflict";
case "23503":
@@ -40,6 +45,8 @@ export function classifyDatabaseFailure(error: unknown): DatabaseFailureKind {
}
}
-export function publicDatabaseError(error: unknown): string {
+export function publicDatabaseError(
+ error: SupabaseFailure | null | undefined
+): string {
return DATABASE_ERROR_MESSAGES[classifyDatabaseFailure(error)];
}