adds testing for validations

This commit is contained in:
Agusti Fernandez Pardo committed 2022-03-24 23:10:24 +01:00
1 parent 713f53acc4
commit dfa227f1b6
4 files changed
+63 -24

No files matched your search

+12 -7
View File
@@ -28,15 +28,20 @@ type ResponseData = {
export async function eventType(req: NextApiRequest, res: NextApiResponse<ResponseData>) {
const { query, method } = req;
if (method === "GET") {
const safe = await schema.safeParse(query);
if (safe.success) {
try {
try {
const safe = await schema.safeParse(query);
// if (!safe.success) {
// res.status(500).json({ error: safe.error.message });
// }
if (safe.success) {
const event = await prisma.eventType.findUnique({ where: { id: safe.data.id } });
res.status(200).json({ data: event });
} catch (error) {
console.log(error);
res.status(400).json({ error: error });
if (event) res.status(200).json({ data: event });
if (!event) res.status(404).json({ error: "Event type not found" });
}
} catch (error) {
console.log("catched", error);
res.status(500).json({ error: error });
}
} else {
// Reject any other HTTP method than POST
+20 -10
View File
@@ -14,32 +14,42 @@ const schema = z
})
.strict(); // Adding strict so that we can disallow passing in extra fields
type schema = z.infer<typeof schema>;
const validate = withValidation({
schema,
type: "Zod",
mode: "body",
});
interface Body {
title: string;
slug: string;
length: number;
}
// interface Body {
// title: string;
// slug: string;
// length: number;
// }
type Data = {
data?: EventType;
error?: string;
};
type NextApiRequestWithBody = NextApiRequest & {
body: Body;
// body: Body;
};
async function createEventType(req: NextApiRequestWithBody, res: NextApiResponse<Data>) {
const { body, method }: { body: Body; method?: string } = req;
const { body, method } = req;
if (method === "POST") {
schema.safeParse(body);
const newEvent = await prisma.eventType.create({ data: body });
res.status(201).json({ data: newEvent });
const safe = schema.safeParse(body);
if (safe.success && safe.data) {
await prisma.eventType
.create({
data: { title: safe.data.title, slug: safe.data.slug, length: safe.data.length },
})
.then((event) => res.status(201).json({ data: event }))
.catch((error) => {
console.log(error);
res.status(400).json({ error: "Could not create event type" });
});
}
} else {
// Reject any other HTTP method than POST
res.status(405).json({ error: "Only POST Method allowed" });