42 lines
1.3 KiB
TypeScript
42 lines
1.3 KiB
TypeScript
import type { AnalyticsEventType } from "@/lib/analytics-types";
|
|
|
|
export type TrackInput = {
|
|
type: AnalyticsEventType;
|
|
query?: string;
|
|
category?: string;
|
|
result_count?: number;
|
|
slug?: string;
|
|
source?: string;
|
|
position?: number;
|
|
locale?: string;
|
|
};
|
|
|
|
const DEDUPE_WINDOW_MS = 1500;
|
|
const recent = new Map<string, number>();
|
|
|
|
/**
|
|
* ส่ง event สถิติไปที่ /api/analytics/collect
|
|
* - กลืน error ทั้งหมด (สถิติต้องไม่ทำให้หน้าเว็บพัง)
|
|
* - กัน event ซ้ำใน 1.5 วินาที (เช่น effect ยิงซ้ำตอน re-render)
|
|
*/
|
|
export function trackEvent(input: TrackInput): void {
|
|
if (typeof window === "undefined") return;
|
|
|
|
const key = JSON.stringify(input);
|
|
const now = Date.now();
|
|
const last = recent.get(key);
|
|
if (last !== undefined && now - last < DEDUPE_WINDOW_MS) return;
|
|
recent.set(key, now);
|
|
|
|
try {
|
|
void fetch("/api/analytics/collect", {
|
|
method: "POST",
|
|
headers: { "Content-Type": "application/json" },
|
|
body: JSON.stringify({ events: [input] }),
|
|
keepalive: true,
|
|
}).catch(() => undefined);
|
|
} catch {
|
|
// ไม่ทำอะไร — ปล่อยให้หน้าเว็บทำงานต่อ
|
|
}
|
|
}
|