2021-08-19 12:27:01 +00:00
|
|
|
import type { NextApiRequest, NextApiResponse } from "next";
|
2021-09-22 19:52:38 +00:00
|
|
|
|
2022-07-28 19:58:26 +00:00
|
|
|
import prisma from "@calcom/prisma";
|
|
|
|
|
2021-09-03 20:51:21 +00:00
|
|
|
import { getSession } from "@lib/auth";
|
2021-09-22 19:52:38 +00:00
|
|
|
|
2021-06-05 22:53:33 +00:00
|
|
|
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
|
2021-08-19 12:27:01 +00:00
|
|
|
const session = await getSession({ req: req });
|
2021-12-09 23:51:30 +00:00
|
|
|
if (!session || !session.user?.id) {
|
2021-08-19 12:27:01 +00:00
|
|
|
return res.status(401).json({ message: "Not authenticated" });
|
2021-06-05 22:53:33 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if (req.method === "GET") {
|
|
|
|
const memberships = await prisma.membership.findMany({
|
|
|
|
where: {
|
|
|
|
userId: session.user.id,
|
2021-08-19 12:27:01 +00:00
|
|
|
},
|
2021-06-05 22:53:33 +00:00
|
|
|
});
|
|
|
|
|
|
|
|
const teams = await prisma.team.findMany({
|
|
|
|
where: {
|
|
|
|
id: {
|
2021-08-19 12:27:01 +00:00
|
|
|
in: memberships.map((membership) => membership.teamId),
|
|
|
|
},
|
|
|
|
},
|
2021-06-05 22:53:33 +00:00
|
|
|
});
|
|
|
|
|
|
|
|
return res.status(200).json({
|
|
|
|
membership: memberships.map((membership) => ({
|
2021-08-19 12:27:01 +00:00
|
|
|
role: membership.accepted ? membership.role : "INVITEE",
|
|
|
|
...teams.find((team) => team.id === membership.teamId),
|
|
|
|
})),
|
2021-06-05 22:53:33 +00:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!req.body.teamId) {
|
|
|
|
return res.status(400).json({ message: "Bad request" });
|
|
|
|
}
|
|
|
|
|
|
|
|
// Leave team or decline membership invite of current user
|
|
|
|
if (req.method === "DELETE") {
|
2021-08-19 12:27:01 +00:00
|
|
|
await prisma.membership.delete({
|
2021-06-05 22:53:33 +00:00
|
|
|
where: {
|
2021-08-19 12:27:01 +00:00
|
|
|
userId_teamId: { userId: session.user.id, teamId: req.body.teamId },
|
|
|
|
},
|
2021-06-05 22:53:33 +00:00
|
|
|
});
|
|
|
|
return res.status(204).send(null);
|
|
|
|
}
|
|
|
|
|
|
|
|
// Accept team invitation
|
|
|
|
if (req.method === "PATCH") {
|
2021-08-19 12:27:01 +00:00
|
|
|
await prisma.membership.update({
|
2021-06-05 22:53:33 +00:00
|
|
|
where: {
|
2021-08-19 12:27:01 +00:00
|
|
|
userId_teamId: { userId: session.user.id, teamId: req.body.teamId },
|
2021-06-05 22:53:33 +00:00
|
|
|
},
|
|
|
|
data: {
|
2021-08-19 12:27:01 +00:00
|
|
|
accepted: true,
|
|
|
|
},
|
2021-06-05 22:53:33 +00:00
|
|
|
});
|
|
|
|
|
|
|
|
return res.status(204).send(null);
|
|
|
|
}
|
2021-08-19 12:27:01 +00:00
|
|
|
}
|