Skip to content

feat: add Zod request validation for API endpoints#84

Merged
TytaniumDev merged 4 commits intomainfrom
feat/zod-request-validation
Feb 27, 2026
Merged

feat: add Zod request validation for API endpoints#84
TytaniumDev merged 4 commits intomainfrom
feat/zod-request-validation

Conversation

@TytaniumDev
Copy link
Owner

Summary

  • Add zod v3 dependency for runtime request validation
  • Create api/lib/validation.ts with schemas for:
    • createJobSchema — POST /api/jobs (deckIds, simulations, parallelism)
    • updateSimulationSchema — PATCH /api/jobs/:id/simulations/:simId
    • updateJobSchema — PATCH /api/jobs/:id
  • Add parseBody(schema, body) helper with formatted error messages
  • Replace manual validation in 3 route files with schema validation
  • Add 17 validation unit tests

Behavior change: Invalid parallelism values now return 400 instead of being silently ignored.

Addresses architecture issue #3 from docs/ARCHITECTURE_ISSUES.md.

Test plan

  • Valid POST /api/jobs bodies pass validation
  • Invalid deckIds count returns 400
  • Invalid simulations range returns 400
  • Invalid parallelism returns 400 (was silently ignored)
  • Invalid simulation states return 400
  • Invalid job statuses return 400
  • npm run lint --prefix api passes
  • npm run build --prefix api passes
  • All existing + new unit tests pass

🤖 Generated with Claude Code

Add zod v3 schemas for runtime request validation at API system boundaries.
This prevents malformed payloads (e.g. from Pub/Sub redelivery) from
reaching business logic and provides clear, structured error messages.

Changes:
- Install zod@3 dependency
- Create api/lib/validation.ts with schemas:
  - createJobSchema (POST /api/jobs): deckIds, simulations, parallelism
  - updateSimulationSchema (PATCH /api/jobs/:id/simulations/:simId)
  - updateJobSchema (PATCH /api/jobs/:id)
  - parseBody() helper with formatted error messages
- Replace manual validation in 3 route files with schema validation
- Add 17 validation unit tests in api/lib/validation.test.ts
- Add validation tests to test:unit script chain

Behavior change: invalid parallelism values now return 400 instead of
being silently ignored.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
@gemini-code-assist
Copy link

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request significantly enhances the API's robustness and maintainability by introducing Zod for schema-based request validation. By centralizing validation logic and removing boilerplate from individual route handlers, it improves code clarity, reduces the likelihood of validation bugs, and provides more consistent and informative error responses to clients. This change addresses a documented architectural issue by standardizing how incoming data is validated.

Highlights

  • Zod Integration: Integrated the zod library for robust runtime request validation across key API endpoints.
  • Centralized Validation: Created api/lib/validation.ts to house Zod schemas for createJob, updateSimulation, and updateJob requests, along with a parseBody helper function for consistent error handling.
  • Refactored API Endpoints: Replaced manual validation logic in POST /api/jobs, PATCH /api/jobs/:id, and PATCH /api/jobs/:id/simulations/:simId routes with the new Zod-based validation.
  • Enhanced Error Handling: Invalid request bodies now return standardized 400 Bad Request responses with detailed error messages generated by Zod.
  • New Unit Tests: Added 17 dedicated unit tests in api/lib/validation.test.ts to ensure the correctness and coverage of the new validation schemas.
  • Behavior Change: Invalid parallelism values in job creation requests now correctly trigger a 400 error instead of being silently ignored.
Changelog
  • api/app/api/jobs/[id]/route.ts
    • Imported parseBody and updateJobSchema for Zod validation.
    • Replaced manual job status validation with updateJobSchema.
  • api/app/api/jobs/[id]/simulations/[simId]/route.ts
    • Imported parseBody and updateSimulationSchema for Zod validation.
    • Removed manual simulation state validation and VALID_STATES constant.
    • Replaced manual state validation with updateSimulationSchema.
  • api/app/api/jobs/route.ts
    • Imported parseBody and createJobSchema for Zod validation.
    • Removed manual validation for deckIds, simulations, and parallelism.
    • Adjusted rate limiting to use validated simulations value.
    • Simplified parallelism assignment in job creation.
  • api/lib/validation.test.ts
    • Added a new file containing comprehensive unit tests for createJobSchema, updateSimulationSchema, and updateJobSchema.
  • api/lib/validation.ts
    • Added a new file defining Zod schemas for createJob, updateSimulation, and updateJob API requests.
    • Implemented a generic parseBody helper function for schema validation and formatted error messages.
  • api/package-lock.json
    • Added zod as a new dependency.
  • api/package.json
    • Added zod to project dependencies.
    • Updated the test:unit script to include the new validation tests.
    • Added a dedicated test:validation script.
Activity
  • The author has confirmed that valid POST /api/jobs bodies pass validation.
  • The author has confirmed that invalid deckIds count returns a 400 error.
  • The author has confirmed that invalid simulations range returns a 400 error.
  • The author has confirmed that invalid parallelism now returns a 400 error (previously silently ignored).
  • The author has confirmed that invalid simulation states return a 400 error.
  • The author has confirmed that invalid job statuses return a 400 error.
  • The author has verified that npm run lint --prefix api passes.
  • The author has verified that npm run build --prefix api passes.
  • The author has verified that all existing and new unit tests pass.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request is a great improvement, introducing zod for robust request validation across several API endpoints. By replacing manual checks with declarative schemas in api/lib/validation.ts, the route handlers in api/app/api/jobs/ are now cleaner and more maintainable. The addition of a comprehensive suite of unit tests in api/lib/validation.test.ts ensures the new validation logic is correct and reliable. I have a couple of minor suggestions to further refine the new validation helper and its tests, which should be addressed immediately as per repository guidelines.

simulations: 8,
});
assertEqual(result.success, false, 'should fail');
if (!result.success) assert(result.error.includes('4'), 'error should mention 4');

Choose a reason for hiding this comment

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

medium

This test assertion is a bit weak, as result.error.includes('4') could potentially match other parts of an error string, not just the expected deck count. To make the test more robust and prevent future regressions in user-facing error messages, it's better to assert against the exact error string.

Suggested change
if (!result.success) assert(result.error.includes('4'), 'error should mention 4');
if (!result.success) assertEqual(result.error, 'deckIds: Exactly 4 deckIds are required', 'error message should be specific');
References
  1. This comment suggests a code quality improvement (more robust test assertion) that should be addressed immediately, aligning with the rule to not defer valid code quality suggestions.

Comment on lines 67 to 68
const messages = result.error.issues.map(i => `${i.path.join('.')}: ${i.message}`).filter(Boolean);
return { success: false, error: messages.join('; ') || 'Invalid request body' };

Choose a reason for hiding this comment

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

medium

The current error message formatting for Zod issues without a specific path (e.g., from .refine()) will produce a leading colon, like ': Invalid input'. This can be slightly confusing for API consumers. We can adjust the logic to omit the colon when there's no path. This change also removes the redundant .filter(Boolean) as Zod issues always contain a message.

  const messages = result.error.issues.map(
    (i) => (i.path.length > 0 ? `${i.path.join('.')}: ` : '') + i.message
  );
  return { success: false, error: messages.join('; ') || 'Invalid request body' };
References
  1. This comment suggests a code quality improvement (better error message formatting for API consumers) that should be addressed immediately, aligning with the rule to not defer valid code quality suggestions.

TytaniumDev and others added 3 commits February 26, 2026 23:21
- Handle path-less Zod errors without leading colon
- Use exact string assertion for deckIds validation test

Addresses Gemini review feedback.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Resolve conflicts between Zod validation (PR #84) and error response
helpers (PR #82). Keep Zod schemas for validation, use badRequestResponse
helpers for error formatting, preserve duplicate deck detection.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Resolve package.json conflict: include both validation.test.ts and
cancel-recover.test.ts in test:unit script.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
@TytaniumDev TytaniumDev merged commit aa98eea into main Feb 27, 2026
3 checks passed
@TytaniumDev TytaniumDev deleted the feat/zod-request-validation branch February 27, 2026 07:32
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