Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

Move `crawlBitlyLink` into its own API endpoint

Tim Wilsonc96c3f889aec
diff --git a/apps/web/app/api/links/crawl-bitly/route.ts b/apps/web/app/api/links/crawl-bitly/route.ts
new file mode 100644
index 0000000000..98e125da20
--- /dev/null
+++ b/apps/web/app/api/links/crawl-bitly/route.ts
@@ -0,0 +1,95 @@
+import { redis } from "@/lib/upstash";
+import { z } from "zod";
+
+// POST /api/links/crawl-bitly - receive webhooks for Dub
+export const POST = async (req: Request) => {
+ const body = await req.json();
+
+ const { domain, shortKey, workspaceId } = z
+ .object({
+ domain: z.string(),
+ shortKey: z.string(),
+ workspaceId: z.string(),
+ })
+ .parse(body);
+
+ const link = await crawlBitlyLink({ domain, shortKey, workspaceId });
+
+ return new Response(JSON.stringify(link || null));
+};
+
+async function crawlBitlyLink({
+ domain,
+ shortKey,
+ workspaceId,
+}: {
+ domain: string;
+ shortKey: string;
+ workspaceId: string;
+}) {
+ const response = await fetch(`https://bit.ly/${shortKey}`, {
+ method: "HEAD",
+ redirect: "manual",
+ headers: {
+ Host: domain,
+ "User-Agent":
+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
+ },
+ });
+
+ if (!response.ok && response.status !== 301 && response.status !== 302) {
+ console.error(
+ `[Bitly] Link ${domain}/${shortKey} not found. Falling back to API...`,
+ );
+ return await fetchBitlyLink({ domain, shortKey, workspaceId });
+ }
+
+ const destinationUrl = response.headers.get("location");
+ if (!destinationUrl) {
+ console.error(`[Bitly] No redirect URL found for ${domain}/${shortKey}`);
+ return null;
+ }
+
+ console.log(`[Bitly] Found link ${domain}/${shortKey} -> ${destinationUrl}`);
+
+ return {
+ id: `${domain}/${shortKey}`,
+ long_url: destinationUrl,
+ created_at: new Date().toISOString(),
+ };
+}
+
+async function fetchBitlyLink({
+ domain,
+ shortKey,
+ workspaceId,
+}: {
+ domain: string;
+ shortKey: string;
+ workspaceId: string;
+}) {
+ const apiKey = await redis.get<string>(`import:bitly:${workspaceId}`);
+
+ if (!apiKey) {
+ console.error(`[Bitly] No API key found for workspace ${workspaceId}`);
+ return null;
+ }
+
+ const response = await fetch(
+ `https://api-ssl.bitly.com/v4/bitlinks/${domain}/${shortKey}`,
+ {
+ headers: {
+ Authorization: `Bearer ${apiKey}`,
+ },
+ },
+ );
+
+ if (!response.ok) {
+ console.log(
+ `[Bitly] Hit rate limit, returning 404 for ${domain}/${shortKey} for now...`,
+ );
+ return null;
+ }
+
+ return await response.json();
+}
diff --git a/apps/web/lib/middleware/bitly.ts b/apps/web/lib/middleware/bitly.ts
index fc3757c847..c818ee4c65 100644
--- a/apps/web/lib/middleware/bitly.ts
+++ b/apps/web/lib/middleware/bitly.ts
@@ -1,12 +1,13 @@
-import { redis } from "@/lib/upstash";
import { getUrlFromStringIfValid, linkConstructorSimple } from "@dub/utils";
import { waitUntil } from "@vercel/functions";
+import { z } from "zod";
import { ExpandedLink } from "../api/links";
import { createId } from "../api/utils";
import { EdgeLinkProps } from "../planetscale";
import { conn } from "../planetscale/connection";
import { recordLink } from "../tinybird/record-link";
+const crawlBitlyResultSchema = z.object({
// Create a new Bitly-hosted link to Dub on-demand (e.g. buff.ly)
export const importBitlyLink = async ({
domain,
@@ -15,15 +16,29 @@ export const importBitlyLink = async ({
domain: string;
shortKey: string;
}) => {
- const workspaceId = "cm05wnnpo000711ztj05wwdbu";
- const userId = "cm05wnd49000411ztg2xbup0i";
- const folderId = "fold_LIZsdjTgFVbQVGYSUmYAi5vT";
+ // const workspaceId = "cm05wnnpo000711ztj05wwdbu";
+ // const userId = "cm05wnd49000411ztg2xbup0i";
+ // const folderId = "fold_LIZsdjTgFVbQVGYSUmYAi5vT";
- const link = await crawlBitlyLink({
- domain,
- shortKey,
- workspaceId,
- });
+ const workspaceId = "cm7qknttg00049kc9l62n03wl";
+ const userId = "cm1ze0ukn0000ekkt7zks59hd";
+ const folderId = "fold_LafRWmSfgexbQxm4Tfvxg2dQ";
+
+ let link: z.infer<typeof crawlBitlyResultSchema> | null = null;
+
+ try {
+ const result = await fetch("http://localhost:8888/api/links/crawl-bitly", {
+ method: "POST",
+ body: JSON.stringify({ domain, shortKey, workspaceId }),
+ });
+
+ if (!result.ok) return null;
+
+ link = crawlBitlyResultSchema.parse(await result.json());
+ } catch (e) {
+ console.error("[Bitly] Error crawling Bitly link", e);
+ return null;
+ }
if (!link) {
return null;
@@ -46,7 +61,7 @@ export const importBitlyLink = async ({
domain,
key: shortKey,
}),
- archived: link.archived ?? false,
+ archived: false,
folderId,
createdAt: new Date(link.created_at),
updatedAt: new Date(link.created_at),
@@ -89,78 +104,3 @@ export const importBitlyLink = async ({
return null;
}
};
-
-async function crawlBitlyLink({
- domain,
- shortKey,
- workspaceId,
-}: {
- domain: string;
- shortKey: string;
- workspaceId: string;
-}) {
- const response = await fetch(`https://bit.ly/${shortKey}`, {
- redirect: "manual",
- headers: {
- Host: domain,
- "User-Agent":
- "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
- },
- });
-
- if (!response.ok && response.status !== 301 && response.status !== 302) {
- console.error(
- `[Bitly] Link ${domain}/${shortKey} not found. Falling back to API...`,
- );
- return await fetchBitlyLink({ domain, shortKey, workspaceId });
- }
-
- const destinationUrl = response.headers.get("location");
- if (!destinationUrl) {
- console.error(`[Bitly] No redirect URL found for ${domain}/${shortKey}`);
- return null;
- }
-
- console.log(`[Bitly] Found link ${domain}/${shortKey} -> ${destinationUrl}`);
-
- return {
- id: `${domain}/${shortKey}`,
- long_url: destinationUrl,
- created_at: new Date().toISOString(),
- };
-}
-
-async function fetchBitlyLink({
- domain,
- shortKey,
- workspaceId,
-}: {
- domain: string;
- shortKey: string;
- workspaceId: string;
-}) {
- const apiKey = await redis.get<string>(`import:bitly:${workspaceId}`);
-
- if (!apiKey) {
- console.error(`[Bitly] No API key found for workspace ${workspaceId}`);
- return null;
- }
-
- const response = await fetch(
- `https://api-ssl.bitly.com/v4/bitlinks/${domain}/${shortKey}`,
- {
- headers: {
- Authorization: `Bearer ${apiKey}`,
- },
- },
- );
-
- if (!response.ok) {
- console.log(
- `[Bitly] Hit rate limit, returning 404 for ${domain}/${shortKey} for now...`,
- );
- return null;
- }
-
- return await response.json();
-}