Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ZodSerializerDto is not working with array schema #130

Open
Xayrulloh opened this issue Jan 27, 2025 · 1 comment
Open

ZodSerializerDto is not working with array schema #130

Xayrulloh opened this issue Jan 27, 2025 · 1 comment

Comments

@Xayrulloh
Copy link

Xayrulloh commented Jan 27, 2025

I was using ZodSerializerDto decorator and when it comes to array schema like z.array(schema) or schema.array it is throwing an error like

Image

Firstly I didn't know that it because of ZodSerializerDto so I checked the output with schema.parse(response) and it didn't throw any error.

Until it fixes I'll create and use interceptor

import {
  Injectable,
  NestInterceptor,
  ExecutionContext,
  CallHandler,
  InternalServerErrorException,
  Logger,
} from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { ZodSchema } from 'zod';

@Injectable()
export class ZodValidationInterceptor<T> implements NestInterceptor {
  constructor(private schema: ZodSchema<T>) {}

  intercept(context: ExecutionContext, next: CallHandler): Observable<T> {
    return next.handle().pipe(
      map((data) => {
        const result = this.schema.safeParse(data);

        if (!result.success) {
          Logger.error(result.error)

          throw new InternalServerErrorException('Oops something went wrong');
        }

        return result.data;
      }),
    );
  }
}

interceptor code

you should call it as

@UseInterceptors(new ZodValidationInterceptor(YOUR_SCHEMA))
@maxijonson
Copy link

Related to #89 , though I would like to see this use-case fixed.

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

No branches or pull requests

2 participants