Skip to content

Fix/query engine limitfields mock - #231

Merged
yash-pouranik merged 6 commits into
geturbackend:mainfrom
Mansi0905:fix/query-engine-limitfields-mock
May 31, 2026
Merged

Fix/query engine limitfields mock#231
yash-pouranik merged 6 commits into
geturbackend:mainfrom
Mansi0905:fix/query-engine-limitfields-mock

Conversation

@Mansi0905

@Mansi0905 Mansi0905 commented May 29, 2026

Copy link
Copy Markdown
Contributor

fix: add limitFields() to QueryEngine mock so CI passes

  • Added limitFields() to the mockQueryEngine in data.controller.read.test.js
  • Keeps features.sort().limitFields().populate() chain intact in getAllData
  • Previously the missing mock method caused chain to break,
    resulting in populate() never being called and a 500 response

Summary by CodeRabbit

  • New Features

    • Added cursor-based pagination (?cursor), count retrieval (?count=true), field limiting and improved relationship handling for data queries.
  • Bug Fixes

    • Improved DB connection validation and error handling.
    • Fixed control flow for invalid path normalization to return early.
  • Refactor

    • Standardized data endpoint responses to include success, items, and pagination/count metadata.
  • Tests

    • Updated tests to mock the new field-limiting query step.

@coderabbitai

coderabbitai Bot commented May 29, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 2b555f57-a860-4e7a-b347-a9bbabaca7ea

📥 Commits

Reviewing files that changed from the base of the PR and between 7d885d3 and b3aa09c.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (3)
  • apps/dashboard-api/src/controllers/project.controller.js
  • apps/public-api/src/__tests__/data.controller.read.test.js
  • apps/public-api/src/controllers/data.controller.js
✅ Files skipped from review due to trivial changes (1)
  • apps/public-api/src/tests/data.controller.read.test.js
🚧 Files skipped from review as they are similar to previous changes (2)
  • apps/public-api/src/controllers/data.controller.js
  • apps/dashboard-api/src/controllers/project.controller.js

📝 Walkthrough

Walkthrough

Adds QueryEngine field-limiting and cursor pagination to public and dashboard data endpoints; rewrites dashboard getData response shape; refactors external DB config verification, upload path handling, analytics logs mapping; and applies dispersed comment/format cleanups across project controller.

Changes

QueryEngine Integration & Data Query Features

Layer / File(s) Summary
QueryEngine mock, public getAllData, dashboard getData
apps/public-api/src/__tests__/data.controller.read.test.js, apps/public-api/src/controllers/data.controller.js, apps/dashboard-api/src/controllers/project.controller.js
Adds limitFields() to the QueryEngine test mock; inserts limitFields() before populate() in public getAllData; rewrites dashboard getData to use compiled model + QueryEngine with limitFields(), populate(), count, paginate()/cursorPaginate(), next-cursor generation, and a structured {success,data:{items,...}} response.

Data Validation, Upload, & Analytics Refactors

Layer / File(s) Summary
External configuration DB URI verification
apps/dashboard-api/src/controllers/project.controller.js
Refactors updateExternalConfig to extract validated payload fields up front and reorganize DB URI verification while preserving encryption and update behavior.
Recent project logs aggregation pipeline
apps/dashboard-api/src/controllers/project.controller.js
Adjusts getAllProject aggregation to apply $sort and $limit before $group used for per-project health/metrics counts.
Analytics logs mapping and grouping
apps/dashboard-api/src/controllers/project.controller.js
Ensures last1h grouping uses minutes and introduces rawLogs mapped into final logs array shape including path and status.
File upload path validation with early return
apps/dashboard-api/src/controllers/project.controller.js
confirmUpload now fails fast with an early 403 when normalizeProjectPath returns invalid.
User password field stripping in row edits
apps/dashboard-api/src/controllers/project.controller.js
editRow now removes req.body.password directly for updates targeting the users collection.
Auth, mail templates, RLS, and misc cleanups
apps/dashboard-api/src/controllers/project.controller.js
Minor comment/header cleanups and formatting tweaks across sanitizeAuthProviders, getSingleProject, regenerateApiKey, isSafeUri, createCollection, updateProject, mail-template endpoints, deleteProject, toggleAuth, updateAuthProviders, updateCollectionRls, and Resend proxy routes; behavioral semantics preserved.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • geturbackend/urBackend#140: Related changes to apps/dashboard-api/src/controllers/project.controller.js analytics logic and metrics grouping.

Suggested labels

level:intermediate, quality:clean, mentor:yash-pouranik

Suggested reviewers

  • yash-pouranik

Poem

🐰 In fields of QueryEngine I play,
I nibble fields and hop away.
Cursor tokens in my paw,
Logs mapped neat, no messy flaw.
Code hops forward — bright new day!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'Fix/query engine limitfields mock' clearly describes the main change—adding a missing limitFields() mock implementation to fix the QueryEngine chain in tests.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

ESLint skipped: no ESLint configuration detected in root package.json. To enable, add eslint to devDependencies.


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.

@yash-pouranik

Copy link
Copy Markdown
Member

@coderabbitai review

@coderabbitai

coderabbitai Bot commented May 29, 2026

Copy link
Copy Markdown
Contributor
✅ 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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Caution

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

⚠️ Outside diff range comments (2)
apps/dashboard-api/src/controllers/project.controller.js (2)

766-773: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Normalize getData errors to the controller contract.

This endpoint now returns { success, data, message } on success, but its 404 branches still return raw { error }, and the catch block forwards err.message directly. That also turns QueryEngine validation failures into generic 500s here instead of a controlled 4xx response.

🛠️ Suggested direction
-module.exports.getData = async (req, res) => {
+module.exports.getData = async (req, res, next) => {
   try {
     const { projectId, collectionName } = req.params;
     const project = await Project.findOne({ _id: projectId, owner: req.user._id });
-    if (!project) return res.status(404).json({ error: "Project not found." });
+    if (!project) return next(new AppError(404, "Project not found."));

     const collectionConfig = project.collections.find(c => c.name === collectionName);
     if (!collectionConfig) {
-      return res.status(404).json({
-        error: "Collection not found",
-        collection: collectionName
-      });
+      return next(new AppError(404, "Collection not found."));
     }

     // ...
   } catch (err) {
-    res.status(500).json({ error: err.message });
+    if (err?.statusCode === 400 || err?.name === "QueryFilterError") {
+      return next(new AppError(400, err.message || "Invalid query filter."));
+    }
+    return next(new AppError(500, "Failed to fetch data."));
   }
 };

As per coding guidelines, **/src/controllers/**/*.{js,ts}: All API endpoints return: { success: bool, data: {}, message: "" }. Use AppError class for errors — never raw throw, never expose MongoDB errors to client.

Also applies to: 852-853

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/dashboard-api/src/controllers/project.controller.js` around lines 766 -
773, Normalize all error responses in the getData controller to the standard {
success: boolean, data: {}, message: "" } shape: replace the raw 404 returns
(when project is missing and when collectionConfig is missing) to return
res.status(404).json({ success:false, data:{}, message: "Project not found." })
and res.status(404).json({ success:false, data:{}, message: `Collection
${collectionName} not found.` }) respectively, and update the catch block to
wrap errors using the AppError class (map QueryEngine validation errors to a 4xx
AppError) before sending a response so you never forward raw err.message or
MongoDB internals to the client; locate these changes around the getData
controller and the collectionName/project/collectionConfig checks and the
existing catch that currently forwards err.message.

337-344: ⚠️ Potential issue | 🟠 Major | 🏗️ Heavy lift

Move the log cap after per-project aggregation.

$limit: 100 is applied before $group, so health is computed from the latest 100 logs across all of the owner's projects, not the latest logs for each project. A busy project can crowd out the rest, and those projects will default to healthy even if their recent requests were failing.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/dashboard-api/src/controllers/project.controller.js` around lines 337 -
344, The $limit stage is currently placed before the $group, so
errorCount/successCount (from the aggregation that references _id: "$projectId",
errorCount, successCount) are computed from the latest 100 logs across all
projects instead of per-project; remove the pre-group { $limit: 100 } and either
move a limit after grouping (if you intend to cap number of projects) or, to cap
logs per project, change the $group to collect per-project logs with $push and
$slice (e.g. push a log entry array then $slice to 100) and compute
errorCount/successCount from that sliced array so each project’s health uses its
most recent up to 100 logs.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@apps/dashboard-api/src/controllers/project.controller.js`:
- Around line 766-773: Normalize all error responses in the getData controller
to the standard { success: boolean, data: {}, message: "" } shape: replace the
raw 404 returns (when project is missing and when collectionConfig is missing)
to return res.status(404).json({ success:false, data:{}, message: "Project not
found." }) and res.status(404).json({ success:false, data:{}, message:
`Collection ${collectionName} not found.` }) respectively, and update the catch
block to wrap errors using the AppError class (map QueryEngine validation errors
to a 4xx AppError) before sending a response so you never forward raw
err.message or MongoDB internals to the client; locate these changes around the
getData controller and the collectionName/project/collectionConfig checks and
the existing catch that currently forwards err.message.
- Around line 337-344: The $limit stage is currently placed before the $group,
so errorCount/successCount (from the aggregation that references _id:
"$projectId", errorCount, successCount) are computed from the latest 100 logs
across all projects instead of per-project; remove the pre-group { $limit: 100 }
and either move a limit after grouping (if you intend to cap number of projects)
or, to cap logs per project, change the $group to collect per-project logs with
$push and $slice (e.g. push a log entry array then $slice to 100) and compute
errorCount/successCount from that sliced array so each project’s health uses its
most recent up to 100 logs.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: c08301b7-87a2-486f-82ea-3977c0f0ac29

📥 Commits

Reviewing files that changed from the base of the PR and between e5f0bdf and 7d885d3.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (3)
  • apps/dashboard-api/src/controllers/project.controller.js
  • apps/public-api/src/__tests__/data.controller.read.test.js
  • apps/public-api/src/controllers/data.controller.js

@yash-pouranik

Copy link
Copy Markdown
Member

please fix this last

@yash-pouranik

Copy link
Copy Markdown
Member

@Mansi0905

@Mansi0905

Copy link
Copy Markdown
Contributor Author

@Mansi0905
this is fixed @yash-pouranik

These issues are already addressed in PR #230 (fix/dashboard-getData-query-engine) which contains the full getData refactor and aggregation fix. This PR (#231) only adds limitFields() to the QueryEngine mock to fix CI.

@yash-pouranik

Copy link
Copy Markdown
Member

ok got it
but why did u remove jsdoc comments and normal comments
@Mansi0905

@Mansi0905

Copy link
Copy Markdown
Contributor Author

ok got it but why did u remove jsdoc comments and normal comments @Mansi0905

Sorry about that! The comments were accidentally removed during the rebase conflict resolution process @yash-pouranik

@Mansi0905

Copy link
Copy Markdown
Contributor Author

ok got it but why did u remove jsdoc comments and normal comments @Mansi0905

ready to merge? or do i need to change em?

@yash-pouranik

Copy link
Copy Markdown
Member

U havent revovered the comments? and jsdoc as well?

@yash-pouranik

Copy link
Copy Markdown
Member

@Mansi0905
also merge conflicts are there so
delete ur package-lock.json
merge main branch with ur.
and check if package-lock.json came
then push

@Mansi0905

Copy link
Copy Markdown
Contributor Author

U havent revovered the comments? and jsdoc as well?

i have recovered them already

@yash-pouranik

Copy link
Copy Markdown
Member

cool

@yash-pouranik
yash-pouranik merged commit 38ac081 into geturbackend:main May 31, 2026
8 checks passed
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