2023-04-28 16:10:29 -05:00
|
|
|
import { prisma } from "@/lib/api/db";
|
2023-06-16 07:55:21 -05:00
|
|
|
import { CollectionIncludingMembersAndLinkCount } from "@/types/global";
|
2023-04-28 16:10:29 -05:00
|
|
|
import getPermission from "@/lib/api/getPermission";
|
2023-06-24 16:54:35 -05:00
|
|
|
import { Collection, UsersAndCollections } from "@prisma/client";
|
2023-04-28 16:10:29 -05:00
|
|
|
|
2023-06-09 17:31:14 -05:00
|
|
|
export default async function updateCollection(
|
2023-10-22 23:28:39 -05:00
|
|
|
userId: number,
|
|
|
|
collectionId: number,
|
|
|
|
data: CollectionIncludingMembersAndLinkCount
|
2023-05-26 23:11:29 -05:00
|
|
|
) {
|
2023-10-22 23:28:39 -05:00
|
|
|
if (!collectionId)
|
2023-04-28 16:10:29 -05:00
|
|
|
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,
|
2023-10-22 23:28:39 -05:00
|
|
|
collectionId,
|
2023-11-19 15:22:27 -06:00
|
|
|
});
|
2023-04-28 16:10:29 -05:00
|
|
|
|
|
|
|
if (!(collectionIsAccessible?.ownerId === userId))
|
|
|
|
return { response: "Collection is not accessible.", status: 401 };
|
|
|
|
|
|
|
|
const updatedCollection = await prisma.$transaction(async () => {
|
|
|
|
await prisma.usersAndCollections.deleteMany({
|
|
|
|
where: {
|
|
|
|
collection: {
|
2023-10-22 23:28:39 -05:00
|
|
|
id: collectionId,
|
2023-04-28 16:10:29 -05:00
|
|
|
},
|
|
|
|
},
|
|
|
|
});
|
|
|
|
|
|
|
|
return await prisma.collection.update({
|
|
|
|
where: {
|
2023-10-22 23:28:39 -05:00
|
|
|
id: collectionId,
|
2023-04-28 16:10:29 -05:00
|
|
|
},
|
2023-06-16 07:55:21 -05:00
|
|
|
|
2023-04-28 16:10:29 -05:00
|
|
|
data: {
|
2023-10-22 23:28:39 -05:00
|
|
|
name: data.name.trim(),
|
|
|
|
description: data.description,
|
|
|
|
color: data.color,
|
|
|
|
isPublic: data.isPublic,
|
2023-04-28 16:10:29 -05:00
|
|
|
members: {
|
2023-10-22 23:28:39 -05:00
|
|
|
create: data.members.map((e) => ({
|
2023-07-22 18:00:49 -05:00
|
|
|
user: { connect: { id: e.user.id || e.userId } },
|
2023-04-28 16:10:29 -05:00
|
|
|
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
|
|
|
},
|
|
|
|
},
|
|
|
|
},
|
|
|
|
},
|
|
|
|
},
|
2023-04-28 16:10:29 -05:00
|
|
|
});
|
|
|
|
});
|
|
|
|
|
|
|
|
return { response: updatedCollection, status: 200 };
|
|
|
|
}
|