69 lines
2.5 KiB
TypeScript
69 lines
2.5 KiB
TypeScript
import { containersStateSchema } from "@mmapp/contracts/containers"
|
|
import { z } from "zod"
|
|
import type { FastifyPluginAsyncZod } from "@fastify/type-provider-zod"
|
|
import {
|
|
getEnabledServerById,
|
|
listContainers,
|
|
listContainersState,
|
|
listContainersForServer,
|
|
removeContainer,
|
|
restartContainer,
|
|
startContainer,
|
|
stopContainer,
|
|
} from "../services/containers-live.js"
|
|
import { ServerIdParamSchema, type ServerIdParams } from "../types/server.js"
|
|
|
|
const RosIdBodySchema = z.object({
|
|
rosId: z.string().min(1),
|
|
})
|
|
|
|
type RosIdBody = z.infer<typeof RosIdBodySchema>
|
|
type MutateFn = typeof startContainer
|
|
|
|
export function createContainersRoutes(deps: { getState?: typeof listContainersState } = {}): FastifyPluginAsyncZod {
|
|
return async (app) => {
|
|
app.get("/containers/state", async (_req, reply) => {
|
|
const state = containersStateSchema.safeParse(await (deps.getState ?? listContainersState)())
|
|
if (!state.success) return reply.status(502).send({ error: "Некорректное состояние каталога контейнеров" })
|
|
return reply.send(state.data)
|
|
})
|
|
app.get("/containers", async (_req, reply) => {
|
|
const containers = await listContainers()
|
|
return reply.send({ containers })
|
|
})
|
|
|
|
app.get("/servers/:id/containers", { schema: { params: ServerIdParamSchema } }, async (req, reply) => {
|
|
const params = req.params as ServerIdParams
|
|
const server = await getEnabledServerById(params.id)
|
|
if (!server) return reply.status(404).send({ error: "Server not found" })
|
|
const containers = await listContainersForServer(server)
|
|
return reply.send({ containers })
|
|
})
|
|
|
|
function registerMutate(path: string, fn: MutateFn) {
|
|
app.post(path, { schema: { params: ServerIdParamSchema, body: RosIdBodySchema } }, async (req, reply) => {
|
|
const params = req.params as ServerIdParams
|
|
const body = req.body as RosIdBody
|
|
const server = await getEnabledServerById(params.id)
|
|
if (!server) return reply.status(404).send({ error: "Server not found" })
|
|
try {
|
|
await fn(server, body.rosId)
|
|
return reply.send({ ok: true })
|
|
} catch (err) {
|
|
return reply.status(502).send({
|
|
error: err instanceof Error ? err.message : "Ошибка RouterOS",
|
|
})
|
|
}
|
|
})
|
|
}
|
|
|
|
registerMutate("/servers/:id/containers/start", startContainer)
|
|
registerMutate("/servers/:id/containers/stop", stopContainer)
|
|
registerMutate("/servers/:id/containers/restart", restartContainer)
|
|
registerMutate("/servers/:id/containers/remove", removeContainer)
|
|
}
|
|
|
|
}
|
|
|
|
export default createContainersRoutes()
|