refactor: create api link endpoint

This commit is contained in:
Sonny
2023-06-03 20:17:39 +02:00
parent 678da44b80
commit f5986d34ad

View File

@@ -1,91 +1,53 @@
import { NextApiRequest, NextApiResponse } from "next";
import { getServerSession } from "next-auth/next";
import { boolean, number, object, string } from "yup";
import { apiHandler } from "lib/api/handler";
import getUserCategory from "lib/category/getUserCategory";
import getUserLinkByName from "lib/link/getLinkFromCategoryByName";
import { VALID_URL_REGEX } from "constants/url";
import prisma from "utils/prisma";
import { authOptions } from "../auth/[...nextauth]";
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
const session = await getServerSession(req, res, authOptions); // je sais plus d'où ça vient
console.log("session", session);
if (!session?.user) {
return res.status(400).send({ error: "You must be connected" });
}
export default apiHandler({
post: createLink,
});
const name = req.body?.name as string;
const url = req.body?.url as string;
const favorite = Boolean(req.body?.favorite) || false;
const categoryId = Number(req.body?.categoryId);
const bodySchema = object({
name: string()
.trim()
.required("name is required")
.max(32, "name is too long"),
url: string()
.trim()
.required("url is required")
.matches(VALID_URL_REGEX, "invalid url format"),
categoryId: number().required("categoryId must be a number"),
favorite: boolean().default(() => false),
}).typeError("Missing request Body");
if (!name) {
return res.status(400).send({ error: "Nom du lien manquant" });
}
if (!url) {
return res.status(400).send({ error: "URL du lien manquant" });
}
if (!categoryId) {
return res.status(400).send({ error: "Catégorie du lien manquante" });
}
try {
const link = await prisma.link.findFirst({
where: { name, categoryId },
});
async function createLink({ req, res, user }) {
const { name, url, favorite, categoryId } = await bodySchema.validate(
req.body
);
const link = await getUserLinkByName(user, name, categoryId);
if (link) {
return res.status(400).send({
error: "Un lien avec ce nom existe déjà dans cette catégorie",
});
}
} catch (error) {
console.error(error);
return res.status(400).send({
error:
"Une erreur est survenue lors de la création du lien (link/create->findLink)",
});
throw new Error("Link name is already used in this category");
}
try {
const category = await prisma.category.findFirst({
where: { id: categoryId },
});
const category = await getUserCategory(user, categoryId);
if (!category) {
return res.status(400).send({ error: "Cette catégorie n'existe pas" });
}
} catch (error) {
console.error(error);
return res.status(400).send({
error:
"Une erreur est survenue lors de la création du lien (link/create->findCategory)",
});
throw new Error("Unable to find category " + categoryId);
}
try {
const { id: authorId } = await prisma.user.findFirstOrThrow({
where: { email: session.user.email },
});
await prisma.link.create({
data: {
name,
url,
categoryId,
favorite,
authorId,
authorId: user.id,
},
});
return res
.status(200)
.send({ success: "Lien créé avec succès", categoryId });
} catch (error) {
console.error(error);
return res.status(400).send({
error:
"Une erreur est survenue lors de la création du lien (link/create->createLink)",
});
}
return res.send({ success: "Link successfully created", categoryId });
}