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

fix: remove readOnly fields from body schema parsing before Zod generation #1625

Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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