import type { LoaderFunctionArgs } from "react-router"; import { loadWebConfig } from "@hivegrid/config"; import { getTranslations } from "~/locale/i18next.server"; import { apiPath } from "~/utils/app/CanonicalUrlUtils"; import { requireAuth } from "~/utils/loaders.middleware"; import { getTenantIdFromUrl } from "~/utils/services/.server/urlService"; import { getUserInfo } from "~/utils/session.server"; import { getAbsoluteApiUrl } from "~/utils/url.server"; export const loader = async ({ request, params }: LoaderFunctionArgs) => { await requireAuth({ request, params }); const { t } = await getTranslations(request); const tenantId = await getTenantIdFromUrl(params); const userInfo = await getUserInfo(request); if (!tenantId || !userInfo.userId) { return Response.json({ error: t("notifications.errors.streamTenantSessionRequired") }, { status: 401 }); } const apiAccessToken = loadWebConfig().config.apiAccessToken; if (!apiAccessToken) { return Response.json({ error: t("notifications.errors.streamServiceTokenMissing") }, { status: 503 }); } const apiUrl = new URL(getAbsoluteApiUrl(request, apiPath("notifications/stream", { mode: "host-aware" }))); const requestUrl = new URL(request.url); const afterCursor = request.headers.get("last-event-id") ?? requestUrl.searchParams.get("afterCursor"); if (afterCursor) { apiUrl.searchParams.set("afterCursor", afterCursor); } const response = await fetch(apiUrl, { headers: { authorization: `Bearer ${apiAccessToken}`, "x-hivegrid-tenant-id": tenantId, "x-hivegrid-user-id": userInfo.userId, ...(request.headers.get("last-event-id") ? { "last-event-id": request.headers.get("last-event-id") as string } : {}), ...(request.headers.get("x-request-id") ? { "x-request-id": request.headers.get("x-request-id") as string } : {}), }, }); return new Response(response.body, { status: response.status, headers: { "content-type": response.headers.get("content-type") ?? "text/event-stream; charset=utf-8", "cache-control": response.headers.get("cache-control") ?? "no-cache", ...(response.headers.get("x-request-id") ? { "x-request-id": response.headers.get("x-request-id") as string } : {}), }, }); };