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.

backfill with crawl

Steven Teybc645ffded6d
diff --git a/apps/web/lib/middleware/bitly.ts b/apps/web/lib/middleware/bitly.ts
index 88312f315e..acc6534ba3 100644
--- a/apps/web/lib/middleware/bitly.ts
+++ b/apps/web/lib/middleware/bitly.ts
@@ -7,15 +7,6 @@ import { EdgeLinkProps } from "../planetscale";
import { conn } from "../planetscale/connection";
import { recordLink } from "../tinybird/record-link";
-type BitlyLink = {
- id: string;
- long_url: string;
- archived: boolean;
- created_at: string;
- custom_bitlinks: string[];
- tags: string[];
-};
-
// Create a new buff.ly link in Dub on-demand
export const importBitlyLink = async (shortKey: string) => {
const workspaceId = "cm05wnnpo000711ztj05wwdbu";
@@ -29,19 +20,11 @@ export const importBitlyLink = async (shortKey: string) => {
return null;
}
- let link: BitlyLink | null = null;
-
- for (const domain of ["buff.ly", "bit.ly"]) {
- link = await fetchBitlyLink({
- domain,
- shortKey,
- apiKey,
- });
-
- if (link) {
- break;
- }
- }
+ const link = await fetchBitlyLink({
+ domain: "buff.ly",
+ shortKey,
+ apiKey,
+ });
if (!link) {
return null;
@@ -70,9 +53,8 @@ export const importBitlyLink = async (shortKey: string) => {
domain,
key,
}),
- archived: link.archived,
+ archived: link.archived ?? false,
folderId,
- tagIds: [], // TODO: add tags
createdAt: new Date(link.created_at),
updatedAt: new Date(link.created_at),
};
@@ -129,9 +111,36 @@ async function fetchBitlyLink({
);
if (!response.ok) {
- console.error(`[Bitly] Link ${domain}/${shortKey} not found.`);
- return null;
+ console.log(
+ `[Bitly] Hit rate limit, crawling bit.ly/${shortKey} instead...`,
+ );
+ return await crawlBitlyLink(shortKey);
}
return await response.json();
}
+
+async function crawlBitlyLink(shortKey: string) {
+ const response = await fetch(`https://bit.ly/${shortKey}`, {
+ redirect: "manual",
+ });
+
+ if (!response.ok && response.status !== 301 && response.status !== 302) {
+ console.error(`[Bitly] Link bit.ly/${shortKey} not found.`);
+ return null;
+ }
+
+ const destinationUrl = response.headers.get("location");
+ if (!destinationUrl) {
+ console.error(`[Bitly] No redirect URL found for bit.ly/${shortKey}`);
+ return null;
+ }
+
+ console.log(`[Bitly] Found link buff.ly/${shortKey} -> ${destinationUrl}`);
+
+ return {
+ id: `buff.ly/${shortKey}`,
+ long_url: destinationUrl,
+ created_at: new Date().toISOString(),
+ };
+}