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

refactored the site refresh functionality and fixed site update #4394

Merged
merged 1 commit into from
Feb 7, 2025

Conversation

Baalmart
Copy link
Contributor

@Baalmart Baalmart commented Feb 7, 2025

Description

refactored the site refresh functionality and fixed site update

Changes Made

  • Broke down the monolithic function into smaller, focused methods
  • Maintained original error handling and logging
  • Used Promise.all for concurrent API calls
  • Simplified data processing
  • Kept the existing utility method calls
  • Made the code more readable and maintainable
  • modify the validateMandatorySiteIdentifier validation so that it doesn't require
  • Removed nested arrays in validation chains

Testing

  • Tested locally
  • Tested against staging environment
  • Relevant tests passed: [List test names]

Affected Services

  • Which services were modified:
    • Device Registry

Endpoints Ready for Testing

  • New endpoints ready for testing:
    • Update Site
    • Refresh Site

API Documentation Updated?

  • Yes, API documentation was updated
  • No, API documentation does not need updating

Summary by CodeRabbit

  • New Features

    • Site management operations now require a valid site identifier during refresh and deletion, improving data accuracy and response quality.
    • Enhanced processing of site details with real-time data fetching and additional data cleanup for consistent performance.
  • Refactor

    • Simplified validation logic for tenant-related operations, resulting in more robust error handling and a smoother user experience.

Copy link
Contributor

coderabbitai bot commented Feb 7, 2025

📝 Walkthrough

Walkthrough

This pull request updates the site operations by enforcing a mandatory site identifier validation on both the PUT /refresh and DELETE endpoints. New asynchronous utility methods have been introduced to manage site details, including fetching, preparing, and cleaning data. Additionally, the validation logic has been refactored to use a oneOf chain for the mandatory site identifier and simplified tenant validation for refresh and delete operations.

Changes

File Change Summary
src/.../routes/v2/sites.routes.js Updated PUT /refresh and DELETE routes to include the new validateMandatorySiteIdentifier middleware before existing validations and controller actions.
src/.../utils/site.util.js Added new asynchronous methods: fetchSiteDetails, prepareSiteRequestBody, fetchAdditionalSiteDetails, and cleanWeatherStationData; updated the refresh method to utilize these new utilities.
src/.../validators/site.validators.js Changed validateMandatorySiteIdentifier to a oneOf validation chain and simplified validateRefreshSite and validateDeleteSite to only perform tenant validation with the isOptional flag.

Sequence Diagram(s)

sequenceDiagram
  participant C as Client
  participant R as Router
  participant V as Validator
  participant SC as Site Controller
  participant SU as Site Utility

  C->>R: PUT /refresh (with site identifier)
  R->>V: validateMandatorySiteIdentifier
  V-->>R: Validation result
  R->>V: validateRefreshSite (tenant optional)
  V-->>R: Validation result
  R->>SC: Refresh request
  SC->>SU: fetchSiteDetails
  SU-->>SC: Site details
  SC->>SU: prepareSiteRequestBody
  SU-->>SC: Prepared request body
  SC->>SU: fetchAdditionalSiteDetails
  SU-->>SC: Additional site info
  SC-->>R: Refresh outcome
  R-->>C: Response
Loading
sequenceDiagram
  participant C as Client
  participant R as Router
  participant V as Validator
  participant SC as Site Controller

  C->>R: DELETE Request (with site identifier)
  R->>V: validateMandatorySiteIdentifier
  V-->>R: Validation result
  R->>V: validateDeleteSite (tenant optional)
  V-->>R: Validation result
  R->>SC: Delete request
  SC-->>R: Deletion confirmation
  R-->>C: Response
Loading

Possibly related PRs

  • removing the name as one of Site identifiers #3811: Addresses validation enhancements by removing the name as a site identifier, closely connected to the new mandatory site identifier validation.
  • Just refactoring Site model #3914: Involves refactoring the Site model with route validations, mirroring the introduction of mandatory validations in the PUT and DELETE endpoints.
  • bulk updating Sites #4056: Updates validation logic for site routes to utilize the new validateMandatorySiteIdentifier middleware, directly aligning with the changes implemented here.

Poem

In our code’s gentle hum, a change takes flight,
Routes now whisper their valid identifier’s might.
Async techniques weave data in a seamless dance,
Validators refine each call at every chance.
A robust rhythm in logic—our code sings bright.
🚀✨

Warning

Review ran into problems

🔥 Problems

Errors were encountered while retrieving linked issues.

Errors (1)
  • JIRA integration encountered authorization issues. Please disconnect and reconnect the integration in the CodeRabbit UI.
✨ 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.

Copy link

codecov bot commented Feb 7, 2025

Codecov Report

Attention: Patch coverage is 8.92857% with 51 lines in your changes missing coverage. Please review.

Project coverage is 11.22%. Comparing base (a2f4281) to head (38ba824).

Files with missing lines Patch % Lines
src/device-registry/utils/site.util.js 0.00% 51 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@           Coverage Diff            @@
##           staging    #4394   +/-   ##
========================================
  Coverage    11.21%   11.22%           
========================================
  Files          156      156           
  Lines        17970    17955   -15     
  Branches       388      388           
========================================
  Hits          2016     2016           
+ Misses       15952    15937   -15     
  Partials         2        2           
Files with missing lines Coverage Δ
src/device-registry/routes/v2/sites.routes.js 100.00% <100.00%> (ø)
src/device-registry/validators/site.validators.js 32.67% <100.00%> (ø)
src/device-registry/utils/site.util.js 4.36% <0.00%> (+0.13%) ⬆️

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

🧹 Nitpick comments (3)
src/device-registry/validators/site.validators.js (1)

345-345: Consider retaining site identifier validation.

The simplified validators now only check for optional tenant validation. While the mandatory site identifier validation is moved to the route level, consider keeping additional validations specific to refresh and delete operations.

-const validateRefreshSite = [createTenantValidation({ isOptional: true })];
+const validateRefreshSite = [
+  createTenantValidation({ isOptional: true }),
+  body("status")
+    .optional()
+    .isIn(["active", "decommissioned"])
+    .withMessage("status must be either 'active' or 'decommissioned'")
+];

-const validateDeleteSite = [createTenantValidation({ isOptional: true })];
+const validateDeleteSite = [
+  createTenantValidation({ isOptional: true }),
+  body("force")
+    .optional()
+    .isBoolean()
+    .withMessage("force must be a boolean value")
+];

Also applies to: 347-347

src/device-registry/utils/site.util.js (2)

51-81: Optimize object property deletion.

The delete operator usage on lines 53-54 can impact performance. Consider using object destructuring or creating a new object with desired properties.

-let request = { ...siteDetails };
-delete request._id;
-delete request.devices;
+const { _id, devices, ...request } = siteDetails;
🧰 Tools
🪛 Biome (1.9.4)

[error] 53-53: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)


[error] 54-54: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)


105-120: Consider using object destructuring for better performance.

The cleanWeatherStationData function could be optimized using object destructuring.

-return Object.keys(station)
-  .filter((key) => !fieldsToRemove.includes(key))
-  .reduce((acc, key) => {
-    acc[key] = station[key];
-    return acc;
-  }, {});
+const { elevation, countrycode, timezoneoffset, name, type, ...cleanedStation } = station;
+return cleanedStation;
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a2f4281 and 38ba824.

📒 Files selected for processing (3)
  • src/device-registry/routes/v2/sites.routes.js (1 hunks)
  • src/device-registry/utils/site.util.js (3 hunks)
  • src/device-registry/validators/site.validators.js (2 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
src/device-registry/utils/site.util.js

[error] 53-53: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)


[error] 54-54: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)

⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: build-push-deploy-device-registry
  • GitHub Check: Analyze (python)
  • GitHub Check: Analyze (javascript)
🔇 Additional comments (6)
src/device-registry/routes/v2/sites.routes.js (1)

72-77: LGTM! Enhanced validation for site operations.

The addition of validateMandatorySiteIdentifier to both the refresh and delete routes improves input validation by ensuring that a valid site identifier is provided before proceeding with these operations.

Also applies to: 78-83

src/device-registry/validators/site.validators.js (1)

233-241: LGTM! Improved validation chain for site identification.

The oneOf validation chain provides flexible site identification through either an ID, lat_long, or generated_name, making the API more versatile while maintaining strict validation.

src/device-registry/utils/site.util.js (4)

32-50: LGTM! Well-structured site details retrieval.

The fetchSiteDetails function provides clear error handling and logging while maintaining a consistent response structure.


83-103: LGTM! Efficient concurrent API calls.

The fetchAdditionalSiteDetails function effectively uses Promise.all for concurrent API calls to optimize performance.


855-897: LGTM! Well-refactored refresh functionality.

The refresh method has been effectively broken down into smaller, focused functions with proper error handling and data flow.


909-938: Review the delete functionality implementation.

The delete functionality is currently disabled with a "coming soon" message. Consider implementing proper deletion logic or providing a more specific timeline for implementation.

Would you like me to help implement the delete functionality with proper validation and safety checks?

🧰 Tools
🪛 Biome (1.9.4)

[error] 918-929: This code is unreachable

... because this statement will return from the function beforehand

(lint/correctness/noUnreachable)

Copy link
Contributor

github-actions bot commented Feb 7, 2025

Device registry changes in this PR available for preview here

@Baalmart Baalmart merged commit 332415f into staging Feb 7, 2025
51 of 52 checks passed
@Baalmart Baalmart deleted the hf-refresh-sites branch February 7, 2025 17:01
@Baalmart Baalmart mentioned this pull request Feb 7, 2025
1 task
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant