Skip to content

Conversation

asharma991
Copy link

Date: 16/10/2024

Developer Name: Abhishek


Issue Ticket Number

#2209
#866

Description

This PR is to integrate swagger with the website-backend repo. I'm implementing it through the yaml files and I'm segregating them via common components and schemas

Documentation Updated?

  • Yes
  • No

Under Feature Flag

  • Yes
  • No

Database Changes

  • Yes
  • No

Breaking Changes

  • Yes
  • No

Development Tested?

  • Yes
  • No

Screenshots

image
image

Test Coverage

Screenshot 1

Additional Notes

@asharma991 asharma991 changed the title Swagger integration WIP: Swagger integration Oct 16, 2024
Copy link

coderabbitai bot commented May 13, 2025

Summary by CodeRabbit

  • New Features

    • Introduced interactive Swagger API documentation, accessible at /api-docs.
    • Comprehensive OpenAPI documentation now covers all backend API endpoints, including arts, auctions, authentication, badges, challenges, contributions, health checks, logs, members, and pull requests.
    • API documentation includes detailed request/response schemas, authentication requirements, and standardized error messages for improved clarity and usability.
  • Chores

    • Added new dependencies to support API documentation.

Walkthrough

Swagger/OpenAPI documentation has been integrated into the Express backend. The update adds the swagger-ui-express and yamljs dependencies, introduces a modular OpenAPI 3.0 specification (with components and route definitions in YAML), and mounts the Swagger UI at /api-docs. No existing API logic or exports were modified.

Changes

File(s) Change Summary
app.js Integrated Swagger UI middleware at /api-docs, loading OpenAPI spec from bundled.yaml using swagger-ui-express and yamljs.
package.json Added dependencies: swagger-ui-express (^5.0.1) and yamljs (^0.3.0). No other changes.
bundled.yaml Added a comprehensive OpenAPI 3.0 specification for the RDS Website Backend, defining all API endpoints, schemas, responses, and security requirements.
docs/swagger.yaml Introduced the main OpenAPI specification file referencing modular path and component definitions.
docs/components.yaml Added detailed OpenAPI component schemas for entities (Recruiter, Log, Auction, Art, etc.), error responses, and bearer authentication.
docs/routes/index.yaml Centralized index referencing all modular API route definition files for OpenAPI paths.
docs/routes/arts.yaml Defined OpenAPI endpoints for arts management: list, get by user, add new art.
docs/routes/auctions.yaml Defined OpenAPI endpoints for auctions: list, create, get by ID, bid.
docs/routes/auth.yaml Defined OpenAPI endpoints for authentication: GitHub login/callback, signout, QR code/device auth, update authorization status.
docs/routes/badges.yaml Defined OpenAPI endpoints for badges: list, create, assign, remove badges from users.
docs/routes/challenges.yaml Defined OpenAPI endpoints for challenges: list, create, subscribe to challenges.
docs/routes/contributions.yaml Defined OpenAPI endpoint for retrieving user contributions by username.
docs/routes/healthCheck.yaml Defined OpenAPI endpoints for health check: unauthenticated and authenticated variants.
docs/routes/logs.yaml Defined OpenAPI endpoints for logs: list all, filter by type, with pagination and authentication.
docs/routes/members.yaml Defined OpenAPI endpoints for member management: list members, idle members, recruiters, move/archive members.
docs/routes/pullrequests.yaml Defined OpenAPI endpoints for pull requests: list open, stale, and user-specific pull requests.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Browser
    participant ExpressApp
    participant SwaggerUI

    User->>Browser: Navigates to /api-docs
    Browser->>ExpressApp: GET /api-docs
    ExpressApp->>SwaggerUI: Serve Swagger UI with OpenAPI spec (bundled.yaml)
    SwaggerUI-->>Browser: Renders interactive API documentation
    Browser-->>User: Displays Swagger UI for API exploration
Loading

Poem

🐇
Swagger hops in, docs in tow,
YAML fields in tidy row.
Endpoints mapped, responses neat,
All our APIs now complete!
With /api-docs a breeze to see—
The backend’s story, clear as can be.
Hooray for docs, from rabbit and me!

Tip

⚡️ Faster reviews with caching
  • CodeRabbit now supports caching for code and dependencies, helping speed up reviews. This means quicker feedback, reduced wait times, and a smoother review experience overall. Cached data is encrypted and stored securely. This feature will be automatically enabled for all accounts on May 16th. To opt out, configure Review - Disable Cache at either the organization or repository level. If you prefer to disable all data retention across your organization, simply turn off the Data Retention setting under your Organization Settings.

Enjoy the performance boost—your workflow just got faster.

✨ Finishing Touches
  • 📝 Generate Docstrings

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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

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: 31

🔭 Outside diff range comments (6)
docs/swagger.yaml (1)

1-16: ⚠️ Potential issue

Add global security definitions to the OpenAPI specification.

The static analysis tool flagged a HIGH security issue (CKV_OPENAPI_4): The global security field is missing. This is important for defining default authentication requirements across all endpoints.

components:
  $ref: "./components.yaml#/components"

+security:
+  - bearerAuth: []
🧰 Tools
🪛 Checkov (3.2.334)

[HIGH] 1-17: Ensure that the global security field has rules defined

(CKV_OPENAPI_4)

docs/routes/logs.yaml (1)

47-90: 🛠️ Refactor suggestion

Unify response schema naming and add pagination support

The GET /logs/{type} endpoint:

  • Returns the logs array under logs, unlike the data field in GET /logs.
  • Lacks pagination query parameters despite offering next/prev links in the generic logs endpoint.

Please:

  1. Standardize the array property (logs vs. data) across all log endpoints.
  2. Include page and size query parameters if pagination is supported.
docs/routes/healthCheck.yaml (1)

27-59: 🧹 Nitpick (assertive)

Clarify summary for versioned health check

The summary for /healthcheck/v2 is identical to the unauthenticated endpoint. Consider updating the summary to reflect the authenticated nature of this version, e.g.:

summary: Returns the authenticated health status (v2) of the server
docs/routes/pullrequests.yaml (1)

87-119: ⚠️ Potential issue

Missing path parameter definition

GET /pullrequests/user/{username} does not define the username path parameter. You should include:

parameters:
  - in: path
    name: username
    required: true
    schema:
      type: string
    description: GitHub username

Without this, the endpoint will not render correctly in Swagger UI.

docs/routes/auctions.yaml (1)

112-176: 🛠️ Refactor suggestion

⚠️ Potential issue

Incorrect use of HTTP 204 with response body. The POST /auctions/bid/{id} endpoint also returns a body under a 204 status. Switch to 201 Created or eliminate the content section beneath 204 to comply with the spec.

docs/routes/auth.yaml (1)

231-270: 🛠️ Refactor suggestion

Missing security for authorization status update. Protect the PATCH /auth/qr-code-auth/authorization_status/{authorization_status} route by adding:

security:
  - bearerAuth: []

This ensures only authenticated users can change authorization status.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 72d59ef and 9e31442.

📒 Files selected for processing (16)
  • app.js (2 hunks)
  • bundled.yaml (1 hunks)
  • docs/components.yaml (1 hunks)
  • docs/routes/arts.yaml (1 hunks)
  • docs/routes/auctions.yaml (1 hunks)
  • docs/routes/auth.yaml (1 hunks)
  • docs/routes/badges.yaml (1 hunks)
  • docs/routes/challenges.yaml (1 hunks)
  • docs/routes/contributions.yaml (1 hunks)
  • docs/routes/healthCheck.yaml (1 hunks)
  • docs/routes/index.yaml (1 hunks)
  • docs/routes/logs.yaml (1 hunks)
  • docs/routes/members.yaml (1 hunks)
  • docs/routes/pullrequests.yaml (1 hunks)
  • docs/swagger.yaml (1 hunks)
  • package.json (1 hunks)
🧰 Additional context used
🪛 Checkov (3.2.334)
docs/swagger.yaml

[HIGH] 1-17: Ensure that the global security field has rules defined

(CKV_OPENAPI_4)

bundled.yaml

[HIGH] 1-2045: Ensure that the global security field has rules defined

(CKV_OPENAPI_4)


[HIGH] 1-2045: Ensure that security operations is not empty.

(CKV_OPENAPI_5)


[MEDIUM] 25-50: Ensure that arrays have a maximum number of items

(CKV_OPENAPI_21)

🔇 Additional comments (9)
package.json (1)

45-47: Appropriate dependencies added for Swagger integration.

The addition of swagger-ui-express and yamljs packages provides the necessary functionality to integrate and serve Swagger API documentation in the Express application. These dependencies are correctly placed in alphabetical order and use consistent versioning patterns.

app.js (1)

24-24: Appropriate Swagger UI setup.

The Swagger UI is correctly mounted at the "/api-docs" path with the explorer option enabled, providing an interactive interface for API documentation. The placement after application middlewares but before the 404 handler is appropriate.

docs/swagger.yaml (1)

11-15: Good modular structure for OpenAPI specification.

The modular approach using $ref to reference paths and components from separate files is a good practice. This improves maintainability by keeping the specification organized and easier to update.

docs/routes/contributions.yaml (1)

1-32: Well-structured OpenAPI route definition.

The endpoint is well-structured with appropriate tags, parameters, and response definitions. The use of references to common components for response schemas promotes reusability and consistency across the API documentation.

docs/routes/index.yaml (1)

1-66: API path index looks solid

The central routing index cleanly aggregates all modular route files with correct JSON Pointer escapes (~1) and relative paths. This will simplify maintenance and clarity when adding new endpoints.

docs/routes/healthCheck.yaml (1)

2-25: Looks good: unauthenticated health check

GET /healthcheck is properly documented without security and covers both 200 and 500 responses. The uptime schema is clear.

docs/routes/arts.yaml (1)

1-179: API spec for Arts routes is well-structured. All endpoints include appropriate tags, path definitions, response codes, and references to shared components. No issues detected.

bundled.yaml (2)

10-16: Review operation-level security consistency
Some endpoints (e.g., GET /arts) have no security declaration while others do. Please verify which routes should be public vs. protected and add or adjust security blocks accordingly.


16-20: 🧹 Nitpick (assertive)

Uniformly quote HTTP status codes
Response keys mix quoted and unquoted numeric codes (e.g., 200 vs. '404'). For YAML consistency and to avoid potential parsing issues, quote all status codes:

- 200:
+ '200':

Likely an incorrect or invalid review comment.

const app = express();

// Swagger config
const swaggerDocument = YAML.load("bundled.yaml");
Copy link

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 YAML loading.

The current implementation doesn't handle potential errors when loading the YAML file, which could cause the application to crash during startup if the file is missing or malformed.

// Swagger config
-const swaggerDocument = YAML.load("bundled.yaml");
+let swaggerDocument;
+try {
+  swaggerDocument = YAML.load("bundled.yaml");
+} catch (error) {
+  console.error("Error loading Swagger document:", error.message);
+  swaggerDocument = { info: { title: "API Documentation Unavailable", version: "1.0.0" } };
+}
📝 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 swaggerDocument = YAML.load("bundled.yaml");
// Swagger config
let swaggerDocument;
try {
swaggerDocument = YAML.load("bundled.yaml");
} catch (error) {
console.error("Error loading Swagger document:", error.message);
swaggerDocument = {
info: {
title: "API Documentation Unavailable",
version: "1.0.0"
}
};
}

💡 Verification agent

🧩 Analysis chain

Verify the path to the bundled.yaml file.

The Swagger document is loaded from "bundled.yaml" in the project root, but the OpenAPI specification files appear to be in the "docs/" directory. Ensure that:

  1. This file exists in the project root, or
  2. A build/bundling step creates this file, or
  3. The path should be updated to "docs/swagger.yaml" or similar

🏁 Script executed:

#!/bin/bash
# Check if bundled.yaml exists in the project root
if [ -f "bundled.yaml" ]; then
  echo "bundled.yaml exists in the project root"
else
  echo "bundled.yaml does not exist in the project root"
  echo "Checking for other YAML files that might be the intended target:"
  find . -name "*.yaml" | grep -v "node_modules"
fi

Length of output: 114


bundled.yaml path is valid; add error handling for YAML.load

  • The file bundled.yaml does exist at the project root, so the import path is correct.
  • To avoid runtime crashes or obscure errors if the YAML fails to parse, wrap the load call in a try/catch and handle failures explicitly.

Suggested change in app.js (at around line 19):

- const swaggerDocument = YAML.load("bundled.yaml");
+ let swaggerDocument;
+ try {
+   swaggerDocument = YAML.load("bundled.yaml");
+ } catch (err) {
+   console.error("Failed to load Swagger document from bundled.yaml:", err);
+   // Exit or fallback as appropriate
+   process.exit(1);
+ }

Comment on lines +2 to +5
info:
title: RDS Website Backend
version: 1.0.0
description: Documentation for the RDS Website Backend APIs
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Consider adding more API metadata.

The current info section is minimal. Consider adding additional metadata such as contact information, license, terms of service, or external documentation links to make the API documentation more comprehensive.

info:
  title: RDS Website Backend
  version: 1.0.0
  description: Documentation for the RDS Website Backend APIs
+  contact:
+    name: API Support
+    email: [email protected]
+    url: https://example.com/support
+  license:
+    name: MIT
+    url: https://opensource.org/licenses/MIT

Comment on lines +7 to +9
servers:
- url: "http://localhost:5000"
description: Local development server
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Enhance server configuration for multiple environments.

Currently, only a local development server is defined. Consider adding server URLs for other environments like staging and production to make the documentation more complete and useful across different environments.

servers:
  - url: "http://localhost:5000"
    description: Local development server
+  - url: "https://api-staging.example.com"
+    description: Staging server
+  - url: "https://api.example.com"
+    description: Production server
📝 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
servers:
- url: "http://localhost:5000"
description: Local development server
servers:
- url: "http://localhost:5000"
description: Local development server
- url: "https://api-staging.example.com"
description: Staging server
- url: "https://api.example.com"
description: Production server

Comment on lines +14 to +20
responses:
200:
description: Return contributions
content:
application/json:
schema:
$ref: "../components.yaml#/components/schemas/Contributions"
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Consider adding pagination parameters.

For endpoints returning potentially large collections of data, it's a good practice to include pagination parameters. This allows clients to control the amount of data returned and improves API performance.

      parameters:
        - in: path
          name: username
          schema:
            type: string
          required: true
          description: username of user
+        - in: query
+          name: page
+          schema:
+            type: integer
+            default: 1
+          required: false
+          description: Page number for pagination
+        - in: query
+          name: limit
+          schema:
+            type: integer
+            default: 10
+            maximum: 100
+          required: false
+          description: Number of contributions per page

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +3 to +6
get:
summary: Used to get all the contributions of user
tags:
- Contributions
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Enhance the endpoint documentation with more details.

The current summary is brief. Consider adding a more descriptive summary and a detailed description field to provide better context for API consumers. Also, consider specifying the security requirements for this endpoint.

  get:
    summary: Used to get all the contributions of user
+    description: Retrieves a comprehensive list of contributions made by the specified user, including details such as contribution type, timestamp, and associated projects.
    tags:
      - Contributions
+    security:
+      - bearerAuth: []
📝 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
get:
summary: Used to get all the contributions of user
tags:
- Contributions
get:
summary: Used to get all the contributions of user
description: Retrieves a comprehensive list of contributions made by the specified user, including details such as contribution type, timestamp, and associated projects.
tags:
- Contributions
security:
- bearerAuth: []

Comment on lines +85 to +103
/members/intro/{username}:
post:
summary: Adds a recruiter to the recruiters collection
description: Adds a recruiter to the recruiters collection
tags:
- Members
parameters:
- in: path
name: username
required: true
schema:
type: string
description: The username of the recruiter to be added to the intro list
requestBody:
required: true
content:
application/json:
schema:
$ref: "../components.yaml#/components/schemas/Recruiter"
Copy link

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Add security requirement to protect recruiter addition endpoint
The POST /members/intro/{username} operation is missing a security block. If this endpoint should be restricted to authenticated users, add:

security:
  - bearerAuth: []

to ensure only authorized clients can add recruiters.


🏁 Script executed:

#!/bin/bash
# Search for any existing security blocks in the OpenAPI docs
rg -n "security:" -C3 docs

Length of output: 6642


Add authentication to the recruiter-intro endpoint
The POST /members/intro/{username} operation in docs/routes/members.yaml is missing the standard security block. To align with the rest of your API (e.g., badges, members list, move/archival endpoints), insert the following under post: (around line 85), before parameters::

      security:
        - bearerAuth: []

Example diff:

   /members/intro/{username}:
     post:
       summary: Adds a recruiter to the recruiters collection
       description: Adds a recruiter to the recruiters collection
       tags:
         - Members
+      security:
+        - bearerAuth: []
       parameters:
         - in: path
           name: username

This ensures only authenticated clients can add recruiters.

Comment on lines +2 to +6
info:
title: RDS Website Backend
version: 1.0.0
description: Documentation for the RDS Website Backend APIs
servers:
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Enhance API metadata in the info section
Consider enriching your info block with termsOfService, contact, and license fields to provide clearer context and support details:

info:
  title: RDS Website Backend
  version: 1.0.0
+ termsOfService: https://example.com/terms/
+ contact:
+   name: API Support
+   url: https://example.com/support
+   email: [email protected]
+ license:
+   name: MIT
+   url: https://opensource.org/licenses/MIT

Comment on lines +1502 to +1504
type: string
desciption: message describing the status of the request
members:
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix typographical error in members schema
In the /members response, the message property uses desciption instead of description. Update it (and any similar instances) so Swagger will display the field description.

Comment on lines +24 to +28
arts:
type: array
items:
type: object
properties:
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Consider adding array size constraints
Unbounded arrays in responses (e.g., the arts list) may mislead clients about expected payload sizes. You can document maxItems (and minItems) to bound the array:

properties:
  arts:
    type: array
    items:
      $ref: '#/components/schemas/Art'
    maxItems: 1000

Comment on lines +1 to +8
openapi: 3.0.0
info:
title: RDS Website Backend
version: 1.0.0
description: Documentation for the RDS Website Backend APIs
servers:
- url: 'http://localhost:5000'
description: Local development server
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Define a global security requirement
To reduce repetition, you can add a top-level security field that applies bearerAuth by default to all operations. Public endpoints can then override with security: []. Example:

security:
  - bearerAuth: []
🧰 Tools
🪛 Checkov (3.2.334)

[HIGH] 1-2045: Ensure that the global security field has rules defined

(CKV_OPENAPI_4)


[HIGH] 1-2045: Ensure that security operations is not empty.

(CKV_OPENAPI_5)

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