2023-02-18 21:32:02 -06:00
|
|
|
import { prisma } from "@/lib/api/db";
|
2023-03-08 15:31:24 -06:00
|
|
|
import { existsSync, mkdirSync } from "fs";
|
2023-02-08 15:11:33 -06:00
|
|
|
|
2023-03-28 02:31:50 -05:00
|
|
|
export default async function (collectionName: string, userId: number) {
|
|
|
|
if (!collectionName)
|
|
|
|
return {
|
|
|
|
response: "Please enter a valid name for the collection.",
|
|
|
|
status: 400,
|
|
|
|
};
|
2023-02-08 15:11:33 -06:00
|
|
|
|
2023-03-28 02:31:50 -05:00
|
|
|
const findCollection = await prisma.user.findUnique({
|
2023-02-08 15:11:33 -06:00
|
|
|
where: {
|
2023-03-28 02:31:50 -05:00
|
|
|
id: userId,
|
2023-02-08 15:11:33 -06:00
|
|
|
},
|
2023-02-13 18:09:13 -06:00
|
|
|
select: {
|
2023-02-08 15:11:33 -06:00
|
|
|
collections: {
|
|
|
|
where: {
|
2023-02-13 18:09:13 -06:00
|
|
|
name: collectionName,
|
2023-02-08 15:11:33 -06:00
|
|
|
},
|
|
|
|
},
|
|
|
|
},
|
|
|
|
});
|
|
|
|
|
|
|
|
const checkIfCollectionExists = findCollection?.collections[0];
|
|
|
|
|
2023-03-28 02:31:50 -05:00
|
|
|
if (checkIfCollectionExists)
|
|
|
|
return { response: "Collection already exists.", status: 400 };
|
2023-02-08 15:11:33 -06:00
|
|
|
|
2023-03-08 15:31:24 -06:00
|
|
|
const newCollection = await prisma.collection.create({
|
2023-02-08 15:11:33 -06:00
|
|
|
data: {
|
2023-02-18 21:32:02 -06:00
|
|
|
owner: {
|
|
|
|
connect: {
|
2023-03-28 02:31:50 -05:00
|
|
|
id: userId,
|
2023-02-18 21:32:02 -06:00
|
|
|
},
|
2023-02-08 15:11:33 -06:00
|
|
|
},
|
2023-02-18 21:32:02 -06:00
|
|
|
name: collectionName,
|
2023-02-08 15:11:33 -06:00
|
|
|
},
|
|
|
|
});
|
|
|
|
|
2023-03-08 15:31:24 -06:00
|
|
|
const collectionPath = `data/archives/${newCollection.id}`;
|
|
|
|
if (!existsSync(collectionPath))
|
|
|
|
mkdirSync(collectionPath, { recursive: true });
|
|
|
|
|
2023-03-28 02:31:50 -05:00
|
|
|
return { response: newCollection, status: 200 };
|
2023-02-08 15:11:33 -06:00
|
|
|
}
|