import { and, eq, isNull } from "drizzle-orm"; import { topics } from "~~/drizzle/schema"; import { db } from "~~/server/lib/db"; import { cancelPendingRename } from "~~/server/utils/renames"; import { topicEvents, userEvents } from "~~/server/utils/events"; export default defineEventHandler(async (event) => { await protectRoute(event); const topicId = getRouterParam(event, "topicId"); const userId = event.context.user?.id; if (!topicId || !userId) { setResponseStatus(event, 400); return { ok: false }; } const topic = await db.query.topics.findFirst({ where: { id: topicId, userId } }); if (!topic) { setResponseStatus(event, 404); return { ok: false }; } const cleared = await db.update(topics).set({ renaming: false, renameAttemptId: null, renameExpiresAt: null, }).where(and( eq(topics.id, topicId), eq(topics.userId, userId), topic.renameAttemptId ? eq(topics.renameAttemptId, topic.renameAttemptId) : isNull(topics.renameAttemptId), )).returning({ id: topics.id }); if (cleared.length === 0) { return { ok: false }; } cancelPendingRename(topicId, topic.renameAttemptId); const payload = { topicId, renaming: false }; userEvents.emit(userId, "topics", { op: "update", payload }); topicEvents.emit(topicId, { type: "topic_updated", payload }); return { ok: true }; });