The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
improved implementation
Steven Tey3ed86c1b1a32
diff --git a/apps/web/app/api/cron/links/event/route.ts b/apps/web/app/api/cron/links/event/route.tsindex da71b0b7ee..8fb9ed9705 100644--- a/apps/web/app/api/cron/links/event/route.ts+++ b/apps/web/app/api/cron/links/event/route.ts@@ -6,7 +6,6 @@ import { ProjectProps } from "@/lib/types";import { formatRedisLink, redis } from "@/lib/upstash";import {APP_DOMAIN_WITH_NGROK,- DUB_THUMBNAIL,GOOGLE_FAVICON_URL,getApexDomain,log,@@ -26,9 +25,10 @@ export async function POST(req: Request) {}}- const { linkId, type } = body as {+ const { linkId, type, imageToUpload } = body as {linkId: string;type: "create" | "edit" | "transfer";+ imageToUpload?: string;};const link = await prisma.link.findUnique({@@ -81,16 +81,6 @@ export async function POST(req: Request) {// increment links usage and send alert if neededif (type === "create" && link.projectId) {- if (link.image === DUB_THUMBNAIL) {- await prisma.link.update({- where: {- id: link.id,- },- data: {- image: `https://${process.env.STORAGE_DOMAIN}/images/${link.id}`,- },- });- }const project = await prisma.project.update({where: {id: link.projectId,diff --git a/apps/web/app/api/links/[linkId]/route.ts b/apps/web/app/api/links/[linkId]/route.tsindex 47eab36102..17b2d9bdb0 100644--- a/apps/web/app/api/links/[linkId]/route.ts+++ b/apps/web/app/api/links/[linkId]/route.ts@@ -31,7 +31,6 @@ export const GET = withAuth(async ({ headers, link }) => {color: true,},});- // link is guaranteed to exist because if not we will return 404return NextResponse.json({...link,@@ -46,6 +45,13 @@ export const GET = withAuth(async ({ headers, link }) => {// PUT /api/links/[linkId] – update a linkexport const PUT = withAuth(async ({ req, headers, project, link }) => {+ if (!link) {+ throw new DubApiError({+ code: "not_found",+ message: "Link not found.",+ });+ }+const body = updateLinkBodySchema.parse(await req.json());const updatedLink = {@@ -69,8 +75,8 @@ export const PUT = withAuth(async ({ req, headers, project, link }) => {project,// if domain and key are the same, we don't need to check if the key existsskipKeyChecks:- link!.domain === updatedLink.domain &&- link!.key.toLowerCase() === updatedLink.key?.toLowerCase(),+ link.domain === updatedLink.domain &&+ link.key.toLowerCase() === updatedLink.key?.toLowerCase(),});if (error) {@@ -82,15 +88,15 @@ export const PUT = withAuth(async ({ req, headers, project, link }) => {const [response, _] = await Promise.allSettled([editLink({- // link is guaranteed to exist because if not we will return 404- domain: link!.domain,- key: link!.key,+ oldDomain: link.domain,+ oldKey: link.key,+ oldImage: link.image || undefined,updatedLink: processedLink as any, // TODO: fix types}),qstash.publishJSON({url: `${APP_DOMAIN_WITH_NGROK}/api/cron/links/event`,body: {- linkId: link!.id,+ linkId: link.id,type: "edit",},}),@@ -104,8 +110,13 @@ export const PUT = withAuth(async ({ req, headers, project, link }) => {// DELETE /api/links/[linkId] – delete a linkexport const DELETE = withAuth(async ({ headers, link }) => {- // link is guaranteed to exist because if not we will return 404- const response = await deleteLink(link!.id);+ if (!link) {+ throw new DubApiError({+ code: "not_found",+ message: "Link not found.",+ });+ }+ const response = await deleteLink(link.id);return NextResponse.json(response[0], {headers,diff --git a/apps/web/lib/api/links.ts b/apps/web/lib/api/links.tsindex b406474e0c..9a9bf864f0 100644--- a/apps/web/lib/api/links.ts+++ b/apps/web/lib/api/links.ts@@ -14,7 +14,6 @@ import {import {DEFAULT_REDIRECTS,DUB_DOMAINS,- DUB_THUMBNAIL,SHORT_DOMAIN,getDomainWithoutWWW,getParamsFromURL,@@ -440,10 +439,10 @@ export async function processLink({// custom social media image checksconst uploadedImage = image && image.startsWith("data:image") ? true : false;- if (uploadedImage && !process.env.CLOUDINARY_URL) {+ if (uploadedImage && !process.env.STORAGE_SECRET_ACCESS_KEY) {return {link: payload,- error: "Missing Cloudinary environment variable.",+ error: "Missing storage access key.",code: "bad_request",};}@@ -521,9 +520,8 @@ export async function addLink(link: LinkWithTagIdsProps) {key,title: truncate(title, 120),description: truncate(description, 240),- // if there's an uploaded image, we put a placeholder image URL- // since we'll update this in the callback event after we get the link ID- image: uploadedImage ? DUB_THUMBNAIL : image,+ // if it's an uploaded image, make this null first because we'll update it later+ image: uploadedImage ? null : image,utm_source,utm_medium,utm_campaign,@@ -554,10 +552,22 @@ export async function addLink(link: LinkWithTagIdsProps) {},});+ const uploadedImageUrl = `https://${process.env.STORAGE_DOMAIN}/images/${response.id}`;+if (proxy && image && uploadedImage) {- const { url } = await storage.upload(`images/${response.id}`, image);- image = url;- console.log("image", image);+ await Promise.all([+ // upload image to storage+ storage.upload(`images/${response.id}`, image),+ // update the null image we set earlier to the uploaded image URL+ prisma.link.update({+ where: {+ id: response.id,+ },+ data: {+ image: uploadedImageUrl,+ },+ }),+ ]);}const shortLink = linkConstructor({@@ -567,7 +577,8 @@ export async function addLink(link: LinkWithTagIdsProps) {const tags = response.tags.map(({ tag }) => tag);return {...response,- image, // return the uploaded image URL (instead of the placeholder one)+ // set the image URL to the uploaded image URL+ image: uploadedImage ? uploadedImageUrl : response.image,tagId: tags?.[0]?.id ?? null, // backwards compatibilitytags,shortLink,@@ -693,12 +704,14 @@ export async function propagateBulkLinkChanges(}export async function editLink({- domain: oldDomain = SHORT_DOMAIN,- key: oldKey,+ oldDomain = SHORT_DOMAIN,+ oldKey,+ oldImage,updatedLink,}: {- domain?: string;- key: string;+ oldDomain?: string;+ oldKey: string;+ oldImage?: string;updatedLink: LinkWithTagIdsProps;}) {let {@@ -736,11 +749,10 @@ export async function editLink({if (proxy && image) {// only upload image if proxy is true and there's an imageif (uploadedImage) {- const { url } = await storage.upload(`images/${id}`, image);- image = url;+ await storage.upload(`images/${id}`, image);}- } else {// if there's no proxy enabled or no image, delete the image+ } else if (oldImage?.startsWith(`https://${process.env.STORAGE_DOMAIN}`)) {await storage.delete(`images/${id}`);}@@ -754,7 +766,9 @@ export async function editLink({key,title: truncate(title, 120),description: truncate(description, 240),- image,+ image: uploadedImage+ ? `https://${process.env.STORAGE_DOMAIN}/images/${id}`+ : image,utm_source,utm_medium,utm_campaign,@@ -824,7 +838,7 @@ export async function deleteLink(linkId: string) {id: link.id,},}),- storage.delete(`images/${link.id}`),+ link.proxy && link.image && storage.delete(`images/${link.id}`),redis.hdel(link.domain, link.key.toLowerCase()),recordLink({ link, deleted: true }),link.projectId &&