2023-02-08 15:11:33 -06:00
|
|
|
import type { NextApiRequest, NextApiResponse } from "next";
|
2023-02-18 21:32:02 -06:00
|
|
|
import { prisma } from "@/lib/api/db";
|
|
|
|
import { Session } from "next-auth";
|
2023-03-08 15:31:24 -06:00
|
|
|
import { existsSync, mkdirSync } from "fs";
|
2023-02-08 15:11:33 -06:00
|
|
|
|
2023-02-24 11:32:28 -06:00
|
|
|
export default async function (
|
2023-02-08 15:11:33 -06:00
|
|
|
req: NextApiRequest,
|
2023-02-18 21:32:02 -06:00
|
|
|
res: NextApiResponse,
|
|
|
|
session: Session
|
2023-02-08 15:11:33 -06:00
|
|
|
) {
|
|
|
|
if (!session?.user?.email) {
|
|
|
|
return res.status(401).json({ response: "You must be logged in." });
|
|
|
|
}
|
|
|
|
|
|
|
|
const email: string = session.user.email;
|
|
|
|
const collectionName: string = req?.body?.collectionName;
|
|
|
|
|
|
|
|
if (!collectionName) {
|
|
|
|
return res
|
|
|
|
.status(401)
|
|
|
|
.json({ response: "Please enter a valid name for the collection." });
|
|
|
|
}
|
|
|
|
|
|
|
|
const findCollection = await prisma.user.findFirst({
|
|
|
|
where: {
|
|
|
|
email,
|
|
|
|
},
|
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];
|
|
|
|
|
|
|
|
if (checkIfCollectionExists) {
|
|
|
|
return res.status(400).json({ response: "Collection already exists." });
|
|
|
|
}
|
|
|
|
|
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: {
|
|
|
|
id: session.user.id,
|
|
|
|
},
|
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-02-08 15:11:33 -06:00
|
|
|
return res.status(200).json({
|
2023-03-08 15:31:24 -06:00
|
|
|
response: newCollection,
|
2023-02-08 15:11:33 -06:00
|
|
|
});
|
|
|
|
}
|