Skip to content

Mock server - #20

Merged
Amir-Zouerami merged 6 commits into
mainfrom
mock-server
Nov 12, 2025
Merged

Amir-Zouerami merged 6 commits into
mainfrom
mock-server

Conversation

@Amir-Zouerami

@Amir-Zouerami Amir-Zouerami commented Nov 12, 2025

Copy link
Copy Markdown
Owner

Summary by CodeRabbit

  • New Features

    • Added a mock server that returns generated API responses for all HTTP methods based on project specs.
    • Added a diagnostics health-check endpoint.
  • Chores

    • Enforced a lint rule requiring content definitions for successful (2xx/3xx) responses.
    • Added mock-friendly schema tooling and dependencies to improve generated sample data.
    • Introduced runtime test config to allow transformation of specific packages during testing.

@Amir-Zouerami Amir-Zouerami self-assigned this Nov 12, 2025
@coderabbitai

coderabbitai Bot commented Nov 12, 2025

Copy link
Copy Markdown
Contributor

Caution

Review failed

The pull request is closed.

Walkthrough

Adds a mock-server feature that generates runtime responses from OpenAPI specs, Spectral linting for success responses, ApiLinting integration for endpoint operations, new exceptions, tests, package/jest changes for faker/json-schema-faker, and seed/schema updates for x-faker-driven mocking.

Changes

Cohort / File(s) Summary
Mock Server Core
src/mock-server/mock-server.service.ts, src/mock-server/mock-server.controller.ts, src/mock-server/mock-server.module.ts, src/mock-server/mock-server.service.spec.ts
New MockServerModule with controller that routes catch-all /mock requests (JWT guarded) and MockServerService that locates operations in a project's dereferenced OpenAPI spec, selects responses (status-code selection/fallbacks), extracts JSON schema, and generates locale-aware mock bodies via JSONSchemaFaker + Faker. Includes unit test scaffold.
Mock Server Exceptions
src/mock-server/exceptions/mock-endpoint-not-found.exception.ts, src/mock-server/exceptions/mock-response-not-found.exception.ts, src/mock-server/exceptions/mock-generation-conflict.exception.ts
Three new exception classes (MockEndpointNotFoundException, MockResponseNotFoundException, MockGenerationConflictException) extending BaseAppException with specific messages, HTTP statuses, and error codes.
Spectral Linting
.spectral.yaml
Adds success-response-content-defined Spectral rule enforcing that 2xx/3xx success responses (excluding 204/205) define a content object or $ref; severity set to error and recommended.
Endpoint Linting Integration
src/projects/endpoints/endpoints.service.ts, src/projects/endpoints/endpoints.module.ts, src/projects/endpoints/endpoints.service.spec.ts
EndpointsService now injects ApiLintingService and runs a private lintOperation (builds minimal OpenAPI object and validates operation) before create/update; EndpointsModule imports ApiLintingModule; test updated to provide mock ApiLintingService.
Module Integration & Exports
src/app.module.ts, src/projects/projects.module.ts
AppModule imports/registers MockServerModule; ProjectsModule now exports ProjectsService via @Module.exports.
Seed & Test Configuration / Dependencies
prisma/seed.ts, package.json, test/jest-e2e.json
Seed reworked for mocking (x-faker hints, response schemas, new POST /users, diagnostics endpoint); added runtime deps @faker-js/faker, json-schema-faker, path-to-regexp and dev type @types/json-schema-faker; Jest configs (package.json and jest-e2e.json) updated transformIgnorePatterns to allow transpile of specific packages.
Minor Formatting
src/auth/auth.service.spec.ts
Small import-line formatting change (removed inline comment).

Sequence Diagram(s)

sequenceDiagram
    participant C as Client
    participant Ctrl as MockServerController
    participant Svc as MockServerService
    participant PS as ProjectsService
    participant AC as AccessControlService
    participant JSF as JSONSchemaFaker+Faker

    C->>Ctrl: request /mock/… (method, headers: x-mock-project-id, x-mock-status-code, x-mock-locale)
    Ctrl->>Svc: generateMockResponse(projectId, method, path, user, status, locale)
    Svc->>AC: verify access(user, projectId)
    AC-->>Svc: allowed/denied
    Svc->>PS: get dereferenced OpenAPI spec(projectId)
    PS-->>Svc: spec
    Svc->>Svc: match operation(method, path)
    Svc->>Svc: select response (requested or fallback)
    Svc->>Svc: extract application/json schema (or $ref)
    Svc->>JSF: generate mock body(schema, locale)
    JSF-->>Svc: mock body
    Svc-->>Ctrl: { status, body }
    Ctrl->>C: HTTP response (status + body) / or throws mapped exception
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~50 minutes

  • Pay special attention to:
    • src/mock-server/mock-server.service.ts — spec dereferencing, operation matching (path param normalization), response selection and fallback rules, locale handling, and all error-to-exception mappings.
    • .spectral.yaml rule correctness (pattern matching 2xx/3xx and exclusion of 204/205) and integration with ApiLinting flow.
    • prisma/seed.ts changes for x-faker usage and response schema consistency.
    • Jest transformIgnorePatterns and added dependencies for test-time transpilation.

Possibly related PRs

Poem

🐇 I hop through specs with glee,

Faker seeds a mock-filled tree,
Paths align and responses play,
Locale whispers guide the way,
Hop, little mock — serve joy today! 🎈

Pre-merge checks and finishing touches

❌ Failed checks (1 inconclusive)
Check name Status Explanation Resolution
Title check ❓ Inconclusive The title 'Mock server' is overly generic and does not clearly summarize the main changes in the pull request, which involves adding mock response generation capabilities with multiple supporting components. Consider using a more specific title like 'Add mock server with response generation' or 'Implement mock server module for API endpoint mocking' to better convey the scope of changes.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

📜 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 f6dc294 and 324cddd.

📒 Files selected for processing (4)
  • .spectral.yaml (1 hunks)
  • prisma/seed.ts (10 hunks)
  • src/mock-server/mock-server.controller.ts (1 hunks)
  • src/mock-server/mock-server.service.ts (1 hunks)

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

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 6

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 35c3edf and f6dc294.

⛔ Files ignored due to path filters (1)
  • bun.lock is excluded by !**/*.lock
📒 Files selected for processing (17)
  • .spectral.yaml (1 hunks)
  • package.json (4 hunks)
  • prisma/seed.ts (10 hunks)
  • src/app.module.ts (2 hunks)
  • src/auth/auth.service.spec.ts (1 hunks)
  • src/mock-server/exceptions/mock-endpoint-not-found.exception.ts (1 hunks)
  • src/mock-server/exceptions/mock-generation-conflict.exception.ts (1 hunks)
  • src/mock-server/exceptions/mock-response-not-found.exception.ts (1 hunks)
  • src/mock-server/mock-server.controller.ts (1 hunks)
  • src/mock-server/mock-server.module.ts (1 hunks)
  • src/mock-server/mock-server.service.spec.ts (1 hunks)
  • src/mock-server/mock-server.service.ts (1 hunks)
  • src/projects/endpoints/endpoints.module.ts (1 hunks)
  • src/projects/endpoints/endpoints.service.spec.ts (3 hunks)
  • src/projects/endpoints/endpoints.service.ts (6 hunks)
  • src/projects/projects.module.ts (1 hunks)
  • test/jest-e2e.json (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (8)
src/mock-server/mock-server.module.ts (2)
src/app.module.ts (1)
  • Module (37-117)
src/projects/projects.module.ts (1)
  • Module (18-40)
src/mock-server/exceptions/mock-response-not-found.exception.ts (1)
src/common/exceptions/base-app.exception.ts (1)
  • BaseAppException (3-15)
src/mock-server/mock-server.controller.ts (3)
src/types/fastify.d.ts (1)
  • FastifyRequest (16-24)
src/auth/decorators/current-user.decorator.ts (1)
  • CurrentUser (7-10)
src/auth/dto/user.dto.ts (1)
  • UserDto (6-40)
src/mock-server/exceptions/mock-generation-conflict.exception.ts (1)
src/common/exceptions/base-app.exception.ts (1)
  • BaseAppException (3-15)
src/projects/endpoints/endpoints.service.ts (2)
src/common/constants/http.constants.ts (1)
  • VALID_HTTP_METHODS (6-15)
src/common/exceptions/spec-linting.exception.ts (1)
  • SpecLintingException (12-28)
src/mock-server/mock-server.service.ts (6)
src/auth/dto/user.dto.ts (1)
  • UserDto (6-40)
src/common/exceptions/project-not-found.exception.ts (1)
  • ProjectNotFoundException (4-12)
src/mock-server/exceptions/mock-endpoint-not-found.exception.ts (1)
  • MockEndpointNotFoundException (4-12)
src/mock-server/exceptions/mock-response-not-found.exception.ts (1)
  • MockResponseNotFoundException (4-12)
src/mock-server/exceptions/mock-generation-conflict.exception.ts (1)
  • MockGenerationConflictException (4-12)
src/common/constants/http.constants.ts (1)
  • VALID_HTTP_METHODS (6-15)
src/mock-server/exceptions/mock-endpoint-not-found.exception.ts (1)
src/common/exceptions/base-app.exception.ts (1)
  • BaseAppException (3-15)
src/projects/endpoints/endpoints.module.ts (2)
src/app.module.ts (1)
  • Module (37-117)
src/projects/projects.module.ts (1)
  • Module (18-40)
🔇 Additional comments (1)
src/auth/auth.service.spec.ts (1)

3-3: Good cleanup.

Removing the inline comment from the import statement improves code cleanliness without any functional impact.

Comment thread .spectral.yaml Outdated
Comment thread prisma/seed.ts Outdated
Comment on lines +24 to +31
@ApiParam({
name: 'projectId',
description: 'The ID of the project to generate a mock response for.',
})
@ApiParam({
name: '*',
description: 'The API path to mock (e.g., "users/123/profile").',
})

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Fix inaccurate Swagger path parameter definition

This route never declares a projectId path segment—the wildcard * captures the entire downstream path, while the controller reads the project ID from the x-mock-project-id header. Documenting a projectId path parameter causes generated clients (and humans) to send requests like /mock/{projectId}/users, which makes mockPath resolve to '123/users' and the service look up /123/users, inevitably triggering MockEndpointNotFoundException. Either remove this param from the Swagger docs or actually add a :projectId segment and adjust the handler accordingly; as written, it’s a user-facing correctness bug.

Apply this diff if the project ID is meant to stay in the header:

-	@ApiParam({
-		name: 'projectId',
-		description: 'The ID of the project to generate a mock response for.',
-	})
🤖 Prompt for AI Agents
In src/mock-server/mock-server.controller.ts around lines 24 to 31, remove the
incorrect @ApiParam describing a path-level projectId (it doesn't exist in the
route) and instead document the X header used to convey the project ID: delete
the @ApiParam block for name 'projectId' and add an @ApiHeader (name:
'x-mock-project-id', description: 'Project ID used to select mock data',
required: true) so Swagger clients are informed the project ID is passed via
header while keeping the wildcard path param for the downstream route.

Comment thread src/mock-server/mock-server.service.ts
Comment thread src/mock-server/mock-server.service.ts
Comment thread src/mock-server/mock-server.service.ts
@Amir-Zouerami
Amir-Zouerami merged commit 5530a42 into main Nov 12, 2025
1 check passed
@Amir-Zouerami
Amir-Zouerami deleted the mock-server branch November 12, 2025 19:00
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