Skip to content

Commit

Permalink
fix: exclude readOnly fields from CreateBody schema in Zod generation (
Browse files Browse the repository at this point in the history
  • Loading branch information
yoshi2no authored Sep 14, 2024
1 parent 2245435 commit bdc584b
Showing 1 changed file with 32 additions and 2 deletions.
34 changes: 32 additions & 2 deletions packages/zod/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,28 @@ export type ZodValidationSchemaDefinition = {

const minAndMaxTypes = ['number', 'string', 'array'];

const removeReadOnlyProperties = (schema: SchemaObject): SchemaObject => {
if (schema.properties) {
return {
...schema,
properties: Object.entries(schema.properties).reduce<
Record<string, SchemaObject>
>((acc, [key, value]) => {
if ('readOnly' in value && value.readOnly) return acc;
acc[key] = value as SchemaObject;
return acc;
}, {}),
};
}
if (schema.items && 'properties' in schema.items) {
return {
...schema,
items: removeReadOnlyProperties(schema.items as SchemaObject),
};
}
return schema;
};

export const generateZodValidationSchemaDefinition = (
schema: SchemaObject | undefined,
context: ContextSpecs,
Expand Down Expand Up @@ -546,12 +568,14 @@ const parseBodyAndResponse = ({
name,
strict,
generate,
parseType,
}: {
data: ResponseObject | RequestBodyObject | ReferenceObject | undefined;
context: ContextSpecs;
name: string;
strict: boolean;
generate: boolean;
parseType: 'body' | 'response';
}): {
input: ZodValidationSchemaDefinition;
isArray: boolean;
Expand Down Expand Up @@ -597,7 +621,9 @@ const parseBodyAndResponse = ({

return {
input: generateZodValidationSchemaDefinition(
resolvedJsonSchema.items as SchemaObject,
parseType === 'body'
? removeReadOnlyProperties(resolvedJsonSchema.items as SchemaObject)
: (resolvedJsonSchema.items as SchemaObject),
context,
name,
strict,
Expand All @@ -615,7 +641,9 @@ const parseBodyAndResponse = ({

return {
input: generateZodValidationSchemaDefinition(
resolvedJsonSchema,
parseType === 'body'
? removeReadOnlyProperties(resolvedJsonSchema)
: resolvedJsonSchema,
context,
name,
strict,
Expand Down Expand Up @@ -811,6 +839,7 @@ const generateZodRoute = async (
name: camel(`${operationName}-body`),
strict: override.zod.strict.body,
generate: override.zod.generate.body,
parseType: 'body',
});

const responses = (
Expand All @@ -825,6 +854,7 @@ const generateZodRoute = async (
name: camel(`${operationName}-${code}-response`),
strict: override.zod.strict.response,
generate: override.zod.generate.response,
parseType: 'response',
}),
);

Expand Down

0 comments on commit bdc584b

Please sign in to comment.