Skip to content

Conversation

@UlisesGascon
Copy link
Member

@UlisesGascon UlisesGascon commented May 3, 2025

closes #232

Summary by CodeRabbit

  • New Features

    • Added OpenAPI documentation for the VisionBoard API, including health check and report generation endpoints, accessible at /api/docs.
    • Integrated Swagger validation middleware for API request and response validation.
  • Chores

    • Introduced a test environment configuration for database and server setup.
    • Updated Playwright test scripts to run in test mode and set environment variables accordingly.
    • Added the swagger-endpoint-validator dependency.
  • Refactor

    • Improved server initialization and shutdown logic for more robust startup, graceful shutdown, and connection handling.

@UlisesGascon UlisesGascon self-assigned this May 3, 2025
@coderabbitai
Copy link

coderabbitai bot commented May 3, 2025

Walkthrough

This change introduces Swagger/OpenAPI support to the project. It adds a new OpenAPI 3.0 specification file for the VisionBoard API, defines endpoints for health and report generation, and integrates Swagger validation middleware into the HTTP server. The server initialization logic is refactored to support Swagger, including request and response validation, Swagger UI, and logging of the Swagger docs URL. The configuration is updated to support a test environment, and Playwright test scripts are set to use NODE_ENV=test. A new dependency, swagger-endpoint-validator, is added.

Changes

Files/Group Change Summary
src/httpServer/index.js Refactored server initialization; integrated Swagger validation middleware; improved start/stop logic and logging.
src/httpServer/swagger/api-v1.yml Added new OpenAPI 3.0 specification file defining /api/v1/__health and /api/v1/generate-reports endpoints.
knexfile.js Added test environment configuration referencing dbSettings.
package.json Added swagger-endpoint-validator dependency; set NODE_ENV=test for Playwright test scripts.
playwright.config.js Set NODE_ENV: 'test' in Playwright's local server environment configuration.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant ExpressApp
    participant SwaggerValidator
    participant APIHandler

    Client->>ExpressApp: HTTP Request to /api/v1/*
    ExpressApp->>SwaggerValidator: Validate request/response (strict mode)
    SwaggerValidator-->>ExpressApp: Pass/fail validation
    ExpressApp->>APIHandler: Route to endpoint handler
    APIHandler-->>ExpressApp: Response
    ExpressApp-->>Client: HTTP Response
Loading

Assessment against linked issues

Objective Addressed Explanation
Install swagger dependencies (middleware) (#232)
Limit the swagger validation to the api endpoints and ignore the rest (website and admin UI) (#232)
Ensure that the middleware is validating requests and responses in strict mode (#232)
Include a log message with a direct link to the Swagger UI url (#232)
Enable Swagger UI Mode (#232)

Possibly related PRs

Poem

In a warren of code, a Swagger appeared,
Endpoints described, the docs crystal clear.
Now rabbits can test, with NODE_ENV set,
Health checks and reports, no bugs to regret.
With specs and with logs, our tails wag with glee—
For the VisionBoard API, as neat as can be!
🐇✨


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between f33ff31 and 81ee8cb.

📒 Files selected for processing (1)
  • src/httpServer/index.js (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/httpServer/index.js
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Playwright Tests
✨ Finishing Touches
  • 📝 Generate Docstrings

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

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 generate sequence diagram to generate a sequence diagram of the changes in 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.

@UlisesGascon UlisesGascon added this to the v1.0.0 milestone May 3, 2025
@UlisesGascon UlisesGascon requested a review from Copilot May 3, 2025 14:48
@socket-security
Copy link

socket-security bot commented May 3, 2025

Review the following changes in direct dependencies. Learn more about Socket for GitHub.

Diff Package Supply Chain
Security
Vulnerability Quality Maintenance License
Addedswagger-endpoint-validator@​4.1.0741008882100

View full report

This comment was marked as resolved.

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

🧹 Nitpick comments (5)
src/httpServer/swagger/api-v1.yml (2)

34-34: Remove trailing whitespace.

There are trailing spaces on this line that should be removed.

-  
+
🧰 Tools
🪛 YAMLlint (1.35.1)

[error] 34-34: trailing spaces

(trailing-spaces)


93-93: Add newline at end of file.

Add a newline character at the end of the file to comply with YAML best practices.

 components:
   schemas: {}
+
🧰 Tools
🪛 YAMLlint (1.35.1)

[error] 93-93: no new line character at the end of file

(new-line-at-end-of-file)

src/httpServer/index.js (3)

11-12: Pin the Swagger validator version to avoid unintended breaking changes
swagger-endpoint-validator is imported without an explicit semver range. Because the library is still < 1.0 (and even minor bumps may contain breaking API changes), pulling latest on every CI run can introduce non-deterministic production builds.

-    "swagger-endpoint-validator": "*"
+    "swagger-endpoint-validator": "1.4.3"   // example, replace with the version you’ve tested against

Locking the dependency (or using a caret for a known-good major version) keeps builds reproducible and shields you from surprise validator failures.


51-55: icons is not a recognised option for serve-static
serve-static silently ignores unknown options; the icons flag only exists in serve-index. Keeping it here may confuse future maintainers.

-  app.use('/assets', serveStatic(publicPath, {
-    index: false,
-    dotfiles: 'deny',
-    icons: true
-  }))
+  app.use('/assets', serveStatic(publicPath, {
+    index: false,
+    dotfiles: 'deny'
+  }))

If directory listings with icons are desired, layer serve-index instead.


58-64: Prevent ERR_HTTP_HEADERS_SENT when the error handler is invoked late
If an error bubbles up after the response headers were already flushed, writing a second status line will crash the process. Safeguard with res.headersSent and delegate to Express’ default handler.

-  app.use((err, req, res, next) => {
-    logger.error(`Server error: ${err.message}`, { stack: err.stack })
-    res.status(500).json({
-      error: 'Internal Server Error',
-      message: 'Check server logs for more details'
-    })
-  })
+  app.use((err, req, res, next) => {
+    logger.error(`Server error: ${err.message}`, { stack: err.stack })
+    if (res.headersSent) return next(err)
+    res.status(500).json({
+      error: 'Internal Server Error',
+      message: 'Check server logs for more details'
+    })
+  })

This avoids double-send crashes and still preserves the clean JSON error format.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between ce7da38 and f33ff31.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (5)
  • knexfile.js (1 hunks)
  • package.json (2 hunks)
  • playwright.config.js (1 hunks)
  • src/httpServer/index.js (3 hunks)
  • src/httpServer/swagger/api-v1.yml (1 hunks)
🧰 Additional context used
🧠 Learnings (1)
playwright.config.js (1)
Learnt from: UlisesGascon
PR: OpenPathfinder/visionBoard#233
File: playwright.config.js:59-59
Timestamp: 2025-05-03T07:11:12.696Z
Learning: In the visionBoard repository, the team has deliberately chosen to run Playwright tests without explicitly setting NODE_ENV=test in the webServer command, as part of a change that implements automatic database migrations on server start.
🧬 Code Graph Analysis (2)
knexfile.js (1)
src/config/index.js (1)
  • dbSettings (3-22)
src/httpServer/index.js (3)
server.js (2)
  • server (1-1)
  • serverInstance (4-4)
src/utils/index.js (1)
  • logger (16-35)
src/config/index.js (1)
  • staticServer (28-31)
🪛 YAMLlint (1.35.1)
src/httpServer/swagger/api-v1.yml

[error] 34-34: trailing spaces

(trailing-spaces)


[error] 93-93: no new line character at the end of file

(new-line-at-end-of-file)

🔇 Additional comments (7)
knexfile.js (1)

6-7: LGTM! Good addition of a test environment configuration.

Adding a dedicated test environment configuration is a good practice that helps separate test and development environments. This change ensures the database settings are consistent when the application runs in test mode.

package.json (2)

24-28: Good practice: Consistent NODE_ENV=test setting for all test scripts.

Setting NODE_ENV=test for all Playwright test scripts ensures a consistent testing environment and aligns with the test configuration added in knexfile.js.


65-65: LGTM! Appropriate dependency addition for Swagger integration.

The swagger-endpoint-validator package is correctly added to dependencies with a proper semver range (^4.1.0) to support the Swagger documentation and validation features.

playwright.config.js (1)

63-66: Potential inconsistency with prior team decision.

This change sets NODE_ENV=test in the webServer configuration, which is consistent with the updated test scripts in package.json. However, a previous learning indicates the team deliberately chose not to set NODE_ENV=test in the webServer command in PR #233.

Can you clarify if this change intentionally overrides the previous decision to not set NODE_ENV in the webServer configuration? If this is intentional, consider documenting the reason for the change.

src/httpServer/swagger/api-v1.yml (3)

1-6: Well-structured OpenAPI specification with proper metadata.

The OpenAPI 3.0 specification includes appropriate metadata with title, description, and version information for the VisionBoard API.


8-33: Good implementation of health check endpoint.

The health check endpoint is well-defined with clear descriptions, appropriate tags, and a properly structured response schema that includes status and timestamp fields.


35-90: Well-structured report generation endpoint with proper response handling.

The report generation endpoint is well-documented with appropriate descriptions, tags, and distinct response schemas for success (202) and failure (500) scenarios. The schemas properly define required fields and use appropriate data types and formats.

- Ignores the Swagger-UI assets in the validation
- Add body-parsing middleware before Swagger & routers
- Prevent `ERR_HTTP_HEADERS_SENT` when the error handler is invoked late
- icons is not an option for `serve-static`
@UlisesGascon UlisesGascon merged commit 424ae8c into main May 3, 2025
7 checks passed
@UlisesGascon UlisesGascon deleted the ulises/232 branch May 3, 2025 15:09
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

Add support for swagger

2 participants