StefanTerdell / zod-to-json-schema

Converts Zod schemas to Json schemas
ISC License
854 stars 67 forks source link

additionalProperties should be conditional with zod object strict() not passthrough() #85

Closed wwags33 closed 5 months ago

wwags33 commented 1 year ago

My objects pass zod parse, but they are failing ajv validation due to additionalProperties being false on all objects the schema.

const User = z.object({
  name: z.string(),
  company: z.object({
    id: z.string(),
    name: z.string(),
  }),
});
type UserType = z.infer<typeof User>;

const UserJsonSchema = zodToJsonSchema(User, 'User');
const isValidUser = ajv.compile<UserType>(UserJsonSchema);

const userObj = {
  name: 'John Doe',
  company: {
    id: '1234',
    name: 'Acme Corp',
    domain: 'acme.com';
});

User.parse(userObj); // Passes, and strips company.domain.
isValidUser(userObj) // Returns false due to company object schema having additionalProperties: false

I would expect the additionalProperties to be false if the zod definition included strict on each object:

const User = z.object({
  name: z.string(),
  company: z.object({
    id: z.string(),
    name: z.string(),
  }).strict(),
}).strict();

In this case, zod parse would match the validation behavior.

Instead I am required to add .passthrough() to all objects in the schema to get similar parse/validate functionality.

const User = z.object({
  name: z.string(),
  company: z.object({
    id: z.string(),
    name: z.string(),
  }).passthrough(),
}).passthrough();
StefanTerdell commented 9 months ago

But with the other way around, leaving additionalProperties undefined and passing it through a validator and most parsers would retain the properties instead of stripping them like Zod, so I'm not sure there's a clear answer here

StefanTerdell commented 9 months ago

Ive thought about it and it makes sense, but it since it's a breaking change I will probably put it behind an option. Not sure if I have time to put it in the upcoming release though, we'll see

gthecht commented 6 months ago

Hi, I wrote a branch with an option to allow this, Its my first time submitting a PR to someone else's repo, so I'm not sure what the correct way to do so is...