Files
khb_microservices/packages/passwords_backupper/src/http-api.ts
2026-10-22 20:46:23 +03:00

26 lines
1.6 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import Fastify, { type FastifyInstance } from "fastify";
import type { BackupService } from "./service.js";
/** Управление сервисом резервного копирования паролей. Токен из settings.json5 (`passwords_backupper.http.token`), открыт только /healthz. */
export function buildApi(service: BackupService, token: string): FastifyInstance {
const app = Fastify();
app.addHook("onRequest", async (req, reply) => {
if (req.url === "/healthz") return;
if (req.headers.authorization !== `Bearer ${token}`) return reply.code(401).send({ error: "unauthorized" });
});
app.get("/healthz", async () => {
const st = service.status();
return { ok: true, running: st.running !== null, lastSuccessAt: st.lastSuccessAt, time: new Date().toISOString() };
});
/** Запуск копирования (его вызывает scheduler по расписанию и ИТ вручную); 202 сразу, итог - в /status и в Slack при сбое. */
app.post("/runs", async (req, reply) => {
const started = service.start(req.headers["x-trigger"] === "manual" ? "manual" : "schedule");
if (!started) return reply.code(409).send({ error: "копирование уже идёт" });
return reply.code(202).send({ runId: started.record.id, startedAt: started.record.startedAt });
});
/** Итог последнего запуска (без секретов: только размеры, имена и замечания). */
app.get("/status", async () => service.status());
return app;
}