Skip to content

Conversation

@adithyadinesh0412
Copy link
Collaborator

@adithyadinesh0412 adithyadinesh0412 commented Nov 10, 2025

Summary by CodeRabbit

  • New Features

    • Added sorting capability to entity listings and search results, enabling users to organize results by specified fields and preferred order.
  • Refactor

    • Improved language handling consistency in search operations.

@coderabbitai
Copy link

coderabbitai bot commented Nov 10, 2025

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

The changes extend entity listing functionality to support sorting by adding sortOrder and sortKey parameters to the controller handler and propagating them through helper methods. These parameters are integrated into MongoDB aggregation pipelines to apply sorting during entity queries and traversals.

Changes

Cohort / File(s) Summary
Sorting Parameter Propagation
src/controllers/v1/entities.js
Passes req.query.sortOrder and req.query.sortKey to the subEntityList helper method in the sub-entity listing endpoint.
Helper Method Sorting Support
src/module/entities/helper.js
Adds optional sortOrder and sortKey parameters (default: '') to multiple methods: subEntityList(), subEntities(), entityTraversal(), and search(). Integrates sorting into MongoDB aggregation pipelines with conditional $sort stages. Refactors language-dependent query branches into dynamic pipelines that adapt based on language selection.

Sequence Diagram

sequenceDiagram
    participant Client
    participant Controller as Controller<br/>(entities.js)
    participant Helper as Helper<br/>(helper.js)
    participant MongoDB as MongoDB<br/>Aggregation

    Client->>Controller: GET /entities (with sortOrder, sortKey)
    Controller->>Helper: subEntityList(..., sortOrder, sortKey)
    Helper->>Helper: Check if sortOrder & sortKey provided
    alt Sorting Enabled
        Helper->>MongoDB: Build pipeline with $sort stage
        Note over MongoDB: Apply sort before<br/>facet/count operations
    else No Sorting
        Helper->>MongoDB: Execute pipeline without $sort
    end
    MongoDB-->>Helper: Return sorted/unsorted results
    Helper-->>Controller: Return entity data
    Controller-->>Client: Return response
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

  • Parameter propagation consistency: Verify that sortOrder and sortKey are correctly threaded through all affected methods (subEntityList, subEntities, entityTraversal, search) and that default values are applied appropriately.
  • Aggregation pipeline logic: Confirm that the dynamic $sort stage is correctly positioned before facet/count operations and that sorting is only applied when both parameters are non-empty.
  • Language-dependent behavior: Review the refactored pipeline logic for language-conditional name field selection to ensure sorting works correctly for both English and translated fields.
  • Call site updates: Verify all internal callers have been updated to pass the new parameters where necessary.

Poem

🐰 With sortOrder and sortKey in tow,
Entities now dance in a proper row,
Sorted by choice, ascending or down,
The finest feature in our rabbit town! 🌟

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'Sorting in subEntityList API' directly and clearly describes the main change: adding sorting support to the subEntityList API functionality.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@adithyadinesh0412
Copy link
Collaborator Author

@coderabbitai full review

@coderabbitai
Copy link

coderabbitai bot commented Nov 11, 2025

@adithyadinesh0412, I'll conduct a full review of all the changes in this PR focusing on the sorting implementation in the subEntityList API.

✅ Actions performed

Full review triggered.

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/module/entities/helper.js (1)

540-600: Critical: Missing sortOrder and sortKey parameters in immediateEntities signature.

The immediateEntities method calls this.search with sortOrder and sortKey parameters (lines 588-589), but these parameters are not defined in the method signature (line 540). This will result in undefined being passed to the search method, breaking the sorting functionality for immediate entities.

Apply this diff to fix the signature and propagate the parameters:

-	static immediateEntities(entityId, searchText = '', pageSize = '', pageNo = '', tenantId) {
+	static immediateEntities(entityId, searchText = '', pageSize = '', pageNo = '', tenantId, sortOrder = '', sortKey = '') {
 		return new Promise(async (resolve, reject) => {

And update the call in subEntities (line 511):

 				} else {
 					// Retrieve immediate entities
 					entitiesDocument = await this.immediateEntities(
 						entitiesData.entityId,
 						entitiesData.search,
 						entitiesData.limit,
 						entitiesData.pageNo,
 						language,
-						tenantId
+						tenantId,
+						sortOrder,
+						sortKey
 					)
 				}
🧹 Nitpick comments (2)
src/module/entities/helper.js (2)

261-261: Remove commented debug code.

The commented console.log statement should be removed to keep the codebase clean.

Apply this diff:

 							obj['entityId'] = entity
 							let entitiesDocument = await this.subEntities(obj, language, tenantId, sortOrder, sortKey)
-							// console.log('entitiesDocument----------->>>>> ',entitiesDocument)
 
 							if (Array.isArray(entitiesDocument.data) && entitiesDocument.data.length > 0) {

703-706: Validate language parameter to prevent field path injection.

The language parameter is used directly to construct a MongoDB field path ($translations.${language}.name on line 706). While language codes are typically controlled values, it's a best practice to validate them against a whitelist to prevent potential field path injection.

Consider adding validation:

 				let finalEntityDocuments = []
 				// check the language criteria is set to english or not
 				const isEnglish = !language || language === CONSTANTS.common.ENGLISH_LANGUGE_CODE
+				
+				// Validate language code if provided
+				if (language && !isEnglish) {
+					const validLanguageCodes = /^[a-z]{2,3}(-[A-Z]{2})?$/  // e.g., 'en', 'hi', 'en-US'
+					if (!validLanguageCodes.test(language)) {
+						throw {
+							status: HTTP_STATUS_CODE.bad_request.status,
+							message: 'Invalid language code format'
+						}
+					}
+				}
+				
 				// construct the name expression based on language
 				const nameExpr = isEnglish ? '$metaInformation.name' : `$translations.${language}.name`
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f1e3d0d and fb349fa.

📒 Files selected for processing (2)
  • src/controllers/v1/entities.js (1 hunks)
  • src/module/entities/helper.js (10 hunks)
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2025-08-01T11:20:44.813Z
Learnt from: MallanagoudaB
Repo: ELEVATE-Project/entity-management PR: 172
File: src/generics/kafka/producers.js:22-37
Timestamp: 2025-08-01T11:20:44.813Z
Learning: In the ELEVATE-Project/entity-management service, the team consistently uses the async Promise executor pattern `return new Promise(async (resolve, reject) => { ... })` throughout the entire codebase including controllers, helpers, database queries, and services. This is an established coding standard that should be maintained for consistency.

Applied to files:

  • src/module/entities/helper.js
🔇 Additional comments (4)
src/module/entities/helper.js (4)

237-239: LGTM!

The new sorting parameters are correctly added with appropriate default values and will be falsy in conditional checks when not provided.


616-626: LGTM!

The entityTraversal signature is correctly updated with the sorting parameters, and they are properly propagated to the search method.


730-748: LGTM!

The pipeline construction and aggregation logic are correct. The use of $arrayElemAt to extract the count (line 742) and the spread operator to combine pipeline stages (lines 730-746) are appropriate.


491-508: No action needed for sorting parameters in immediateEntities.

The original concern can be dismissed. immediateEntities and entityTraversal are mutually exclusive code paths serving different purposes: the former retrieves direct related entities from groups, while the latter performs hierarchical traversal. immediateEntities has no sorting capability by design and is never called with sorting expectations elsewhere in the codebase. The implementation is correct as-is.

Copy link
Collaborator

@VISHNUDAS-tunerlabs VISHNUDAS-tunerlabs left a comment

Choose a reason for hiding this comment

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

reviewed on nov 14

parentInfoRequired = false
parentInfoRequired = false,
sortOrder = '',
sortKey = ''
Copy link
Collaborator

Choose a reason for hiding this comment

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

update function signature

@VISHNUDAS-tunerlabs VISHNUDAS-tunerlabs merged commit 314be18 into ELEVATE-Project:develop Nov 14, 2025
1 check passed
@coderabbitai coderabbitai bot mentioned this pull request Jan 20, 2026
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.

2 participants