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

124 lines
3.0 KiB
TypeScript
Raw Normal View History

import { prisma } from "@/lib/api/db";
import getPermission from "@/lib/api/getPermission";
2024-09-17 13:03:05 -05:00
import {
UpdateCollectionSchema,
UpdateCollectionSchemaType,
} from "@/lib/shared/schemaValidation";
export default async function updateCollection(
userId: number,
collectionId: number,
2024-09-17 13:03:05 -05:00
body: UpdateCollectionSchemaType
2023-05-26 23:11:29 -05:00
) {
if (!collectionId)
return { response: "Please choose a valid collection.", status: 401 };
2024-09-17 13:03:05 -05:00
const dataValidation = UpdateCollectionSchema.safeParse(body);
if (!dataValidation.success) {
return {
response: `Error: ${
dataValidation.error.issues[0].message
} [${dataValidation.error.issues[0].path.join(", ")}]`,
status: 400,
};
}
const data = dataValidation.data;
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) {
2024-10-07 22:43:44 -05:00
if (data.parentId !== "root") {
const findParentCollection = await prisma.collection.findUnique({
where: {
id: data.parentId,
},
select: {
ownerId: true,
parentId: true,
},
});
if (
findParentCollection?.ownerId !== userId ||
typeof data.parentId !== "number" ||
findParentCollection?.parentId === data.parentId
)
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,
icon: data.icon,
iconWeight: data.iconWeight,
isPublic: data.isPublic,
parent:
2024-10-07 22:43:44 -05:00
data.parentId && data.parentId !== "root"
? {
connect: {
id: data.parentId,
},
}
2024-10-07 22:43:44 -05:00
: data.parentId === "root"
? {
disconnect: true,
}
: undefined,
members: {
create: data.members.map((e) => ({
2024-09-17 13:03:05 -05:00
user: { connect: { 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 };
}