Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature: Add bit.ly as a shortening link - 545 #601

Open
wants to merge 3 commits into
base: main
Choose a base branch
from

Conversation

pritam1322
Copy link

@pritam1322 pritam1322 commented Feb 9, 2025

What kind of change does this PR introduce?

Feature: Add bit.ly as a shortening link #545

Why was this change needed?

#545
Please link to related issues when possible, and explain WHY you changed things, not WHAT you changed.

Other information:

eg: Did you discuss this change with anybody before working on it (not required, but can be a good idea for bigger changes). Any plans for the future, etc?

Checklist:

Put a "X" in the boxes below to indicate you have followed the checklist;

  • I have read the CONTRIBUTING guide.
  • I checked that there were not similar issues or PRs already open for this.
  • This PR fixes just ONE issue (do not include multiple issues or types of change in the same PR) For example, don't try and fix a UI issue and include new dependencies in the same PR.

Summary by CodeRabbit

  • New Features
    • Integrated Bitly as an option for URL shortening with enhanced analytics.
    • When configured with the appropriate API token, users can generate short links, retrieve the original URLs from short links, and access detailed click statistics.
    • The new Bitly option complements existing providers, ensuring a seamless experience regardless of the selected shortening service.

Copy link

vercel bot commented Feb 9, 2025

@pritam1322 is attempting to deploy a commit to the Listinai Team on Vercel.

A member of the Team first needs to authorize it.

Copy link

coderabbitai bot commented Feb 9, 2025

Walkthrough

This PR introduces a new Bitly provider in the NestJS URL shortening library. A new file implements the Bitly class adhering to the ShortLinking interface with methods to create, convert, and retrieve short links along with their statistics via the Bitly API. Additionally, the ShortLinkService is updated to include a provider check for the BITLY_TOKEN, enabling Bitly integration alongside existing providers. The implementation also covers recursive pagination for aggregating link statistics.

Changes

File(s) Change Summary
libraries/nestjs-libraries/.../providers/bitly.ts Added new Bitly class implementing the ShortLinking interface with methods: linksStatistics, convertLinkToShortLink, convertShortLinkToLink, getAllLinksStatistics for Bitly API interaction.
libraries/nestjs-libraries/.../short.link.service.ts Updated getProvider function to return an instance of Bitly when BITLY_TOKEN is set, while retaining existing provider handling.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant ShortLinkService
    participant Bitly

    Client->>+ShortLinkService: Request URL shortening or stats
    ShortLinkService->>ShortLinkService: Check BITLY_TOKEN environment variable
    alt BITLY_TOKEN is set
        ShortLinkService->>+Bitly: Invoke relevant Bitly method
        Bitly-->>-ShortLinkService: Return short link / statistics
    else BITLY_TOKEN not set
        ShortLinkService->>ShortLinkService: Fallback to other providers
    end
    ShortLinkService-->>-Client: Deliver result
Loading

Possibly related issues

Possibly related PRs

Suggested reviewers

  • nevo-david

Poem

In a field of code under skies so blue,
I hopped and found Bitly, shiny and new.
Short links dance with each graceful click,
A rabbit's delight, both smooth and quick.
Hop on, dear coder, let these links stick!

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 092ea21 and 2083da0.

📒 Files selected for processing (2)
  • libraries/nestjs-libraries/src/short-linking/providers/bitly.ts (1 hunks)
  • libraries/nestjs-libraries/src/short-linking/short.link.service.ts (2 hunks)
🔇 Additional comments (1)
libraries/nestjs-libraries/src/short-linking/short.link.service.ts (1)

6-6: LGTM!

The Bitly provider integration follows the same pattern as other providers and is correctly implemented.

Also applies to: 17-19

Comment on lines +50 to +55
async convertShortLinkToLink(shortLink: string) {
const linkId = shortLink.split('/').pop();
const response = await fetch(`https://api-ssl.bitly.com/v4/bitlinks/${linkId}`, options);
const data = await response.json();
return data.long_url;
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Add error handling for link retrieval.

The method lacks error handling for failed API calls and response validation.

 async convertShortLinkToLink(shortLink: string) {
   const linkId = shortLink.split('/').pop();
-  const response  = await fetch(`https://api-ssl.bitly.com/v4/bitlinks/${linkId}`, options);
-  const data = await response.json();
-  return data.long_url;
+  try {
+    const response = await fetch(`https://api-ssl.bitly.com/v4/bitlinks/${linkId}`, options);
+    if (!response.ok) {
+      throw new Error(`Failed to retrieve original link: ${response.statusText}`);
+    }
+    
+    const data = await response.json();
+    if (!data.long_url) {
+      throw new Error('Invalid response: missing long_url property');
+    }
+    
+    return data.long_url;
+  } catch (error) {
+    console.error('Error retrieving original link:', error);
+    throw error;
+  }
 }

Comment on lines +34 to +48
async convertLinkToShortLink(id: string, link: string) {
return (
await (
await fetch(`https://api-ssl.bitly.com/v4/shorten`, {
...options,
method: 'POST',
body: JSON.stringify({
long_url: link,
group_guid: id,
domain: this.shortLinkDomain,
}),
})
).json()
).link;
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Add error handling for link creation.

The method lacks error handling for failed API calls and response validation.

 async convertLinkToShortLink(id: string, link: string) {
-  return (
-    await (
-      await fetch(`https://api-ssl.bitly.com/v4/shorten`, {
-        ...options,
-        method: 'POST',
-        body: JSON.stringify({
-          long_url: link,
-          group_guid: id,
-          domain: this.shortLinkDomain,
-        }),
-      })
-    ).json()
-  ).link;
+  try {
+    const response = await fetch(`https://api-ssl.bitly.com/v4/shorten`, {
+      ...options,
+      method: 'POST',
+      body: JSON.stringify({
+        long_url: link,
+        group_guid: id,
+        domain: this.shortLinkDomain,
+      }),
+    });
+    
+    if (!response.ok) {
+      throw new Error(`Failed to create short link: ${response.statusText}`);
+    }
+    
+    const data = await response.json();
+    if (!data.link) {
+      throw new Error('Invalid response: missing link property');
+    }
+    
+    return data.link;
+  } catch (error) {
+    console.error('Error creating short link:', error);
+    throw error;
+  }
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
async convertLinkToShortLink(id: string, link: string) {
return (
await (
await fetch(`https://api-ssl.bitly.com/v4/shorten`, {
...options,
method: 'POST',
body: JSON.stringify({
long_url: link,
group_guid: id,
domain: this.shortLinkDomain,
}),
})
).json()
).link;
}
async convertLinkToShortLink(id: string, link: string) {
try {
const response = await fetch(`https://api-ssl.bitly.com/v4/shorten`, {
...options,
method: 'POST',
body: JSON.stringify({
long_url: link,
group_guid: id,
domain: this.shortLinkDomain,
}),
});
if (!response.ok) {
throw new Error(`Failed to create short link: ${response.statusText}`);
}
const data = await response.json();
if (!data.link) {
throw new Error('Invalid response: missing link property');
}
return data.link;
} catch (error) {
console.error('Error creating short link:', error);
throw error;
}
}

Comment on lines +3 to +8
const options = {
headers: {
Authorization: `Bearer ${process.env.BITLY_TOKEN}`,
'Content-Type': 'application/json',
},
};
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Add token validation and error handling.

The Bitly token is accessed directly from environment variables without validation. Consider adding validation to ensure the token exists and has the correct format.

 const options = {
   headers: {
-    Authorization: `Bearer ${process.env.BITLY_TOKEN}`,
+    Authorization: `Bearer ${
+      process.env.BITLY_TOKEN ?? 
+      (() => { throw new Error('BITLY_TOKEN environment variable is not set') })()
+    }`,
     'Content-Type': 'application/json',
   },
 };
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const options = {
headers: {
Authorization: `Bearer ${process.env.BITLY_TOKEN}`,
'Content-Type': 'application/json',
},
};
const options = {
headers: {
- Authorization: `Bearer ${process.env.BITLY_TOKEN}`,
+ Authorization: `Bearer ${
+ process.env.BITLY_TOKEN ??
+ (() => { throw new Error('BITLY_TOKEN environment variable is not set') })()
+ }`,
'Content-Type': 'application/json',
},
};

Comment on lines +13 to +32
async linksStatistics(links: string[]) {
return Promise.all(
links.map(async (link) => {
const linkId = link.split('/').pop();
const response = await (
await fetch(`https://api-ssl.bitly.com/v4/bitlinks/${linkId}`, options)
).json();

const clicksResponse = await (
await fetch(`https://api-ssl.bitly.com/v4/bitlinks/${linkId}/clicks/summary`, options)
).json();

return {
short: link,
original: response.long_url,
clicks: clicksResponse.total_clicks || 0,
};
})
);
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Add error handling and rate limiting for API calls.

The method makes multiple API calls without error handling or rate limiting considerations. This could lead to failures or API rate limits being exceeded.

 async linksStatistics(links: string[]) {
+  const delay = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));
   return Promise.all(
-    links.map(async (link) => {
+    links.map(async (link, index) => {
+      // Add delay between requests to avoid rate limiting
+      await delay(index * 100);
+
       const linkId = link.split('/').pop();
-      const response = await (
-        await fetch(`https://api-ssl.bitly.com/v4/bitlinks/${linkId}`, options)
-      ).json();
+      try {
+        const response = await fetch(`https://api-ssl.bitly.com/v4/bitlinks/${linkId}`, options);
+        if (!response.ok) {
+          throw new Error(`Failed to fetch bitlink: ${response.statusText}`);
+        }
+        const data = await response.json();

-      const clicksResponse = await (
-        await fetch(`https://api-ssl.bitly.com/v4/bitlinks/${linkId}/clicks/summary`, options)
-      ).json();
+        const clicksResponse = await fetch(
+          `https://api-ssl.bitly.com/v4/bitlinks/${linkId}/clicks/summary`,
+          options
+        );
+        if (!clicksResponse.ok) {
+          throw new Error(`Failed to fetch clicks: ${clicksResponse.statusText}`);
+        }
+        const clicksData = await clicksResponse.json();

-      return {
-        short: link,
-        original: response.long_url,
-        clicks: clicksResponse.total_clicks || 0,
-      };
+        return {
+          short: link,
+          original: data.long_url,
+          clicks: clicksData.total_clicks || 0,
+        };
+      } catch (error) {
+        console.error(`Error processing link ${link}:`, error);
+        return {
+          short: link,
+          original: '',
+          clicks: 0,
+        };
+      }
     })
   );
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
async linksStatistics(links: string[]) {
return Promise.all(
links.map(async (link) => {
const linkId = link.split('/').pop();
const response = await (
await fetch(`https://api-ssl.bitly.com/v4/bitlinks/${linkId}`, options)
).json();
const clicksResponse = await (
await fetch(`https://api-ssl.bitly.com/v4/bitlinks/${linkId}/clicks/summary`, options)
).json();
return {
short: link,
original: response.long_url,
clicks: clicksResponse.total_clicks || 0,
};
})
);
}
async linksStatistics(links: string[]) {
const delay = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));
return Promise.all(
links.map(async (link, index) => {
// Add delay between requests to avoid rate limiting
await delay(index * 100);
const linkId = link.split('/').pop();
try {
const response = await fetch(`https://api-ssl.bitly.com/v4/bitlinks/${linkId}`, options);
if (!response.ok) {
throw new Error(`Failed to fetch bitlink: ${response.statusText}`);
}
const data = await response.json();
const clicksResponse = await fetch(
`https://api-ssl.bitly.com/v4/bitlinks/${linkId}/clicks/summary`,
options
);
if (!clicksResponse.ok) {
throw new Error(`Failed to fetch clicks: ${clicksResponse.statusText}`);
}
const clicksData = await clicksResponse.json();
return {
short: link,
original: data.long_url,
clicks: clicksData.total_clicks || 0,
};
} catch (error) {
console.error(`Error processing link ${link}:`, error);
return {
short: link,
original: '',
clicks: 0,
};
}
})
);
}

Comment on lines +57 to +87
async getAllLinksStatistics(
groupId: string,
page = 1
): Promise<{ short: string; original: string; clicks: string }[]> {
const response = await (
await fetch(
`https://api-ssl.bitly.com/v4/groups/${groupId}/bitlinks?page=${page}&size=100`,
options
)
).json();

const mapLinks = await Promise.all(
response.links.map(async (link: any) => {
const clicksResponse = await (
await fetch(`https://api-ssl.bitly.com/v4/bitlinks/${link.id}/clicks/summary`, options)
).json();

return {
short: link.link,
original: link.long_url,
clicks: clicksResponse.total_clicks || 0,
};
})
);

if (mapLinks.length < 100) {
return mapLinks;
}

return [...mapLinks, ...(await this.getAllLinksStatistics(groupId, page + 1))];
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Improve error handling and implement iterative pagination.

The method has several issues:

  1. Missing error handling for API calls
  2. No rate limiting consideration
  3. Recursive implementation could lead to stack overflow with large datasets
 async getAllLinksStatistics(
   groupId: string,
   page = 1
 ): Promise<{ short: string; original: string; clicks: string }[]> {
-  const response = await (
-    await fetch(
-      `https://api-ssl.bitly.com/v4/groups/${groupId}/bitlinks?page=${page}&size=100`,
-      options
-    )
-  ).json();
+  try {
+    let allLinks = [];
+    let currentPage = page;
+    
+    while (true) {
+      const response = await fetch(
+        `https://api-ssl.bitly.com/v4/groups/${groupId}/bitlinks?page=${currentPage}&size=100`,
+        options
+      );
+      
+      if (!response.ok) {
+        throw new Error(`Failed to fetch links: ${response.statusText}`);
+      }
+      
+      const data = await response.json();
+      if (!data.links || !Array.isArray(data.links)) {
+        throw new Error('Invalid response: missing or invalid links array');
+      }
+      
+      const delay = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));
+      const mapLinks = await Promise.all(
+        data.links.map(async (link: any, index: number) => {
+          // Add delay between requests to avoid rate limiting
+          await delay(index * 100);
+          
+          try {
+            const clicksResponse = await fetch(
+              `https://api-ssl.bitly.com/v4/bitlinks/${link.id}/clicks/summary`,
+              options
+            );
+            
+            if (!clicksResponse.ok) {
+              throw new Error(`Failed to fetch clicks: ${clicksResponse.statusText}`);
+            }
+            
+            const clicksData = await clicksResponse.json();
+            return {
+              short: link.link,
+              original: link.long_url,
+              clicks: clicksData.total_clicks || 0,
+            };
+          } catch (error) {
+            console.error(`Error fetching clicks for ${link.id}:`, error);
+            return {
+              short: link.link,
+              original: link.long_url,
+              clicks: 0,
+            };
+          }
+        })
+      );
+      
+      allLinks = [...allLinks, ...mapLinks];
+      
+      if (mapLinks.length < 100) {
+        break;
+      }
+      
+      currentPage++;
+    }
+    
+    return allLinks;
+  } catch (error) {
+    console.error('Error fetching all links:', error);
+    throw error;
+  }
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
async getAllLinksStatistics(
groupId: string,
page = 1
): Promise<{ short: string; original: string; clicks: string }[]> {
const response = await (
await fetch(
`https://api-ssl.bitly.com/v4/groups/${groupId}/bitlinks?page=${page}&size=100`,
options
)
).json();
const mapLinks = await Promise.all(
response.links.map(async (link: any) => {
const clicksResponse = await (
await fetch(`https://api-ssl.bitly.com/v4/bitlinks/${link.id}/clicks/summary`, options)
).json();
return {
short: link.link,
original: link.long_url,
clicks: clicksResponse.total_clicks || 0,
};
})
);
if (mapLinks.length < 100) {
return mapLinks;
}
return [...mapLinks, ...(await this.getAllLinksStatistics(groupId, page + 1))];
}
async getAllLinksStatistics(
groupId: string,
page = 1
): Promise<{ short: string; original: string; clicks: string }[]> {
try {
let allLinks = [];
let currentPage = page;
while (true) {
const response = await fetch(
`https://api-ssl.bitly.com/v4/groups/${groupId}/bitlinks?page=${currentPage}&size=100`,
options
);
if (!response.ok) {
throw new Error(`Failed to fetch links: ${response.statusText}`);
}
const data = await response.json();
if (!data.links || !Array.isArray(data.links)) {
throw new Error('Invalid response: missing or invalid links array');
}
const delay = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));
const mapLinks = await Promise.all(
data.links.map(async (link: any, index: number) => {
// Add delay between requests to avoid rate limiting
await delay(index * 100);
try {
const clicksResponse = await fetch(
`https://api-ssl.bitly.com/v4/bitlinks/${link.id}/clicks/summary`,
options
);
if (!clicksResponse.ok) {
throw new Error(`Failed to fetch clicks: ${clicksResponse.statusText}`);
}
const clicksData = await clicksResponse.json();
return {
short: link.link,
original: link.long_url,
clicks: clicksData.total_clicks || 0,
};
} catch (error) {
console.error(`Error fetching clicks for ${link.id}:`, error);
return {
short: link.link,
original: link.long_url,
clicks: 0,
};
}
})
);
allLinks = [...allLinks, ...mapLinks];
if (mapLinks.length < 100) {
break;
}
currentPage++;
}
return allLinks;
} catch (error) {
console.error('Error fetching all links:', error);
throw error;
}
}

Copy link
Collaborator

@egelhaus egelhaus left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@egelhaus egelhaus linked an issue Feb 9, 2025 that may be closed by this pull request
1 task
@Azadbangladeshi-com
Copy link

Work permit visa needed

@egelhaus
Copy link
Collaborator

egelhaus commented Feb 9, 2025

@Azadbangladeshi-com ?
What do you mean by that?

@nevo-david
Copy link
Contributor

@Azadbangladeshi-com ? What do you mean by that?

it's spam

@egelhaus
Copy link
Collaborator

can't you ban him from commenting?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Feature: Add bit.ly as a shortening link
4 participants