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

57 lines
1.2 KiB
TypeScript
Raw Normal View History

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-02-08 15:11:33 -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,
},
select: {
2023-02-08 15:11:33 -06:00
collections: {
where: {
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-02-18 21:32:02 -06:00
const createCollection = 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
},
});
return res.status(200).json({
2023-02-18 21:32:02 -06:00
response: createCollection,
2023-02-08 15:11:33 -06:00
});
}