82 lines
2.9 KiB
TypeScript
82 lines
2.9 KiB
TypeScript
import { type Application, type RequestHandler, type Response, Router } from "express";
|
|
import { z } from "zod/v4";
|
|
|
|
import {
|
|
CertificateItemParamsSchema,
|
|
CertificateParamsSchema,
|
|
SaveCertificateConfigurationRequestSchema,
|
|
} from "../../../common/certificate-configurations";
|
|
import type { CertificateConfigurationUseCases } from "../../application/certificate-configuration.use-cases";
|
|
import { buildCertificateResponse } from "../../application/certificate-configuration-response.builder";
|
|
|
|
function fail(response: Response, code: string) {
|
|
response
|
|
.status(code === "INVALID_REQUEST" ? 400 : code.endsWith("NOT_FOUND") ? 404 : 409)
|
|
.json({ code, requestId: response.getHeader("x-request-id") });
|
|
}
|
|
export function registerCertificateConfigurationRoutes(
|
|
app: Application,
|
|
useCases: CertificateConfigurationUseCases,
|
|
authenticate: RequestHandler
|
|
) {
|
|
const router = Router();
|
|
router.get("/:companyId", (request, response, next) => {
|
|
const params = CertificateParamsSchema.safeParse(request.params);
|
|
if (!(params.success && z.strictObject({}).safeParse(request.query).success)) {
|
|
fail(response, "INVALID_REQUEST");
|
|
return;
|
|
}
|
|
useCases
|
|
.get(params.data.companyId)
|
|
.then((result) => {
|
|
if (!result.isSuccess) {
|
|
fail(response, result.error.code);
|
|
return;
|
|
}
|
|
response.json({
|
|
configurations: result.data.configurations.map((item) =>
|
|
buildCertificateResponse(item, result.data)
|
|
),
|
|
});
|
|
})
|
|
.catch(next);
|
|
});
|
|
for (const path of ["/:companyId", "/:companyId/:id/update"]) {
|
|
router.post(path, (request, response, next) => {
|
|
const params = (
|
|
path.endsWith("update") ? CertificateItemParamsSchema : CertificateParamsSchema
|
|
).safeParse(request.params);
|
|
const body = SaveCertificateConfigurationRequestSchema.safeParse(request.body);
|
|
const actor = z
|
|
.object({ userId: z.uuid() })
|
|
.safeParse("session" in request ? request.session : undefined);
|
|
if (
|
|
!(
|
|
params.success &&
|
|
body.success &&
|
|
actor.success &&
|
|
z.strictObject({}).safeParse(request.query).success
|
|
)
|
|
) {
|
|
fail(response, "INVALID_REQUEST");
|
|
return;
|
|
}
|
|
const id =
|
|
"id" in params.data && typeof params.data.id === "string" ? params.data.id : undefined;
|
|
useCases
|
|
.save(params.data.companyId, id, body.data.values, actor.data.userId)
|
|
.then((result) => {
|
|
if (!result.isSuccess) {
|
|
fail(response, result.error.code);
|
|
return;
|
|
}
|
|
response.status(id ? 200 : 201).json({
|
|
configuration: buildCertificateResponse(result.data.configuration, result.data.context),
|
|
});
|
|
})
|
|
.catch(next);
|
|
});
|
|
}
|
|
app.use("/api/certificate-configurations", authenticate, router);
|
|
}
|