el.xwx.moe/lib/api/controllers/collections/collectionId/updateCollectionById.ts

97 lines
2.3 KiB
TypeScript
Raw Normal View History

import { prisma } from "@/lib/api/db";
2023-06-16 07:55:21 -05:00
import { CollectionIncludingMembersAndLinkCount } from "@/types/global";
import getPermission from "@/lib/api/getPermission";
export default async function updateCollection(
userId: number,
collectionId: number,
data: CollectionIncludingMembersAndLinkCount
2023-05-26 23:11:29 -05:00
) {
if (!collectionId)
return { response: "Please choose a valid collection.", status: 401 };
2023-11-19 15:22:27 -06:00
const collectionIsAccessible = await getPermission({
2023-06-24 16:54:35 -05:00
userId,
collectionId,
2023-11-19 15:22:27 -06:00
});
if (!(collectionIsAccessible?.ownerId === userId))
return { response: "Collection is not accessible.", status: 401 };
if (data.parentId) {
const findParentCollection = await prisma.collection.findUnique({
where: {
id: data.parentId,
},
select: {
ownerId: true,
},
});
if (
findParentCollection?.ownerId !== userId ||
typeof data.parentId !== "number"
)
return {
response: "You are not authorized to create a sub-collection here.",
status: 403,
};
}
const updatedCollection = await prisma.$transaction(async () => {
await prisma.usersAndCollections.deleteMany({
where: {
collection: {
id: collectionId,
},
},
});
return await prisma.collection.update({
where: {
id: collectionId,
},
data: {
name: data.name.trim(),
description: data.description,
color: data.color,
isPublic: data.isPublic,
2024-02-08 07:25:45 -06:00
parent: data.parentId
? {
connect: {
id: data.parentId,
},
}
: undefined,
members: {
create: data.members.map((e) => ({
2023-07-22 18:00:49 -05:00
user: { connect: { id: e.user.id || e.userId } },
canCreate: e.canCreate,
canUpdate: e.canUpdate,
canDelete: e.canDelete,
})),
},
},
2023-05-01 15:00:23 -05:00
include: {
2023-06-16 07:55:21 -05:00
_count: {
select: { links: true },
},
2023-05-01 15:00:23 -05:00
members: {
include: {
user: {
select: {
2023-10-28 00:42:31 -05:00
image: true,
2023-07-08 05:35:43 -05:00
username: true,
2023-05-01 15:00:23 -05:00
name: true,
2023-05-28 00:55:49 -05:00
id: true,
2023-05-01 15:00:23 -05:00
},
},
},
},
},
});
});
return { response: updatedCollection, status: 200 };
}