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 - typefully #15217

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

New Components - typefully #15217

wants to merge 3 commits into from

Conversation

luancazarine
Copy link
Collaborator

@luancazarine luancazarine commented Jan 7, 2025

Resolves #15184.

Summary by CodeRabbit

Release Notes for Typefully Integration

  • New Features

    • Added support for creating drafts in Typefully
    • Introduced functionality to schedule drafts (immediately and in next available slot)
    • Added event sources for tracking new draft publications and scheduling
  • Improvements

    • Enhanced API interaction methods for draft management
    • Added more configuration options for draft creation and scheduling
  • Version Update

    • Upgraded package version from 0.0.1 to 0.1.0
    • Added dependency on @pipedream/platform

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

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

Copy link
Contributor

coderabbitai bot commented Jan 7, 2025

Walkthrough

This pull request introduces comprehensive support for the Typefully application in Pipedream, adding multiple components for draft management. The changes include new sources for tracking draft publications and scheduling, as well as actions for creating and scheduling drafts. The implementation provides a robust integration with the Typefully API, enabling users to interact with drafts through various methods like creating, scheduling, and monitoring draft statuses.

Changes

File Change Summary
components/typefully/actions/create-draft/create-draft.mjs New module for creating drafts with configurable properties
components/typefully/actions/schedule-draft-next-slot/schedule-draft-next-slot.mjs New module for scheduling drafts in the next available time slot
components/typefully/actions/schedule-draft/schedule-draft.mjs New module for scheduling drafts at a specific date and time
components/typefully/package.json Updated version to 0.1.0 and added @pipedream/platform dependency
components/typefully/sources/... Added new sources for tracking draft publications and scheduling
components/typefully/typefully.app.mjs Enhanced with new prop definitions and API interaction methods

Assessment against linked issues

Objective Addressed Explanation
Create Draft Action [#15184]
Schedule Draft Next Slot Action [#15184]
Schedule Draft Action [#15184]
New Draft Published Source [#15184]
New Draft Scheduled Source [#15184]

Possibly related PRs

Suggested labels

action, trigger / source

Suggested reviewers

  • jcortes

Poem

🐰 Drafts hopping through Typefully's gate,
Scheduling tweets at a rabbit's rate!
Create, publish, and share with glee,
A social media symphony!
Pipedream's magic makes it all so neat! 🐾


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.

Sources
 - New Draft Published
 - New Draft Scheduled

Actions
 - Create Draft
 - Schedule Draft Next Slot
 - Schedule Draft
@luancazarine luancazarine marked this pull request as ready for review January 8, 2025 17:38
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 (6)
components/typefully/sources/common/base.mjs (1)

44-44: Simplify timestamp assignment using Date.now()

The use of Date.parse(new Date()) can be simplified for better readability and efficiency.

Apply this diff to streamline the timestamp assignment:

-              ts: Date.parse(new Date()),
+              ts: Date.now(),
components/typefully/typefully.app.mjs (2)

90-96: Add input validation for createDraft method

The method should validate the required fields in the request data before making the API call.

 createDraft(opts = {}) {
+  const { data } = opts;
+  if (!data?.content) {
+    throw new Error("Draft content is required");
+  }
   return this._makeRequest({
     method: "POST",
     path: "/drafts/",
     ...opts,
   });
 }

66-70: Add date format validation for scheduleDate prop

The scheduleDate prop should include a pattern to validate the ISO format.

 scheduleDate: {
   type: "string",
   label: "Schedule Date",
   description: "Date to schedule the draft (ISO format - YYYY-MM-DDTHH:MM:SSZ)",
+  pattern: "^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z$",
+  examples: ["2025-01-15T14:30:00Z"],
 },
components/typefully/actions/schedule-draft/schedule-draft.mjs (1)

3-68: Consider extracting common code to a shared utility

There's significant code duplication between create-draft.mjs and schedule-draft.mjs. Consider creating a shared utility for common functionality.

Create a new file components/typefully/common/draft-utils.mjs:

export const transformDraftData = (data) => {
  return {
    content: data.content,
    threadify: data.threadify,
    share: data.share,
    auto_retweet_enabled: data.autoRetweetEnabled,
    auto_plug_enabled: data.autoPlugEnabled,
    ...(data.scheduleDate && { schedule_date: data.scheduleDate }),
  };
};

export const validateScheduleDate = (date) => {
  const dateRegex = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/;
  if (!dateRegex.test(date)) {
    throw new Error("Invalid schedule date format. Expected: YYYY-MM-DDTHH:MM:SSZ");
  }
};
components/typefully/actions/schedule-draft-next-slot/schedule-draft-next-slot.mjs (2)

46-57: Extract "next-free-slot" to a constant and improve error handling

The hardcoded value should be defined as a constant, and error handling should be improved.

+const NEXT_FREE_SLOT = "next-free-slot";
+
 async run({ $ }) {
+  const transformedData = {
+    content: this.content,
+    threadify: this.threadify,
+    share: this.share,
+    schedule_date: NEXT_FREE_SLOT,
+    auto_retweet_enabled: this.autoRetweetEnabled,
+    auto_plug_enabled: this.autoPlugEnabled,
+  };
+
   const response = await this.typefully.createDraft({
     $,
-    data: {
-      "content": this.content,
-      "threadify": this.threadify,
-      "share": this.share,
-      "schedule-date": "next-free-slot",
-      "auto_retweet_enabled": this.autoRetweetEnabled,
-      "auto_plug_enabled": this.autoPlugEnabled,
-    },
+    data: transformedData,
   });
+
+  if (!response?.id) {
+    throw new Error("Failed to schedule draft: Invalid response from API");
+  }

3-62: Add rate limiting considerations

Since this component uses the "next-free-slot" feature, it's important to consider rate limiting to prevent overwhelming the scheduling system.

Consider implementing a delay between consecutive calls to this endpoint. You can add this to the app's _makeRequest method or implement it specifically for this action.

Example implementation in typefully.app.mjs:

const RATE_LIMIT_DELAY = 1000; // 1 second

async _makeRequest({ $ = this, path, ...opts }) {
  if (path.includes('/drafts/') && opts.method === 'POST') {
    await new Promise(resolve => setTimeout(resolve, RATE_LIMIT_DELAY));
  }
  // ... rest of the implementation
}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between fed27d2 and 7913361.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (10)
  • components/typefully/actions/create-draft/create-draft.mjs (1 hunks)
  • components/typefully/actions/schedule-draft-next-slot/schedule-draft-next-slot.mjs (1 hunks)
  • components/typefully/actions/schedule-draft/schedule-draft.mjs (1 hunks)
  • components/typefully/package.json (2 hunks)
  • components/typefully/sources/common/base.mjs (1 hunks)
  • components/typefully/sources/new-draft-published/new-draft-published.mjs (1 hunks)
  • components/typefully/sources/new-draft-published/test-event.mjs (1 hunks)
  • components/typefully/sources/new-draft-scheduled/new-draft-scheduled.mjs (1 hunks)
  • components/typefully/sources/new-draft-scheduled/test-event.mjs (1 hunks)
  • components/typefully/typefully.app.mjs (1 hunks)
✅ Files skipped from review due to trivial changes (2)
  • components/typefully/sources/new-draft-scheduled/test-event.mjs
  • components/typefully/sources/new-draft-published/test-event.mjs
🔇 Additional comments (4)
components/typefully/sources/new-draft-scheduled/new-draft-scheduled.mjs (1)

14-20: Methods are correctly implemented

The getFunction and getSummary methods are properly defined and extend the base module as expected.

components/typefully/sources/new-draft-published/new-draft-published.mjs (1)

14-20: Methods are correctly implemented

The getFunction and getSummary methods are properly defined and extend the base module as expected.

components/typefully/package.json (2)

3-3: LGTM! Version bump follows semantic versioning.

The minor version increment from 0.0.1 to 0.1.0 correctly reflects the addition of new features (Typefully components) while maintaining backward compatibility.


15-17: Verify the @pipedream/platform version.

Let's ensure we're using the latest stable version of the platform package.

✅ Verification successful

The package is already using the latest version (3.0.3)

The current version specification ^3.0.3 in package.json is correct and up-to-date.

🏁 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 or deprecation notices in recent versions
npm view @pipedream/platform@">3.0.3" version --json

Length of output: 754

Comment on lines +73 to +89
_baseUrl() {
return "https://api.typefully.com/v1";
},
_headers() {
return {
"x-api-key": `${this.$auth.api_key}`,
};
},
_makeRequest({
$ = this, path, ...opts
}) {
return axios($, {
url: this._baseUrl() + path,
headers: this._headers(),
...opts,
});
},
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add error handling to _makeRequest method

The base request method should include error handling to provide meaningful error messages when API calls fail.

 _makeRequest({
   $ = this, path, ...opts
 }) {
+  const baseURL = this._baseUrl();
+  const headers = this._headers();
   return axios($, {
-    url: this._baseUrl() + path,
-    headers: this._headers(),
+    url: `${baseURL}${path}`,
+    headers,
     ...opts,
+  }).catch((error) => {
+    const statusCode = error.response?.status;
+    const message = error.response?.data?.message || error.message;
+    throw new Error(`Typefully API request failed: ${statusCode} - ${message}`);
   });
 }
📝 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
_baseUrl() {
return "https://api.typefully.com/v1";
},
_headers() {
return {
"x-api-key": `${this.$auth.api_key}`,
};
},
_makeRequest({
$ = this, path, ...opts
}) {
return axios($, {
url: this._baseUrl() + path,
headers: this._headers(),
...opts,
});
},
_baseUrl() {
return "https://api.typefully.com/v1";
},
_headers() {
return {
"x-api-key": `${this.$auth.api_key}`,
};
},
_makeRequest({
$ = this, path, ...opts
}) {
const baseURL = this._baseUrl();
const headers = this._headers();
return axios($, {
url: `${baseURL}${path}`,
headers,
...opts,
}).catch((error) => {
const statusCode = error.response?.status;
const message = error.response?.data?.message || error.message;
throw new Error(`Typefully API request failed: ${statusCode} - ${message}`);
});
},

Comment on lines +46 to +60
async run({ $ }) {
const response = await this.typefully.createDraft({
$,
data: {
content: this.content,
threadify: this.threadify,
share: this.share,
auto_retweet_enabled: this.autoRetweetEnabled,
auto_plug_enabled: this.autoPlugEnabled,
},
});

$.export("$summary", `Created draft with ID: ${response.id}.`);
return response;
},
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Improve response handling and add parameter transformation

The run method should:

  1. Transform camelCase parameters to snake_case for API consistency
  2. Add proper error handling for the API response
 async run({ $ }) {
+  // Transform parameters to snake_case format
+  const transformedData = {
+    content: this.content,
+    threadify: this.threadify,
+    share: this.share,
+    auto_retweet_enabled: this.autoRetweetEnabled,
+    auto_plug_enabled: this.autoPlugEnabled,
+  };
+
   const response = await this.typefully.createDraft({
     $,
-    data: {
-      content: this.content,
-      threadify: this.threadify,
-      share: this.share,
-      auto_retweet_enabled: this.autoRetweetEnabled,
-      auto_plug_enabled: this.autoPlugEnabled,
-    },
+    data: transformedData,
   });
+
+  if (!response?.id) {
+    throw new Error("Failed to create draft: Invalid response from API");
+  }
📝 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 run({ $ }) {
const response = await this.typefully.createDraft({
$,
data: {
content: this.content,
threadify: this.threadify,
share: this.share,
auto_retweet_enabled: this.autoRetweetEnabled,
auto_plug_enabled: this.autoPlugEnabled,
},
});
$.export("$summary", `Created draft with ID: ${response.id}.`);
return response;
},
async run({ $ }) {
// Transform parameters to snake_case format
const transformedData = {
content: this.content,
threadify: this.threadify,
share: this.share,
auto_retweet_enabled: this.autoRetweetEnabled,
auto_plug_enabled: this.autoPlugEnabled,
};
const response = await this.typefully.createDraft({
$,
data: transformedData,
});
if (!response?.id) {
throw new Error("Failed to create draft: Invalid response from API");
}
$.export("$summary", `Created draft with ID: ${response.id}.`);
return response;
}

Comment on lines +52 to +63
async run({ $ }) {
const response = await this.typefully.createDraft({
$,
data: {
"content": this.content,
"threadify": this.threadify,
"share": this.share,
"schedule-date": this.scheduleDate,
"auto_retweet_enabled": this.autoRetweetEnabled,
"auto_plug_enabled": this.autoPlugEnabled,
},
});
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix parameter naming inconsistency and add date validation

Issues found:

  1. Inconsistent parameter naming (schedule-date vs snake_case)
  2. Missing date validation before API call
 async run({ $ }) {
+  // Validate schedule date format
+  const dateRegex = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/;
+  if (!dateRegex.test(this.scheduleDate)) {
+    throw new Error("Invalid schedule date format. Expected: YYYY-MM-DDTHH:MM:SSZ");
+  }
+
+  const transformedData = {
+    content: this.content,
+    threadify: this.threadify,
+    share: this.share,
+    schedule_date: this.scheduleDate,
+    auto_retweet_enabled: this.autoRetweetEnabled,
+    auto_plug_enabled: this.autoPlugEnabled,
+  };
+
   const response = await this.typefully.createDraft({
     $,
-    data: {
-      "content": this.content,
-      "threadify": this.threadify,
-      "share": this.share,
-      "schedule-date": this.scheduleDate,
-      "auto_retweet_enabled": this.autoRetweetEnabled,
-      "auto_plug_enabled": this.autoPlugEnabled,
-    },
+    data: transformedData,
   });
📝 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 run({ $ }) {
const response = await this.typefully.createDraft({
$,
data: {
"content": this.content,
"threadify": this.threadify,
"share": this.share,
"schedule-date": this.scheduleDate,
"auto_retweet_enabled": this.autoRetweetEnabled,
"auto_plug_enabled": this.autoPlugEnabled,
},
});
async run({ $ }) {
// Validate schedule date format
const dateRegex = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/;
if (!dateRegex.test(this.scheduleDate)) {
throw new Error("Invalid schedule date format. Expected: YYYY-MM-DDTHH:MM:SSZ");
}
const transformedData = {
content: this.content,
threadify: this.threadify,
share: this.share,
schedule_date: this.scheduleDate,
auto_retweet_enabled: this.autoRetweetEnabled,
auto_plug_enabled: this.autoPlugEnabled,
};
const response = await this.typefully.createDraft({
$,
data: transformedData,
});

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] typefully
1 participant