refactor(api): extract comment router support
This commit is contained in:
@@ -0,0 +1,112 @@
|
||||
import { TRPCError } from "@trpc/server";
|
||||
|
||||
export const commentAuthorSelect = {
|
||||
id: true,
|
||||
name: true,
|
||||
email: true,
|
||||
image: true,
|
||||
} as const;
|
||||
|
||||
export const commentWithAuthorInclude = {
|
||||
author: { select: commentAuthorSelect },
|
||||
} as const;
|
||||
|
||||
export const commentThreadInclude = {
|
||||
author: { select: commentAuthorSelect },
|
||||
replies: {
|
||||
include: {
|
||||
author: { select: commentAuthorSelect },
|
||||
},
|
||||
orderBy: { createdAt: "asc" as const },
|
||||
},
|
||||
} as const;
|
||||
|
||||
export function parseCommentMentions(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);
|
||||
}
|
||||
|
||||
export function buildCommentCreateData(input: {
|
||||
entityType: string;
|
||||
entityId: string;
|
||||
parentId?: string | undefined;
|
||||
authorId: string;
|
||||
body: string;
|
||||
mentions: string[];
|
||||
}) {
|
||||
return {
|
||||
entityType: input.entityType,
|
||||
entityId: input.entityId,
|
||||
...(input.parentId !== undefined ? { parentId: input.parentId } : {}),
|
||||
authorId: input.authorId,
|
||||
body: input.body,
|
||||
mentions: input.mentions,
|
||||
};
|
||||
}
|
||||
|
||||
export function commentBelongsToEntity(input: {
|
||||
comment: {
|
||||
entityType: string;
|
||||
entityId: string;
|
||||
};
|
||||
entityType: string;
|
||||
entityId: string;
|
||||
}): boolean {
|
||||
return (
|
||||
input.comment.entityType === input.entityType &&
|
||||
input.comment.entityId === input.entityId
|
||||
);
|
||||
}
|
||||
|
||||
export function assertCommentManageableByActor(input: {
|
||||
authorId: string;
|
||||
actorUserId: string;
|
||||
isAdmin: boolean;
|
||||
action: "resolve" | "delete";
|
||||
}) {
|
||||
if (input.authorId === input.actorUserId || input.isAdmin) {
|
||||
return;
|
||||
}
|
||||
|
||||
throw new TRPCError({
|
||||
code: "FORBIDDEN",
|
||||
message: input.action === "resolve"
|
||||
? "Only the comment author or an admin can resolve comments"
|
||||
: "Only the comment author or an admin can delete comments",
|
||||
});
|
||||
}
|
||||
|
||||
function truncateCommentNotificationBody(body: string): string {
|
||||
return body.length > 120 ? `${body.slice(0, 120)}...` : body;
|
||||
}
|
||||
|
||||
export function buildCommentMentionNotifications(input: {
|
||||
mentionedUserIds: string[];
|
||||
authorName: string;
|
||||
body: string;
|
||||
entityId: string;
|
||||
entityType: string;
|
||||
senderId: string;
|
||||
link: string;
|
||||
}) {
|
||||
const truncatedBody = truncateCommentNotificationBody(input.body);
|
||||
|
||||
return input.mentionedUserIds.map((userId) => ({
|
||||
userId,
|
||||
type: "COMMENT_MENTION" as const,
|
||||
title: `${input.authorName} mentioned you in a comment`,
|
||||
body: truncatedBody,
|
||||
entityId: input.entityId,
|
||||
entityType: input.entityType,
|
||||
senderId: input.senderId,
|
||||
link: input.link,
|
||||
channel: "in_app" as const,
|
||||
}));
|
||||
}
|
||||
@@ -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({
|
||||
|
||||
Reference in New Issue
Block a user