The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Add PUT endpoint to Dub API
Steven Tey7639ee587222
diff --git a/components/layout/app/nav-tabs.tsx b/components/layout/app/nav-tabs.tsxindex 0deb80f513..779be575eb 100644--- a/components/layout/app/nav-tabs.tsx+++ b/components/layout/app/nav-tabs.tsx@@ -56,8 +56,6 @@ export default function NavTabs() {return <div className="-mb-0.5 h-12 w-full" />;}- console.log("HACKY", router.asPath.split("?")[0]);-if (!error) {return (<div className="-mb-0.5 flex h-12 items-center justify-start space-x-2 overflow-x-auto scrollbar-hide">diff --git a/lib/api/links.ts b/lib/api/links.tsindex fc2415cc59..530b4bcb42 100644--- a/lib/api/links.ts+++ b/lib/api/links.ts@@ -270,16 +270,15 @@ export async function addLink(link: LinkProps) {return response;}-export async function editLink(- link: LinkProps,- {- oldDomain,- oldKey,- }: {- oldDomain: string;- oldKey: string;- },-) {+export async function editLink({+ domain: oldDomain,+ key: oldKey,+ updatedLink,+}: {+ domain: string;+ key: string;+ updatedLink: LinkProps;+}) {const {id,domain,@@ -295,7 +294,7 @@ export async function editLink(ios,android,geo,- } = link;+ } = updatedLink;const hasPassword = password && password.length > 0 ? true : false;const exat = expiresAt ? new Date(expiresAt).getTime() : null;const changedKey = key !== oldKey;@@ -315,7 +314,7 @@ export async function editLink(id,},data: {- ...link,+ ...updatedLink,key,title: truncate(title, 120),description: truncate(description, 240),@@ -326,6 +325,7 @@ export async function editLink(utm_term,utm_content,geo: geo || undefined,+ updatedAt: new Date(),},}),// only upload image to cloudinary if proxy is true and there's an image@@ -383,7 +383,13 @@ export async function editLink(return response;}-export async function deleteLink(domain: string, key: string) {+export async function deleteLink({+ domain,+ key,+}: {+ domain: string;+ key: string;+}) {return await Promise.all([prisma.link.delete({where: {diff --git a/lib/auth.ts b/lib/auth.tsindex b6adb7d0f2..ce51666def 100644--- a/lib/auth.ts+++ b/lib/auth.ts@@ -241,9 +241,10 @@ const withLinksAuth =} = {},) =>async (req: NextApiRequest, res: NextApiResponse) => {- const { slug, domain } = req.query as {- slug?: string;- domain?: string;+ const { slug, domain, key } = req.query as {+ slug?: string; // project slug (query param)+ domain?: string; // link domain (query param)+ key?: string; // link key (path param)};// if slug is misconfgured@@ -270,12 +271,6 @@ const withLinksAuth =.end("Unauthorized: API is not supported for dub.sh links yet.");}- if (req.method === "PUT") {- return res- .status(403)- .end("Unauthorized: API is not supported for editing links yet.");- }-const url = new URL(req.url || "", API_DOMAIN);if (url.pathname.includes("/stats/")) {@@ -412,8 +407,6 @@ const withLinksAuth =}}- // if key is defined, fetch link details- const { key } = req.query;if (key) {if (typeof key !== "string") {return res.status(400).end("Missing or misconfigured link key.");diff --git a/pages/api/index.ts b/pages/api/index.tsindex 7b603691db..e21cbd788e 100644--- a/pages/api/index.ts+++ b/pages/api/index.ts@@ -180,120 +180,7 @@ export default async function handler(): Promise<content: {"application/json": {schema: {- type: "object",- properties: {- domain: {- type: "string",- description: "The domain of the short link.",- },- url: {- type: "string",- description: "The destination URL of the short link.",- },- key: {- type: "string",- description:- "The short link slug. If not provided, a random 7-character slug will be generated.",- },- archived: {- type: "boolean",- description: "Whether the short link is archived.",- default: false,- },- expiresAt: {- type: "string",- format: "date-time",- description:- "The date and time when the short link will expire.",- default: null,- nullable: true,- },- password: {- type: "string",- description:- "The password required to access the destination URL of the short link.",- default: null,- nullable: true,- },- proxy: {- type: "boolean",- description:- "Whether the short link uses Custom Social Media Cards feature.",- default: false,- },- title: {- type: "string",- description:- "The title of the short link generated via api.dub.co/metatags. Will be used for Custom Social Media Cards if `proxy` is true.",- default: null,- nullable: true,- },- description: {- type: "string",- description:- "The description of the short link generated via api.dub.co/metatags. Will be used for Custom Social Media Cards if `proxy` is true.",- default: null,- nullable: true,- },- image: {- type: "string",- description:- "The image of the short link generated via api.dub.co/metatags. Will be used for Custom Social Media Cards if `proxy` is true.",- default: null,- nullable: true,- },- rewrite: {- type: "boolean",- description: "Whether the short link uses link cloaking.",- default: false,- },- ios: {- type: "string",- description:- "The iOS destination URL for the short link for iOS device targeting.",- default: null,- nullable: true,- },- android: {- type: "string",- description:- "The Android destination URL for the short link for Android device targeting.",- default: null,- nullable: true,- },- geo: {- type: "object",- description:- "Geo targeting information for the short link.",- additionalProperties: {- type: "string",- format: "uri",- },- default: null,- nullable: true,- },- publicStats: {- type: "boolean",- description:- "Whether the short link's stats are publicly accessible.",- default: false,- },- tagId: {- type: "string",- format: "cuid",- description:- "The unique id of the tag assigned to the short link.",- default: null,- nullable: true,- },- comments: {- type: "string",- description: "The comments for the short link.",- default: null,- nullable: true,- },- },- required: ["domain", "url"],+ $ref: "#/components/schemas/LinkBody",},},},@@ -373,6 +260,77 @@ export default async function handler(): Promise<},},},+ put: {+ description: "Edit link for the authenticated user or project.",+ operationId: "editLink",+ security: [+ {+ bearerToken: [],+ },+ ],+ summary: "Edit a link",+ parameters: [+ {+ name: "key",+ description:+ "The key of the link to edit. E.g. for dub.sh/github, the key is 'github'.",+ in: "path",+ required: true,+ schema: {+ description:+ "The key of the link to edit. E.g. for dub.sh/github, the key is 'github'.",+ type: "string",+ },+ },+ {+ name: "domain",+ description:+ "The domain of the link to edit. E.g. for dub.sh/github, the domain is 'dub.sh'.",+ in: "query",+ required: true,+ schema: {+ description:+ "The domain of the link to edit. E.g. for dub.sh/github, the domain is 'dub.sh'.",+ type: "string",+ },+ },+ {+ name: "slug",+ description:+ "The project slug of the link to edit. E.g. for app.dub.co/vercel, the slug is 'vercel'.",+ in: "query",+ required: true,+ schema: {+ description:+ "The project slug of the link to edit. E.g. for app.dub.co/vercel, the slug is 'vercel'.",+ type: "string",+ },+ },+ ],+ requestBody: {+ description: "Details of the link to edit.",+ required: true,+ content: {+ "application/json": {+ schema: {+ $ref: "#/components/schemas/LinkBody",+ },+ },+ },+ },+ responses: {+ "200": {+ description: "The created link",+ content: {+ "application/json": {+ schema: {+ $ref: "#/components/schemas/Link",+ },+ },+ },+ },+ },+ },delete: {description: "Delete a link for the authenticated user or project.",operationId: "deleteLink",@@ -623,6 +581,120 @@ export default async function handler(): Promise<},},},+ LinkBody: {+ type: "object",+ properties: {+ domain: {+ type: "string",+ description: "The domain of the short link.",+ },+ url: {+ type: "string",+ description: "The destination URL of the short link.",+ },+ key: {+ type: "string",+ description:+ "The short link slug. If not provided, a random 7-character slug will be generated.",+ },+ archived: {+ type: "boolean",+ description: "Whether the short link is archived.",+ default: false,+ },+ expiresAt: {+ type: "string",+ format: "date-time",+ description: "The date and time when the short link will expire.",+ default: null,+ nullable: true,+ },+ password: {+ type: "string",+ description:+ "The password required to access the destination URL of the short link.",+ default: null,+ nullable: true,+ },+ proxy: {+ type: "boolean",+ description:+ "Whether the short link uses Custom Social Media Cards feature.",+ default: false,+ },+ title: {+ type: "string",+ description:+ "The title of the short link generated via api.dub.co/metatags. Will be used for Custom Social Media Cards if `proxy` is true.",+ default: null,+ nullable: true,+ },+ description: {+ type: "string",+ description:+ "The description of the short link generated via api.dub.co/metatags. Will be used for Custom Social Media Cards if `proxy` is true.",+ default: null,+ nullable: true,+ },+ image: {+ type: "string",+ description:+ "The image of the short link generated via api.dub.co/metatags. Will be used for Custom Social Media Cards if `proxy` is true.",+ default: null,+ nullable: true,+ },+ rewrite: {+ type: "boolean",+ description: "Whether the short link uses link cloaking.",+ default: false,+ },+ ios: {+ type: "string",+ description:+ "The iOS destination URL for the short link for iOS device targeting.",+ default: null,+ nullable: true,+ },+ android: {+ type: "string",+ description:+ "The Android destination URL for the short link for Android device targeting.",+ default: null,+ nullable: true,+ },+ geo: {+ type: "object",+ description: "Geo targeting information for the short link.",+ additionalProperties: {+ type: "string",+ format: "uri",+ },+ default: null,+ nullable: true,+ },+ publicStats: {+ type: "boolean",+ description:+ "Whether the short link's stats are publicly accessible.",+ default: false,+ },+ tagId: {+ type: "string",+ format: "cuid",+ description:+ "The unique id of the tag assigned to the short link.",+ default: null,+ nullable: true,+ },+ comments: {+ type: "string",+ description: "The comments for the short link.",+ default: null,+ nullable: true,+ },+ },+ required: ["domain", "url"],+ },},securitySchemes: {bearerToken: {diff --git a/pages/api/links/[key]/index.ts b/pages/api/links/[key]/index.tsindex bd3009d933..139f2738e9 100644--- a/pages/api/links/[key]/index.ts+++ b/pages/api/links/[key]/index.ts@@ -14,34 +14,38 @@ export const config = {export default withLinksAuth(async (req, res, session, project, domain, link) => {- const { key: oldKey, domain: oldDomain } = req.query as {- key: string;- domain: string;- };-// GET /api/links/:key – get a linkif (req.method === "GET") {return res.status(200).json(link);// PUT /api/links/:key – edit a link} else if (req.method === "PUT") {- let { domain, key, url, rewrite } = req.body;- if (!domain || !key || !url) {- return res.status(400).end("Missing domain or key or url.");+ // if request body is empty or not a valid json+ if (!req.body || typeof req.body !== "object") {+ return res.status(400).end("Missing or invalid request body.");+ }+ if (Object.keys(req.body).length === 0) {+ return res.status(304).end("No fields to update.");}+ let { key, url, rewrite } = req.body;+// for default dub.sh links (not part of a project)if (!project) {- if (key.includes("/")) {- return res.status(422).end("Key cannot contain '/'.");- }- const keyBlacklisted = await isBlacklistedKey(key);- if (keyBlacklisted) {- return res.status(422).end("Invalid key.");+ if (key) {+ if (key.includes("/")) {+ return res.status(422).end("Key cannot contain '/'.");+ }+ const keyBlacklisted = await isBlacklistedKey(key);+ if (keyBlacklisted) {+ return res.status(422).end("Invalid key.");+ }}- const domainBlacklisted = await isBlacklistedDomain(url);- if (domainBlacklisted) {- return res.status(422).end("Invalid url.");+ if (url) {+ const domainBlacklisted = await isBlacklistedDomain(url);+ if (domainBlacklisted) {+ return res.status(422).end("Invalid url.");+ }}if (rewrite) {return res@@ -50,25 +54,23 @@ export default withLinksAuth(}}- key = processKey(key);- if (!key) {- return res.status(422).end("Invalid key.");+ if (key) {+ key = processKey(key);+ if (!key) {+ return res.status(422).end("Invalid key.");+ }}const [response, invalidFavicon] = await Promise.allSettled([- editLink(- {+ editLink({+ domain: domain || "dub.sh",+ key: link!.key, // link is guaranteed to exist because if not we will return 404,+ updatedLink: {+ ...link,...req.body,- key,- domain: req.body.domain || "dub.sh",- userId: session.user.id,- },- {- oldDomain: oldDomain || "dub.sh",- oldKey,},- ),- ...(!project+ }),+ ...(!project && url? [fetch(`${GOOGLE_FAVICON_URL}${getApexDomain(url)}`).then((res) => !res.ok,@@ -99,7 +101,10 @@ export default withLinksAuth(// DELETE /api/links/:key – delete a link} else if (req.method === "DELETE") {- const response = await deleteLink(domain || "dub.sh", oldKey);+ const response = await deleteLink({+ domain: domain || "dub.sh",+ key: link!.key, // link is guaranteed to exist because if not we will return 404+ });return res.status(200).json(response[0]);} else {res.setHeader("Allow", ["GET", "PUT", "DELETE"]);