Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions src/common/controllers/example-zod.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { Controller, Post, Body } from '@nestjs/common';
import { ZodValidationPipe } from '../pipes/zod-validation.pipe';
import { ExampleZodSchema, ExampleZodDto } from '../dto/example-zod.dto';

@Controller('example-zod')
export class ExampleZodController {
@Post()
create(@Body(new ZodValidationPipe(ExampleZodSchema)) dto: ExampleZodDto) {
return {
success: true,
data: dto,
};
}
}
11 changes: 11 additions & 0 deletions src/common/decorators/zod-body.decorator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { createParamDecorator, ExecutionContext } from '@nestjs/common';
import { ZodTypeAny } from 'zod';
import { ZodValidationPipe } from '../pipes/zod-validation.pipe';

export function ZodBody(schema: ZodTypeAny) {
return createParamDecorator((_data: unknown, ctx: ExecutionContext) => {
const request = ctx.switchToHttp().getRequest();
const pipe = new ZodValidationPipe(schema);
return pipe.transform(request.body, { type: 'body' });
})();
}
9 changes: 9 additions & 0 deletions src/common/dto/example-zod.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { z } from 'zod';

export const ExampleZodSchema = z.object({
title: z.string().min(1, 'Title is required'),
description: z.string().optional(),
tags: z.array(z.string()).default([]),
});

export type ExampleZodDto = z.infer<typeof ExampleZodSchema>;
2 changes: 1 addition & 1 deletion src/common/pipes/zod-validation.pipe.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -177,4 +177,4 @@ describe('ZodValidationPipe', () => {
expect(details[0].message).toContain('Localized:');
}
});
});
});
2 changes: 1 addition & 1 deletion src/common/pipes/zod-validation.pipe.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ export interface ZodValidationPipeOptions {

/**
* A pipe that validates and parses an incoming payload against a Zod schema.
* Instantiated per-schema, e.g. `@Body(new ZodValidationPipe(createAgentSchema))`.
* Instantiated per-schema, e.g. `@Body(new ZodValidationPipe(createAgentSchema)) کیا۔
* Rejects unknown/invalid data with a structured VALIDATION_ERROR whose
* `details` use the canonical {@link formatZodError} shape, supporting localized error message overrides.
*/
Expand Down
Loading