-
Notifications
You must be signed in to change notification settings - Fork 255
Expand file tree
/
Copy pathapiHandler.ts
More file actions
58 lines (51 loc) · 1.64 KB
/
apiHandler.ts
File metadata and controls
58 lines (51 loc) · 1.64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import { NextRequest } from 'next/server';
import { captureEvent } from './posthog';
interface ApiHandlerConfig {
/**
* Whether to track this API request in PostHog.
* @default true
*/
track?: boolean;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
type AnyHandler = (...args: any[]) => Promise<Response> | Response;
/**
* Creates an API route handler with automatic request tracking.
*
* @example
* // Simple handler
* export const GET = apiHandler(async (request) => {
* return Response.json({ data: 'hello' });
* });
*
* @example
* // Handler with route params
* export const GET = apiHandler(async (request, { params }) => {
* const { id } = await params;
* return Response.json({ id });
* });
*
* @example
* // Disable tracking (for health checks, etc.)
* export const GET = apiHandler(async () => {
* return Response.json({ status: 'ok' });
* }, { track: false });
*/
export function apiHandler<H extends AnyHandler>(
handler: H,
config: ApiHandlerConfig = {}
): H {
const { track = true } = config;
const wrappedHandler = async (request: NextRequest, ...rest: unknown[]) => {
if (track) {
const path = request.nextUrl.pathname;
const method = request.method;
const source = request.headers.get('X-Sourcebot-Client-Source') ?? 'unknown';
// Fire and forget - don't await to avoid blocking the request
captureEvent('api_request', { path, method, source });
}
// Call the original handler with all arguments
return handler(request, ...rest);
};
return wrappedHandler as H;
}