Skip to content

Commit

Permalink
Fixed P2002 error with merging tags
Browse files Browse the repository at this point in the history
  • Loading branch information
michaelschwobe committed Oct 13, 2023
1 parent 62e2bbd commit 3b9ec27
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 14 deletions.
22 changes: 19 additions & 3 deletions app/models/tag.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -134,12 +134,28 @@ export async function deleteTagByName({
export async function mergeTag({
sourceTagId,
targetTagId,
userId,
}: {
sourceTagId: Tag["id"];
targetTagId: Tag["id"];
userId: User["id"];
}) {
return prisma.tagOnBookmark.updateMany({
where: { tagId: sourceTagId },
data: { tagId: targetTagId },
const [sourceRelations, targetRelations] = await Promise.all([
prisma.tagOnBookmark.findMany({ where: { tagId: sourceTagId } }),
prisma.tagOnBookmark.findMany({ where: { tagId: targetTagId } }),
]);
const sourceBookmarkIds = sourceRelations.map((el) => el.bookmarkId);
const targetBookmarkIds = targetRelations.map((el) => el.bookmarkId);
const uniqueBookmarkIds = sourceBookmarkIds.filter(
(bookmarkId) => !targetBookmarkIds.includes(bookmarkId),
);
const createBookmarkRelations = uniqueBookmarkIds.map((bookmarkId) =>
prisma.tagOnBookmark.create({
data: { tagId: targetTagId, bookmarkId },
}),
);
const deleteSourceTag = prisma.tag.deleteMany({
where: { id: sourceTagId, userId },
});
return prisma.$transaction([...createBookmarkRelations, deleteSourceTag]);
}
16 changes: 5 additions & 11 deletions app/routes/tags.$tagId.merge.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,13 +27,7 @@ import { Icon } from "~/components/ui/icon";
import { Input } from "~/components/ui/input";
import { LinkButton } from "~/components/ui/link-button";
import { SelectItem, SimpleSelect } from "~/components/ui/select";
import {
deleteTag,
getTag,
getTagByName,
getTags,
mergeTag,
} from "~/models/tag.server";
import { getTag, getTagByName, getTags, mergeTag } from "~/models/tag.server";
import { requireUserId } from "~/utils/auth.server";
import {
formatMetaTitle,
Expand Down Expand Up @@ -80,16 +74,16 @@ export const action = async ({ params, request }: ActionFunctionArgs) => {
const targetTag = await getTagByName({ name: submission.value.name });
invariantResponse(targetTag, "Target Tag Not Found", { status: 404 });

const { count } = await mergeTag({
const mergeTagResults = await mergeTag({
sourceTagId: sourceTag.id,
targetTagId: targetTag.id,
userId,
});
await deleteTag({ id: sourceTag.id, userId });

return redirectWithToast(`/tags/${targetTag.id}`, {
type: "success",
title: "Tags merged:",
description: `${count} relations updated`,
title: "Tag merged:",
description: `${mergeTagResults.length - 1} relation(s) updated`,
});
};

Expand Down

0 comments on commit 3b9ec27

Please sign in to comment.