Skip to content

Open-source status page, incident response and uptime monitoring

2.4 KB
Raw Blame
import { createRoute } from "@hono/zod-openapi";
import { Events } from "@openstatus/analytics";
import { and, db, eq } from "@openstatus/db";
import { monitorIncidentTable } from "@openstatus/db/src/schema/monitor_incidents";

import { OpenStatusApiError, openApiErrorResponses } from "@/libs/errors";
import { trackMiddleware } from "@/libs/middlewares";

import type { incidentsApi } from "./index";
import { IncidentSchema, ParamsSchema } from "./schema";

const putRoute = createRoute({
  method: "put",
  tags: ["incident"],
  summary: "Update an incident",
  description: "Acknowledge or resolve an incident",
  path: "/{id}",
  middleware: [trackMiddleware(Events.UpdateIncident)],
  request: {
    params: ParamsSchema,
    body: {
      description: "The incident to update",
      content: {
        "application/json": {
          schema: IncidentSchema.pick({
            acknowledgedAt: true,
            resolvedAt: true,
          })
            .partial()
            .refine(
              (data) =>
                data.acknowledgedAt !== undefined ||
                data.resolvedAt !== undefined,
              "Either acknowledgedAt or resolvedAt must be provided",
            ),
        },
      },
    },
  },
  responses: {
    200: {
      content: {
        "application/json": {
          schema: IncidentSchema,
        },
      },
      description: "Update a monitor",
    },
    ...openApiErrorResponses,
  },
});

export function registerPutIncident(app: typeof incidentsApi) {
  return app.openapi(putRoute, async (c) => {
    const input = c.req.valid("json");
    const workspaceId = c.get("workspace").id;
    const { id } = c.req.valid("param");

    const _incident = await db
      .select()
      .from(monitorIncidentTable)
      .where(
        and(
          eq(monitorIncidentTable.id, Number(id)),
          eq(monitorIncidentTable.workspaceId, workspaceId),
        ),
      )
      .get();

    if (!_incident) {
      throw new OpenStatusApiError({
        code: "NOT_FOUND",
        message: `Incident ${id} not found`,
      });
    }

    const _newIncident = await db
      .update(monitorIncidentTable)
      // TODO: we should set the acknowledgedBy and resolvedBy fields
      .set({ ...input, updatedAt: new Date() })
      .where(eq(monitorIncidentTable.id, Number(id)))
      .returning()
      .get();

    const data = IncidentSchema.parse(_newIncident);

    return c.json(data, 200);
  });
}