el.xwx.moe/lib/api/controllers/collections/updateCollection.ts

74 lines
1.8 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";
2023-06-24 16:54:35 -05:00
import { Collection, UsersAndCollections } from "@prisma/client";
export default async function updateCollection(
2023-06-16 07:55:21 -05:00
collection: CollectionIncludingMembersAndLinkCount,
2023-05-26 23:11:29 -05:00
userId: number
) {
if (!collection.id)
return { response: "Please choose a valid collection.", status: 401 };
2023-06-24 16:54:35 -05:00
const collectionIsAccessible = (await getPermission(
userId,
collection.id
)) as
| (Collection & {
members: UsersAndCollections[];
})
| null;
if (!(collectionIsAccessible?.ownerId === userId))
return { response: "Collection is not accessible.", status: 401 };
const updatedCollection = await prisma.$transaction(async () => {
await prisma.usersAndCollections.deleteMany({
where: {
collection: {
id: collection.id,
},
},
});
return await prisma.collection.update({
where: {
id: collection.id,
},
2023-06-16 07:55:21 -05:00
data: {
name: collection.name,
description: collection.description,
2023-06-02 06:59:52 -05:00
color: collection.color,
2023-05-28 18:14:44 -05:00
isPublic: collection.isPublic,
members: {
create: collection.members.map((e) => ({
2023-07-03 15:43:53 -05:00
user: { connect: { email: e.user.email.toLowerCase() } },
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: {
email: true,
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 };
}