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

102 lines
2.1 KiB
TypeScript
Raw Normal View History

2023-02-18 21:32:02 -06:00
import { prisma } from "@/lib/api/db";
import createFolder from "@/lib/api/storage/createFolder";
2024-09-14 15:00:19 -05:00
import {
PostCollectionSchema,
PostCollectionSchemaType,
} from "@/lib/shared/schemaValidation";
2023-02-08 15:11:33 -06:00
export default async function postCollection(
2024-09-14 15:00:19 -05:00
body: PostCollectionSchemaType,
2023-05-26 23:11:29 -05:00
userId: number
) {
2024-09-14 15:00:19 -05:00
const dataValidation = PostCollectionSchema.safeParse(body);
if (!dataValidation.success) {
2023-03-28 02:31:50 -05:00
return {
2024-09-14 15:00:19 -05:00
response: `Error: ${
dataValidation.error.issues[0].message
} [${dataValidation.error.issues[0].path.join(", ")}]`,
2023-03-28 02:31:50 -05:00
status: 400,
};
2024-09-14 15:00:19 -05:00
}
const collection = dataValidation.data;
2023-02-08 15:11:33 -06:00
if (collection.parentId) {
const findParentCollection = await prisma.collection.findUnique({
where: {
id: collection.parentId,
},
select: {
ownerId: true,
},
});
if (
findParentCollection?.ownerId !== userId ||
typeof collection.parentId !== "number"
)
return {
response: "You are not authorized to create a sub-collection here.",
status: 403,
};
}
const newCollection = await prisma.collection.create({
2023-02-08 15:11:33 -06:00
data: {
2023-07-23 13:27:12 -05:00
name: collection.name.trim(),
2023-04-24 16:30:40 -05:00
description: collection.description,
2023-06-02 06:59:52 -05:00
color: collection.color,
icon: collection.icon,
iconWeight: collection.iconWeight,
parent: collection.parentId
? {
2024-02-22 02:51:24 -06:00
connect: {
id: collection.parentId,
},
}
: undefined,
2024-10-26 12:44:52 -05:00
owner: {
connect: {
id: userId,
},
},
createdBy: {
connect: {
id: userId,
},
},
2023-02-08 15:11:33 -06:00
},
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-07-08 05:35:43 -05:00
username: true,
2023-05-01 15:00:23 -05:00
name: true,
},
},
},
},
},
2023-02-08 15:11:33 -06:00
});
await prisma.user.update({
where: {
id: userId,
},
data: {
collectionOrder: {
push: newCollection.id,
},
},
});
createFolder({ filePath: `archives/${newCollection.id}` });
2023-03-28 02:31:50 -05:00
return { response: newCollection, status: 200 };
2023-02-08 15:11:33 -06:00
}