Skip to content

Conversation

michelle0927
Copy link
Collaborator

@michelle0927 michelle0927 commented Jan 9, 2025

Resolves #15227

Summary by CodeRabbit

  • New Features

    • Added MessageBird integration with support for creating contacts.
    • Implemented SMS and voice message sending capabilities.
    • Created a webhook for receiving new messages across multiple platforms.
    • Introduced new modules for handling incoming SMS and voice messages.
    • Added a new source component to emit events for newly received SMS messages.
  • Improvements

    • Updated package version to 0.1.0.
    • Enhanced API interaction methods for MessageBird service.
  • Changes

    • Restructured MessageBird component configuration.
    • Updated main entry point in package configuration.
    • Removed unnecessary .gitignore file to allow tracking of specified files.

Copy link

vercel bot commented Jan 9, 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 15, 2025 5:44pm
pipedream-docs ⬜️ Ignored (Inspect) Jan 15, 2025 5:44pm
pipedream-docs-redirect-do-not-edit ⬜️ Ignored (Inspect) Jan 15, 2025 5:44pm

Copy link
Contributor

coderabbitai bot commented Jan 9, 2025

Walkthrough

This pull request introduces a comprehensive implementation of MessageBird components for Pipedream, including a new application configuration, actions for creating contacts, sending SMS and voice messages, and a source for handling incoming messages. The changes involve creating new MessageBird app modules, defining multiple actions for contact and message management, and implementing webhook-based message reception sources. The project structure has been updated with new files and modifications to the package configuration.

Changes

File Change Summary
.gitignore Removed file that previously ignored JavaScript files and dist directory
components/messagebird/messagebird.app.mjs New app definition with comprehensive API interaction methods and property definitions
components/messagebird/actions/create-contact/create-contact.mjs New action for creating contacts via MessageBird API
components/messagebird/actions/send-sms/send-sms.mjs New action for sending SMS messages
components/messagebird/actions/send-voice-message/send-voice-message.mjs New action for sending voice messages
components/messagebird/sources/new-message-received/new-message-received.mjs New source for handling incoming messages with webhook support
components/messagebird/sources/new-message-received/test-event.mjs Test event module for message reception
components/messagebird/package.json Updated version, main entry point, and added dependencies
components/message_bird/message_bird.app.mjs New app definition and methods for MessageBird API interactions
components/message_bird/actions/create-contact/create-contact.mjs New action for creating contacts in the MessageBird API
components/message_bird/actions/send-sms/send-sms.mjs New action for sending SMS messages in the MessageBird API
components/message_bird/actions/send-voice-message/send-voice-message.mjs New action for sending voice messages in the MessageBird API
components/message_bird/sources/new-sms-message-received/new-sms-message-received.mjs New source for handling incoming SMS messages

Assessment against linked issues

Objective Addressed Explanation
Create Contact Action [#15227]
Send Voice Message Action [#15227]
Send SMS Action [#15227]
Message Received Source [#15227]

Possibly related PRs

Suggested labels

action, trigger / source

Suggested reviewers

  • jcortes

Poem

🐰 Hop, hop, MessageBird takes flight!
APIs dancing with pure delight
Contacts, SMS, voice so clear
Webhooks singing, messages near
Code's new melody, rabbit's cheer! 🚀


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
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: 13

🧹 Nitpick comments (6)
components/messagebird/sources/new-message-received/test-event.mjs (1)

5-7: Use consistent test IDs

The test event contains multiple UUIDs and a platform reference that appear to be from a real system. For test events, use consistent, obviously fake IDs to make the test data more recognizable.

-    "id": "404544c5-9920-45f1-8990-0855634ab7ac",
-    "channelId": "52ad151f-f7b4-46f9-a5c6-d3318e650c84",
+    "id": "test-message-id-123",
+    "channelId": "test-channel-id-123",

Also applies to: 16-17, 34-34

components/messagebird/actions/create-contact/create-contact.mjs (3)

6-6: Update documentation URL domain

The documentation URL uses 'bird.com' instead of 'messagebird.com'.

-  description: "Creates a new contact. [See the documentation](https://docs.bird.com/api/contacts-api/api-reference/manage-workspace-contacts/create-a-contact)",
+  description: "Creates a new contact. [See the documentation](https://docs.messagebird.com/api/contacts-api/api-reference/manage-workspace-contacts/create-a-contact)",

26-30: Add input validation for display name

The display name property lacks validation for length and format. Consider adding constraints to prevent invalid inputs.

   displayName: {
     type: "string",
     label: "Display Name",
     description: "The display name for the contact",
+    validate: (value) => {
+      if (!value?.trim()) {
+        return "Display name cannot be empty";
+      }
+      if (value.length > 100) {
+        return "Display name cannot exceed 100 characters";
+      }
+    },
   },

31-36: Add email format validation

The email property should include format validation to ensure valid email addresses.

   email: {
     type: "string",
     label: "Email",
     description: "The email address of the contact",
     optional: true,
+    validate: (value) => {
+      if (value && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)) {
+        return "Please enter a valid email address";
+      }
+    },
   },
components/messagebird/actions/send-sms/send-sms.mjs (1)

6-6: Update documentation URL domain

The documentation URL uses 'bird.com' instead of 'messagebird.com'.

-  description: "Sends an SMS message. [See the documentation](https://docs.bird.com/api/channels-api/supported-channels/programmable-sms/sending-sms-messages)",
+  description: "Sends an SMS message. [See the documentation](https://docs.messagebird.com/api/channels-api/supported-channels/programmable-sms/sending-sms-messages)",
components/messagebird/actions/send-voice-message/send-voice-message.mjs (1)

6-6: Update documentation URL domain

The documentation URL uses 'bird.com' instead of 'messagebird.com'.

-  description: "Send a voice message to any phone number globally. [See the documentation](https://docs.bird.com/api/voice-api/voice-calls-api/initiate-an-outbound-call)",
+  description: "Send a voice message to any phone number globally. [See the documentation](https://docs.messagebird.com/api/voice-api/voice-calls-api/initiate-an-outbound-call)",
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 6b76304 and 80c5b73.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (9)
  • components/messagebird/.gitignore (0 hunks)
  • components/messagebird/actions/create-contact/create-contact.mjs (1 hunks)
  • components/messagebird/actions/send-sms/send-sms.mjs (1 hunks)
  • components/messagebird/actions/send-voice-message/send-voice-message.mjs (1 hunks)
  • components/messagebird/app/messagebird.app.ts (0 hunks)
  • components/messagebird/messagebird.app.mjs (1 hunks)
  • components/messagebird/package.json (1 hunks)
  • components/messagebird/sources/new-message-received/new-message-received.mjs (1 hunks)
  • components/messagebird/sources/new-message-received/test-event.mjs (1 hunks)
💤 Files with no reviewable changes (2)
  • components/messagebird/.gitignore
  • components/messagebird/app/messagebird.app.ts
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: Verify TypeScript components
  • GitHub Check: pnpm publish
  • GitHub Check: Publish TypeScript components
  • GitHub Check: Lint Code Base
🔇 Additional comments (1)
components/messagebird/package.json (1)

15-17: Verify platform dependency version

Please verify if version 3.0.3 of @pipedream/platform is the latest stable version that's compatible with your implementation.

✅ Verification successful

@pipedream/platform dependency is using the latest version

The package is correctly using version 3.0.3, which is confirmed to be the latest available version in the npm registry.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check latest version of @pipedream/platform
npm view @pipedream/platform versions --json | jq -r '.[-1]'

# Check for any breaking changes in recent versions
npm view @pipedream/platform@">3.0.3" version --json

Length of output: 754

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: 4

🧹 Nitpick comments (1)
components/messagebird/sources/new-message-received/new-message-received.mjs (1)

30-46: Add validation for platform values

Consider adding validation to ensure the platform value matches MessageBird's supported channels. Also, consider using constants for the platform options to prevent typos and enable easier maintenance.

+const PLATFORM_OPTIONS = {
+  SMS: "sms",
+  WHATSAPP: "whatsapp",
+  EMAIL: "email",
+  LINE: "line",
+  INSTAGRAM: "instagram",
+  FACEBOOK: "facebook",
+  VIBER: "viber",
+  LINKEDIN: "linkedin",
+  TIKTOK: "tiktok",
+  TELEGRAM: "telegram",
+};

   platform: {
     type: "string",
     label: "Platform",
     description: "The type of inbound message to watch for",
-    options: [
-      "sms",
-      "whatsapp",
-      "email",
-      "line",
-      "instagram",
-      "facebook",
-      "viber",
-      "linkedin",
-      "tiktok",
-      "telegram",
-    ],
+    options: Object.values(PLATFORM_OPTIONS),
+    validate: (value) => Object.values(PLATFORM_OPTIONS).includes(value),
   },
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 80c5b73 and 9765ed1.

📒 Files selected for processing (2)
  • components/messagebird/package.json (1 hunks)
  • components/messagebird/sources/new-message-received/new-message-received.mjs (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • components/messagebird/package.json
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Verify TypeScript components
  • GitHub Check: Publish TypeScript components
  • GitHub Check: Lint Code Base
🔇 Additional comments (1)
components/messagebird/sources/new-message-received/new-message-received.mjs (1)

7-7: Update documentation URL

The documentation URL appears to be incorrect. It points to docs.bird.com instead of the official MessageBird documentation.

jcortes
jcortes previously approved these changes Jan 9, 2025
Copy link
Collaborator

@jcortes jcortes left a comment

Choose a reason for hiding this comment

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

Hi @michelle0927 lgtm! Ready for QA!

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: 8

♻️ Duplicate comments (3)
components/message_bird/message_bird.app.mjs (2)

24-26: ⚠️ Potential issue

Fix API base URL

The base URL is incorrect. According to MessageBird's documentation, it should be "https://conversations.messagebird.com/v1".

    _baseUrl() {
-     return "https://rest.messagebird.com";
+     return "https://conversations.messagebird.com/v1";
    },

27-39: 🛠️ Refactor suggestion

Enhance request error handling

The _makeRequest method should include proper error handling and request timeout.

    _makeRequest({
      $ = this,
      path,
+     timeout = 10000,
      ...opts
    }) {
+     const headers = {
+       "Authorization": `AccessKey ${this.$auth.access_key}`,
+       "Content-Type": "application/json",
+     };
+
+     try {
        return axios($, {
          url: `${this._baseUrl()}${path}`,
-         headers: {
-           "Authorization": `AccessKey ${this.$auth.access_key}`,
-         },
+         headers,
+         timeout,
          ...opts,
        });
+     } catch (error) {
+       const status = error.response?.status;
+       const message = error.response?.data?.errors?.[0]?.description || error.message;
+       throw new Error(`MessageBird API request failed: ${status} - ${message}`);
+     }
    },
components/messagebird/messagebird.app.mjs (1)

136-138: ⚠️ Potential issue

Fix API base URL

The base URL is incorrect. According to MessageBird's documentation, it should be "https://conversations.messagebird.com/v1".

    _baseUrl() {
-     return "https://api.bird.com";
+     return "https://conversations.messagebird.com/v1";
    },
🧹 Nitpick comments (5)
components/message_bird/actions/send-sms/send-sms.mjs (1)

30-41: Add input validation for required fields

Consider validating the required fields before making the API call to provide better error messages.

   async run({ $ }) {
+    if (!this.originator) {
+      throw new Error("Originator is required");
+    }
+    if (!this.body) {
+      throw new Error("Message body is required");
+    }
+    if (!this.recipients) {
+      throw new Error("Recipients are required");
+    }
     const response = await this.messagebird.sendSMS({
components/message_bird/actions/create-contact/create-contact.mjs (1)

29-37: Handle empty optional fields

Remove optional fields from the request if they are empty to avoid sending unnecessary null values.

   async run({ $ }) {
+    const data = {
+      msisdn: this.phone,
+      ...(this.firstName && { firstName: this.firstName }),
+      ...(this.lastName && { lastName: this.lastName }),
+    };
     const response = await this.messagebird.createContact({
       $,
-      data: {
-        msisdn: this.phone,
-        firstName: this.firstName,
-        lastName: this.lastName,
-      },
+      data,
     });
components/message_bird/sources/new-sms-message-received/new-sms-message-received.mjs (1)

16-18: Consider configurable polling interval

Allow users to configure the polling interval based on their needs while maintaining reasonable limits.

       type: "$.interface.timer",
-      default: {
-        intervalSeconds: DEFAULT_POLLING_SOURCE_TIMER_INTERVAL,
-      },
+      label: "Polling Interval",
+      description: "How often to poll for new messages (in seconds)",
+      default: {
+        intervalSeconds: DEFAULT_POLLING_SOURCE_TIMER_INTERVAL,
+      },
+      min: 60, // Minimum 1 minute
+      max: 900, // Maximum 15 minutes
components/message_bird/message_bird.app.mjs (1)

40-65: Add pagination support to list methods

The list methods should support pagination to handle large datasets efficiently.

    listSMSMessages(opts = {}) {
+     const { page = 1, perPage = 10, ...otherOpts } = opts;
      return this._makeRequest({
        path: "/messages",
+       params: {
+         page,
+         per_page: perPage,
+         ...otherOpts.params,
+       },
-       ...opts,
+       ...otherOpts,
      });
    },
components/messagebird/messagebird.app.mjs (1)

211-228: Add rate limiting support for message sending

The message sending methods should implement rate limiting to prevent API throttling.

+   async _getRateLimit() {
+     const response = await this._makeRequest({
+       path: "/rate-limit",
+     });
+     return response.remaining;
+   },
    async sendVoiceMessage({
      workspaceId, channelId, ...opts
    }) {
+     const remaining = await this._getRateLimit();
+     if (remaining <= 0) {
+       throw new Error("Rate limit exceeded. Please try again later.");
+     }
      return this._makeRequest({
        method: "POST",
        path: `/workspaces/${workspaceId}/channels/${channelId}/calls`,
        ...opts,
      });
    },
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 9765ed1 and 8424040.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (7)
  • components/message_bird/actions/create-contact/create-contact.mjs (1 hunks)
  • components/message_bird/actions/send-sms/send-sms.mjs (1 hunks)
  • components/message_bird/actions/send-voice-message/send-voice-message.mjs (1 hunks)
  • components/message_bird/message_bird.app.mjs (1 hunks)
  • components/message_bird/package.json (1 hunks)
  • components/message_bird/sources/new-sms-message-received/new-sms-message-received.mjs (1 hunks)
  • components/messagebird/messagebird.app.mjs (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • components/message_bird/package.json
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: Verify TypeScript components
  • GitHub Check: pnpm publish
  • GitHub Check: Publish TypeScript components
  • GitHub Check: Lint Code Base

GTFalcao
GTFalcao previously approved these changes Jan 14, 2025
Copy link
Collaborator

@GTFalcao GTFalcao left a comment

Choose a reason for hiding this comment

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

LGTM!

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: 1

♻️ Duplicate comments (6)
components/messagebird/messagebird.app.mjs (4)

11-34: 🛠️ Refactor suggestion

Add error handling and input validation in async options.

The async options functions need proper error handling and input validation to prevent UI failures.

Additionally, consider adding debouncing to prevent race conditions when dependencies change rapidly.

 async options({ prevContext }) {
+  try {
     const { next: pageToken } = prevContext;
+    if (typeof pageToken === 'string' && pageToken.length > 1000) {
+      throw new Error('Invalid page token');
+    }
     const {
       results, nextPageToken,
     } = await this.listWorkspaces({
       organizationId: this._organizationId(),
       params: pageToken
         ? {
           pageToken,
         }
         : {},
     });
     return {
       options: results?.map(({
         id: value, name: label,
       }) => ({
         value,
         label,
       })) || [],
       context: {
         next: nextPageToken,
       },
     };
+  } catch (error) {
+    console.error('Failed to fetch options:', error);
+    return {
+      options: [],
+      context: { next: null },
+    };
+  }
 },

Also applies to: 40-68, 74-102, 109-122


126-128: ⚠️ Potential issue

Fix API base URL.

The base URL is incorrect. It should point to the official MessageBird API endpoint.

 _baseUrl() {
-  return "https://api.bird.com";
+  return "https://conversations.messagebird.com/v1";
 },

132-144: 🛠️ Refactor suggestion

Enhance request error handling and add request timeout.

The _makeRequest method should include proper error handling and request timeout.

 _makeRequest({
   $ = this,
   path,
+  timeout = 10000,
   ...otherOpts
 }) {
+  const headers = {
+    "Authorization": `AccessKey ${this.$auth.api_key}`,
+    "Content-Type": "application/json",
+  };
+
+  try {
     return axios($, {
       url: `${this._baseUrl()}${path}`,
-      headers: {
-        "Authorization": `AccessKey ${this.$auth.api_key}`,
-      },
+      headers,
+      timeout,
       ...otherOpts,
     });
+  } catch (error) {
+    const status = error.response?.status;
+    const message = error.response?.data?.errors?.[0]?.description || error.message;
+    throw new Error(`MessageBird API request failed: ${status} - ${message}`);
+  }
 },

145-153: 🛠️ Refactor suggestion

Add webhook event type validation.

The webhook creation method should validate event types against supported values.

+const VALID_WEBHOOK_EVENTS = [
+  "message.created",
+  "message.updated",
+  "conversation.created",
+  "conversation.updated",
+];
+
 createWebhook({
   workspaceId, ...opts
 }) {
+  const { events } = opts.data || {};
+  if (events?.some((event) => !VALID_WEBHOOK_EVENTS.includes(event))) {
+    throw new Error(`Invalid webhook event. Supported events: ${VALID_WEBHOOK_EVENTS.join(", ")}`);
+  }
   return this._makeRequest({
     method: "POST",
     path: `/organizations/${this._organizationId()}/workspaces/${workspaceId}/webhook-subscriptions`,
     ...opts,
   });
 },
components/messagebird/sources/new-message-received/new-message-received.mjs (2)

40-50: ⚠️ Potential issue

Implement webhook security measures

The webhook implementation lacks security controls.

     async activate() {
+      // Validate webhook URL
+      if (!this.http.endpoint || !this.http.endpoint.startsWith('https://')) {
+        throw new Error('Invalid webhook URL. HTTPS is required.');
+      }
+
+      try {
+        // Generate and store webhook secret
+        const webhookSecret = crypto.randomBytes(32).toString('hex');
+        this.db.set('webhookSecret', webhookSecret);
+
         const { id } = await this.messagebird.createWebhook({
           workspaceId: this.workspaceId,
           data: {
             service: "channels",
             event: `${this.platform}.inbound`,
             url: this.http.endpoint,
+            headers: {
+              'X-Webhook-Secret': webhookSecret,
+            },
           },
         });
         this._setHookId(id);
+      } catch (error) {
+        console.error('Failed to create webhook:', error);
+        throw error;
+      }
     },

62-74: ⚠️ Potential issue

Add robust error handling for database and metadata operations

The methods lack error handling for database operations and event structure validation.

     _getHookId() {
+      try {
         return this.db.get("hookId");
+      } catch (error) {
+        console.error("Failed to retrieve hook ID:", error);
+        throw error;
+      }
     },
     _setHookId(hookId) {
+      if (!hookId) {
+        throw new Error("Hook ID is required");
+      }
+      try {
         this.db.set("hookId", hookId);
+      } catch (error) {
+        console.error("Failed to store hook ID:", error);
+        throw error;
+      }
     },
     generateMeta(event) {
+      if (!event?.payload?.id || !event?.createdAt) {
+        throw new Error("Invalid event structure");
+      }
       return {
         id: event.payload.id,
         summary: `New Message ID: ${event.payload.id}`,
         ts: Date.parse(event.createdAt),
       };
     },
🧹 Nitpick comments (2)
components/messagebird/messagebird.app.mjs (1)

202-219: Add rate limiting for message sending endpoints.

The message sending methods should implement rate limiting to prevent API quota exhaustion.

+const MESSAGE_RATE_LIMIT = {
+  maxRequests: 60,
+  perSeconds: 60,
+};
+
+let messageCounter = 0;
+let lastResetTime = Date.now();
+
 sendVoiceMessage({
   workspaceId, channelId, ...opts
 }) {
+  const now = Date.now();
+  if (now - lastResetTime > MESSAGE_RATE_LIMIT.perSeconds * 1000) {
+    messageCounter = 0;
+    lastResetTime = now;
+  }
+  if (messageCounter >= MESSAGE_RATE_LIMIT.maxRequests) {
+    throw new Error(`Rate limit exceeded. Maximum ${MESSAGE_RATE_LIMIT.maxRequests} messages per ${MESSAGE_RATE_LIMIT.perSeconds} seconds.`);
+  }
+  messageCounter++;
   return this._makeRequest({
     method: "POST",
     path: `/workspaces/${workspaceId}/channels/${channelId}/calls`,
     ...opts,
   });
 },

Apply similar rate limiting to sendSmsMessage method.

components/messagebird/sources/new-message-received/new-message-received.mjs (1)

21-37: Add platform validation and default value

The platform prop should include validation and a default value for better user experience.

     platform: {
       type: "string",
       label: "Platform",
       description: "The type of inbound message to watch for",
+      default: "sms",
+      reloadProps: true,
       options: [
         "sms",
         "whatsapp",
         "email",
         "line",
         "instagram",
         "facebook",
         "viber",
         "linkedin",
         "tiktok",
         "telegram",
       ],
+      validate: (value) => {
+        const validPlatforms = ["sms", "whatsapp", "email", "line", "instagram", "facebook", "viber", "linkedin", "tiktok", "telegram"];
+        if (!validPlatforms.includes(value)) {
+          throw new Error("Invalid platform selected");
+        }
+      },
     },
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 800df0a and 9b44fb4.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (5)
  • components/messagebird/actions/create-contact/create-contact.mjs (1 hunks)
  • components/messagebird/actions/send-sms/send-sms.mjs (1 hunks)
  • components/messagebird/actions/send-voice-message/send-voice-message.mjs (1 hunks)
  • components/messagebird/messagebird.app.mjs (1 hunks)
  • components/messagebird/sources/new-message-received/new-message-received.mjs (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • components/messagebird/actions/send-sms/send-sms.mjs
  • components/messagebird/actions/send-voice-message/send-voice-message.mjs
  • components/messagebird/actions/create-contact/create-contact.mjs
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Verify TypeScript components
  • GitHub Check: pnpm publish
  • GitHub Check: Publish TypeScript components
🔇 Additional comments (3)
components/messagebird/messagebird.app.mjs (1)

1-5: LGTM! App configuration follows Pipedream's standard format.

components/messagebird/sources/new-message-received/new-message-received.mjs (2)

7-7: Update documentation URL

The documentation URL is incorrect. It should point to the official MessageBird documentation.

-  description: "Emit new event for each new message received. [See the documentation](https://docs.bird.com/api/notifications-api/api-reference/webhook-subscriptions/create-a-webhook-subscription)",
+  description: "Emit new event for each new message received. [See the documentation](https://developers.messagebird.com/api/conversations/#webhooks)",

84-84: Improve test coverage

The component lacks comprehensive test coverage.

Add test cases for:

  1. Different platform types
  2. Error scenarios
  3. Webhook lifecycle
  4. Event validation

Run this script to verify current test coverage:

#!/bin/bash
# Search for test files and their content
fd "test" components/messagebird/sources/new-message-received/ -t f -x cat {}

@michelle0927
Copy link
Collaborator Author

/approve

@michelle0927
Copy link
Collaborator Author

/approve

@michelle0927 michelle0927 merged commit 6e6631e into master Jan 17, 2025
11 checks passed
@michelle0927 michelle0927 deleted the issue-15227 branch January 17, 2025 19:02
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.

[Components] messagebird
3 participants