All files / src/lib/app/routes overlay.ts

100% Statements 23/23
100% Branches 20/20
100% Functions 4/4
100% Lines 22/22

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68                                  24x 6x 3x   3x 3x       31x 6x       6x 6x 1x     5x 5x 1x     4x 6x 1x     3x 6x   6x                     3x 1x     2x      
import type { Hono } from "hono";
import type { AppEnv } from "../types";
import {
  formatOverlayRoomId,
  isOverlayRelayConfigured,
  sendOverlayMessage,
  type OverlayMessage,
} from "../../overlaySocket";
 
interface TestMessageRequest {
  roomId?: string;
  text?: string;
  author?: string;
  platform?: string;
  avatarUrl?: string;
}
 
const sanitizeOptional = (value?: string): string | undefined => {
  if (typeof value !== "string") {
    return undefined;
  }
  const trimmed = value.trim();
  return trimmed.length > 0 ? trimmed : undefined;
};
 
export function registerOverlayRoutes(app: Hono<AppEnv>): void {
  app.post("/test-message", async (c) => {
    const overrides = {
      endpoint: c.env.WS_URL,
    };
 
    const hasEnvOverrides = Boolean(overrides.endpoint?.trim().length);
    if (!isOverlayRelayConfigured() && !hasEnvOverrides) {
      return c.json({ message: "Overlay relay not configured" }, 503);
    }
 
    const body = await c.req.json<TestMessageRequest>().catch(() => null);
    if (!body) {
      return c.json({ message: "Invalid JSON body" }, 400);
    }
 
    const formattedRoomId = formatOverlayRoomId(body.roomId ?? "");
    if (!formattedRoomId) {
      return c.json({ message: "roomId is required" }, 400);
    }
 
    const text = body.text?.trim() || "Test message";
    const author = body.author?.trim() || "hono:test";
 
    const message: OverlayMessage | null = await sendOverlayMessage(
      {
        roomId: formattedRoomId,
        text,
        author,
        platform: sanitizeOptional(body.platform),
        avatarUrl: sanitizeOptional(body.avatarUrl),
      },
      overrides
    );
 
    if (!message) {
      return c.json({ message: "Unable to publish chat message" }, 500);
    }
 
    return c.json({ status: "sent", message });
  });
}