1+ import type * as api from '@gitbook/api' ;
12import type { headers as nextHeaders } from 'next/headers' ;
23import { GITBOOK_API_PUBLIC_URL , GITBOOK_DISABLE_TRACKING } from './env' ;
34
@@ -48,6 +49,22 @@ export async function serveProxyAnalyticsEvent(req: Request) {
4849 } ) ;
4950 }
5051
52+ const body = ( await req . json ( ) ) as { events : api . SiteInsightsEvent [ ] } ;
53+ // Here we should filter every event that is older than 5 minutes as the API will reject them anyway, we might as well do it here
54+ const filteredEvents = body . events . filter ( ( event ) => {
55+ const eventDate = event . timestamp ? new Date ( event . timestamp ) : Date . now ( ) ;
56+ const now = new Date ( ) ;
57+ const fiveMinutesAgo = new Date ( now . getTime ( ) - 5 * 60 * 1000 ) ;
58+ return eventDate > fiveMinutesAgo ;
59+ } ) ;
60+
61+ if ( filteredEvents . length === 0 ) {
62+ return new Response ( 'No valid events to process' , {
63+ status : 400 ,
64+ headers : { 'content-type' : 'text/plain' } ,
65+ } ) ;
66+ }
67+
5168 // We make the request to the public API URL to ensure the request is properly enriched by the router..
5269 const url = new URL ( `${ GITBOOK_API_PUBLIC_URL } /v1/orgs/${ org } /sites/${ site } /insights/events` ) ;
5370 return await fetch ( url . toString ( ) , {
@@ -59,6 +76,8 @@ export async function serveProxyAnalyticsEvent(req: Request) {
5976 ...( longitude ? { 'x-location-longitude' : longitude } : { } ) ,
6077 ...( continent ? { 'x-location-continent' : continent } : { } ) ,
6178 } ,
62- body : req . body ,
79+ body : JSON . stringify ( {
80+ events : filteredEvents ,
81+ } ) ,
6382 } ) ;
6483}
0 commit comments