anatine / zod-plugins

Plugins and utilities for Zod

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Getting no data inside `refine` in zod-nestjs

apudiu opened this issue · comments

Is refine supported?

import { createZodDto } from '@anatine/zod-nestjs';
import { extendApi } from '@anatine/zod-openapi';
import { z } from 'zod';
import { config } from '../../utils/config';
import { formatFromBytes } from '../../utils/Helpers';

const CreateFeedSchema = extendApi(
  z
    .object({
      title: z.string().min(5).max(35).nullish(),
      body: z.string().max(140).nullish(),
      attachment: z.instanceof(File).nullish(),
    })
    .refine(
      (d) => {
        console.log({
          d, // {}  << Here's the issue <<------------------<<-----------<<
        });
        if (d.title) return true;
        if (d.body) return true;
        if (d.attachment) return true;

        return false;
      },
      {
        path: ['title'],
        message: "Title, Body and attachment can't be empty at the same time",
      },
    )
    .superRefine((d, ctx) => {
      if (!d.attachment) return;

      // file size validation
      const allowedMaxSize = config.file.maxSize;
      if (d.attachment.size > allowedMaxSize) {
        ctx.addIssue({
          code: z.ZodIssueCode.too_big,
          type: 'number',
          maximum: allowedMaxSize,
          inclusive: true,
          fatal: true,
          message: `Max file size is ${formatFromBytes(allowedMaxSize, ['megabyte']).megabyte} MB`,
        });
      }

      // mime validation
      const allowedMimes = config.file.image.mimes;
      if (!allowedMimes.includes(d.attachment.type)) {
        ctx.addIssue({
          code: z.ZodIssueCode.custom,
          message: `Only ${allowedMimes} are allowed`,
        });
      }
    }),
);

export class CreateFeedDto extends createZodDto(CreateFeedSchema) {}

Because of this following payload always throws

{
    "title": "A1",
    "body": null,
    "attachment": 1234
}

this error
Title, Body and attachment can't be empty at the same time
Is there anything I'm doing wrong? According to zod's documentation, I think I'm ok.