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

New Components - tinyurl #15456

Merged
merged 3 commits into from
Feb 5, 2025
Merged

New Components - tinyurl #15456

merged 3 commits into from
Feb 5, 2025

Conversation

luancazarine
Copy link
Collaborator

@luancazarine luancazarine commented Jan 29, 2025

Resolves #15135.

Summary by CodeRabbit

  • New Features

    • Added the ability to easily create shortened links using TinyURL.
    • Introduced functionality to retrieve analytics data including clicks, device types, and geographic breakdowns.
    • Enabled updating link metadata such as domain, alias, expiration, and description.
    • Launched an event source to notify users when a new shortened link is created.
    • Enhanced the TinyURL integration with additional configurable options and streamlined API interactions.
  • Chores

    • Added package configuration to improve dependency management and project metadata.

Copy link

vercel bot commented Jan 29, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

3 Skipped Deployments
Name Status Preview Comments Updated (UTC)
docs-v2 ⬜️ Ignored (Inspect) Visit Preview Jan 30, 2025 7:53pm
pipedream-docs ⬜️ Ignored (Inspect) Jan 30, 2025 7:53pm
pipedream-docs-redirect-do-not-edit ⬜️ Ignored (Inspect) Jan 30, 2025 7:53pm

@luancazarine luancazarine added the ai-assisted Content generated by AI, with human refinement and modification label Jan 29, 2025
Copy link
Contributor

coderabbitai bot commented Jan 29, 2025

Walkthrough

This pull request introduces several new modules for TinyURL integration. It adds action modules for creating shortened links, retrieving link analytics, and updating link metadata. A new polling source for new link creation events is implemented alongside enhancements to the TinyURL app component with additional properties and methods. A new utility function for parsing objects and a package manifest are also included. Error handling is standardized through configuration errors on API failures.

Changes

File(s) Change Summary
components/tinyurl/actions/.../create-shortened-link.mjs
components/tinyurl/actions/.../retrieve-link-analytics.mjs
components/tinyurl/actions/.../update-link-metadata.mjs
Added three new action modules for creating shortened links, retrieving analytics, and updating link metadata with asynchronous run methods and error handling.
components/tinyurl/common/utils.mjs Introduced the parseObject function to safely parse objects and JSON strings with error handling.
components/tinyurl/package.json Added a new package manifest with component metadata and dependency on @pipedream/platform.
components/tinyurl/sources/.../new-link-created.mjs Added a new polling source module that emits events when a new TinyURL is created, includes state management for tracking the last event timestamp.
components/tinyurl/tinyurl.app.mjs Enhanced the TinyURL app by adding new property definitions (e.g., urls, alias, expiresAt, tags) and methods (_baseUrl, _headers, _makeRequest, createTinyURL, updateTinyURLMetadata, listURLs); removed the obsolete authKeys method.

Sequence Diagram(s)

Loading
sequenceDiagram
    participant User
    participant Action as Create Shortened Link Action
    participant TinyURLService as TinyURL API
    User->>Action: Invoke Create Shortened Link
    Action->>TinyURLService: Call createTinyURL()
    TinyURLService-->>Action: Return shortened URL (or error)
    Action-->>User: Return summary message / error
Loading
sequenceDiagram
    participant Timer
    participant Source as New-Link-Created Source
    participant DB as Database (state storage)
    participant TinyURLService as TinyURL API
    Timer->>Source: Poll for new links
    Source->>DB: _getLastDate() to retrieve last timestamp
    Source->>TinyURLService: Fetch new URLs since last date
    TinyURLService-->>Source: Return list of new URLs
    Source->>DB: _setLastDate() to update last timestamp
    Source-->>Timer: Emit event(s) for each new URL

Assessment against linked issues

Objective Addressed Explanation
Actions: create-shortened-link, update-link-metadata, retrieve-link-analytics [#15135]
Polling: new-link-created [#15135]
Polling: new-link-click-instant, new-link-metadata-instant [#15135] Not implemented; changes do not address these event triggers.

Possibly related PRs

  • New Components - l2s #14115: Introduces URL shortening functionality using a different service (L2S), sharing a similar code-level approach to URL creation.

Suggested reviewers

  • michelle0927

Poem

I'm a rabbit with hops so spry,
I watch these changes swiftly fly.
Tiny links now stretch with grace,
Analytics and updates keeping pace.
My whiskers twitch with code delight,
In URL meadows, everything's just right!
🐇✨

✨ 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.

Sorry, something went wrong.

Sources
 - New Link Created

Actions
 - Create Shortened Link
 - Update Link Metadata
 - Retrieve Link Analytics
@luancazarine luancazarine marked this pull request as ready for review February 3, 2025 17:52
Copy link
Contributor

@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: 3

🧹 Nitpick comments (16)
components/tinyurl/tinyurl.app.mjs (7)

6-25: Consider adding error handling
In urls prop definition, if listURLs() fails or returns malformed data, the function may throw without a user-friendly error. Wrap the request or parsing logic in a try/catch to provide clearer error messages to users.


26-30: Optional: Provide example URL
You could enhance the url prop definition by providing an example of a typical long URL (e.g., "https://www.example.com") to guide users.


31-36: Default domain check
The default domain is "tinyurl.com", which is sensible. If you plan on supporting multiple domains or subdomains dynamically, consider prompting the user to select one from a known list to avoid potential typos.


43-48: Validate date format
Consider adding regex or date validation to ensure users supply a valid ISO8601 string for expiresAt. An invalid date might cause unexpected API errors.


49-54: Clarity on tags
Tags help group URLs, but consider whether there's a limit or recommended naming scheme. Documenting any constraints can improve user trust.


60-65: Headers generation
Implementation is straightforward. However, be mindful of logging authorization tokens in production logs to avoid security leaks.


66-76: Remove console.log or expose debug level
console.log("config: ", config); may unnecessarily leak sensitive data. Use a debug flag or remove it for production.

components/tinyurl/common/utils.mjs (1)

1-25: Consider nested JSON and return types
The parsing logic is solid for straightforward cases, but it handles only one level of parsing for array items. If deeper JSON objects must be parsed recursively, you’ll need a nested approach. Also, returning undefined may cause confusion; consider returning null for clarity.

components/tinyurl/actions/retrieve-link-analytics/retrieve-link-analytics.mjs (3)

7-7: Add documentation URL.

The documentation URL is missing in the description.

-  description: "Retrieves analytics for a specific TinyURL link, including total clicks, geographic breakdowns, and device types. [See the documentation]()",
+  description: "Retrieves analytics for a specific TinyURL link, including total clicks, geographic breakdowns, and device types. [See the documentation](https://tinyurl.com/app/dev)",

35-35: Fix typo in description.

There's a typo in the word "analytics".

-      description: "The start datetime of analitics report",
+      description: "The start datetime of analytics report",

50-66: Enhance error handling and input validation.

The current implementation could be improved with better error handling and input validation:

  1. Validate datetime format for from and to fields
  2. Ensure from date is not after to date
  3. Add more specific error messages
   async run({ $ }) {
+    if (this.from && this.to && new Date(this.from) > new Date(this.to)) {
+      throw new ConfigurationError("Start date must be before end date");
+    }
+
     try {
       const analytics = await this.tinyurl.retrieveAnalytics({
         $,
         params: {
           from: this.from,
           to: this.to,
           alias: this.urls,
           tag: this.tag,
         },
       });
       $.export("$summary", `Retrieved analytics for link ${this.urls}`);
       return analytics;
     } catch ({ response }) {
-      throw new ConfigurationError(response?.data?.errors[0]);
+      const error = response?.data?.errors?.[0] || "Failed to retrieve analytics";
+      throw new ConfigurationError(error);
     }
   },
components/tinyurl/actions/create-shortened-link/create-shortened-link.mjs (2)

8-8: Add documentation URL.

The documentation URL is missing in the description.

-  description: "Creates a new shortened link. [See the documentation]()",
+  description: "Creates a new shortened link. [See the documentation](https://tinyurl.com/app/dev)",

54-72: Enhance error handling and URL validation.

The current implementation could benefit from additional validation and error handling:

  1. Validate URL format
  2. Add more specific error messages
  3. Validate expiration date format
   async run({ $ }) {
+    // Validate URL format
+    try {
+      new URL(this.url);
+    } catch (e) {
+      throw new ConfigurationError("Invalid URL format");
+    }
+
+    // Validate expiration date if provided
+    if (this.expiresAt && isNaN(new Date(this.expiresAt).getTime())) {
+      throw new ConfigurationError("Invalid expiration date format. Use ISO8601 format.");
+    }
+
     try {
       const response = await this.tinyurl.createTinyURL({
         $,
         data: {
           url: this.url,
           domain: this.domain,
           alias: this.alias,
           tags: this.tags ? parseObject(this.tags)?.join(",") : undefined,
           expires_at: this.expiresAt,
           description: this.description,
         },
       });
       $.export("$summary", `Created TinyURL: ${response.data.tiny_url}`);
       return response;
     } catch ({ response }) {
-      throw new ConfigurationError(response?.data?.errors[0]);
+      const error = response?.data?.errors?.[0] || "Failed to create shortened URL";
+      throw new ConfigurationError(error);
     }
   },
components/tinyurl/actions/update-link-metadata/update-link-metadata.mjs (3)

8-8: Add documentation URL.

The documentation URL is missing in the description.

-  description: "Updates the metadata of an existing TinyURL. [See the documentation]()",
+  description: "Updates the metadata of an existing TinyURL. [See the documentation](https://tinyurl.com/app/dev)",

65-85: Enhance error handling and validation.

The current implementation could benefit from additional validation and error handling:

  1. Validate at least one update field is provided
  2. Validate date format for expiration
  3. Add more specific error messages
   async run({ $ }) {
+    // Ensure at least one update field is provided
+    const hasUpdates = [
+      this.newDomain,
+      this.newAlias,
+      this.newStats,
+      this.newTags,
+      this.newExpiresAt,
+      this.newDescription
+    ].some(field => field !== undefined);
+
+    if (!hasUpdates) {
+      throw new ConfigurationError("At least one field must be provided for update");
+    }
+
+    // Validate expiration date if provided
+    if (this.newExpiresAt && isNaN(new Date(this.newExpiresAt).getTime())) {
+      throw new ConfigurationError("Invalid expiration date format. Use ISO8601 format.");
+    }
+
     try {
       const response = await this.tinyurl.updateTinyURLMetadata({
         $,
         data: {
           domain: this.domain,
           alias: this.urls,
           new_domain: this.newDomain,
           new_alias: this.newAlias,
           new_stats: this.newStats,
           new_tags: this.newTags ? parseObject(this.newTags) : undefined,
           new_expires_at: this.newExpiresAt,
           new_description: this.newDescription,
         },
       });
       $.export("$summary", `Updated TinyURL metadata for link: ${response.data.tiny_url}`);
       return response;
     } catch ({ response }) {
-      throw new ConfigurationError(response?.data?.errors[0]);
+      const error = response?.data?.errors?.[0] || "Failed to update TinyURL metadata";
+      throw new ConfigurationError(error);
     }
   },

49-49: Improve premium feature descriptions.

The descriptions for premium features should be more prominent and consistent.

-      description: "Tags you would like this TinyURL to have. Overwrites the existing tags. **Paid accounts only**",
+      description: "⭐ PREMIUM FEATURE: Tags you would like this TinyURL to have. Overwrites the existing tags.",
-      description: "TinyURL expiration in ISO8601 format. If not set so TinyURL never expires, **Paid accounts only**",
+      description: "⭐ PREMIUM FEATURE: TinyURL expiration in ISO8601 format. If not set, TinyURL never expires.",

Also applies to: 55-55

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 666b7c4 and d2e5a91.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (7)
  • components/tinyurl/actions/create-shortened-link/create-shortened-link.mjs (1 hunks)
  • components/tinyurl/actions/retrieve-link-analytics/retrieve-link-analytics.mjs (1 hunks)
  • components/tinyurl/actions/update-link-metadata/update-link-metadata.mjs (1 hunks)
  • components/tinyurl/common/utils.mjs (1 hunks)
  • components/tinyurl/package.json (1 hunks)
  • components/tinyurl/sources/new-link-created/new-link-created.mjs (1 hunks)
  • components/tinyurl/tinyurl.app.mjs (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • components/tinyurl/package.json
🧰 Additional context used
🪛 GitHub Check: Lint Code Base
components/tinyurl/actions/retrieve-link-analytics/retrieve-link-analytics.mjs

[warning] 12-12:
Component prop alert must have a label. See https://pipedream.com/docs/components/guidelines/#props


[warning] 12-12:
Component prop alert must have a description. See https://pipedream.com/docs/components/guidelines/#props

🔇 Additional comments (13)
components/tinyurl/tinyurl.app.mjs (6)

1-2: Import looks good
No issues with importing axios from @pipedream/platform.


37-42: Alias property
This looks fine. Optional property design is good for letting TinyURL auto-generate an alias if omitted.


57-59: Base URL
Simple and clear. Points directly to the TinyURL API.


77-83: createTinyURL is well-structured
The method concisely makes a POST request to the create endpoint.


84-90: updateTinyURLMetadata follows the same pattern
Implementation remains consistent and leverages _makeRequest().


91-97: Verify usage of opts
You spread opts into _makeRequest(), but it’s assigned to the opts key instead of merging into top-level config properties like params or data. Verify that the TinyURL API call receives the correct payload.

components/tinyurl/sources/new-link-created/new-link-created.mjs (7)

1-3: Imports and app reference
Importing DEFAULT_POLLING_SOURCE_TIMER_INTERVAL and referencing tinyurl app is correct.


4-20: Source definition
Props, including db and timer, follow standard Pipedream pattern. Clear naming for the source is good.


22-24: Get last date
Retrieving last date from db provides a neat checkpoint for polling.


25-27: Set last date
Implementation is straightforward and updates the stored date.


28-52: Check ordering and existence
When pulling data from listURLs(), ensure the results are sorted by created_at if you rely on the first item being the most recent. Also, confirm the from parameter is recognized by the TinyURL API.


54-57: Deploy hook
Limiting initial fetch to 25 is a standard approach for a quick warm-up.


59-61: Run method
Calls emitEvent() for regular polling, which is consistent.

@luancazarine luancazarine merged commit f139761 into master Feb 5, 2025
11 checks passed
@luancazarine luancazarine deleted the issue-15135 branch February 5, 2025 14:24
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
ai-assisted Content generated by AI, with human refinement and modification
Projects
None yet
Development

Successfully merging this pull request may close these issues.

[Components] tinyurl
2 participants