Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

record the conversion events

Kiran Ke8fbf22d37aa
diff --git a/apps/web/app/api/track/conversions/route.ts b/apps/web/app/api/track/conversions/route.ts
index e84733fde2..abc8b142ee 100644
--- a/apps/web/app/api/track/conversions/route.ts
+++ b/apps/web/app/api/track/conversions/route.ts
@@ -2,29 +2,31 @@ import { parseRequestBody } from "@/lib/api/utils";
import { withSessionEdge } from "@/lib/auth/edge";
import { getClickEvent, recordConversion } from "@/lib/tinybird";
import { conversionRequestSchema } from "@/lib/zod/schemas/conversions";
+import { internal_runWithWaitUntil as waitUntil } from "next/dist/server/web/internal-edge-wait-until";
import { NextResponse } from "next/server";
export const runtime = "edge";
// POST /api/track/conversions – Post a conversion event
export const POST = withSessionEdge(async ({ req }) => {
- const body = await parseRequestBody(req);
- const parsed = conversionRequestSchema.parse(body);
+ const body = conversionRequestSchema.parse(await parseRequestBody(req));
+ const { clickId, eventName, eventType, metadata, customerId } = body;
- const { clickId, eventName, eventType, metadata, customerId } = parsed;
+ waitUntil(async () => {
+ const clickEvent = await getClickEvent(clickId);
+ console.log("click event", clickEvent);
- const clickEvent = await getClickEvent(clickId);
+ if (!clickEvent) {
+ return;
+ // return NextResponse.json({ success: false }, { status: 404 });
+ }
- if (!clickEvent) {
- return NextResponse.json({ success: false }, { status: 404 });
- }
-
- await recordConversion({
- ...clickEvent,
- eventName,
- eventType,
- metadata,
- customerId,
+ await recordConversion({
+ ...clickEvent,
+ metadata,
+ event_name: eventName,
+ event_type: eventType,
+ });
});
return NextResponse.json({ success: true });
diff --git a/apps/web/lib/planetscale.ts b/apps/web/lib/planetscale.ts
index 17c275eee5..d73c134f5a 100644
--- a/apps/web/lib/planetscale.ts
+++ b/apps/web/lib/planetscale.ts
@@ -143,7 +143,6 @@ export async function getRandomKey({
export const getToken = async (hashedKey: string) => {
const { rows } = await conn.execute<User>(
- // "SELECT User.id, User.name, User.email FROM Token JOIN User ON Token.userId = User.id WHERE hashedKey = ? LIMIT 1",
"SELECT * FROM User WHERE User.ID IN (SELECT userId FROM Token WHERE hashedKey = ? AND userId IS NOT NULL) LIMIT 1",
[hashedKey],
);
diff --git a/apps/web/lib/tinybird.ts b/apps/web/lib/tinybird.ts
index 11eba45adb..6518936834 100644
--- a/apps/web/lib/tinybird.ts
+++ b/apps/web/lib/tinybird.ts
@@ -12,7 +12,7 @@ import { detectBot, detectQr, getIdentityHash } from "./middleware/utils";
import { conn } from "./planetscale";
import { LinkProps } from "./types";
import { ratelimit } from "./upstash";
-import { ConversionEvent, clickEventSchema } from "./zod/schemas/conversions";
+import { ConversionEvent, clickEventSchemaTB } from "./zod/schemas/conversions";
/**
* Recording clicks with geo, ua, referer and timestamp data
@@ -158,8 +158,6 @@ export async function recordLink({
).then((res) => res.json());
}
-// TODO:
-// Review this is the right way to fetch
export async function getClickEvent(clickId: string) {
const url = new URL(
`${process.env.TINYBIRD_API_URL}/v0/pipes/click_by_id.json`,
@@ -185,10 +183,22 @@ export async function getClickEvent(clickId: string) {
return null;
}
- return clickEventSchema.parse(data[0]);
+ return clickEventSchemaTB.parse(data[0]);
}
// Record conversion event in Tinybird
export async function recordConversion(event: ConversionEvent) {
- console.log("event", event);
+ return await fetch(
+ `${process.env.TINYBIRD_API_URL}/v0/events?name=dub_conversion_events&wait=true`,
+ {
+ method: "POST",
+ headers: {
+ Authorization: `Bearer ${process.env.TINYBIRD_API_KEY}`,
+ },
+ body: JSON.stringify({
+ ...event,
+ timestamp: new Date(Date.now()).toISOString(),
+ }),
+ },
+ );
}
diff --git a/apps/web/lib/zod/schemas/conversions.ts b/apps/web/lib/zod/schemas/conversions.ts
index f643bada57..b7a0293fe8 100644
--- a/apps/web/lib/zod/schemas/conversions.ts
+++ b/apps/web/lib/zod/schemas/conversions.ts
@@ -1,42 +1,69 @@
import z from "@/lib/zod";
-export const clickEventSchema = z.object({
+export const eventType = z
+ .union([z.literal("lead"), z.literal("sale")], {
+ errorMap: () => ({
+ message: "Must be either 'lead' or 'sale'",
+ }),
+ })
+ .default("lead");
+
+export const clickEventSchemaTB = z.object({
timestamp: z.string(),
click_id: z.string(),
link_id: z.string(),
url: z.string(),
country: z.string().nullable(),
city: z.string().nullable(),
+ region: z.string().nullable(),
+ latitude: z.string().nullable(),
+ longitude: z.string().nullable(),
device: z.string().nullable(),
+ device_model: z.string().nullable(),
+ device_vendor: z.string().nullable(),
browser: z.string().nullable(),
+ browser_version: z.string().nullable(),
os: z.string().nullable(),
+ os_version: z.string().nullable(),
+ engine: z.string().nullable(),
+ engine_version: z.string().nullable(),
+ cpu_architecture: z.string().nullable(),
+ ua: z.string().nullable(),
+ bot: z.number().nullable(),
referer: z.string().nullable(),
+ referer_url: z.string().nullable(),
});
+export const conversionEventSchemaTB = clickEventSchemaTB
+ .omit({ url: true })
+ .and(
+ z.object({
+ event_name: z.string(),
+ event_type: eventType,
+ metadata: z.string().nullable(), // TODO: Fix the type
+ customer_id: z.string().nullish(),
+ }),
+ );
+
+const literalSchema = z.union([z.string(), z.number(), z.boolean(), z.null()]);
+type Literal = z.infer<typeof literalSchema>;
+type Json = Literal | { [key: string]: Json } | Json[];
+
export const conversionRequestSchema = z.object({
clickId: z.string({ required_error: "clickId is required" }),
eventName: z
.string({ required_error: "eventName is required" })
.min(1)
- .max(50),
- eventType: z
- .union([z.literal("lead"), z.literal("sale")], {
- errorMap: () => ({
- message: "Must be either 'lead' or 'sale'",
- }),
- })
- .default("lead"),
- metadata: z.record(z.unknown()).nullish(),
- customerId: z.string().max(100).nullish(),
+ .max(50)
+ .default(""),
+ eventType: eventType.default("lead"),
+ metadata: z
+ .record(z.unknown())
+ .nullish()
+ .transform((val) => (val ? JSON.stringify(val) : "")),
+ customerId: z.string().max(100).nullish().default(""),
});
-export const conversionEventSchema = clickEventSchema.merge(
- conversionRequestSchema.pick({
- eventName: true,
- eventType: true,
- metadata: true,
- customerId: true,
- }),
-);
-
-export type ConversionEvent = z.infer<typeof conversionEventSchema>;
+export type ConversionEvent = z.infer<typeof conversionEventSchemaTB> & {
+ metadata: string;
+};
diff --git a/packages/tinybird/datasources/dub_conversion_events.datasource b/packages/tinybird/datasources/dub_conversion_events.datasource
new file mode 100644
index 0000000000..e2ab3e469f
--- /dev/null
+++ b/packages/tinybird/datasources/dub_conversion_events.datasource
@@ -0,0 +1,32 @@
+
+SCHEMA >
+ `timestamp` DateTime64(3) `json:$.timestamp`,
+ `link_id` String `json:$.link_id`,
+ `click_id` String `json:$.click_id`,
+ `event_name` LowCardinality(String) `json:$.event_name`,
+ `event_type` LowCardinality(String) `json:$.event_type`,
+ `metadata` String `json:$.metadata`,
+ `customer_id` String `json:$.customer_id`,
+ `country` LowCardinality(String) `json:$.country`,
+ `city` String `json:$.city`,
+ `region` String `json:$.region`,
+ `latitude` String `json:$.latitude`,
+ `longitude` String `json:$.longitude`,
+ `device` LowCardinality(String) `json:$.device`,
+ `device_model` LowCardinality(String) `json:$.device_model`,
+ `device_vendor` LowCardinality(String) `json:$.device_vendor`,
+ `browser` LowCardinality(String) `json:$.browser`,
+ `browser_version` String `json:$.browser_version`,
+ `os` LowCardinality(String) `json:$.os`,
+ `os_version` String `json:$.os_version`,
+ `engine` LowCardinality(String) `json:$.engine`,
+ `engine_version` String `json:$.engine_version`,
+ `cpu_architecture` LowCardinality(String) `json:$.cpu_architecture`,
+ `ua` String `json:$.ua`,
+ `bot` UInt8 `json:$.bot`,
+ `referer` String `json:$.referer`,
+ `referer_url` String `json:$.referer_url`
+
+ENGINE "MergeTree"
+ENGINE_PARTITION_KEY "toYYYYMM(timestamp)"
+ENGINE_SORTING_KEY "timestamp, link_id, click_id"
\ No newline at end of file
diff --git a/packages/tinybird/endpoints/click_by_id.pipe b/packages/tinybird/endpoints/click_by_id.pipe
index 05e17f7199..03d7eab3d9 100644
--- a/packages/tinybird/endpoints/click_by_id.pipe
+++ b/packages/tinybird/endpoints/click_by_id.pipe
@@ -8,4 +8,4 @@ DESCRIPTION >
undefined
SQL >
- % SELECT * FROM dub_click_events_mv WHERE click_id = {{ clickId }} LIMIT 1
\ No newline at end of file
+ % SELECT * FROM dub_click_events WHERE click_id = {{ clickId }} LIMIT 1
\ No newline at end of file