The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Polyfill `shortLink` in API responses
Steven Teyd0d2c3ea4960
diff --git a/apps/web/app/api/links/[linkId]/route.ts b/apps/web/app/api/links/[linkId]/route.tsindex 6af9d8949d..67b9dbbb8d 100644--- a/apps/web/app/api/links/[linkId]/route.ts+++ b/apps/web/app/api/links/[linkId]/route.ts@@ -13,80 +13,78 @@ export const GET = withAuth(async ({ headers, link }) => {});// PUT /api/links/[linkId] – update a link-export const PUT = withAuth(- async ({ req, headers, project, link, session }) => {- let body;- try {- body = await req.json();- } catch (error) {- return new Response("Missing or invalid body.", { status: 400, headers });- }- if (Object.keys(body).length === 0) {- return new Response("No fields to update.", { status: 304, headers });- }+export const PUT = withAuth(async ({ req, headers, project, link }) => {+ let body;+ try {+ body = await req.json();+ } catch (error) {+ return new Response("Missing or invalid body.", { status: 400, headers });+ }+ if (Object.keys(body).length === 0) {+ return new Response("No fields to update.", { status: 304, headers });+ }- const updatedLink = {- ...link,- ...body,- };+ const updatedLink = {+ ...link,+ ...body,+ };- if (updatedLink.projectId !== link?.projectId) {- return new Response(- "Transferring links to another project is not yet supported.",- {- status: 403,- headers,- },- );- }-- const {- link: processedLink,- error,- status,- } = await processLink({- payload: updatedLink,- project,- });+ if (updatedLink.projectId !== link?.projectId) {+ return new Response(+ "Transferring links to another project is not yet supported.",+ {+ status: 403,+ headers,+ },+ );+ }- if (error) {- return new Response(error, { status, headers });- }+ const {+ link: processedLink,+ error,+ status,+ } = await processLink({+ payload: updatedLink,+ project,+ });- const [response, _] = await Promise.allSettled([- editLink({- // link is guaranteed to exist because if not we will return 404- domain: link!.domain,- key: link!.key,- updatedLink: processedLink,- }),- ...(link &&- processedLink.domain === "dub.sh" &&- processedLink.url !== link.url- ? [- qstash.publishJSON({- url: `${APP_DOMAIN_WITH_NGROK}/api/cron/verify`,- body: {- linkId: link.id,- },- }),- ]- : []),- // @ts-ignore- ]).then((results) => results.map((result) => result.value));+ if (error) {+ return new Response(error, { status, headers });+ }- if (response === null) {- return new Response("Duplicate key: This short link already exists.", {- status: 409,- headers,- });- }+ const [response, _] = await Promise.allSettled([+ editLink({+ // link is guaranteed to exist because if not we will return 404+ domain: link!.domain,+ key: link!.key,+ updatedLink: processedLink,+ }),+ ...(link &&+ processedLink.domain === "dub.sh" &&+ processedLink.url !== link.url+ ? [+ qstash.publishJSON({+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/verify`,+ body: {+ linkId: link.id,+ },+ }),+ ]+ : []),+ // @ts-ignore+ ]).then((results) => results.map((result) => result.value));- return NextResponse.json(response, {+ if (response === null) {+ return new Response("Duplicate key: This short link already exists.", {+ status: 409,headers,});- },-);+ }++ return NextResponse.json(response, {+ headers,+ });+});// DELETE /api/links/[linkId] – delete a linkexport const DELETE = withAuth(async ({ headers, link, project }) => {diff --git a/apps/web/app/api/links/info/route.ts b/apps/web/app/api/links/info/route.tsindex 06c28e814f..1ae140e820 100644--- a/apps/web/app/api/links/info/route.ts+++ b/apps/web/app/api/links/info/route.ts@@ -1,5 +1,6 @@import { withAuth } from "@/lib/auth";import prisma from "@/lib/prisma";+import { linkConstructor } from "@dub/utils";import { NextResponse } from "next/server";// GET /api/links/info – get the info for a link@@ -25,7 +26,16 @@ export const GET = withAuth(async ({ headers, searchParams }) => {headers,});}- return NextResponse.json(response, {- headers,- });+ return NextResponse.json(+ {+ ...response,+ shortLink: linkConstructor({+ domain: response.domain,+ key: response.key,+ }),+ },+ {+ headers,+ },+ );});diff --git a/apps/web/app/api/route.ts b/apps/web/app/api/route.tsindex 86f738265c..5f4ce38eea 100644--- a/apps/web/app/api/route.ts+++ b/apps/web/app/api/route.ts@@ -727,6 +727,12 @@ export function GET(): NextResponse<OpenAPIV3.Document> {LinkResponse: {type: "object",properties: {+ shortLink: {+ type: "string",+ description:+ "The full URL of the short link, including the https protocol (e.g. https://dub.sh/try).",+ readOnly: true,+ },utm_source: {type: "string",description: "The UTM source of the short link.",diff --git a/apps/web/lib/api/links.ts b/apps/web/lib/api/links.tsindex 143d2e5c89..4deb00690d 100644--- a/apps/web/lib/api/links.ts+++ b/apps/web/lib/api/links.ts@@ -14,6 +14,7 @@ import {getParamsFromURL,getUrlFromString,isDubDomain,+ linkConstructor,nanoid,truncate,validKeyRegex,@@ -42,7 +43,7 @@ export async function getLinksForProject({userId?: string | null;showArchived?: boolean;}): Promise<LinkProps[]> {- return await prisma.link.findMany({+ const links = await prisma.link.findMany({where: {projectId,archived: showArchived ? undefined : false,@@ -71,6 +72,14 @@ export async function getLinksForProject({skip: (parseInt(page) - 1) * 100,}),});++ return links.map((link) => ({+ ...link,+ shortLink: linkConstructor({+ domain: link.domain,+ key: link.key,+ }),+ }));}export async function getLinksCount({@@ -379,6 +388,9 @@ export async function processLink({}}+ // remove shortLink attribute from payload since it's a polyfill+ delete payload["shortLink"];+return {link: {...payload,@@ -487,7 +499,13 @@ export async function addLink(link: LinkProps) {},});}- return response;+ return {+ ...response,+ shortLink: linkConstructor({+ domain: response.domain,+ key: response.key,+ }),+ };}export async function bulkCreateLinks(links: LinkProps[]) {@@ -545,7 +563,13 @@ export async function bulkCreateLinks(links: LinkProps[]) {}),);- return createdLinks;+ return createdLinks.map((link) => ({+ ...link,+ shortLink: linkConstructor({+ domain: link?.domain,+ key: link?.key,+ }),+ }));}export async function editLink({@@ -657,7 +681,13 @@ export async function editLink({});}- return response;+ return {+ ...response,+ shortLink: linkConstructor({+ domain: response.domain,+ key: response.key,+ }),+ };}export async function deleteLink({