🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.
Delete failed actions
Bill Yangb9b90ce2a356
diff --git a/client/src/actions/getPageviews.ts b/client/src/actions/getPageviews.tsdeleted file mode 100644index 24aadb26e..000000000--- a/client/src/actions/getPageviews.ts+++ /dev/null@@ -1,52 +0,0 @@-"use server";--import { clickhouse } from "@/lib/clickhouse";-import { getTimeStatement } from "./utils";-import { TimeBucket } from "../lib/timeSelectionStore";--export type GetPageViewsResponse = { time: string; pageviews: number }[];--const TimeBucketToFn = {- hour: "toStartOfHour",- day: "toStartOfDay",- week: "toStartOfWeek",- month: "toStartOfMonth",-};--export async function getPageViews({- startDate,- endDate,- timezone = "America/Los_Angeles",- bucket,-}: {- startDate: string;- endDate: string;- timezone: string;- bucket: TimeBucket;-}): Promise<{ data?: GetPageViewsResponse; error?: string }> {- const query = `- SELECT- ${TimeBucketToFn[bucket]}(toTimeZone(timestamp, '${timezone}')) AS time,- count() AS pageviews- FROM pageviews- WHERE- ${getTimeStatement(startDate, endDate, timezone)}- GROUP BY- time- ORDER BY- time ASC- `;-- try {- const result = await clickhouse.query({- query,- format: "JSONEachRow",- });-- const data: GetPageViewsResponse = await result.json();- return { data };- } catch (error) {- console.error("Error fetching pageviews:", error);- return { error: "Failed to fetch pageviews" };- }-}diff --git a/client/src/app/components/MainSection/MainSection.tsx b/client/src/app/components/MainSection/MainSection.tsxindex 6aa1d0662..db1b7aaeb 100644--- a/client/src/app/components/MainSection/MainSection.tsx+++ b/client/src/app/components/MainSection/MainSection.tsx@@ -1,12 +1,13 @@"use client";import { Card, CardContent, CardLoader } from "@/components/ui/card";import { useTimeSelection } from "../../../lib/timeSelectionStore";-import { useGetPageviews } from "../../../hooks/useGetPageviews";import { BucketSelection } from "./BucketSelection";import { Chart } from "./Chart";+import { useGetPageviews } from "../../../hooks/api";export function MainSection() {const { data, isLoading, error } = useGetPageviews();+ console.log(data);return (<Card>diff --git a/client/src/app/components/sections/Browsers/Browsers.tsx b/client/src/app/components/sections/Browsers/Browsers.tsxindex 960208491..7c0670118 100644--- a/client/src/app/components/sections/Browsers/Browsers.tsx+++ b/client/src/app/components/sections/Browsers/Browsers.tsx@@ -2,8 +2,8 @@import { Compass } from "lucide-react";import Image from "next/image";-import { useGetBrowsers } from "../../../../hooks/useGetBrowsers";import { StandardCard } from "../../shared/StandardCard";+import { useGetBrowsers } from "../../../../hooks/api";const BROWSER_TO_LOGO: Record<string, string> = {Chrome: "Chrome.svg",diff --git a/client/src/app/components/sections/Countries/Countries.tsx b/client/src/app/components/sections/Countries/Countries.tsxindex 8284a4524..1088e6c88 100644--- a/client/src/app/components/sections/Countries/Countries.tsx+++ b/client/src/app/components/sections/Countries/Countries.tsx@@ -1,10 +1,10 @@"use client";import React from "react";-import { useGetCountries } from "../../../../hooks/useGetCountries";import { StandardCard } from "../../shared/StandardCard";import { countries } from "countries-list";import * as CountryFlags from "country-flag-icons/react/3x2";+import { useGetCountries } from "../../../../hooks/api";export function Countries() {const { data, isLoading } = useGetCountries();diff --git a/client/src/app/components/sections/Devices/Devices.tsx b/client/src/app/components/sections/Devices/Devices.tsxindex 63d6819af..bcec478f4 100644--- a/client/src/app/components/sections/Devices/Devices.tsx+++ b/client/src/app/components/sections/Devices/Devices.tsx@@ -1,6 +1,6 @@"use client";-import { useGetDevices } from "../../../../hooks/useGetDevices";+import { useGetDevices } from "../../../../hooks/api";import { StandardCard } from "../../shared/StandardCard";export function Devices() {diff --git a/client/src/app/components/sections/Map/Chloropleth.tsx b/client/src/app/components/sections/Map/Chloropleth.tsxindex ae4b76152..457683f56 100644--- a/client/src/app/components/sections/Map/Chloropleth.tsx+++ b/client/src/app/components/sections/Map/Chloropleth.tsx@@ -1,12 +1,12 @@"use client";-import { useGetCountries } from "../../../../hooks/useGetCountries";import { LatLngExpression } from "leaflet";import "leaflet/dist/leaflet.css";import { useEffect, useMemo, useState } from "react";import { Feature, FeatureCollection } from "geojson";import { scaleLinear } from "d3-scale";import dynamic from "next/dynamic";+import { useGetCountries } from "../../../../hooks/api";const MapContainer = dynamic(() => import("react-leaflet").then((mod) => mod.MapContainer),diff --git a/client/src/app/components/sections/Map/Map.tsx b/client/src/app/components/sections/Map/Map.tsxindex 6521158a1..5e30cea3b 100644--- a/client/src/app/components/sections/Map/Map.tsx+++ b/client/src/app/components/sections/Map/Map.tsx@@ -20,8 +20,8 @@ import {import { countries } from "countries-list";import * as CountryFlags from "country-flag-icons/react/3x2";-import { useGetCountries } from "../../../../hooks/useGetCountries";import React from "react";+import { useGetCountries } from "../../../../hooks/api";const geoUrl = "/countries.geojson";diff --git a/client/src/app/components/sections/OperatingSystems/OperatingSystems.tsx b/client/src/app/components/sections/OperatingSystems/OperatingSystems.tsxindex a26c2a8ea..505e60e18 100644--- a/client/src/app/components/sections/OperatingSystems/OperatingSystems.tsx+++ b/client/src/app/components/sections/OperatingSystems/OperatingSystems.tsx@@ -1,9 +1,9 @@"use client";import { Compass } from "lucide-react";-import { useGetOperatingSystems } from "../../../../hooks/useGetOperatingSystems";import { StandardCard } from "../../shared/StandardCard";import Image from "next/image";+import { useGetOperatingSystems } from "../../../../hooks/api";const OS_TO_LOGO: Record<string, string> = {Windows: "Windows.svg",diff --git a/client/src/app/components/sections/Pages/Pages.tsx b/client/src/app/components/sections/Pages/Pages.tsxindex 4241abbc2..48bc42845 100644--- a/client/src/app/components/sections/Pages/Pages.tsx+++ b/client/src/app/components/sections/Pages/Pages.tsx@@ -1,6 +1,6 @@"use client";-import { useGetPages } from "../../../../hooks/useGetPages";+import { useGetPages } from "../../../../hooks/api";import { StandardCard } from "../../shared/StandardCard";export function Pages() {diff --git a/client/src/app/components/sections/Referrers/Referrers.tsx b/client/src/app/components/sections/Referrers/Referrers.tsxindex 99dd6f3bf..3d9475b63 100644--- a/client/src/app/components/sections/Referrers/Referrers.tsx+++ b/client/src/app/components/sections/Referrers/Referrers.tsx@@ -1,6 +1,6 @@"use client";-import { useGetReferrers } from "../../../../hooks/useGetReferrers";+import { useGetReferrers } from "../../../../hooks/api";import { StandardCard } from "../../shared/StandardCard";export function Referrers() {diff --git a/client/src/hooks/api.ts b/client/src/hooks/api.tsnew file mode 100644index 000000000..6327a17a1--- /dev/null+++ b/client/src/hooks/api.ts@@ -0,0 +1,108 @@+import { useQuery, UseQueryResult } from "@tanstack/react-query";+import { useTimeSelection } from "../lib/timeSelectionStore";+import { getStartAndEndDate } from "./utils";++export type APIResponse<T> = {+ data: T;+ error?: string;+};++export function useGenericQuery<T>(+ endpoint: string+): UseQueryResult<APIResponse<T>> {+ const { time } = useTimeSelection();+ const { startDate, endDate } = getStartAndEndDate(time);++ return useQuery({+ queryKey: [endpoint, time],+ queryFn: () => {+ const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;+ return fetch(+ `${process.env.BACKEND_URL}/${endpoint}?startDate=${startDate}&endDate=${endDate}&timezone=${timezone}`+ ).then((res) => res.json());+ },+ });+}++export type GetCountriesResponse = {+ country: string;+ count: number;+ percentage: number;+}[];++export function useGetCountries() {+ return useGenericQuery<GetCountriesResponse>("countries");+}++type GetDevicesResponse = {+ device_type: string;+ count: number;+ percentage: number;+}[];++export function useGetDevices() {+ return useGenericQuery<GetDevicesResponse>("devices");+}++type GetOperatingSystemsResponse = {+ operating_system: string;+ count: number;+ percentage: number;+}[];++export function useGetOperatingSystems() {+ return useGenericQuery<GetOperatingSystemsResponse>("operating-systems");+}++type GetBrowsersResponse = {+ browser: string;+ count: number;+ percentage: number;+}[];++export function useGetBrowsers() {+ return useGenericQuery<GetBrowsersResponse>("browsers");+}++type GetPagesResponse = {+ pathname: string;+ count: number;+ percentage: number;+}[];++export function useGetPages() {+ return useGenericQuery<GetPagesResponse>("pages");+}++type GetReferrersResponse = {+ referrer: string;+ count: number;+ percentage: number;+}[];++export function useGetReferrers() {+ return useGenericQuery<GetReferrersResponse>("referrers");+}++type GetPageViewsResponse = {+ time: string;+ pageviews: number;+}[];++export function useGetPageviews(): UseQueryResult<+ APIResponse<GetPageViewsResponse>+> {+ const { time, bucket } = useTimeSelection();++ const { startDate, endDate } = getStartAndEndDate(time);++ return useQuery({+ queryKey: ["pageviews", time, bucket],+ queryFn: () => {+ const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;+ return fetch(+ `${process.env.BACKEND_URL}/pageviews?startDate=${startDate}&endDate=${endDate}&timezone=${timezone}&bucket=${bucket}`+ ).then((res) => res.json());+ },+ });+}diff --git a/client/src/hooks/useGetBrowsers.ts b/client/src/hooks/useGetBrowsers.tsdeleted file mode 100644index 352e62ae6..000000000--- a/client/src/hooks/useGetBrowsers.ts+++ /dev/null@@ -1,22 +0,0 @@-import { useQuery } from "@tanstack/react-query";-import { useTimeSelection } from "../lib/timeSelectionStore";-import { getBrowsers } from "../actions/getBrowsers";-import { getStartAndEndDate } from "./utils";--export function useGetBrowsers() {- const { time } = useTimeSelection();-- const { startDate, endDate } = getStartAndEndDate(time);-- return useQuery({- queryKey: ["browsers", time],- queryFn: () => {- const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;- return getBrowsers({- startDate,- endDate,- timezone,- });- },- });-}diff --git a/client/src/hooks/useGetCountries.ts b/client/src/hooks/useGetCountries.tsdeleted file mode 100644index 58b7f10e9..000000000--- a/client/src/hooks/useGetCountries.ts+++ /dev/null@@ -1,22 +0,0 @@-import { useQuery } from "@tanstack/react-query";-import { useTimeSelection } from "../lib/timeSelectionStore";-import { getCountries } from "../actions/getCountries";-import { getStartAndEndDate } from "./utils";--export function useGetCountries() {- const { time } = useTimeSelection();-- const { startDate, endDate } = getStartAndEndDate(time);-- return useQuery({- queryKey: ["countries", time],- queryFn: () => {- const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;- return getCountries({- startDate,- endDate,- timezone,- });- },- });-}diff --git a/client/src/hooks/useGetDevices.ts b/client/src/hooks/useGetDevices.tsdeleted file mode 100644index 9a349733b..000000000--- a/client/src/hooks/useGetDevices.ts+++ /dev/null@@ -1,22 +0,0 @@-import { useQuery } from "@tanstack/react-query";-import { useTimeSelection } from "../lib/timeSelectionStore";-import { getDevices } from "../actions/getDevices";-import { getStartAndEndDate } from "./utils";--export function useGetDevices() {- const { time } = useTimeSelection();-- const { startDate, endDate } = getStartAndEndDate(time);-- return useQuery({- queryKey: ["devices", time],- queryFn: () => {- const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;- return getDevices({- startDate,- endDate,- timezone,- });- },- });-}diff --git a/client/src/hooks/useGetOperatingSystems.ts b/client/src/hooks/useGetOperatingSystems.tsdeleted file mode 100644index ac37569d5..000000000--- a/client/src/hooks/useGetOperatingSystems.ts+++ /dev/null@@ -1,22 +0,0 @@-import { useQuery } from "@tanstack/react-query";-import { useTimeSelection } from "../lib/timeSelectionStore";-import { getStartAndEndDate } from "./utils";-import { getOperatingSystems } from "../actions/getOperatingSystems";--export function useGetOperatingSystems() {- const { time } = useTimeSelection();-- const { startDate, endDate } = getStartAndEndDate(time);-- return useQuery({- queryKey: ["operating-systems", time],- queryFn: () => {- const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;- return getOperatingSystems({- startDate,- endDate,- timezone,- });- },- });-}diff --git a/client/src/hooks/useGetPages.ts b/client/src/hooks/useGetPages.tsdeleted file mode 100644index 2c7aa0aa4..000000000--- a/client/src/hooks/useGetPages.ts+++ /dev/null@@ -1,22 +0,0 @@-import { useQuery } from "@tanstack/react-query";-import { useTimeSelection } from "../lib/timeSelectionStore";-import { getStartAndEndDate } from "./utils";-import { getPages } from "../actions/getPages";--export function useGetPages() {- const { time } = useTimeSelection();-- const { startDate, endDate } = getStartAndEndDate(time);-- return useQuery({- queryKey: ["pages", time],- queryFn: () => {- const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;- return getPages({- startDate,- endDate,- timezone,- });- },- });-}diff --git a/client/src/hooks/useGetPageviews.ts b/client/src/hooks/useGetPageviews.tsdeleted file mode 100644index 48f244f5d..000000000--- a/client/src/hooks/useGetPageviews.ts+++ /dev/null@@ -1,23 +0,0 @@-import { useQuery } from "@tanstack/react-query";-import { useTimeSelection } from "../lib/timeSelectionStore";-import { getPageViews } from "../actions/getPageviews";-import { getStartAndEndDate } from "./utils";--export function useGetPageviews() {- const { time, bucket } = useTimeSelection();-- const { startDate, endDate } = getStartAndEndDate(time);-- return useQuery({- queryKey: ["pageviews", time, bucket],- queryFn: () => {- const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;- return getPageViews({- startDate,- endDate,- timezone,- bucket,- });- },- });-}diff --git a/client/src/hooks/useGetReferrers.ts b/client/src/hooks/useGetReferrers.tsdeleted file mode 100644index afc4d0dcd..000000000--- a/client/src/hooks/useGetReferrers.ts+++ /dev/null@@ -1,22 +0,0 @@-import { useQuery } from "@tanstack/react-query";-import { useTimeSelection } from "../lib/timeSelectionStore";-import { getReferrers } from "../actions/getReferrers";-import { getStartAndEndDate } from "./utils";--export function useGetReferrers() {- const { time } = useTimeSelection();-- const { startDate, endDate } = getStartAndEndDate(time);-- return useQuery({- queryKey: ["referrers", time],- queryFn: () => {- const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;- return getReferrers({- startDate,- endDate,- timezone,- });- },- });-}diff --git a/server/package-lock.json b/server/package-lock.jsonindex 6bb473418..e19c254e4 100644--- a/server/package-lock.json+++ b/server/package-lock.json@@ -8,7 +8,7 @@"name": "analytics-backend","version": "1.0.0","dependencies": {- "@clickhouse/client": "^0.2.7",+ "@clickhouse/client": "^1.10.1","@fastify/cors": "^10.0.2","@fastify/one-line-logger": "^1.4.0","@fastify/static": "^8.0.4",@@ -27,20 +27,20 @@}},"node_modules/@clickhouse/client": {- "version": "0.2.7",- "resolved": "https://registry.npmjs.org/@clickhouse/client/-/client-0.2.7.tgz",- "integrity": "sha512-ZiyarrGngHc+f5AjZSA7mkQfvnE/71jgXk304B0ps8V+aBpE2CsFB6AQmE/Mk2YkP5j+8r/JfG+m0AZWmE27ig==",+ "version": "1.10.1",+ "resolved": "https://registry.npmjs.org/@clickhouse/client/-/client-1.10.1.tgz",+ "integrity": "sha512-Ot/6l4hFALK6NtZDS2UegukfRXWkkftWHCnzKUwanpOQ3Jd+RVKx5dxQreeBG5XcRjt1xyf5904PFjbCnaulXg==","dependencies": {- "@clickhouse/client-common": "0.2.7"+ "@clickhouse/client-common": "1.10.1"},"engines": {"node": ">=16"}},"node_modules/@clickhouse/client-common": {- "version": "0.2.7",- "resolved": "https://registry.npmjs.org/@clickhouse/client-common/-/client-common-0.2.7.tgz",- "integrity": "sha512-vgZm+8c5Cu1toIx1/xplF5dEHlCPw+7pJDOOEtLv2CIUVZ0Bl6nGVZ43EWxRdHeah9ivTfoRWhN1zI1PxjH0xQ=="+ "version": "1.10.1",+ "resolved": "https://registry.npmjs.org/@clickhouse/client-common/-/client-common-1.10.1.tgz",+ "integrity": "sha512-Duh3cign2ChvXABpjVj9Hkz5y20Zf48OE0Y50S4qBVPdhI81S4Rh4MI/bEwvwMnzHubSkiEQ+VhC5HzV8ybnpg=="},"node_modules/@cspotcode/source-map-support": {"version": "0.8.1",diff --git a/server/package.json b/server/package.jsonindex d8f68eac9..5c88a8283 100644--- a/server/package.json+++ b/server/package.json@@ -9,7 +9,7 @@"start": "node dist/index.js"},"dependencies": {- "@clickhouse/client": "^0.2.7",+ "@clickhouse/client": "^1.10.1","@fastify/cors": "^10.0.2","@fastify/one-line-logger": "^1.4.0","@fastify/static": "^8.0.4",diff --git a/client/src/actions/getBrowsers.ts b/server/src/api/getBrowsers.tssimilarity index 63%rename from client/src/actions/getBrowsers.tsrename to server/src/api/getBrowsers.tsindex 6e65a4748..dbaeb86be 100644--- a/client/src/actions/getBrowsers.ts+++ b/server/src/api/getBrowsers.ts@@ -1,6 +1,6 @@-"use server";--import { clickhouse } from "@/lib/clickhouse";+import { FastifyReply, FastifyRequest } from "fastify";+import clickhouse from "../db/clickhouse/clickhouse";+import { GenericRequest } from "./types";import { getTimeStatement, processResults } from "./utils";type GetBrowsersResponse = {@@ -9,15 +9,10 @@ type GetBrowsersResponse = {percentage: number;}[];-export async function getBrowsers({- startDate,- endDate,- timezone = "America/Los_Angeles",-}: {- startDate: string;- endDate: string;- timezone: string;-}): Promise<{ data?: GetBrowsersResponse; error?: string }> {+export async function getBrowsers(+ { query: { startDate, endDate, timezone } }: FastifyRequest<GenericRequest>,+ res: FastifyReply+) {const query = `SELECTbrowser,@@ -36,9 +31,9 @@ export async function getBrowsers({});const data = await processResults<GetBrowsersResponse[number]>(result);- return { data };+ return res.send({ data });} catch (error) {console.error("Error fetching browsers:", error);- return { error: "Failed to fetch browsers" };+ return res.status(500).send({ error: "Failed to fetch browsers" });}}diff --git a/client/src/actions/getCountries.ts b/server/src/api/getCountries.tssimilarity index 63%rename from client/src/actions/getCountries.tsrename to server/src/api/getCountries.tsindex abb1cb6c0..fe38fc947 100644--- a/client/src/actions/getCountries.ts+++ b/server/src/api/getCountries.ts@@ -1,6 +1,6 @@-"use server";--import { clickhouse } from "@/lib/clickhouse";+import { FastifyReply, FastifyRequest } from "fastify";+import clickhouse from "../db/clickhouse/clickhouse";+import { GenericRequest } from "./types";import { getTimeStatement, processResults } from "./utils";type GetCountriesResponse = {@@ -9,15 +9,10 @@ type GetCountriesResponse = {percentage: number;}[];-export async function getCountries({- startDate,- endDate,- timezone = "America/Los_Angeles",-}: {- startDate: string;- endDate: string;- timezone: string;-}): Promise<{ data?: GetCountriesResponse; error?: string }> {+export async function getCountries(+ { query: { startDate, endDate, timezone } }: FastifyRequest<GenericRequest>,+ res: FastifyReply+) {const query = `SELECTcountry,@@ -36,9 +31,9 @@ export async function getCountries({});const data = await processResults<GetCountriesResponse[number]>(result);- return { data };+ return res.send({ data });} catch (error) {console.error("Error fetching countries:", error);- return { error: "Failed to fetch countries" };+ return res.status(500).send({ error: "Failed to fetch countries" });}}diff --git a/client/src/actions/getDevices.ts b/server/src/api/getDevices.tssimilarity index 64%rename from client/src/actions/getDevices.tsrename to server/src/api/getDevices.tsindex c2ce01efb..fc0358a69 100644--- a/client/src/actions/getDevices.ts+++ b/server/src/api/getDevices.ts@@ -1,6 +1,6 @@-"use server";--import { clickhouse } from "@/lib/clickhouse";+import { FastifyReply, FastifyRequest } from "fastify";+import clickhouse from "../db/clickhouse/clickhouse";+import { GenericRequest } from "./types";import { getTimeStatement, processResults } from "./utils";type GetDevicesResponse = {@@ -9,15 +9,10 @@ type GetDevicesResponse = {percentage: number;}[];-export async function getDevices({- startDate,- endDate,- timezone = "America/Los_Angeles",-}: {- startDate: string;- endDate: string;- timezone: string;-}): Promise<{ data?: GetDevicesResponse; error?: string }> {+export async function getDevices(+ { query: { startDate, endDate, timezone } }: FastifyRequest<GenericRequest>,+ res: FastifyReply+) {const query = `SELECTdevice_type,@@ -36,9 +31,9 @@ export async function getDevices({});const data = await processResults<GetDevicesResponse[number]>(result);- return { data };+ return res.send({ data });} catch (error) {console.error("Error fetching devices:", error);- return { error: "Failed to fetch devices" };+ return res.status(500).send({ error: "Failed to fetch devices" });}}diff --git a/client/src/actions/getOperatingSystems.ts b/server/src/api/getOperatingSystems.tssimilarity index 64%rename from client/src/actions/getOperatingSystems.tsrename to server/src/api/getOperatingSystems.tsindex ac324f8e7..d71704f4b 100644--- a/client/src/actions/getOperatingSystems.ts+++ b/server/src/api/getOperatingSystems.ts@@ -1,6 +1,6 @@-"use server";--import { clickhouse } from "@/lib/clickhouse";+import { FastifyReply, FastifyRequest } from "fastify";+import clickhouse from "../db/clickhouse/clickhouse";+import { GenericRequest } from "./types";import { getTimeStatement, processResults } from "./utils";type GetOperatingSystemsResponse = {@@ -9,15 +9,10 @@ type GetOperatingSystemsResponse = {percentage: number;}[];-export async function getOperatingSystems({- startDate,- endDate,- timezone = "America/Los_Angeles",-}: {- startDate: string;- endDate: string;- timezone: string;-}): Promise<{ data?: GetOperatingSystemsResponse; error?: string }> {+export async function getOperatingSystems(+ { query: { startDate, endDate, timezone } }: FastifyRequest<GenericRequest>,+ res: FastifyReply+) {const query = `SELECToperating_system,@@ -38,9 +33,9 @@ export async function getOperatingSystems({const data = await processResults<GetOperatingSystemsResponse[number]>(result);- return { data };+ return res.send({ data });} catch (error) {console.error("Error fetching operating systems:", error);- return { error: "Failed to fetch operating systems" };+ return res.status(500).send({ error: "Failed to fetch operating systems" });}}diff --git a/server/src/api/getPageViews.ts b/server/src/api/getPageViews.tsnew file mode 100644index 000000000..8105cee77--- /dev/null+++ b/server/src/api/getPageViews.ts@@ -0,0 +1,54 @@+import { FastifyReply, FastifyRequest } from "fastify";+import clickhouse from "../db/clickhouse/clickhouse";+import { getTimeStatement, processResults } from "./utils";++const TimeBucketToFn = {+ hour: "toStartOfHour",+ day: "toStartOfDay",+ week: "toStartOfWeek",+ month: "toStartOfMonth",+};++type TimeBucket = "hour" | "day" | "week" | "month";++type GetPageViewsResponse = { time: string; pageviews: number }[];++export async function getPageViews(+ {+ query: { startDate, endDate, timezone, bucket },+ }: FastifyRequest<{+ Querystring: {+ startDate: string;+ endDate: string;+ timezone: string;+ bucket: TimeBucket;+ };+ }>,+ res: FastifyReply+) {+ const query = `+ SELECT+ ${TimeBucketToFn[bucket]}(toTimeZone(timestamp, '${timezone}')) AS time,+ count() AS pageviews+ FROM pageviews+ WHERE+ ${getTimeStatement(startDate, endDate, timezone)}+ GROUP BY+ time+ ORDER BY+ time ASC+ `;++ try {+ const result = await clickhouse.query({+ query,+ format: "JSONEachRow",+ });++ const data = await processResults<GetPageViewsResponse[number]>(result);+ return res.send({ data });+ } catch (error) {+ console.error("Error fetching pageviews:", error);+ return res.status(500).send({ error: "Failed to fetch pageviews" });+ }+}diff --git a/client/src/actions/getPages.ts b/server/src/api/getPages.tssimilarity index 64%rename from client/src/actions/getPages.tsrename to server/src/api/getPages.tsindex c98a0fbd2..768579a78 100644--- a/client/src/actions/getPages.ts+++ b/server/src/api/getPages.ts@@ -1,7 +1,7 @@-"use server";--import { clickhouse } from "@/lib/clickhouse";+import { FastifyReply, FastifyRequest } from "fastify";import { getTimeStatement, processResults } from "./utils";+import clickhouse from "../db/clickhouse/clickhouse";+import { GenericRequest } from "./types";type GetPagesResponse = {pathname: string;@@ -9,15 +9,10 @@ type GetPagesResponse = {percentage: number;}[];-export async function getPages({- startDate,- endDate,- timezone = "America/Los_Angeles",-}: {- startDate: string;- endDate: string;- timezone: string;-}): Promise<{ data?: GetPagesResponse; error?: string }> {+export async function getPages(+ { query: { startDate, endDate, timezone } }: FastifyRequest<GenericRequest>,+ res: FastifyReply+) {const query = `SELECTpathname,@@ -38,9 +33,9 @@ export async function getPages({});const data = await processResults<GetPagesResponse[number]>(result);- return { data };+ return res.send({ data });} catch (error) {console.error("Error fetching pages:", error);- return { error: "Failed to fetch pages" };+ return res.status(500).send({ error: "Failed to fetch pages" });}}diff --git a/client/src/actions/getReferrers.ts b/server/src/api/getReferrers.tssimilarity index 65%rename from client/src/actions/getReferrers.tsrename to server/src/api/getReferrers.tsindex abb5936ce..28db09f87 100644--- a/client/src/actions/getReferrers.ts+++ b/server/src/api/getReferrers.ts@@ -1,7 +1,7 @@-"use server";--import { clickhouse } from "@/lib/clickhouse";+import { FastifyReply, FastifyRequest } from "fastify";import { getTimeStatement, processResults } from "./utils";+import clickhouse from "../db/clickhouse/clickhouse";+import { GenericRequest } from "./types";type GetReferrersResponse = {referrer: string;@@ -9,15 +9,10 @@ type GetReferrersResponse = {percentage: number;}[];-export async function getReferrers({- startDate,- endDate,- timezone = "America/Los_Angeles",-}: {- startDate: string;- endDate: string;- timezone: string;-}): Promise<{ data?: GetReferrersResponse; error?: string }> {+export async function getReferrers(+ { query: { startDate, endDate, timezone } }: FastifyRequest<GenericRequest>,+ res: FastifyReply+) {const query = `SELECTdomainWithoutWWW(referrer) AS referrer,@@ -38,9 +33,9 @@ export async function getReferrers({});const data = await processResults<GetReferrersResponse[number]>(result);- return { data };+ return res.send({ data });} catch (error) {console.error("Error fetching referrers:", error);- return { error: "Failed to fetch referrers" };+ return res.status(500).send({ error: "Failed to fetch referrers" });}}diff --git a/server/src/api/types.ts b/server/src/api/types.tsnew file mode 100644index 000000000..30bea3de7--- /dev/null+++ b/server/src/api/types.ts@@ -0,0 +1,3 @@+export interface GenericRequest {+ Querystring: { startDate: string; endDate: string; timezone: string };+}diff --git a/client/src/actions/utils.ts b/server/src/api/utils.tssimilarity index 100%rename from client/src/actions/utils.tsrename to server/src/api/utils.tsdiff --git a/server/src/index.ts b/server/src/index.tsindex 7b5d42a41..336054baf 100644--- a/server/src/index.ts+++ b/server/src/index.ts@@ -9,6 +9,13 @@ import { initializePostgres } from "./db/postgres/postgres";import cron from "node-cron";import { cleanupOldSessions } from "./db/postgres/session-cleanup";import { getLiveUsercount } from "./api/getLiveUsercount";+import { getCountries } from "./api/getCountries";+import { getOperatingSystems } from "./api/getOperatingSystems";+import { getBrowsers } from "./api/getBrowsers";+import { getDevices } from "./api/getDevices";+import { getReferrers } from "./api/getReferrers";+import { getPages } from "./api/getPages";+import { getPageViews } from "./api/getPageViews";const server = Fastify({logger: {@@ -39,6 +46,13 @@ server.get("/health", async () => {server.get("/live-user-count", async () => {return { count: await getLiveUsercount() };});+server.get("/countries", getCountries);+server.get("/browsers", getBrowsers);+server.get("/operating-systems", getOperatingSystems);+server.get("/devices", getDevices);+server.get("/pages", getPages);+server.get("/referrers", getReferrers);+server.get("/pageviews", getPageViews);// Track pageview endpointserver.post<{ Body: TrackingPayload }>(