H
Hono2mo ago
wineT

[zod-openapi] How to generate a separate requestBody component?

I have several routes that get media files from user requests, and I want to separate them into a separate component to reuse them. But, I also have an array of allowed types to upload. So, I want to make the schema autogenerate itself when I add a new mime type to the array. I wrote this abomination and it doesn't work. I should have stopped when typescript stopped showing the appropriate type for mediaRequestBody.
const requestSchema = z.string().openapi({format: 'binary'})

type MediaRequestBody = {
[K in MediaMime]: {
schema: typeof requestSchema
}
}
// Example: mediaMimeTypes = ['video/mp4', 'video/webm', 'etc'] as const
export const mediaRequestBody = mediaMimeTypes.reduce((o, key) => {
return {
...o,
[key]: requestSchema
}
}, {}) as MediaRequestBody
const requestSchema = z.string().openapi({format: 'binary'})

type MediaRequestBody = {
[K in MediaMime]: {
schema: typeof requestSchema
}
}
// Example: mediaMimeTypes = ['video/mp4', 'video/webm', 'etc'] as const
export const mediaRequestBody = mediaMimeTypes.reduce((o, key) => {
return {
...o,
[key]: requestSchema
}
}, {}) as MediaRequestBody
Here is how I'm using it:
export const UpdateUserMediaRoute = createRoute({
method: 'put',
path: '/users/{userId}/media/{mediaId}',
request: {
params: ...
body: {
content: mediaRequestBody
}
},
responses: ...
})
export const UpdateUserMediaRoute = createRoute({
method: 'put',
path: '/users/{userId}/media/{mediaId}',
request: {
params: ...
body: {
content: mediaRequestBody
}
},
responses: ...
})
What am I doing wrong?
1 Reply
6190
61902mo ago
am not sure is it help for you but have you try .merge or .extend ? https://zod.dev/?id=merge https://zod.dev/?id=extend
GitHub
TypeScript-first schema validation with static type inference
TypeScript-first schema validation with static type inference
GitHub
TypeScript-first schema validation with static type inference
TypeScript-first schema validation with static type inference
Want results from more Discord servers?
Add your server