fosrl.pangolin/server/routers/org/createOrg.ts

58 lines
1.4 KiB
TypeScript
Raw Normal View History

2024-10-01 21:34:07 -04:00
import { Request, Response, NextFunction } from 'express';
2024-10-01 21:53:49 -04:00
import { z } from 'zod';
import { db } from '@server/db';
import { orgs } from '@server/db/schema';
2024-10-01 21:34:07 -04:00
import response from "@server/utils/response";
import HttpCode from '@server/types/HttpCode';
2024-10-01 21:53:49 -04:00
import createHttpError from 'http-errors';
const createOrgSchema = z.object({
name: z.string().min(1).max(255),
domain: z.string().min(1).max(255),
});
2024-10-01 21:34:07 -04:00
2024-10-03 22:31:20 -04:00
const MAX_ORGS = 5;
export async function createOrg(req: Request, res: Response, next: NextFunction): Promise<any> {
2024-10-01 21:53:49 -04:00
try {
const parsedBody = createOrgSchema.safeParse(req.body);
if (!parsedBody.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
parsedBody.error.errors.map(e => e.message).join(', ')
)
);
}
2024-10-03 22:31:20 -04:00
const userOrgIds = req.userOrgs;
if (userOrgIds && userOrgIds.length > MAX_ORGS) {
return next(
createHttpError(
HttpCode.FORBIDDEN,
`Maximum number of organizations reached.`
)
);
}
2024-10-01 21:53:49 -04:00
const { name, domain } = parsedBody.data;
const newOrg = await db.insert(orgs).values({
name,
domain,
}).returning();
return res.status(HttpCode.CREATED).send(
2024-10-02 21:17:38 -04:00
response(res, {
2024-10-01 21:53:49 -04:00
data: newOrg[0],
success: true,
error: false,
message: "Organization created successfully",
status: HttpCode.CREATED,
})
);
} catch (error) {
next(error);
}
}