Skip to content

Conversation

@UlisesGascon
Copy link
Member

@UlisesGascon UlisesGascon commented Jun 15, 2025

Related #216

image

Summary by CodeRabbit

  • New Features
    • Introduced a new API endpoint to create projects via POST requests, with validation and conflict handling.
    • Added comprehensive API documentation for the new project creation endpoint and its responses.
  • Bug Fixes
    • Enhanced test reliability by resetting the database state before each test and clearing mocks after each test.
  • Chores
    • Added the "lodash" library as a new dependency.
  • Tests
    • Expanded test coverage for the new project creation endpoint, including successful creation, validation errors, and conflict scenarios.

@UlisesGascon UlisesGascon self-assigned this Jun 15, 2025
@coderabbitai
Copy link

coderabbitai bot commented Jun 15, 2025

Walkthrough

A new POST /api/v1/project endpoint was implemented to create projects, with input validation, conflict checks, and error handling. The OpenAPI spec and data store were updated to support project creation and lookup by name. Comprehensive tests for the new endpoint were added, and the lodash dependency was introduced.

Changes

File(s) Change Summary
src/httpServer/routers/apiV1.js Added POST /project endpoint for project creation with validation, conflict detection, and error handling.
src/httpServer/swagger/api-v1.yml Documented new POST /api/v1/project endpoint and introduced a detailed Project schema and error schemas.
src/store/index.js Added getProjectByName function and exposed it via initializeStore.
tests/httpServer/apiV1.test.js Added tests for POST /api/v1/project covering success, validation, conflict, and error scenarios; test setup/teardown enhanced with DB reset and mocks clearing.
package.json Added "lodash": "^4.17.21" to dependencies.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant API_Router
    participant Store
    participant DB

    Client->>API_Router: POST /api/v1/project { name }
    API_Router->>Store: getProjectByName(name)
    Store->>DB: SELECT * FROM projects WHERE name = ?
    DB-->>Store: project or null
    Store-->>API_Router: project or null
    alt project exists
        API_Router-->>Client: 409 Conflict
    else invalid name
        API_Router-->>Client: 400 Bad Request
    else valid and unique
        API_Router->>Store: addProject({ name, ... })
        Store->>DB: INSERT INTO projects ...
        DB-->>Store: new project
        Store-->>API_Router: new project
        API_Router-->>Client: 201 Created + Location header + project JSON
    end
    alt unexpected error
        API_Router-->>Client: 500 Internal Server Error
    end
Loading

Poem

In the garden of code, a new seed’s been sown,
POST a project, and watch it be grown.
With checks for a name, and conflicts denied,
The store now finds by name, far and wide.
Swagger sings of the new API delight—
The rabbit hops on, coding through the night! 🐇

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

@UlisesGascon UlisesGascon force-pushed the ulises/v1-create-project branch from 74f0f2e to e17a443 Compare June 15, 2025 14:16
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: 3

🔭 Outside diff range comments (1)
src/store/index.js (1)

46-60: 🛠️ Refactor suggestion

Race-condition risk when checking duplicates – add a DB uniqueness constraint

getProjectByName + the pre-insert duplicate check in addProject run outside a transaction.
Two concurrent requests with the same slug can still slip through and hit the INSERT, causing a duplicate row (or whichever wins last).

Hard-lock it at the persistence layer:

-- create table projects ( ...
-   name text not null,
+-- add a UNIQUE constraint so the DB enforces slug uniqueness
+   name text not null UNIQUE,

Then in code, rely on catching the database error:

-  const projectExists = await knex('projects').where({ name }).first()
-  if (projectExists) {
-    throw new Error(`Project with name (${name}) already exists`)
-  }
-  return knex('projects').insert(project).returning('*').then(r => r[0])
+  try {
+    return await knex('projects').insert(project).returning('*').then(r => r[0])
+  } catch (err) {
+    if (err.code === '23505') { // unique_violation in Postgres
+      throw new Error(`Project with name (${name}) already exists`)
+    }
+    throw err
+  }

This removes the timing window and the extra SELECT.

🧹 Nitpick comments (4)
src/store/index.js (1)

250-252: Minor: expose getProjectByName via same “getter” style

Other getters are anonymous wrappers: getProjectById: (id) => getOne('projects', id).
For consistency you could mirror that style:

-    getProjectByName: getProjectByName(knex)
+    getProjectByName: (name) => getProjectByName(knex)(name)

Not blocking – just stylistic.

src/httpServer/routers/apiV1.js (1)

21-26: Double validation: kebabCase may mask bad input

_.kebabCase('Invalid Name!') becomes invalid-name, which passes isSlug, so the later 400 branch is never hit.
OpenAPI validation already rejects bad patterns before we reach the handler. Consider:

  • Remove the in-handler slug check (keep OpenAPI as single source of truth), or
  • Validate the raw name before transforming.

Keeps behaviour predictable.

__tests__/httpServer/apiV1.test.js (1)

83-95: Test too brittle – asserts entire OpenAPI error payload

The exact shape of the validation error object is owned by swagger-endpoint-validator; a minor lib upgrade will break this test without a code change.

Prefer partial matching:

-      expect(response.body).toStrictEqual({ errors: [...] })
+      expect(response.body).toHaveProperty('errors')
+      expect(response.body.errors[0]).toMatchObject({
+        errorCode: 'pattern.openapi.validation',
+        path: '/body/name'
+      })

Keeps intent while future-proofing.

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

290-290: YAML lint: add trailing newline

The file lacks a terminating newline, flagged by yamllint.

@@
-        - updated_at
\ No newline at end of file
+        - updated_at
+
🧰 Tools
🪛 YAMLlint (1.37.1)

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

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

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 68ec9d0 and e17a443.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (5)
  • __tests__/httpServer/apiV1.test.js (3 hunks)
  • package.json (1 hunks)
  • src/httpServer/routers/apiV1.js (1 hunks)
  • src/httpServer/swagger/api-v1.yml (2 hunks)
  • src/store/index.js (2 hunks)
🧰 Additional context used
🪛 YAMLlint (1.37.1)
src/httpServer/swagger/api-v1.yml

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

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

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

♻️ Duplicate comments (1)
src/httpServer/swagger/api-v1.yml (1)

88-93: Align error response examples with schema
Provide consistent example blocks for the 400, 409, and 500 responses that match the ErrorResponse structure (an errors array of ErrorObject).

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

58-63: Enhance request schema with descriptions
Consider adding a description for the name property to clarify that it must be a slug (alphanumeric, dash, underscore) and optionally include a minLength: 1 constraint to forbid empty strings.


65-75: Include response examples for 201
It’s helpful to provide a concrete example under application/json for the 201 response so clients can see the exact Project payload shape.


76-93: Reorder HTTP response codes
For readability and consistency, sort the response codes in ascending order (400, 409, 500) instead of listing 400 last.


152-271: Consider refactoring policy flags into a nested object
The Project schema has a long flat list of nullable boolean policy fields. To improve maintainability and reduce verbosity, nest these under a single policies object or use patternProperties instead of enumerating each flag.


298-304: Set a maximum for the errors array
To adhere to array-size best practices (e.g., Checkov CKV_OPENAPI_21), consider adding a maxItems constraint (such as maxItems: 10) to the errors array in ErrorResponse.

🧰 Tools
🪛 Checkov (3.2.334)

[MEDIUM] 299-304: Ensure that arrays have a maximum number of items

(CKV_OPENAPI_21)


317-317: Add newline at end-of-file
YAML files should end with a single newline to satisfy linters like YAMLlint.

🧰 Tools
🪛 YAMLlint (1.37.1)

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

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

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e17a443 and 81e5cb1.

📒 Files selected for processing (3)
  • __tests__/httpServer/apiV1.test.js (3 hunks)
  • src/httpServer/routers/apiV1.js (1 hunks)
  • src/httpServer/swagger/api-v1.yml (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • tests/httpServer/apiV1.test.js
  • src/httpServer/routers/apiV1.js
🧰 Additional context used
🪛 Checkov (3.2.334)
src/httpServer/swagger/api-v1.yml

[MEDIUM] 299-304: Ensure that arrays have a maximum number of items

(CKV_OPENAPI_21)

🪛 YAMLlint (1.37.1)
src/httpServer/swagger/api-v1.yml

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

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

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Playwright Tests

@UlisesGascon UlisesGascon merged commit 35ee87b into main Jun 15, 2025
7 checks passed
@UlisesGascon UlisesGascon deleted the ulises/v1-create-project branch June 15, 2025 14:55
@UlisesGascon UlisesGascon added this to the v1.0.0 milestone Jun 16, 2025
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