2021-09-02 12:13:19 +00:00
|
|
|
import type { NextApiRequest, NextApiResponse } from "next";
|
2021-09-22 19:52:38 +00:00
|
|
|
|
2021-09-03 20:51:21 +00:00
|
|
|
import { getSession } from "@lib/auth";
|
2021-11-11 05:44:53 +00:00
|
|
|
import { getAvailabilityFromSchedule } from "@lib/availability";
|
2021-09-02 12:13:19 +00:00
|
|
|
import prisma from "@lib/prisma";
|
|
|
|
|
|
|
|
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
|
2021-11-11 05:44:53 +00:00
|
|
|
const session = await getSession({ req });
|
2021-11-10 11:16:32 +00:00
|
|
|
const userId = session?.user?.id;
|
|
|
|
if (!userId) {
|
2021-09-02 12:13:19 +00:00
|
|
|
res.status(401).json({ message: "Not authenticated" });
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2021-11-10 11:16:32 +00:00
|
|
|
if (!req.body.schedule || req.body.schedule.length !== 7) {
|
|
|
|
return res.status(400).json({ message: "Bad Request." });
|
|
|
|
}
|
|
|
|
|
2021-11-11 05:44:53 +00:00
|
|
|
const availability = getAvailabilityFromSchedule(req.body.schedule);
|
2021-11-10 11:16:32 +00:00
|
|
|
|
2021-09-02 12:13:19 +00:00
|
|
|
if (req.method === "POST") {
|
|
|
|
try {
|
2021-11-11 05:44:53 +00:00
|
|
|
await prisma.user.update({
|
2021-11-10 11:16:32 +00:00
|
|
|
where: {
|
2021-11-11 05:44:53 +00:00
|
|
|
id: userId,
|
2021-09-02 12:13:19 +00:00
|
|
|
},
|
2021-11-11 05:44:53 +00:00
|
|
|
data: {
|
|
|
|
availability: {
|
|
|
|
/* We delete user availabilty */
|
|
|
|
deleteMany: {
|
|
|
|
userId: {
|
|
|
|
equals: userId,
|
2021-11-10 11:16:32 +00:00
|
|
|
},
|
|
|
|
},
|
2021-11-11 05:44:53 +00:00
|
|
|
/* So we can replace it */
|
|
|
|
createMany: {
|
|
|
|
data: availability.map((schedule) => ({
|
|
|
|
days: schedule.days,
|
|
|
|
startTime: schedule.startTime,
|
|
|
|
endTime: schedule.endTime,
|
|
|
|
})),
|
|
|
|
},
|
|
|
|
},
|
|
|
|
},
|
|
|
|
});
|
2021-09-02 12:13:19 +00:00
|
|
|
return res.status(200).json({
|
|
|
|
message: "created",
|
|
|
|
});
|
|
|
|
} catch (error) {
|
|
|
|
console.error(error);
|
|
|
|
return res.status(500).json({ message: "Unable to create schedule." });
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|