Quick TypeScript setup for this repository.
Commands:
- Install deps:
npm install- Development (auto-restart):
npm run dev- Build:
npm run build- Run built app:
npm startThis project uses Zod for request validation, providing strong type safety and improved error handling.
- Validation Schemas: Defined in
src/models/user.schema.tsusing Zod - Validation Middleware: Located in
src/utils/validate.ts - Route Integration: Applied in
src/routes/user.routes.ts
Valid request:
{
"name": "John",
"surname": "Doe",
"email": "john.doe@example.com",
"age": 25
}Invalid request (missing required fields):
{
"name": "John"
}Error response:
{
"message": "Validation failed",
"errors": [
{ "field": "surname", "message": "Surname is required" },
{
"field": "email",
"message": "Invalid input: expected string, received undefined"
}
]
}- Define your schema in the appropriate model file:
import { z } from 'zod';
export const mySchema = z.object({
field: z.string().min(1),
// ... other fields
});- Apply the validation middleware to your routes:
import { validate } from '../utils/validate';
import { mySchema } from '../models/my.schema';
router.post('/endpoint', validate(mySchema, 'body'), controller);- Type Safety: Automatic TypeScript type inference from schemas
- Consistent Error Handling: Standardized validation error responses
- Better DX: Clear error messages help developers understand validation issues
- Runtime Safety: Ensures data structure at runtime matches TypeScript types