ecyrbe / zodios

typescript http client and server with zod validation
https://www.zodios.org/
MIT License
1.71k stars 46 forks source link

[question]Patial Schemas validation is not working #285

Closed tamaki-tech closed 1 year ago

tamaki-tech commented 1 year ago

Hello, First, I'd like to thank you for this library.

There's something I'd like to ask.

I want to use schema responses contains Optional properties with Zodios.

But I got a validation Error.

do i need to do anything?

import { makeApi, Zodios } from "@zodios/core";
import { z } from "zod";
import { API_URL } from "@/config";

const LoginRequest = z.object({ login_id: z.string(), password: z.string() });
const LoginResponse = z
  .object({ access_token: z.string(), session: z.string() })
  .partial();
const ValidationError = z.object({
  loc: z.array(
    z.union([
      z.union([z.string(), z.number()]),
      z.array(z.union([z.string(), z.number()])),
    ])
  ),
  msg: z.string(),
  type: z.string(),
});
const HTTPValidationError = z
  .object({ detail: z.array(ValidationError) })
  .partial();

const endpoints = makeApi([
  {
    method: "post",
    path: "/api/login",
    alias: "login",
    requestFormat: "json",
    parameters: [
      {
        name: "body",
        type: "Body",
        schema: LoginRequest,
      },
    ],
    response: LoginResponse,
    errors: [
      {
        status: 422,
        description: `Validation Error`,
        schema: HTTPValidationError,
      },
    ],
  },
]);

export const api = new Zodios(API_URL, endpoints);

スクリーンショット 2023-01-12 11 27 40

ecyrbe commented 1 year ago

Hello, You should read zod documentation. Partial is only for allowing undefined properties. If you want to also allow null values, use nullable : https://github.com/colinhacks/zod#nullables

const LoginResponse = z
  .object({ 
     access_token: z.string().nullable(), 
     session: z.string().nullable() 
   }).partial();