The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Improve /track/ endpoints
Steven Teyf9ad68bac11e
diff --git a/apps/web/lib/api/conversions/track-sale.ts b/apps/web/lib/api/conversions/track-sale.tsindex a37ea4242e..bd4a97987b 100644--- a/apps/web/lib/api/conversions/track-sale.ts+++ b/apps/web/lib/api/conversions/track-sale.ts@@ -57,14 +57,16 @@ export const trackSale = async ({let clickData: ClickEventTB | null = null;let leadEventData: LeadEventTB | null = null;- // Skip if invoice id is already processed+ // Return idempotent response if invoiceId is already processedif (invoiceId) {- const ok = await redis.set(`dub_sale_events:invoiceId:${invoiceId}`, 1, {- ex: 60 * 60 * 24 * 7,- nx: true,- });-- if (!ok) {+ const [oldKeyValue, newKeyValue] = await redis.mget([+ `dub_sale_events:invoiceId:${invoiceId}`,+ `trackSale:${workspace.id}:invoiceId:${invoiceId}`,+ ]);++ if (newKeyValue) {+ return newKeyValue;+ } else if (oldKeyValue) {return {eventName,customer: null,@@ -543,7 +545,7 @@ const _trackSale = async ({})(),);- return trackSaleResponseSchema.parse({+ const trackSaleResponse = trackSaleResponseSchema.parse({eventName,customer,sale: {@@ -554,4 +556,16 @@ const _trackSale = async ({metadata,},});++ if (invoiceId) {+ await redis.set(+ `trackSale:${workspace.id}:invoiceId:${invoiceId}`,+ trackSaleResponse,+ {+ ex: 60 * 60 * 24 * 7,+ },+ );+ }++ return trackSaleResponse;};diff --git a/apps/web/tests/tracks/track-sale.test.ts b/apps/web/tests/tracks/track-sale.test.tsindex 3873cfacf4..f513d0abdd 100644--- a/apps/web/tests/tracks/track-sale.test.ts+++ b/apps/web/tests/tracks/track-sale.test.ts@@ -81,7 +81,7 @@ describe("POST /track/sale", async () => {expectValidSaleResponse(response, sale);});- test("track a sale with an invoiceId that is already processed (should return null customer and sale) ", async () => {+ test("track a sale with an invoiceId that is already processed (should return the same response as before) ", async () => {const response = await http.post<TrackSaleResponse>({path: "/track/sale",body: {@@ -91,12 +91,7 @@ describe("POST /track/sale", async () => {},});- expect(response.status).toEqual(200);- expect(response.data).toStrictEqual({- eventName: "Subscription",- customer: null,- sale: null,- });+ expectValidSaleResponse(response, sale);});test("track a sale with regular vs premium product ID (should create the right commission)", async () => {