cal.pub0.org/apps/web/pages/api/user/profile.ts

50 lines
1.3 KiB
TypeScript
Raw Normal View History

import { PrismaClientKnownRequestError } from "@prisma/client/runtime";
import { pick } from "lodash";
2021-07-11 19:35:56 +00:00
import type { NextApiRequest, NextApiResponse } from "next";
import { getSession } from "@lib/auth";
import prisma from "@lib/prisma";
2021-04-07 15:03:02 +00:00
import { resizeBase64Image } from "@server/lib/resizeBase64Image";
2021-04-07 15:03:02 +00:00
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
2021-07-11 19:35:56 +00:00
const session = await getSession({ req: req });
2021-04-07 15:03:02 +00:00
if (!session) {
2021-07-11 19:35:56 +00:00
res.status(401).json({ message: "Not authenticated" });
return;
}
try {
const avatar = req.body.avatar ? await resizeBase64Image(req.body.avatar) : undefined;
await prisma.user.update({
where: {
id: session.user.id,
},
data: {
...pick(req.body, [
"username",
"name",
"timeZone",
"weekStart",
"hideBranding",
"theme",
"completedOnboarding",
"locale",
]),
avatar,
bio: req.body.description,
2021-07-11 19:35:56 +00:00
},
2021-04-07 15:03:02 +00:00
});
} catch (e) {
if (e instanceof PrismaClientKnownRequestError) {
if (e.code === "P2002") {
return res.status(409).json({ message: "Username already taken" });
}
}
throw e;
}
2021-07-11 19:35:56 +00:00
return res.status(200).json({ message: "Profile updated successfully" });
}