Skip to content

Conversation

@pujitm
Copy link
Member

@pujitm pujitm commented Nov 8, 2024

Summary by CodeRabbit

  • New Features

    • Enhanced logging capabilities in the Notifications service.
    • Improved error handling for notification loading and creation processes.
  • Bug Fixes

    • Optimized resource usage for notification watchers.
    • Ensured consistent notification overview statistics during operations.
  • Style

    • Updated code formatting and organization across various files, including consistent use of single quotes and improved import order.
  • Chores

    • Added @ianvs/prettier-plugin-sort-imports as a development dependency in both API and web projects.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Nov 8, 2024

Walkthrough

The pull request introduces updates to Prettier configuration files in both the api and web directories, enhancing code formatting practices. It includes the addition of the @ianvs/prettier-plugin-sort-imports dependency in package.json files for both projects. The NotificationsResolver and NotificationsService classes have undergone reorganization of import statements and improvements in error handling, while the Indicator.vue component has been reformatted for consistency without altering its functionality.

Changes

File Path Change Summary
api/.prettierrc.cjs Updated Prettier configuration with new settings and plugins, including structured import order.
api/package.json Added @ianvs/prettier-plugin-sort-imports as a devDependency.
api/src/unraid-api/graph/resolvers/notifications/notifications.resolver.ts Reorganized import statements; no changes to method functionality.
api/src/unraid-api/graph/resolvers/notifications/notifications.service.ts Added Logger import; improved error handling and resource management in notification methods.
web/.prettierrc.mjs Modified Prettier settings, including tab width and added import sorting plugin.
web/components/Notifications/Indicator.vue Reordered imports and standardized string formatting; no changes to functionality.
web/package.json Added @ianvs/prettier-plugin-sort-imports as a devDependency.

Possibly related PRs

  • chore(web): add prettier config + tailwind class sorting #955: The changes in this PR involve adding a Prettier configuration file, which is directly related to the updates made in the main PR regarding the Prettier configuration in api/.prettierrc.cjs. Both PRs focus on enhancing code formatting practices using Prettier.

Suggested reviewers

  • zackspear
  • elibosley
  • mdatelle

🐰 In the code, we hop and play,
With Prettier's rules to guide our way.
Imports sorted, errors caught,
A cleaner path is what we've sought.
So let’s rejoice, both near and far,
For tidy code is our shining star! 🌟


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

@github-actions
Copy link
Contributor

github-actions bot commented Nov 8, 2024

This plugin has been deployed to Cloudflare R2 and is available for testing.
Download it at this URL: https://preview.dl.unraid.net/unraid-api/pr/959/dynamix.unraid.net.staging.plg

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

🧹 Outside diff range and nitpick comments (4)
api/.prettierrc.cjs (1)

6-10: LGTM! Consider standardizing printWidth.

The basic Prettier settings look good. Note that 105 characters for printWidth is slightly unusual (80 or 100 is more common), but it's not a significant concern if this aligns with your team's preferences.

api/src/unraid-api/graph/resolvers/notifications/notifications.service.ts (3)

Line range hint 71-73: Incorrect usage of NotificationType[type]

In the handleNotificationAdd method, you're using NotificationType[type] where type is already a value of the NotificationType enum. Accessing NotificationType[type] will return undefined, which may lead to incorrect behavior when loading the notification file.

Apply this diff to pass the correct notification type:

-private async handleNotificationAdd(path: string) {
+private async handleNotificationAdd(path: string): Promise<void> {
    // The path looks like /{notification base path}/{type}/{notification id}
    const type = path.includes('/unread/') ? NotificationType.UNREAD : NotificationType.ARCHIVE;
    this.logger.debug(`Adding ${type} Notification: ${path}`);

-   const notification = await this.loadNotificationFile(path, NotificationType[type]);
+   const notification = await this.loadNotificationFile(path, type);
    this.increment(notification.importance, NotificationsService.overview[type.toLowerCase()]);

    this.publishOverview();
    pubsub.publish(PUBSUB_CHANNEL.NOTIFICATION_ADDED, {
        notificationAdded: notification,
    });
}

Line range hint 123-131: Add error handling for writeFile operation

In the createNotification method, if the writeFile operation fails after the legacy notifier script fails, the error will not be caught, potentially causing unhandled exceptions. Consider adding error handling for the writeFile operation to ensure any errors are appropriately managed.

Apply this diff to handle errors from writeFile:

 public async createNotification(data: NotificationData): Promise<Notification> {
     const id: string = await this.makeNotificationId(data.title);
     const fileData = this.makeNotificationFileData(data);

     try {
         const [command, args] = this.getLegacyScriptArgs(fileData);
         await execa(command, args);
     } catch (error) {
         // Manually write the file if the script fails
         this.logger.debug(`[createNotification] legacy notifier failed: ${error}`);
         this.logger.verbose(`[createNotification] Writing: ${JSON.stringify(fileData, null, 4)}`);

         const path = join(this.paths().UNREAD, id);
         const ini = encodeIni(fileData);
-        await writeFile(path, ini);
+        try {
+            await writeFile(path, ini);
+        } catch (writeError) {
+            this.logger.error(`[createNotification] Failed to write notification file: ${writeError}`);
+            throw writeError;
+        }
     }

     return this.notificationFileToGqlNotification({ id, type: NotificationType.UNREAD }, fileData);
 }

Line range hint 155-167: Handle potential errors from emptyDir operations

In the deleteAllNotifications method, errors from emptyDir are not being handled. If either emptyDir call fails, the notification overview will still be reset, leading to inconsistencies between the file system and the application's state. Consider adding error handling to ensure the overview is only reset when the directories have been successfully emptied.

Apply this diff to handle errors appropriately:

 public async deleteAllNotifications(): Promise<NotificationOverview> {
     const { UNREAD, ARCHIVE } = this.paths();
     // Ensures the directories exist before deleting
-    await emptyDir(ARCHIVE);
-    await emptyDir(UNREAD);
+    try {
+        await emptyDir(ARCHIVE);
+        await emptyDir(UNREAD);
+    } catch (error) {
+        this.logger.error(`[deleteAllNotifications] Failed to empty notification directories: ${error}`);
+        throw error;
+    }

     NotificationsService.overview = {
         unread: {
             alert: 0,
             info: 0,
             warning: 0,
             total: 0,
         },
         archive: {
             alert: 0,
             info: 0,
             warning: 0,
             total: 0,
         },
     };
     return this.getOverview();
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 20e43f4 and 23a1679.

⛔ Files ignored due to path filters (2)
  • api/package-lock.json is excluded by !**/package-lock.json
  • web/package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (7)
  • api/.prettierrc.cjs (1 hunks)
  • api/package.json (1 hunks)
  • api/src/unraid-api/graph/resolvers/notifications/notifications.resolver.ts (1 hunks)
  • api/src/unraid-api/graph/resolvers/notifications/notifications.service.ts (1 hunks)
  • web/.prettierrc.mjs (1 hunks)
  • web/components/Notifications/Indicator.vue (4 hunks)
  • web/package.json (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • web/components/Notifications/Indicator.vue
🔇 Additional comments (9)
web/.prettierrc.mjs (2)

6-6: LGTM!

The quote style change aligns with the singleQuote: true configuration.


7-7: Verify the impact of tabWidth change.

Changing tabWidth from 4 to 2 spaces will affect the entire codebase formatting. While 2 spaces is a common practice in JS/TS projects, this change should be discussed with the team to ensure alignment with coding standards.

api/.prettierrc.cjs (2)

1-4: Well-documented configuration!

The JSDoc comment with documentation link and TypeScript type annotation improves maintainability and provides better IDE support.


11-37: Excellent import organization structure!

The import organization configuration is well-thought-out with several good practices:

  • Clear separation between framework, third-party, and application code
  • Proper handling of type imports
  • Support for decorators which is essential for NestJS
  • Good use of empty lines as visual separators

Let's verify if the import plugin is properly added to package.json:

✅ Verification successful

Import organization setup is properly configured and integrated

The verification confirms that @ianvs/prettier-plugin-sort-imports is correctly added as a dev dependency in version ^4.4.0, which aligns with the configuration in .prettierrc.cjs. The import organization setup is complete and ready to use.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the import plugin is added as a dev dependency

# Test: Check if the plugin is in package.json
jq -r '.devDependencies["@ianvs/prettier-plugin-sort-imports"]' api/package.json

Length of output: 89

web/package.json (1)

32-32: LGTM! The import organizer dependency is correctly added.

The @ianvs/prettier-plugin-sort-imports package is appropriately added to devDependencies and follows proper version constraints.

api/src/unraid-api/graph/resolvers/notifications/notifications.resolver.ts (2)

1-17: LGTM! Import organization follows a clear and logical pattern.

The imports are well-organized following a hierarchical structure:

  1. External dependencies
  2. Internal types and utilities
  3. Local module imports

This organization improves code readability and maintainability.


Line range hint 19-156: Implementation remains unchanged and looks good.

The resolver implementation maintains its existing functionality with proper error handling and access control.

api/package.json (1)

134-134: LGTM! Verify prettier config setup.

The addition of @ianvs/prettier-plugin-sort-imports as a dev dependency is appropriate and well-structured.

Let's verify the corresponding prettier configuration:

✅ Verification successful

Prettier import sorting plugin is correctly configured

The plugin is properly set up in api/.prettierrc.cjs:

  • Added to the plugins array
  • Import order configuration is comprehensive and well-structured
  • Parser plugins include necessary options for TypeScript and decorators
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify prettier configuration exists and includes the import plugin

# Test: Check if .prettierrc.* exists and contains the plugin configuration
echo "Checking for prettier config file..."
fd -t f "^\.prettierrc\." api/

# Test: Verify plugin configuration in the prettier config
echo -e "\nChecking plugin configuration..."
rg -l "@ianvs/prettier-plugin-sort-imports" api/.prettierrc.*

Length of output: 488


Script:

#!/bin/bash
# Description: Check the content of the prettier config file to verify plugin setup

# Show the content of the prettier config file
echo "Content of api/.prettierrc.cjs:"
cat api/.prettierrc.cjs

Length of output: 1360

api/src/unraid-api/graph/resolvers/notifications/notifications.service.ts (1)

Line range hint 235-238: Possible null return value handling

In the parseNotificationDateToIsoDate method, when the input unixStringSeconds is invalid or undefined, the method returns null. Ensure that any code consuming this method can handle null values to prevent potential TypeError exceptions when using the timestamp.

Run the following script to find usages of parseNotificationDateToIsoDate and check for null handling:

✅ Verification successful

Let me gather more information about the schema and validation to understand how null values are handled.


Let me check one more thing to see how the notification schema validation is implemented.


Based on the gathered information, I can now provide the final response:

Null handling for timestamp is properly implemented

The parseNotificationDateToIsoDate method's null return value is safely handled through:

  • Schema validation using Zod where formattedTimestamp is defined as z.string().nullish()
  • Validation of notifications through NotificationSchema().parse() before usage
  • The GraphQL resolver wraps the timestamp in formatTimestamp() before exposing it
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify all usages of parseNotificationDateToIsoDate handle null returns.

# Search for all usages of the method
rg 'parseNotificationDateToIsoDate\(' -A 3

# Search for places where the timestamp is used without null checks
rg 'notification\.timestamp' -A 3

Length of output: 2312


Script:

#!/bin/bash
# Check the notification schema definition and validation
ast-grep --pattern 'NotificationSchema = z.$$$'

# Check for any type definitions related to notifications
rg 'interface.*Notification' -A 5

# Check the formatTimestamp implementation
ast-grep --pattern 'function formatTimestamp($$$)'

Length of output: 957


Script:

#!/bin/bash
# Search for notification schema validation and type definitions
rg 'NotificationSchema\(\)' -B 5 -A 5

# Check for any zod schema definitions for notifications
rg 'z\.object\({.*timestamp' -A 5

Length of output: 5214

Copy link
Member

@elibosley elibosley left a comment

Choose a reason for hiding this comment

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

Absolutely love sorted imports! Any chance we can share these configs between frontend and backend?

@pujitm
Copy link
Member Author

pujitm commented Nov 12, 2024

Absolutely love sorted imports! Any chance we can share these configs between frontend and backend?

Yeah! It'd probably involve some setup changes in the dev environment and another pr tho

@pujitm pujitm merged commit 40404d0 into main Nov 12, 2024
9 checks passed
@pujitm pujitm deleted the chore/organize-imports branch November 12, 2024 14:46
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.

3 participants