2024-11-03 13:57:51 -05:00
|
|
|
import { Request, Response, NextFunction } from "express";
|
|
|
|
import { z } from "zod";
|
|
|
|
import { db } from "@server/db";
|
|
|
|
import { roles } from "@server/db/schema";
|
2024-10-12 21:36:14 -04:00
|
|
|
import response from "@server/utils/response";
|
2024-11-03 13:57:51 -05:00
|
|
|
import HttpCode from "@server/types/HttpCode";
|
|
|
|
import createHttpError from "http-errors";
|
|
|
|
import logger from "@server/logger";
|
|
|
|
import { fromError } from "zod-validation-error";
|
2024-10-12 21:36:14 -04:00
|
|
|
|
|
|
|
const createRoleParamsSchema = z.object({
|
2024-11-03 13:57:51 -05:00
|
|
|
orgId: z.string(),
|
2024-10-12 21:36:14 -04:00
|
|
|
});
|
|
|
|
|
|
|
|
const createRoleSchema = z.object({
|
|
|
|
name: z.string().min(1).max(255),
|
|
|
|
description: z.string().optional(),
|
|
|
|
});
|
|
|
|
|
2024-11-03 13:57:51 -05:00
|
|
|
export async function createRole(
|
|
|
|
req: Request,
|
|
|
|
res: Response,
|
|
|
|
next: NextFunction
|
|
|
|
): Promise<any> {
|
2024-10-12 21:36:14 -04:00
|
|
|
try {
|
|
|
|
const parsedBody = createRoleSchema.safeParse(req.body);
|
|
|
|
if (!parsedBody.success) {
|
|
|
|
return next(
|
|
|
|
createHttpError(
|
|
|
|
HttpCode.BAD_REQUEST,
|
2024-11-03 13:57:51 -05:00
|
|
|
fromError(parsedBody.error).toString()
|
2024-10-12 21:36:14 -04:00
|
|
|
)
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
const roleData = parsedBody.data;
|
|
|
|
|
|
|
|
const parsedParams = createRoleParamsSchema.safeParse(req.params);
|
|
|
|
if (!parsedParams.success) {
|
|
|
|
return next(
|
|
|
|
createHttpError(
|
|
|
|
HttpCode.BAD_REQUEST,
|
2024-11-03 13:57:51 -05:00
|
|
|
fromError(parsedParams.error).toString()
|
2024-10-12 21:36:14 -04:00
|
|
|
)
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
const { orgId } = parsedParams.data;
|
|
|
|
|
2024-11-03 13:57:51 -05:00
|
|
|
const newRole = await db
|
|
|
|
.insert(roles)
|
|
|
|
.values({
|
|
|
|
...roleData,
|
|
|
|
orgId,
|
|
|
|
})
|
|
|
|
.returning();
|
2024-10-12 21:36:14 -04:00
|
|
|
|
|
|
|
return response(res, {
|
|
|
|
data: newRole[0],
|
|
|
|
success: true,
|
|
|
|
error: false,
|
|
|
|
message: "Role created successfully",
|
|
|
|
status: HttpCode.CREATED,
|
|
|
|
});
|
|
|
|
} catch (error) {
|
|
|
|
logger.error(error);
|
2024-11-03 13:57:51 -05:00
|
|
|
return next(
|
2024-11-05 23:55:46 -05:00
|
|
|
createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred")
|
2024-11-03 13:57:51 -05:00
|
|
|
);
|
2024-10-12 21:36:14 -04:00
|
|
|
}
|
2024-11-03 13:57:51 -05:00
|
|
|
}
|