Skip to content

fix: dont insert into resource_variable table if no variables set on resource#880

Merged
adityachoudhari26 merged 2 commits intomainfrom
update-variables-0-length-fix
Mar 27, 2026
Merged

fix: dont insert into resource_variable table if no variables set on resource#880
adityachoudhari26 merged 2 commits intomainfrom
update-variables-0-length-fix

Conversation

@adityachoudhari26
Copy link
Copy Markdown
Member

@adityachoudhari26 adityachoudhari26 commented Mar 27, 2026

Fixes #878

Summary by CodeRabbit

  • Bug Fixes

    • Improved error handling for resource variable updates with clearer, user-facing error messages.
    • Fixed logic to only create resource variables when variables are actually provided.
    • Ensured release/enqueue actions and success responses only run after updates complete successfully.
  • Refactor

    • Centralized extraction of error messages for more consistent API error responses.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Mar 27, 2026

Caution

Review failed

Pull request was closed or merged during review

📝 Walkthrough

Walkthrough

Replaced inline error-message normalization with a new extractMessageFromError utility and refactored resource-variable update flow to only insert when variables exist, add try/catch error handling, and run enqueue/202 response only after successful transaction.

Changes

Cohort / File(s) Summary
Error Handling Utility
apps/api/src/routes/v1/workspaces/utils.ts
Added exported extractMessageFromError(error: unknown): string to normalize Error instances, plain strings, and other values into readable messages.
Resource Variables & Handlers
apps/api/src/routes/v1/workspaces/resources.ts
Refactored updateVariablesForResource to wrap flow in try/catch, return structured 500 errors using extractMessageFromError, conditionally insert into resourceVariable only when Object.entries(body) is non-empty, and moved enqueueReleaseTargetsForResource + 202 response inside the success path. Also updated upsertResourceByIdentifier error handling to use extractMessageFromError.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant API as API Handler
    participant DB as Database (transaction)
    participant Queue as Release Enqueuer

    Client->>API: upsertResourceByIdentifier / updateVariablesForResource
    API->>DB: begin transaction
    alt variables present
        API->>DB: insert resourceVariable entries
    else no variables
        DB-->>API: skip insert
    end
    DB-->>API: commit
    API->>Queue: enqueueReleaseTargetsForResource
    API-->>Client: 202 Accepted
    alt error occurs
        API-->>Client: 500 { error, message: extractMessageFromError(error) }
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Suggested reviewers

  • jsbroks

Poem

🐰 I hopped where errors used to hide,

Empty lists once made me glide.
Now messages plucked with gentle care,
Variables only placed when there.
Hop—no crash—the release flies fair. 🥕

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The PR title clearly describes the main fix: preventing insertion into resource_variable table when no variables are set, which directly addresses the linked issue.
Linked Issues check ✅ Passed The code changes successfully address the linked issue #878 by preventing empty inserts to the resourceVariable table and adding proper error handling.
Out of Scope Changes check ✅ Passed All changes are scoped to fixing the resource variable insertion issue. The addition of extractMessageFromError utility is a supporting change for consistent error messaging.

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

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch update-variables-0-length-fix

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.

Copy link
Copy Markdown
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: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@apps/api/src/routes/v1/workspaces/resources.ts`:
- Around line 219-252: The try/catch around the update-resource-variables
handler is catching ApiError (from findResource) and turning it into a 500;
change the catch to re-throw ApiError so its status code is preserved: inside
the catch check if (error instanceof ApiError) throw error; otherwise keep the
existing res.status(500).json({ error: "...", message:
extractMessageFromError(error) }); this preserves behavior like other handlers
(e.g., getVariablesForResource, deleteResourceByIdentifier) while keeping
enqueueReleaseTargetsForResource and the transactional insert logic intact.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 4ff62082-2585-485b-9132-ec5787a618f8

📥 Commits

Reviewing files that changed from the base of the PR and between e4ac47a and 8821c5e.

📒 Files selected for processing (2)
  • apps/api/src/routes/v1/workspaces/resources.ts
  • apps/api/src/routes/v1/workspaces/utils.ts

Comment on lines +219 to +252
try {
const { workspaceId, identifier } = req.params;
const { body } = req;

const resource = await findResource(workspaceId, identifier);
const { id: resourceId } = resource;

await db.transaction(async (tx) => {
await tx
.delete(schema.resourceVariable)
.where(eq(schema.resourceVariable.resourceId, resource.id));
const entries = Object.entries(body);
if (entries.length > 0)
await tx.insert(schema.resourceVariable).values(
entries.map(([key, value]) => ({
resourceId,
key,
value,
})),
);
});

enqueueReleaseTargetsForResource(db, workspaceId, resourceId);
enqueueReleaseTargetsForResource(db, workspaceId, resourceId);

res.status(202).json({
id: resource.id,
message: "Resource variables update requested",
});
res.status(202).json({
id: resource.id,
message: "Resource variables update requested",
});
} catch (error) {
res.status(500).json({
error: "Failed to update resource variables",
message: extractMessageFromError(error),
});
}
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.

⚠️ Potential issue | 🟠 Major

The conditional insert correctly fixes #878, but the try/catch swallows ApiError status codes.

The entries.length > 0 check correctly prevents the empty .values() call. However, wrapping findResource inside the try/catch causes ApiError exceptions (e.g., 404 Not Found) to be caught and returned as 500 errors.

Other handlers in this file (e.g., getVariablesForResource, deleteResourceByIdentifier) let ApiError propagate to asyncHandler which preserves the correct status code.

🛠️ Proposed fix: Re-throw ApiError to preserve status codes
   } catch (error) {
+    if (error instanceof ApiError) throw error;
     res.status(500).json({
       error: "Failed to update resource variables",
       message: extractMessageFromError(error),
     });
   }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/api/src/routes/v1/workspaces/resources.ts` around lines 219 - 252, The
try/catch around the update-resource-variables handler is catching ApiError
(from findResource) and turning it into a 500; change the catch to re-throw
ApiError so its status code is preserved: inside the catch check if (error
instanceof ApiError) throw error; otherwise keep the existing
res.status(500).json({ error: "...", message: extractMessageFromError(error) });
this preserves behavior like other handlers (e.g., getVariablesForResource,
deleteResourceByIdentifier) while keeping enqueueReleaseTargetsForResource and
the transactional insert logic intact.

@adityachoudhari26 adityachoudhari26 merged commit 8bea3cd into main Mar 27, 2026
6 of 7 checks passed
@adityachoudhari26 adityachoudhari26 deleted the update-variables-0-length-fix branch March 27, 2026 20:04
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.

applying a resource throws an error if no variables are set

1 participant