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

Removed lodash from data-manipulation and sanitize model plugins #22084

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

daniellockyer
Copy link
Member

  • only some small micro-optimizations but we can remove lodash from a sanitize plugin method (needs an empty object fallback because Object.keys is less forgiving than _.keys and there are some tests which don't fully initialize the model)
  • also converts the data-manipulation plugins into for-loops because there are more native than using lodash, and it means we can remove lodash from this file too
  • lodash is a bit of a perf burn on extreme hotpaths, so it's good to clean it up where it's not needed
  • adds a bit of JSDoc to help with editor autocomplete

Copy link

coderabbitai bot commented Jan 30, 2025

Walkthrough

The pull request introduces modifications to two JavaScript files in the Ghost CMS core: data-manipulation.js and sanitize.js. The changes primarily focus on improving code robustness and readability by refactoring iteration methods, enhancing error handling, and updating documentation. The modifications involve simplifying attribute processing logic, adding optional chaining, and implementing safer method implementations for handling dates, boolean conversions, and attribute retrieval.

Changes

File Change Summary
ghost/core/core/server/models/base/plugins/data-manipulation.js - Refactored iteration methods from _.each and Object.keys().forEach to for...in loops
- Enhanced documentation with parameter and return type annotations
- Simplified conditional checks using optional chaining
- Streamlined date formatting and boolean conversion logic
ghost/core/core/server/models/base/plugins/sanitize.js - Updated permittedAttributes method to handle potential undefined schema table references
- Added fallback to empty object when retrieving table keys

Sequence Diagram

sequenceDiagram
    participant Model as Bookshelf.Model
    participant DataManipulation as Data Manipulation Plugin
    participant Attrs as Attributes

    Model->>DataManipulation: fixDatesWhenSave(attrs)
    DataManipulation->>Attrs: Iterate through attributes
    DataManipulation->>Attrs: Apply date formatting
    DataManipulation-->>Model: Return processed attributes

    Model->>DataManipulation: fixDatesWhenFetch(attrs)
    DataManipulation->>Attrs: Iterate through attributes
    DataManipulation->>Attrs: Apply date parsing
    DataManipulation-->>Model: Return processed attributes

    Model->>DataManipulation: fixBools(attrs)
    DataManipulation->>Attrs: Iterate through attributes
    DataManipulation->>Attrs: Convert integers to booleans
    DataManipulation-->>Model: Return processed attributes
Loading
✨ 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.

- only some small micro-optimizations but we can remove lodash from a
  sanitize plugin method (needs an empty object fallback because Object.keys is
  less forgiving than _.keys and there are some tests which don't fully
  initialize the model)
- also converts the data-manipulation plugins into for-loops because
  there are more native than using lodash, and it means we can remove
  lodash from this file too
- lodash is a bit of a perf burn on extreme hotpaths, so it's good to
  clean it up where it's not needed
- adds a bit of JSDoc to help with editor autocomplete
@daniellockyer daniellockyer marked this pull request as ready for review January 30, 2025 16:19
@daniellockyer
Copy link
Member Author

@coderabbitai review

Copy link

coderabbitai bot commented Jan 30, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

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

🔭 Outside diff range comments (1)
ghost/core/core/server/models/base/plugins/sanitize.js (1)

Line range hint 83-136: Consider removing remaining lodash dependencies.

The sanitizeData method still relies heavily on lodash. Consider refactoring to use native alternatives:

 sanitizeData: function sanitizeData(data) {
-    const tableName = _.result(this.prototype, 'tableName');
+    const tableName = this.prototype.tableName;
     let date;
 
-    _.each(data, (value, property) => {
+    for (const [property, value] of Object.entries(data)) {
         if (value !== null
         && Object.prototype.hasOwnProperty.call(schema.tables[tableName], property)
         && schema.tables[tableName][property].type === 'dateTime'
         && typeof value === 'string'
         ) {
             date = new Date(value);
 
             // CASE: client sends `0000-00-00 00:00:00`
             if (isNaN(date)) {
                 throw new errors.ValidationError({
                     message: tpl(messages.invalidDate, {key: property}),
                     code: 'DATE_INVALID'
                 });
             }
 
             data[property] = moment(value).toDate();
         }
 
         if (this.prototype.relationships && this.prototype.relationships.indexOf(property) !== -1) {
             let relations = data[property];
 
             // CASE: 1:1 relation will have single data point
-            if (!_.isArray(data[property])) {
+            if (!Array.isArray(data[property])) {
                 relations = [data[property]];
             }
-            _.each(relations, (relation, indexInArr) => {
-                _.each(relation, (relationValue, relationProperty) => {
+            relations.forEach((relation, indexInArr) => {
+                for (const [relationProperty, relationValue] of Object.entries(relation)) {
                     if (relationValue !== null
                     && Object.prototype.hasOwnProperty.call(schema.tables[this.prototype.relationshipBelongsTo[property]], relationProperty)
                     && schema.tables[this.prototype.relationshipBelongsTo[property]][relationProperty].type === 'dateTime'
                     && typeof relationValue === 'string'
                     ) {
                         date = new Date(relationValue);
 
                         // CASE: client sends `0000-00-00 00:00:00`
                         if (isNaN(date)) {
                             throw new errors.ValidationError({
                                 message: tpl(messages.invalidDate, {key: relationProperty}),
                                 code: 'DATE_INVALID'
                             });
                         }
 
                         data[property][indexInArr][relationProperty] = moment(relationValue).toDate();
                     }
-                });
+                }
             });
         }
-    });
+    }
 
     return data;
 }
🧹 Nitpick comments (3)
ghost/core/core/server/models/base/plugins/data-manipulation.js (3)

32-38: Consider performance optimization for date conversion.

While the lodash removal is good, we can further optimize the implementation:

  1. Cache tableDef?.[key]?.type lookup
  2. Pre-check if the key exists in tableDef to avoid unnecessary property access
 fixDatesWhenSave: function fixDatesWhenSave(attrs) {
     const tableDef = schema.tables[this.tableName];
 
     for (const key in attrs) {
-        if (attrs[key] && tableDef?.[key]?.type === 'dateTime') {
+        const columnDef = tableDef?.[key];
+        if (attrs[key] && columnDef?.type === 'dateTime') {
             attrs[key] = moment(attrs[key]).format('YYYY-MM-DD HH:mm:ss');
         }
     }

Line range hint 57-69: Consider performance optimization for date conversion.

Similar to fixDatesWhenSave, we can optimize the implementation:

 fixDatesWhenFetch: function fixDatesWhenFetch(attrs) {
     const tableDef = schema.tables[this.tableName];
 
     for (const key in attrs) {
-        if (attrs[key] && tableDef?.[key]?.type === 'dateTime') {
+        const columnDef = tableDef?.[key];
+        if (attrs[key] && columnDef?.type === 'dateTime') {
             const dateMoment = moment(attrs[key]);
 
             // CASE: You are somehow able to store e.g. 0000-00-00 00:00:00
             // Protect the code base and return the current date time.
             if (dateMoment.isValid()) {
                 attrs[key] = dateMoment.startOf('seconds').toDate();
             } else {
                 attrs[key] = moment().startOf('seconds').toDate();
             }
         }
     }

83-87: Consider performance optimization for boolean conversion.

Similar to the date methods, we can optimize the implementation:

 fixBools: function fixBools(attrs) {
     const tableDef = schema.tables[this.tableName];
 
     for (const key in attrs) {
-        if (tableDef?.[key]?.type === 'boolean') {
+        const columnDef = tableDef?.[key];
+        if (columnDef?.type === 'boolean') {
             attrs[key] = !!attrs[key];
         }
     }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 6d7c711 and 29ee00f.

📒 Files selected for processing (2)
  • ghost/core/core/server/models/base/plugins/data-manipulation.js (3 hunks)
  • ghost/core/core/server/models/base/plugins/sanitize.js (1 hunks)
🔇 Additional comments (5)
ghost/core/core/server/models/base/plugins/data-manipulation.js (3)

27-29: Great addition of JSDoc type annotations!

The added parameter and return type documentation improves code clarity and IDE support.


50-52: Good JSDoc enhancement!

The added parameter and return type documentation improves code clarity and IDE support.


74-79: Good JSDoc enhancement!

The added parameter and return type documentation improves code clarity and IDE support.

ghost/core/core/server/models/base/plugins/sanitize.js (2)

20-22: Good defensive programming with empty object fallback!

The change from lodash to native Object.keys with a fallback improves robustness against undefined values.


Line range hint 1-1: Remove unused lodash import.

The lodash import is no longer needed for the permittedAttributes method. However, I notice it's still used in the sanitizeData method. Consider refactoring sanitizeData to remove the lodash dependency as well.

Let's verify the lodash usage in this file:

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.

1 participant