fosrl.pangolin/server/routers/site/getSite.ts

96 lines
2.6 KiB
TypeScript
Raw Normal View History

import { Request, Response, NextFunction } from "express";
import { z } from "zod";
import { db } from "@server/db";
import { sites } from "@server/db/schema";
import { eq, and } from "drizzle-orm";
2024-10-01 21:34:07 -04:00
import response from "@server/utils/response";
import HttpCode from "@server/types/HttpCode";
import createHttpError from "http-errors";
import logger from "@server/logger";
import stoi from "@server/utils/stoi";
import { fromError } from "zod-validation-error";
2024-10-01 21:53:49 -04:00
const getSiteSchema = z.object({
siteId: z
.string()
.optional()
.transform(stoi)
.pipe(z.number().int().positive().optional())
.optional(),
2024-10-14 22:26:32 -04:00
niceId: z.string().optional(),
orgId: z.string().optional(),
2024-10-01 21:53:49 -04:00
});
2024-10-01 21:34:07 -04:00
2024-10-13 22:45:48 -04:00
export type GetSiteResponse = {
siteId: number;
name: string;
subdomain: string;
subnet: string;
};
2024-10-13 22:45:48 -04:00
export async function getSite(
req: Request,
res: Response,
next: NextFunction
): Promise<any> {
2024-10-06 18:05:20 -04:00
try {
const parsedParams = getSiteSchema.safeParse(req.params);
if (!parsedParams.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedParams.error).toString()
2024-10-06 18:05:20 -04:00
)
);
}
2024-10-01 21:53:49 -04:00
2024-10-14 22:26:32 -04:00
const { siteId, niceId, orgId } = parsedParams.data;
2024-10-01 21:53:49 -04:00
2024-10-14 22:26:32 -04:00
let site;
if (siteId) {
site = await db
.select()
2024-10-14 22:26:32 -04:00
.from(sites)
.where(eq(sites.siteId, siteId))
.limit(1);
} else if (niceId && orgId) {
site = await db
.select()
2024-10-14 22:26:32 -04:00
.from(sites)
.where(and(eq(sites.niceId, niceId), eq(sites.orgId, orgId)))
.limit(1);
}
if (!site) {
return next(createHttpError(HttpCode.NOT_FOUND, "Site not found"));
2024-10-14 22:26:32 -04:00
}
2024-10-01 21:53:49 -04:00
2024-10-06 18:05:20 -04:00
if (site.length === 0) {
return next(
createHttpError(
HttpCode.NOT_FOUND,
`Site with ID ${siteId} not found`
)
);
}
2024-10-01 21:53:49 -04:00
2024-10-06 18:05:20 -04:00
return response(res, {
2024-10-13 23:16:52 -04:00
data: {
siteId: site[0].siteId,
2024-10-14 22:26:32 -04:00
niceId: site[0].niceId,
2024-10-13 23:16:52 -04:00
name: site[0].name,
subnet: site[0].subnet,
},
2024-10-06 18:05:20 -04:00
success: true,
error: false,
message: "Site retrieved successfully",
status: HttpCode.OK,
});
} catch (error) {
2024-10-14 22:26:32 -04:00
logger.error("Error from getSite: ", error);
return next(
createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred")
);
2024-10-06 18:05:20 -04:00
}
}