cal.pub0.org/pages/api/users/new.ts

52 lines
1.5 KiB
TypeScript
Raw Normal View History

2022-03-26 04:28:53 +00:00
import type { NextApiRequest, NextApiResponse } from "next";
2022-03-29 01:23:22 +00:00
import prisma from "@calcom/prisma";
2022-03-30 12:17:55 +00:00
2022-03-29 01:23:22 +00:00
import { withMiddleware } from "@lib/helpers/withMiddleware";
2022-03-30 12:17:55 +00:00
import type { UserResponse } from "@lib/types";
import { schemaUserBodyParams, schemaUserPublic, withValidUser } from "@lib/validations/user";
/**
* @swagger
* /api/users/new:
* post:
* summary: Add a new user
* consumes:
* - application/json
* parameters:
* - in: body
* name: user
* description: The user to edit
* schema:
* type: object
* $ref: '#/components/schemas/User'
* required: true
* tags:
* - users
* responses:
* 201:
* description: OK, user created
* model: User
* 400:
* description: Bad request. User body is invalid.
* 401:
* description: Authorization information is missing or invalid.
*/
2022-03-30 12:17:55 +00:00
async function createUser(req: NextApiRequest, res: NextApiResponse<UserResponse>) {
const safe = schemaUserBodyParams.safeParse(req.body);
if (!safe.success) throw new Error("Invalid request body", safe.error);
2022-03-29 01:23:22 +00:00
2022-03-30 12:17:55 +00:00
const user = await prisma.user.create({ data: safe.data });
const data = schemaUserPublic.parse(user);
2022-03-30 12:17:55 +00:00
if (data) res.status(201).json({ data, message: "User created successfully" });
else
(error: Error) =>
res.status(400).json({
message: "Could not create new user",
error,
});
}
2022-03-30 12:17:55 +00:00
export default withMiddleware("HTTP_POST")(withValidUser(createUser));