conversion api wrapper
This commit is contained in:
67
src/lib/conversion/server.ts
Normal file
67
src/lib/conversion/server.ts
Normal file
@@ -0,0 +1,67 @@
|
||||
import { json, type RequestHandler } from '@sveltejs/kit';
|
||||
import { buildConversionUserData, buildCustomData, ConversionControl } from './control.ts';
|
||||
import type {
|
||||
ConversionErrorResponseBody,
|
||||
ConversionRequestBody,
|
||||
ConversionResponseBody
|
||||
} from '$lib/types/conversion.js';
|
||||
|
||||
import { StatusCodes } from 'http-status-codes';
|
||||
|
||||
export const createConversionRequestHandler: (control: ConversionControl) => RequestHandler = (
|
||||
control
|
||||
) => {
|
||||
const handle: RequestHandler = async ({ request, getClientAddress }) => {
|
||||
try {
|
||||
const body = (await request.json()) as ConversionRequestBody;
|
||||
|
||||
// Build user data with IP and user agent
|
||||
const ip = getClientAddress();
|
||||
const ua = request.headers.get('user-agent');
|
||||
|
||||
const userData = buildConversionUserData({
|
||||
...body.user,
|
||||
ip,
|
||||
ua: ua ?? body.user?.ua ?? undefined
|
||||
});
|
||||
|
||||
// Build custom data with UTM params if applicable
|
||||
let rawCustomData = body.customData ?? {};
|
||||
if (body.eventName === 'PageView' && body.utms) {
|
||||
// For PageView events, automatically include UTM params if provided
|
||||
rawCustomData = {
|
||||
...rawCustomData,
|
||||
...body.utms
|
||||
};
|
||||
}
|
||||
|
||||
const customData = buildCustomData(rawCustomData);
|
||||
|
||||
// Send the event via the control
|
||||
const response = await control.trackEvent(body.eventName, {
|
||||
eventID: body.eventID,
|
||||
eventSourceURL: body.eventSourceURL,
|
||||
actionSource: 'website',
|
||||
userData,
|
||||
customData
|
||||
});
|
||||
|
||||
// Structure the response
|
||||
const structuredResponse: ConversionResponseBody = {
|
||||
pixelID: response.id,
|
||||
fbtrace_id: response.fbtrace_id,
|
||||
receivedEvents: response.events_received,
|
||||
processedEvents: response.num_processed_entries,
|
||||
messages: response.messages
|
||||
};
|
||||
|
||||
return json(structuredResponse, { status: StatusCodes.OK });
|
||||
} catch (e) {
|
||||
return json(
|
||||
{ error: e instanceof Error ? e.message : String(e) } as ConversionErrorResponseBody,
|
||||
{ status: StatusCodes.INTERNAL_SERVER_ERROR }
|
||||
);
|
||||
}
|
||||
};
|
||||
return handle;
|
||||
};
|
||||
Reference in New Issue
Block a user