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.

combine into 1 sql statement

Steven Tey173b3a6360ed
diff --git a/apps/web/lib/tinybird/record-click.ts b/apps/web/lib/tinybird/record-click.ts
index 10a856cded..eb80b9433a 100644
--- a/apps/web/lib/tinybird/record-click.ts
+++ b/apps/web/lib/tinybird/record-click.ts
@@ -213,30 +213,31 @@ async function sendLinkClickWebhooks({
return;
}
- const [link, tagsResult] = await Promise.all([
- conn
- .execute(`SELECT * FROM Link WHERE id = ?`, [linkId])
- .then((res) => res.rows[0]),
- conn
- .execute(
- `
- SELECT t.id, t.name, t.color
- FROM LinkTag lt
- JOIN Tag t ON lt.tagId = t.id
- WHERE lt.linkId = ?
- ORDER BY lt.createdAt ASC
- `,
- [linkId],
- )
- .then((res) => ({
- tags: res.rows.map((tag) => ({ tag })),
- })),
- ]);
-
- const finalLink = {
- ...link,
- ...tagsResult,
- };
+ const link = await conn
+ .execute(
+ `
+ SELECT
+ l.*,
+ JSON_ARRAYAGG(
+ IF(t.id IS NOT NULL,
+ JSON_OBJECT('tag', JSON_OBJECT('id', t.id, 'name', t.name, 'color', t.color)),
+ NULL
+ )
+ ) as tags
+ FROM Link l
+ LEFT JOIN LinkTag lt ON l.id = lt.linkId
+ LEFT JOIN Tag t ON lt.tagId = t.id
+ WHERE l.id = ?
+ GROUP BY l.id
+ `,
+ [linkId],
+ )
+ .then((res) => {
+ const row = res.rows[0] as any;
+ // Handle case where there are no tags (JSON_ARRAYAGG returns [null])
+ row.tags = row.tags?.[0] === null ? [] : row.tags;
+ return row;
+ });
await sendWebhooks({
trigger: "link.clicked",
@@ -244,7 +245,7 @@ async function sendLinkClickWebhooks({
// @ts-ignore – bot & qr should be boolean
data: transformClickEventData({
...clickData,
- link: transformLink(finalLink as ExpandedLink),
+ link: transformLink(link as ExpandedLink),
}),
});
}