26 lines
1.6 KiB
TypeScript
26 lines
1.6 KiB
TypeScript
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;
|
||
}
|