Skip to content

armgit / umami

Public Imported from GitHub
0

Umami is a privacy-first web and product analytics platform. Traffic, campaigns, behavior, conversions, and revenue in one place. No cookies, no surveillance, self-hosted or in the cloud.

1.5 KB
Raw Blame
import { EVENT_COLUMNS, FILTER_COLUMNS, SEGMENT_TYPES, SESSION_COLUMNS } from '@/lib/constants';
import { getQueryFilters, parseRequest } from '@/lib/request';
import { badRequest, json, unauthorized } from '@/lib/response';
import { fieldsParam, searchParams, withDateRange } from '@/lib/schema';
import { canViewWebsiteSection } from '@/permissions';
import { getWebsiteSegments } from '@/queries/prisma';
import { getValues } from '@/queries/sql';

export async function GET(
  request: Request,
  { params }: { params: Promise<{ websiteId: string }> },
) {
  const schema = withDateRange({
    type: fieldsParam,
    ...searchParams,
  });

  const { auth, query, error } = await parseRequest(request, schema);

  if (error) {
    return error();
  }

  const { websiteId } = await params;

  if (
    !(await canViewWebsiteSection(auth, websiteId, [
      'overview',
      'events',
      'sessions',
      'compare',
      'breakdown',
      'utm',
      'attribution',
    ]))
  ) {
    return unauthorized();
  }

  const { type } = query;

  if (!SESSION_COLUMNS.includes(type) && !EVENT_COLUMNS.includes(type) && !SEGMENT_TYPES[type]) {
    return badRequest();
  }

  let values: any[];

  if (SEGMENT_TYPES[type]) {
    values = (await getWebsiteSegments(websiteId, type))?.data?.map(segment => ({
      value: segment.name,
    }));
  } else {
    const filters = await getQueryFilters(query, websiteId);
    values = await getValues(websiteId, FILTER_COLUMNS[type], filters);
  }

  return json(values.filter(n => n?.value != null).sort());
}