The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
edit bulkCreateLinks and sync endpoint
Steven Tey37114ff6a0c9
diff --git a/apps/web/app/api/cron/import/csv/utils.ts b/apps/web/app/api/cron/import/csv/utils.tsindex f4b9d9a933..cb44f32e8a 100644--- a/apps/web/app/api/cron/import/csv/utils.ts+++ b/apps/web/app/api/cron/import/csv/utils.ts@@ -32,7 +32,7 @@ export const importLinksFromCSV = async ({})),);- const importedLinks = await bulkCreateLinks(processedLinks);+ const importedLinks = await bulkCreateLinks({ links: processedLinks });count += importedLinks.length;diff --git a/apps/web/app/api/cron/import/rebrandly/utils.ts b/apps/web/app/api/cron/import/rebrandly/utils.tsindex adeb36631b..cdaae73e5b 100644--- a/apps/web/app/api/cron/import/rebrandly/utils.ts+++ b/apps/web/app/api/cron/import/rebrandly/utils.ts@@ -190,7 +190,7 @@ export const importLinksFromRebrandly = async ({.filter(Boolean);// bulk create links- await bulkCreateLinks(importedLinks);+ await bulkCreateLinks({ links: importedLinks });count += importedLinks.length;diff --git a/apps/web/app/api/cron/import/short/utils.ts b/apps/web/app/api/cron/import/short/utils.tsindex b6d2d8b16a..958cd8e664 100644--- a/apps/web/app/api/cron/import/short/utils.ts+++ b/apps/web/app/api/cron/import/short/utils.ts@@ -69,7 +69,7 @@ export const importLinksFromShort = async ({.filter(Boolean);// bulk create links- await bulkCreateLinks(importedLinks);+ await bulkCreateLinks({ links: importedLinks });count += importedLinks.length;diff --git a/apps/web/app/api/cron/links/event/route.ts b/apps/web/app/api/cron/links/event/route.tsindex d585a245f2..350bb57329 100644--- a/apps/web/app/api/cron/links/event/route.ts+++ b/apps/web/app/api/cron/links/event/route.ts@@ -1,5 +1,6 @@import { limiter, qstash, receiver } from "@/lib/cron";import prisma from "@/lib/prisma";+import { recordLink } from "@/lib/tinybird";import { ProjectProps } from "@/lib/types";import { formatRedisLink, redis } from "@/lib/upstash";import {@@ -65,24 +66,26 @@ export async function POST(req: Request) {});}+ // update redis and tinybird+ await Promise.all([+ redis.hset(link.domain, {+ [link.key.toLowerCase()]: await formatRedisLink(link),+ }),+ recordLink({ link }),+ ]);+// increment links usage and send alert if neededif (type === "create" && link.projectId) {- const [project, _] = await Promise.all([- prisma.project.update({- where: {- id: link.projectId,- },- data: {- linksUsage: {- increment: 1,- },+ const project = await prisma.project.update({+ where: {+ id: link.projectId,+ },+ data: {+ linksUsage: {+ increment: 1,},- }),- // set the index in redis again cause we don't have the linkId the first time- redis.hset(link.domain, {- [link.key.toLowerCase()]: await formatRedisLink(link),- }),- ]);+ },+ });const percentage = Math.round((project.linksUsage / project.linksLimit) * 100,diff --git a/apps/web/app/api/links/[linkId]/route.ts b/apps/web/app/api/links/[linkId]/route.tsindex 03a7474671..d9246f477b 100644--- a/apps/web/app/api/links/[linkId]/route.ts+++ b/apps/web/app/api/links/[linkId]/route.ts@@ -82,13 +82,10 @@ export const PUT = withAuth(async ({ req, headers, project, link }) => {});// DELETE /api/links/[linkId] – delete a link-export const DELETE = withAuth(async ({ headers, link, project }) => {+export const DELETE = withAuth(async ({ headers, link }) => {// link is guaranteed to exist because if not we will return 404- const response = await deleteLink({- domain: link!.domain,- key: link!.key,- projectId: project.id,- });+ const response = await deleteLink(link!);+return NextResponse.json(response[0], {headers,});diff --git a/apps/web/app/api/links/bulk/route.ts b/apps/web/app/api/links/bulk/route.tsindex 6cb5f12ae0..833397e3ca 100644--- a/apps/web/app/api/links/bulk/route.ts+++ b/apps/web/app/api/links/bulk/route.ts@@ -62,7 +62,7 @@ export const POST = withAuth(}));const validLinksResponse =- validLinks.length > 0 ? await bulkCreateLinks(validLinks) : [];+ validLinks.length > 0 ? await bulkCreateLinks({ links: validLinks }) : [];return NextResponse.json([...validLinksResponse, ...errors], { headers });},diff --git a/apps/web/app/api/links/sync/route.ts b/apps/web/app/api/links/sync/route.tsindex 02c4377451..41d4388573 100644--- a/apps/web/app/api/links/sync/route.ts+++ b/apps/web/app/api/links/sync/route.ts@@ -46,7 +46,7 @@ export const POST = withAuth(async ({ req, session, project }) => {);}- const response = await Promise.all([+ const response = await Promise.allSettled([prisma.link.updateMany({where: {id: {@@ -59,7 +59,15 @@ export const POST = withAuth(async ({ req, session, project }) => {publicStats: false,},}),- bulkCreateLinks(unclaimedLinks),+ bulkCreateLinks({+ links: unclaimedLinks.map((link) => ({+ ...link,+ userId: session.user.id,+ projectId: project.id,+ publicStats: false,+ })),+ skipPrismaCreate: true,+ }),prisma.project.update({where: {id: project.id,diff --git a/apps/web/lib/api/links.ts b/apps/web/lib/api/links.tsindex 1102c36291..1f3d7b11d1 100644--- a/apps/web/lib/api/links.ts+++ b/apps/web/lib/api/links.ts@@ -23,6 +23,7 @@ import cloudinary from "cloudinary";import { LinkProps, ProjectProps, RedisLinkProps } from "../types";import { Session } from "../auth";import { getLinkViaEdge } from "../planetscale";+import { recordLink } from "../tinybird";export async function getLinksForProject({projectId,@@ -454,49 +455,60 @@ export async function addLink(link: LinkProps) {};}-export async function bulkCreateLinks(links: LinkProps[]) {+export async function bulkCreateLinks({+ links,+ skipPrismaCreate,+}: {+ links: LinkProps[];+ skipPrismaCreate?: boolean;+}) {if (links.length === 0) return [];- await prisma.link.createMany({- data: links.map((link) => {- const { utm_source, utm_medium, utm_campaign, utm_term, utm_content } =- getParamsFromURL(link.url);- return {- ...link,- title: truncate(link.title, 120),- description: truncate(link.description, 240),- utm_source,- utm_medium,- utm_campaign,- utm_term,- utm_content,- expiresAt: link.expiresAt ? new Date(link.expiresAt) : null,- geo: link.geo || undefined,- };- }),- skipDuplicates: true,- });+ let createdLinks: LinkProps[] = [];- const createdLinks = (await Promise.all(- links.map(async (link) => {- const { key, domain } = link;- return await prisma.link.findUnique({- where: {- domain_key: {- domain,- key,+ if (skipPrismaCreate) {+ createdLinks = links;+ } else {+ await prisma.link.createMany({+ data: links.map((link) => {+ const { utm_source, utm_medium, utm_campaign, utm_term, utm_content } =+ getParamsFromURL(link.url);+ return {+ ...link,+ title: truncate(link.title, 120),+ description: truncate(link.description, 240),+ utm_source,+ utm_medium,+ utm_campaign,+ utm_term,+ utm_content,+ expiresAt: link.expiresAt ? new Date(link.expiresAt) : null,+ geo: link.geo || undefined,+ };+ }),+ skipDuplicates: true,+ });++ createdLinks = (await Promise.all(+ links.map(async (link) => {+ const { key, domain } = link;+ return await prisma.link.findUnique({+ where: {+ domain_key: {+ domain,+ key,+ },},- },- });- }),- )) as LinkProps[];+ });+ }),+ )) as LinkProps[];+ }const pipeline = redis.pipeline();// split links into domainsconst linksByDomain: Record<string, Record<string, RedisLinkProps>> = {};- // this technically will be a synchronous function since isIframeable won't be run for bulk link creationawait Promise.all(createdLinks.map(async (link) => {const { domain, key } = link;@@ -504,9 +516,12 @@ export async function bulkCreateLinks(links: LinkProps[]) {if (!linksByDomain[domain]) {linksByDomain[domain] = {};}+ // this technically will be a synchronous function since isIframeable won't be run for bulk link creationconst formattedLink = await formatRedisLink(link);-linksByDomain[domain][key.toLowerCase()] = formattedLink;++ // record link in Tinybird+ await recordLink({ link });}),);@@ -595,9 +610,6 @@ export async function editLink({: cloudinary.v2.uploader.destroy(`${domain}/${key}`, {invalidate: true,}),- redis.hset(domain, {- [key.toLowerCase()]: await formatRedisLink(updatedLink),- }),// if key is changed: rename resource in Cloudinary, delete the old key in Redis and change the clicks key name...(changedDomain || changedKey? [@@ -635,32 +647,22 @@ export async function editLink({};}-export async function deleteLink({- domain = SHORT_DOMAIN,- key,- projectId,-}: {- domain?: string;- key: string;- projectId?: string;-}) {+export async function deleteLink(link: LinkProps) {return await Promise.all([prisma.link.delete({where: {- domain_key: {- domain,- key,- },+ id: link.id,},}),- cloudinary.v2.uploader.destroy(`${domain}/${key}`, {+ cloudinary.v2.uploader.destroy(`${link.domain}/${link.key}`, {invalidate: true,}),- redis.hdel(domain, key.toLowerCase()),- projectId &&+ redis.hdel(link.domain, link.key.toLowerCase()),+ recordLink({ link, deleted: true }),+ link.projectId &&prisma.project.update({where: {- id: projectId,+ id: link.projectId,},data: {linksUsage: {diff --git a/apps/web/lib/tinybird.ts b/apps/web/lib/tinybird.tsindex 4f493698c8..3ee5577f05 100644--- a/apps/web/lib/tinybird.ts+++ b/apps/web/lib/tinybird.ts@@ -10,6 +10,7 @@ import { NextRequest, userAgent } from "next/server";import { conn } from "./planetscale";import { ratelimit } from "./upstash";import { detectBot } from "./middleware/utils";+import { LinkProps } from "./types";/*** Recording clicks with geo, ua, referer and timestamp data@@ -105,29 +106,29 @@ export async function recordClick({]);}-// WIP, still needs testing-export async function deleteClickData({- domain,- key,+export async function recordLink({+ link,+ deleted,}: {- domain: string;- key: string;+ link: LinkProps;+ deleted?: boolean;}) {- if (!domain || !key) {- return null;- }- const deleteCondition = `domain='${domain}' AND key='${key}'`;- const response = await fetch(- "https://api.tinybird.co/v0/datasources/click_events/delete",+ return await fetch(+ "https://api.us-east.tinybird.co/v0/events?name=dub_links_metadata&wait=true",{method: "POST",headers: {Authorization: `Bearer ${process.env.TINYBIRD_API_KEY}`,- "Content-Type": "application/x-www-form-urlencoded",},- body: `delete_condition=${encodeURIComponent(deleteCondition)}`,+ body: JSON.stringify({+ timestamp: new Date(Date.now()).toISOString(),+ link_id: link.id,+ domain: link.domain,+ key: link.key,+ url: link.url,+ project_id: link.projectId || "",+ deleted: deleted ? 1 : 0,+ }),},).then((res) => res.json());- console.log({ response });- return response;}diff --git a/apps/web/scripts/restore-backup.ts b/apps/web/scripts/restore-backup.tsindex da296bc8ba..cee3596edb 100644--- a/apps/web/scripts/restore-backup.ts+++ b/apps/web/scripts/restore-backup.ts@@ -54,7 +54,7 @@ async function main() {"checkDisabled","clicks",]);- await bulkCreateLinks(csvLinks);+ await bulkCreateLinks({ links: csvLinks });},});}