added risk endpoints - #104
Conversation
|
The latest updates on your projects. Learn more about Vercel for Git ↗︎
|
|
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 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. 📒 Files selected for processing (1)
WalkthroughThis 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
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)
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)
Poem
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. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
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 usinganyin thewhereclause
Usinganyhere obscures the expected shape of thewhereobject. 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
Ifrequest.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
📒 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 onorganizationId!after checking forerrorResponse; this is safe as long asgetOrganizationFromApiKeyguarantees 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.
There was a problem hiding this comment.
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
anyfor 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 (
!) onorganizationIdsuggests it could be null, but the code already handles this througherrorResponse. 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
📒 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(); |
There was a problem hiding this comment.
🛠️ 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.
| 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 } | |
| ); | |
| } |
#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>
Summary by CodeRabbit
New Features
Documentation