Files
MikrotikManager/backend/src/services/evobgp-settings.ts
T

29 lines
1.7 KiB
TypeScript

import { eq, sql } from "drizzle-orm"
import { evoBgpSettingsPatchSchema, type EvoBgpSavePayload } from "@mmapp/contracts/evobgp"
import { db } from "../db/index.js"
import { evobgpSettings } from "../db/schema.js"
import { executeGuardedApplicationWrite } from "./config-mutation-policy.js"
import type { EvoBgpSettingsRow } from "./evobgp-settings-model.js"
export { publicEvoBgpSettings } from "./evobgp-settings-model.js"
/** A GET must not create a configuration row or emit a mutation. */
export async function readEvoBgpSettings(): Promise<EvoBgpSettingsRow> {
const [row] = await db.select().from(evobgpSettings).where(eq(evobgpSettings.id, 1)).limit(1)
return row ? { baseUrl: row.baseUrl, enabled: row.enabled, apiKey: row.apiKey } : { baseUrl: "", enabled: false, apiKey: "" }
}
export async function writeEvoBgpSettings(input: EvoBgpSavePayload): Promise<EvoBgpSettingsRow> {
const patch = evoBgpSettingsPatchSchema.parse(input)
return executeGuardedApplicationWrite({ kind: "evobgp-settings", id: "1" }, "all", async () => {
await db.insert(evobgpSettings).values({ id: 1 }).onConflictDoNothing()
const values: Partial<EvoBgpSettingsRow> = {}
if (patch.baseUrl !== undefined) values.baseUrl = patch.baseUrl
if (patch.enabled !== undefined) values.enabled = patch.enabled
if (patch.apiKey !== undefined) values.apiKey = patch.apiKey ?? ""
const [row] = await db.update(evobgpSettings).set({ ...values, updatedAt: sql`now()` }).where(eq(evobgpSettings.id, 1)).returning()
if (!row) throw new Error("Сохранение EvoBGP не подтверждено сервером")
return { baseUrl: row.baseUrl, enabled: row.enabled, apiKey: row.apiKey }
})
}