The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
abstract out to waitUntil helper
Steven Tey843aad9e50e8
diff --git a/apps/web/lib/api/links/create-link.ts b/apps/web/lib/api/links/create-link.tsindex 62740cc1c1..27fd4abf80 100644--- a/apps/web/lib/api/links/create-link.ts+++ b/apps/web/lib/api/links/create-link.ts@@ -2,11 +2,11 @@ import { qstash } from "@/lib/cron";import prisma from "@/lib/prisma";import { isStored, storage } from "@/lib/storage";import { recordLink } from "@/lib/tinybird";-import { LinkProps, ProcessedLinkProps } from "@/lib/types";+import { ProcessedLinkProps } from "@/lib/types";import { formatRedisLink, redis } from "@/lib/upstash";+import { waitUntil } from "@/lib/vercel";import { APP_DOMAIN_WITH_NGROK, getParamsFromURL, truncate } from "@dub/utils";import { Prisma } from "@prisma/client";-import { waitUntil } from "@vercel/functions";import { combineTagIds, transformLink } from "./utils";export async function createLink(link: ProcessedLinkProps) {@@ -77,85 +77,71 @@ export async function createLink(link: ProcessedLinkProps) {},});- if (process.env.VERCEL === "1") {- waitUntil(createLinkEffects({ link, response }));- } else {- await createLinkEffects({ link, response });- }+ const uploadedImageUrl = `${process.env.STORAGE_BASE_URL}/images/${response.id}`;++ waitUntil(+ Promise.all([+ // record link in Redis+ redis.hset(link.domain.toLowerCase(), {+ [link.key.toLowerCase()]: await formatRedisLink(response),+ }),+ // record link in Tinybird+ recordLink({+ link: {+ ...response,+ tags: response.tags.map(({ tag }) => ({+ tagId: tag.id,+ })),+ },+ }),+ // if proxy image is set, upload image to R2 and update the link with the uploaded image URL+ ...(proxy && image && !isStored(image)+ ? [+ // upload image to R2+ storage.upload(`images/${response.id}`, image, {+ width: 1200,+ height: 630,+ }),+ // update the null image we set earlier to the uploaded image URL+ prisma.link.update({+ where: {+ id: response.id,+ },+ data: {+ image: uploadedImageUrl,+ },+ }),+ ]+ : []),+ // delete public links after 30 mins+ !response.userId &&+ qstash.publishJSON({+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/links/delete`,+ // delete after 30 mins+ delay: 30 * 60,+ body: {+ linkId: response.id,+ },+ }),+ // update links usage for workspace+ link.projectId &&+ prisma.project.update({+ where: {+ id: link.projectId,+ },+ data: {+ linksUsage: {+ increment: 1,+ },+ },+ }),+ ]),+ );return {...transformLink(response),// optimistically set the image URL to the uploaded image URLimage:- proxy && image && !isStored(image)- ? `${process.env.STORAGE_BASE_URL}/images/${response.id}`- : response.image,+ proxy && image && !isStored(image) ? uploadedImageUrl : response.image,};}--async function createLinkEffects({- link,- response,-}: {- link: ProcessedLinkProps;- response: LinkProps & { tags: { tag: { id: string } }[] };-}) {- const { image, proxy } = link;-- return await Promise.all([- // record link in Redis- redis.hset(link.domain.toLowerCase(), {- [link.key.toLowerCase()]: await formatRedisLink(response),- }),- // record link in Tinybird- recordLink({- link: {- ...response,- tags: response.tags.map(({ tag }) => ({- tagId: tag.id,- })),- },- }),- // if proxy image is set, upload image to R2 and update the link with the uploaded image URL- ...(proxy && image && !isStored(image)- ? [- // upload image to R2- storage.upload(`images/${response.id}`, image, {- width: 1200,- height: 630,- }),- // update the null image we set earlier to the uploaded image URL- prisma.link.update({- where: {- id: response.id,- },- data: {- image: `${process.env.STORAGE_BASE_URL}/images/${response.id}`,- },- }),- ]- : []),- // delete public links after 30 mins- !response.userId &&- qstash.publishJSON({- url: `${APP_DOMAIN_WITH_NGROK}/api/cron/links/delete`,- // delete after 30 mins- delay: 30 * 60,- body: {- linkId: response.id,- },- }),- // update links usage for workspace- link.projectId &&- prisma.project.update({- where: {- id: link.projectId,- },- data: {- linksUsage: {- increment: 1,- },- },- }),- ]);-}diff --git a/apps/web/lib/auth/session.ts b/apps/web/lib/auth/session.tsindex b6d8c16b78..0e4b1e391b 100644--- a/apps/web/lib/auth/session.ts+++ b/apps/web/lib/auth/session.ts@@ -1,7 +1,8 @@import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";import prisma from "@/lib/prisma";+import { ratelimit } from "@/lib/upstash";+import { waitUntil } from "@/lib/vercel";import { getSearchParams } from "@dub/utils";-import { ratelimit } from "../upstash";import { Session, getSession, hashToken } from "./utils";interface WithSessionHandler {@@ -79,14 +80,16 @@ export const withSession =headers,});}- await prisma.token.update({- where: {- hashedKey,- },- data: {- lastUsed: new Date(),- },- });+ waitUntil(+ prisma.token.update({+ where: {+ hashedKey,+ },+ data: {+ lastUsed: new Date(),+ },+ }),+ );session = {user: {id: user.id,diff --git a/apps/web/lib/auth/workspace.ts b/apps/web/lib/auth/workspace.tsindex f800788a7f..4f0b768b38 100644--- a/apps/web/lib/auth/workspace.ts+++ b/apps/web/lib/auth/workspace.ts@@ -1,5 +1,7 @@import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";import prisma from "@/lib/prisma";+import { ratelimit } from "@/lib/upstash";+import { waitUntil } from "@/lib/vercel";import {API_DOMAIN,DUB_WORKSPACE_ID,@@ -9,7 +11,6 @@ import {import { Link as LinkProps } from "@prisma/client";import { exceededLimitError } from "../api/errors";import { PlanProps, WorkspaceProps } from "../types";-import { ratelimit } from "../upstash";import { Session, getSession, hashToken } from "./utils";interface WithWorkspaceHandler {@@ -173,14 +174,16 @@ export const withWorkspace = (message: "Too many requests.",});}- await prisma.token.update({- where: {- hashedKey,- },- data: {- lastUsed: new Date(),- },- });+ waitUntil(+ prisma.token.update({+ where: {+ hashedKey,+ },+ data: {+ lastUsed: new Date(),+ },+ }),+ );session = {user: {id: user.id,diff --git a/apps/web/lib/vercel.ts b/apps/web/lib/vercel.tsnew file mode 100644index 0000000000..fc0a137ec2--- /dev/null+++ b/apps/web/lib/vercel.ts@@ -0,0 +1,9 @@+import { waitUntil as waitUntilHelper } from "@vercel/functions";++export const waitUntil = (fn: Promise<any>) => {+ if (process.env.VERCEL === "1") {+ waitUntilHelper(fn);+ } else {+ return fn;+ }+};