Skip to content

added risk endpoints - #104

Merged
Marfuen merged 3 commits into
mainfrom
mariano/deel-import
Mar 5, 2025
Merged

Marfuen merged 3 commits into
mainfrom
mariano/deel-import

Conversation

@Marfuen

@Marfuen Marfuen commented Mar 5, 2025 •

Copy link
Copy Markdown
Contributor

Summary by CodeRabbit

  • New Features

    • Introduced new API endpoints for secure risk management, including retrieving specific risks, listing and filtering multiple risks, creating new risks, and deleting existing ones.
  • Documentation

    • Enhanced API documentation with improved formatting and a new section detailing the available risk management endpoints and their usage instructions, including error handling scenarios.
    • Added comprehensive documentation for the Risks API endpoints, including request and response formats.

@vercel

vercel Bot commented Mar 5, 2025 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
app ✅ Ready (Inspect) Visit Preview 💬 Add feedback Mar 5, 2025 4:55pm
2 Skipped Deployments
Name Status Preview Comments Updated (UTC)
comp-portal ⬜️ Skipped (Inspect) Mar 5, 2025 4:55pm
web ⬜️ Skipped (Inspect) Mar 5, 2025 4:55pm

@coderabbitai

coderabbitai Bot commented Mar 5, 2025 •

Copy link
Copy Markdown

Warning

Rate limit exceeded

@Marfuen has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 19 minutes and 49 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 86b1a3b and 0051a4e.

📒 Files selected for processing (1)
  • apps/app/src/app/api/v1/risks/[id]/route.ts (1 hunks)

Walkthrough

This pull request introduces new API endpoints for managing risks. Two sets of endpoints are implemented: one for operations on individual risks (retrieval and deletion by ID) and another for managing the risks collection (listing and creation). Both sets perform API key authentication, validate inputs using a schema, query the database with organization context, and return structured JSON responses with appropriate error handling. In parallel, the API documentation has been updated to reflect these endpoints along with formatting improvements.

Changes

File(s) Change Summary
apps/app/src/app/api/v1/risks/[id]/route.ts
apps/app/src/app/api/v1/risks/route.ts
Added new API routes for risks management. The /risks/:id route now supports GET (retrieve a single risk) and DELETE (remove a risk), while the /risks route now supports GET (list risks with filtering) and POST (create a new risk). Both files include API key checks, input validation, database interactions, and refined error handling.
packages/docs/api-reference/v1/index.mdx
packages/docs/api-reference/v1/risks.mdx
Updated API documentation. Formatting in the front matter was refined, a new section for available endpoints was added, and a dedicated risks documentation file was introduced to detail all risks-related endpoints, including request/response examples and error handling guidelines.

Sequence Diagram(s)

sequenceDiagram
    participant C as Client
    participant API as API Server
    participant DB as Database

    %% GET single risk
    C->>API: GET /api/v1/risks/:id (with API key)
    API->>API: Extract org ID from API key
    API->>DB: Query risk by id & organization
    DB-->>API: Risk data or Not Found (404)
    API-->>C: JSON response (risk details or error)

    %% DELETE single risk
    C->>API: DELETE /api/v1/risks/:id (with API key)
    API->>API: Validate organization & risk ownership
    API->>DB: Delete risk by id & organization
    DB-->>API: Deletion confirmation or error
    API-->>C: JSON response (success or error)
Loading
sequenceDiagram
    participant C as Client
    participant API as API Server
    participant DB as Database

    %% GET risks list
    C->>API: GET /api/v1/risks (with API key & query params)
    API->>API: Validate query parameters & extract org ID
    API->>DB: Fetch risks with applied filters
    DB-->>API: List of risks
    API-->>C: JSON response with formatted risks list

    %% POST create risk
    C->>API: POST /api/v1/risks (with API key & request body)
    API->>API: Validate request body with schema
    API->>DB: Insert new risk
    DB-->>API: New risk data or error
    API-->>C: JSON response (created risk details or error)
Loading

Poem

I'm a happy little rabbit, leaping through the code,
New routes and endpoints make my heart explode.
With risks now listed and details set just right,
I nibble on each JSON response, day and night.
Documentation hops along with clear, bold tips—
Together we celebrate these agile, joyful scripts!


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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

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 (8)
packages/docs/api-reference/v1/index.mdx (2)

15-15: Ensure clarity of authentication header details.
While the current references are valid, consider adding a short example snippet showing the exact header format to make it unambiguous for new users.


68-68: Fix mismatched email reference.
There is a mismatch between the displayed support email ("support@trycomp.ai") and the mailto link ("mailto:hello@trycomp.ai"). Consider unifying them to avoid confusion.

-If you have questions or need assistance with the API, please contact our support team at [support@trycomp.ai](mailto:hello@trycomp.ai)
+If you have questions or need assistance with the API, please contact our support team at [support@trycomp.ai](mailto:support@trycomp.ai)
apps/app/src/app/api/v1/risks/[id]/route.ts (2)

25-142: Avoid logging full errors to console in production.
Although printing the error is helpful for debugging, consider using a logging solution that masks sensitive information in production environments.


161-219: Check if child entities require cascading delete or archival.
Currently, only the main risk record is deleted. If there are dependent mitigation tasks or related entities, these may remain orphaned. Confirm whether they should also be removed or archived to maintain data consistency.

apps/app/src/app/api/v1/risks/route.ts (4)

9-30: Consider centralizing repeated enums
The category and department enums here are also repeated in the risk creation schema. Centralizing them into a shared constants file or TypeScript enum can reduce duplication and ensure consistency.


128-131: Avoid using any in the where clause
Using any here obscures the expected shape of the where object. Consider a typed approach to maintain type safety and clarity.

- const where: any = {
+ const where: Prisma.RiskWhereInput = {
    organizationId: organizationId!,
};

248-248: Handle malformed JSON parsing
If request.json() fails to parse malformed JSON, the code will jump to the catch block, sending a 500 response. Consider explicitly catching JSON parse errors and returning a 400 response for invalid request bodies.


249-249: Error handling for large requests
request.json() may be expensive for large bodies. If you anticipate processing large payloads, consider additional checks or streaming approaches to avoid potential performance bottlenecks or memory issues.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 82d0b02 and e0ff9ef.

📒 Files selected for processing (4)
  • apps/app/src/app/api/v1/risks/[id]/route.ts (1 hunks)
  • apps/app/src/app/api/v1/risks/route.ts (1 hunks)
  • packages/docs/api-reference/v1/index.mdx (4 hunks)
  • packages/docs/api-reference/v1/risks.mdx (1 hunks)
🔇 Additional comments (7)
packages/docs/api-reference/v1/index.mdx (3)

2-3: No issues detected with front matter updates.
The switch to double quotes for the title and description is consistent with typical Markdown front matter styling.


33-39: Good addition of the Available Endpoints section.
This helps users quickly navigate to each resource.


57-64: Table formatting looks good.
Clear spacing and alignment in the header and rows improves readability.

packages/docs/api-reference/v1/risks.mdx (1)

1-368: Comprehensive documentation for the Risks endpoints.
All critical details about request/response formats, query parameters, and error responses appear to be well-documented and consistent with the codebase. Nice job!

apps/app/src/app/api/v1/risks/[id]/route.ts (1)

25-142: Ensure null assertion on organizationId is always valid.
The code relies on organizationId! after checking for errorResponse; this is safe as long as getOrganizationFromApiKey guarantees a defined organizationId in the absence of an error. Otherwise, consider a more explicit check.

apps/app/src/app/api/v1/risks/route.ts (2)

7-7: Runtime explicitly set to Node.js
This is correct if the code relies on Node APIs or needs a Node.js environment.


32-60: Risk creation schema is well-defined
The use of zod for validation here is comprehensive. Nice work, especially with the optional and default values.

@vercel
vercel Bot temporarily deployed to Preview – web March 5, 2025 16:46 Inactive
@vercel
vercel Bot temporarily deployed to Preview – comp-portal March 5, 2025 16:46 Inactive

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (4)
apps/app/src/app/api/v1/risks/route.ts (4)

94-96: Consider using a more specific type than 'any'.

Using any for the where clause loses type safety. Consider defining a proper type or interface that reflects the structure of your where conditions.

- const where: any = {
+ const where: {
+   organizationId: string;
+   status?: RiskStatus;
+   category?: RiskCategory;
+   department?: Departments;
+   OR?: Array<{[key: string]: any}>;
+ } = {
  organizationId: organizationId!,
};

95-95: Avoid non-null assertions when possible.

The non-null assertion (!) on organizationId suggests it could be null, but the code already handles this through errorResponse. Consider restructuring to avoid the assertion.

- organizationId: organizationId!,
+ organizationId,

This would require ensuring organizationId is definitely defined at this point, perhaps by adding:

if (!organizationId) {
  return NextResponse.json({ success: false, error: "Invalid organization" }, { status: 400 });
}

earlier in the function.


239-239: Same issue with non-null assertion as mentioned earlier.

Consider handling the organizationId null case explicitly rather than using the non-null assertion operator.

- organizationId: organizationId!,
+ organizationId,

255-262: Include the actual error message in server logs.

For better debugging, consider logging the actual error message or object.

- console.error("Error creating risk:", error);
+ console.error("Error creating risk:", error instanceof Error ? error.message : error);
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e0ff9ef and 86b1a3b.

📒 Files selected for processing (1)
  • apps/app/src/app/api/v1/risks/route.ts (1 hunks)
🔇 Additional comments (12)
apps/app/src/app/api/v1/risks/route.ts (12)

1-4: Imports look good and appropriate for the functionality.

The imports include necessary modules for database access, NextJS request/response handling, API key validation, and schema validation with zod.


6-7: Runtime configuration is correctly specified.

Setting the runtime to "nodejs" is appropriate, especially if you need Node.js-specific features that aren't available in the Edge runtime.


9-15: Well-structured query parameter schema.

The schema correctly defines optional parameters with appropriate enumeration types from the database models, making the validation robust and type-safe.


18-29: Risk creation schema is thorough and well-constrained.

The schema properly defines:

  • Required fields with meaningful validation messages
  • Optional fields with sensible defaults
  • Numeric constraints for probability and impact fields
  • Proper type enforcement using enums from the database models

34-53: Comprehensive API documentation.

The JSDoc comments are excellent, clearly documenting:

  • The endpoint path and purpose
  • Required headers
  • Query parameters with descriptions
  • All possible response status codes and formats

54-62: API key validation is properly implemented.

The function correctly extracts and validates the organization ID from the API key, returning an error response if authentication fails.


113-129: Comprehensive search implementation.

The search functionality is well-implemented with case-insensitive matching across both title and description fields.


132-159: Database query includes appropriate fields and relationships.

The risk selection includes comprehensive fields and owner information, showing awareness of potential relationships. The ordering by updated date is a good default.


161-166: Proper date formatting for JSON response.

The code correctly converts Date objects to ISO strings for JSON serialization.


178-203: Clear and comprehensive documentation for POST endpoint.

The JSDoc comments for the POST endpoint are excellent, clearly documenting all aspects of the endpoint including request body fields, possible responses, and status codes.


217-230: Proper validation of request body.

The validation against the schema and error handling for validation failures is implemented correctly.


1-264: Overall, excellent implementation of the risks API endpoints.

The implementation is well-structured, properly validated, and handles errors appropriately. The endpoints follow RESTful principles and include comprehensive documentation. The code is maintainable and follows best practices for Next.js API routes.

Some minor improvements could be made around type safety and error handling, but these are relatively minor concerns.

}

try {
const body = await request.json();

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add error handling for JSON parsing.

The request body is parsed without error handling, which could lead to issues if the request body isn't valid JSON.

- const body = await request.json();
+ let body;
+ try {
+   body = await request.json();
+ } catch (error) {
+   return NextResponse.json(
+     {
+       success: false,
+       error: "Invalid JSON in request body",
+     },
+     { status: 400 }
+   );
+ }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const body = await request.json();
let body;
try {
body = await request.json();
} catch (error) {
return NextResponse.json(
{
success: false,
error: "Invalid JSON in request body",
},
{ status: 400 }
);
}

@vercel
vercel Bot temporarily deployed to Preview – web March 5, 2025 16:52 Inactive
@vercel
vercel Bot temporarily deployed to Preview – comp-portal March 5, 2025 16:52 Inactive
@Marfuen
Marfuen merged commit 2c61170 into main Mar 5, 2025
Marfuen added a commit that referenced this pull request Jul 21, 2026
#94-#104) (#3466)

A batch of 11 node-tar advisories (Critical->Moderate: decompression DoS, path
traversal, symlink/hardlink escape, PAX parsing differentials) flagged every
tar copy below 7.5.19. bun.lock had tar@6.2.1 (x5, via build tooling: node-gyp,
cacache, @electron/rebuild, app-builder-lib, giget), tar@7.5.11 (fleetctl), and
tar@7.5.20 (already patched).

node-tar backported no fixes to the 6.x line, so the only remediation is
tar >= 7.5.19. Added a bun override "tar": "^7.5.19" — bun.lock now resolves a
single tar@7.5.20 for all consumers. tar@7 is a dual CJS/ESM package with a
stable extract/create API, so the CJS build tools keep working via require().

Reachability was low pre-fix (all vulnerable copies were build-time tooling or
trusted-source CLI extraction, none extract attacker-controlled archives in the
runtime API), but the override removes the vulnerable versions entirely.

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>

This branch was successfully deployed

1 active and 2 inactive deployments
Preview – app — 0051a4e9 Deployed Mar 5, 2025 by vercel[bot]
Preview – web — 0051a4e9 Deployed Mar 5, 2025 by vercel[bot]
Preview – comp-portal — 0051a4e9 Deployed Mar 5, 2025 by vercel[bot]
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.

1 participant