Skip to content

🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.

2.0 KB
Raw Blame
import { FastifyReply, FastifyRequest } from "fastify";
import { FilterParams } from "@rybbit/shared";
import { SessionReplayQueryService } from "../../services/replay/sessionReplayQueryService.js";
import { enrichWithTraits } from "../analytics/utils/utils.js";

export async function getSessionReplays(
  request: FastifyRequest<{
    Params: { siteId: string };
    Querystring: FilterParams<{
      limit?: string;
      offset?: string;
      userId?: string;
      minDuration?: string;
    }>;
  }>,
  reply: FastifyReply
) {
  try {
    const siteId = Number(request.params.siteId);
    const { limit, offset, userId, minDuration, filters } = request.query;

    const sessionReplayService = new SessionReplayQueryService();
    const replays = await sessionReplayService.getSessionReplayList(siteId, {
      limit: limit ? Number(limit) : 50,
      offset: offset ? Number(offset) : 0,
      userId: userId || undefined,
      minDuration: minDuration ? Number(minDuration) : undefined,
      start_date: request.query.start_date,
      end_date: request.query.end_date,
      // A zoomed chart sends only these; dropping them answered with all time.
      start_datetime: request.query.start_datetime,
      end_datetime: request.query.end_datetime,
      time_zone: request.query.time_zone,
      past_minutes_start: request.query.past_minutes_start ? Number(request.query.past_minutes_start) : undefined,
      past_minutes_end: request.query.past_minutes_end ? Number(request.query.past_minutes_end) : undefined,
      filters: filters || "",
    });

    // The replays from ClickHouse use snake_case and enrichWithTraits expects that format
    const replaysWithTraits = await enrichWithTraits(
      replays as unknown as Array<{ identified_user_id: string }>,
      siteId
    );

    return reply.send({ data: replaysWithTraits });
  } catch (error) {
    request.log.error({ err: error }, "Error fetching session replays");
    return reply.status(500).send({ error: "Internal server error" });
  }
}