From 2a31dd9610590d966e2d2cd42c7250651c7d4774 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Sat, 23 May 2026 03:05:45 -0600 Subject: [PATCH] Extract duplicate constraint-error handler in personalities.ts Both POST and PATCH routes had identical catch blocks for the personalities_name_key constraint violation. Extract a shared throwUnlessDuplicateName helper and adopt the shared errorMessage() utility instead of inline instanceof checks. Co-Authored-By: Claude Opus 4.6 --- apps/server/src/routes/personalities.ts | 28 ++++++++++++------------- 1 file changed, 13 insertions(+), 15 deletions(-) diff --git a/apps/server/src/routes/personalities.ts b/apps/server/src/routes/personalities.ts index e47deaba..49aff61d 100644 --- a/apps/server/src/routes/personalities.ts +++ b/apps/server/src/routes/personalities.ts @@ -1,4 +1,4 @@ -import type { FastifyInstance } from "fastify"; +import type { FastifyInstance, FastifyReply } from "fastify"; import type { Pool } from "pg"; import { @@ -10,10 +10,20 @@ import { setActivePersonalityId, updatePersonality, } from "../db/personalities.js"; +import { errorMessage } from "../shared/lib/error-message.js"; const NAME_MAX = 80; const PROMPT_MAX = 1000; +function throwUnlessDuplicateName(error: unknown, reply: FastifyReply) { + if (errorMessage(error).includes("personalities_name_key")) { + return reply + .code(409) + .send({ error: "A personality with that name already exists." }); + } + throw error; +} + type PersonalityRouteDeps = { pool: Pool; }; @@ -58,13 +68,7 @@ export async function registerPersonalityRoutes( const personality = await createPersonality(pool, { name, prompt }); return reply.code(201).send({ personality }); } catch (error) { - const message = error instanceof Error ? error.message : ""; - if (message.includes("personalities_name_key")) { - return reply - .code(409) - .send({ error: "A personality with that name already exists." }); - } - throw error; + return throwUnlessDuplicateName(error, reply); } }); @@ -118,13 +122,7 @@ export async function registerPersonalityRoutes( } return { personality: updated }; } catch (error) { - const message = error instanceof Error ? error.message : ""; - if (message.includes("personalities_name_key")) { - return reply - .code(409) - .send({ error: "A personality with that name already exists." }); - } - throw error; + return throwUnlessDuplicateName(error, reply); } });