refactor(api): extract comment router support

This commit is contained in:
2026-03-31 14:28:07 +02:00
parent 73cfc9341b
commit ab46eca8b3
3 changed files with 265 additions and 64 deletions
+44 -64
View File
@@ -4,23 +4,15 @@ import { createTRPCRouter, protectedProcedure } from "../trpc.js";
import { createNotification } from "../lib/create-notification.js";
import { createAuditEntry } from "../lib/audit.js";
import { assertCommentEntityAccess, CommentEntityTypeSchema } from "../lib/comment-entity-registry.js";
// ─── Helpers ──────────────────────────────────────────────────────────────────
/**
* Parse @mentions from comment body.
* Pattern: @[Display Name](userId)
* Returns an array of unique user IDs.
*/
function parseMentions(body: string): string[] {
const regex = /@\[([^\]]+)\]\(([^)]+)\)/g;
const ids = new Set<string>();
let match: RegExpExecArray | null;
while ((match = regex.exec(body)) !== null) {
ids.add(match[2]!);
}
return Array.from(ids);
}
import {
assertCommentManageableByActor,
buildCommentCreateData,
buildCommentMentionNotifications,
commentBelongsToEntity,
commentThreadInclude,
commentWithAuthorInclude,
parseCommentMentions,
} from "./comment-support.js";
// ─── Router ───────────────────────────────────────────────────────────────────
@@ -42,15 +34,7 @@ export const commentRouter = createTRPCRouter({
entityId: input.entityId,
parentId: null, // only top-level comments
},
include: {
author: { select: { id: true, name: true, email: true, image: true } },
replies: {
include: {
author: { select: { id: true, name: true, email: true, image: true } },
},
orderBy: { createdAt: "asc" },
},
},
include: commentThreadInclude,
orderBy: { createdAt: "asc" },
});
}),
@@ -103,7 +87,7 @@ export const commentRouter = createTRPCRouter({
const policy = await assertCommentEntityAccess(ctx, input.entityType, input.entityId);
const authorId = ctx.dbUser?.id;
if (!authorId) throw new TRPCError({ code: "UNAUTHORIZED" });
const mentions = parseMentions(input.body);
const mentions = parseCommentMentions(input.body);
// If replying, verify the parent exists
if (input.parentId) {
@@ -114,7 +98,11 @@ export const commentRouter = createTRPCRouter({
if (!parent) {
throw new TRPCError({ code: "NOT_FOUND", message: "Parent comment not found" });
}
if (parent.entityType !== input.entityType || parent.entityId !== input.entityId) {
if (!commentBelongsToEntity({
comment: parent,
entityType: input.entityType,
entityId: input.entityId,
})) {
throw new TRPCError({
code: "BAD_REQUEST",
message: "Parent comment does not belong to the requested entity",
@@ -123,39 +111,36 @@ export const commentRouter = createTRPCRouter({
}
const comment = await ctx.db.comment.create({
data: {
data: buildCommentCreateData({
entityType: input.entityType,
entityId: input.entityId,
...(input.parentId !== undefined ? { parentId: input.parentId } : {}),
parentId: input.parentId,
authorId,
body: input.body,
mentions,
},
include: {
author: { select: { id: true, name: true, email: true, image: true } },
},
}),
include: commentWithAuthorInclude,
});
// Create notifications for mentioned users (excluding the author)
const mentionedUserIds = mentions.filter((id) => id !== authorId);
if (mentionedUserIds.length > 0) {
const authorName = comment.author.name ?? comment.author.email;
const truncatedBody =
input.body.length > 120 ? `${input.body.slice(0, 120)}...` : input.body;
const notifications = buildCommentMentionNotifications({
mentionedUserIds,
authorName,
body: input.body,
entityId: input.entityId,
entityType: input.entityType,
senderId: authorId,
link: policy.buildLink(input.entityId),
});
await Promise.all(
mentionedUserIds.map((userId) =>
notifications.map((notification) =>
createNotification({
db: ctx.db,
userId,
type: "COMMENT_MENTION",
title: `${authorName} mentioned you in a comment`,
body: truncatedBody,
entityId: input.entityId,
entityType: input.entityType,
senderId: authorId,
link: policy.buildLink(input.entityId),
channel: "in_app",
...notification,
}),
),
);
@@ -199,21 +184,17 @@ export const commentRouter = createTRPCRouter({
await assertCommentEntityAccess(ctx, existing.entityType, existing.entityId);
// Only the author or an admin can resolve
const isAdmin = dbUser?.systemRole === "ADMIN";
if (existing.authorId !== userId && !isAdmin) {
throw new TRPCError({
code: "FORBIDDEN",
message: "Only the comment author or an admin can resolve comments",
});
}
assertCommentManageableByActor({
authorId: existing.authorId,
actorUserId: userId,
isAdmin: dbUser?.systemRole === "ADMIN",
action: "resolve",
});
const updated = await ctx.db.comment.update({
where: { id: input.id },
data: { resolved: input.resolved },
include: {
author: { select: { id: true, name: true, email: true, image: true } },
},
include: commentWithAuthorInclude,
});
void createAuditEntry({
@@ -249,13 +230,12 @@ export const commentRouter = createTRPCRouter({
await assertCommentEntityAccess(ctx, existing.entityType, existing.entityId);
const isAdmin = dbUser?.systemRole === "ADMIN";
if (existing.authorId !== userId && !isAdmin) {
throw new TRPCError({
code: "FORBIDDEN",
message: "Only the comment author or an admin can delete comments",
});
}
assertCommentManageableByActor({
authorId: existing.authorId,
actorUserId: userId,
isAdmin: dbUser?.systemRole === "ADMIN",
action: "delete",
});
// Delete all replies first (they reference this comment as parent)
await ctx.db.comment.deleteMany({