57 lines
1.6 KiB
TypeScript
57 lines
1.6 KiB
TypeScript
|
|
import { Router, type IRouter } from "express";
|
||
|
|
import { db } from "@workspace/db";
|
||
|
|
import { rulesTable, type Rule } from "@workspace/db";
|
||
|
|
import { eq } from "drizzle-orm";
|
||
|
|
import {
|
||
|
|
ListRulesResponse,
|
||
|
|
UpdateRuleParams,
|
||
|
|
UpdateRuleBody,
|
||
|
|
UpdateRuleResponse,
|
||
|
|
} from "@workspace/api-zod";
|
||
|
|
|
||
|
|
const router: IRouter = Router();
|
||
|
|
|
||
|
|
function serializeRule(r: Rule) {
|
||
|
|
return {
|
||
|
|
id: r.id,
|
||
|
|
ruleId: r.ruleId,
|
||
|
|
axis: r.axis,
|
||
|
|
category: r.category,
|
||
|
|
title: r.title,
|
||
|
|
description: r.description,
|
||
|
|
severity: r.severity,
|
||
|
|
detectionType: r.detectionType,
|
||
|
|
enabled: r.enabled,
|
||
|
|
};
|
||
|
|
}
|
||
|
|
|
||
|
|
router.get("/rules", async (_req, res) => {
|
||
|
|
const rows = await db.select().from(rulesTable).orderBy(rulesTable.id);
|
||
|
|
res.json(ListRulesResponse.parse(rows.map(serializeRule)));
|
||
|
|
});
|
||
|
|
|
||
|
|
router.patch("/rules/:id", async (req, res) => {
|
||
|
|
const params = UpdateRuleParams.safeParse(req.params);
|
||
|
|
if (!params.success) return res.status(400).json({ message: "Ungültige ID" });
|
||
|
|
const parsed = UpdateRuleBody.safeParse(req.body);
|
||
|
|
if (!parsed.success)
|
||
|
|
return res
|
||
|
|
.status(400)
|
||
|
|
.json({ message: "Ungültige Eingabe", details: parsed.error.issues });
|
||
|
|
const d = parsed.data;
|
||
|
|
|
||
|
|
const update: Partial<typeof rulesTable.$inferInsert> = {};
|
||
|
|
if (d.severity !== undefined) update.severity = d.severity;
|
||
|
|
if (d.enabled !== undefined) update.enabled = d.enabled;
|
||
|
|
|
||
|
|
const [updated] = await db
|
||
|
|
.update(rulesTable)
|
||
|
|
.set(update)
|
||
|
|
.where(eq(rulesTable.id, params.data.id))
|
||
|
|
.returning();
|
||
|
|
if (!updated) return res.status(404).json({ message: "Regel nicht gefunden" });
|
||
|
|
return res.json(UpdateRuleResponse.parse(serializeRule(updated)));
|
||
|
|
});
|
||
|
|
|
||
|
|
export default router;
|