Interop with Zod
Hi,
I was wondering if there is a recommended setup for interop with zod or other schema validation libraries?
I mean the following: by generating the proto, you go from
message MyMessage {
optional float goal = 1;
}
to a TS interface like
export interface MyMessage {
goal: float
}
This works great, but when working with RPCs, you might need to use some validation library to ensure that the client json request conforms to the proto interface. Usage of zod is mandatory for libraries like next-rest-framework, and is in general a widespread library.
So the question would be, how to generate also Zod Schemas, so that we get to something like
export interface MyMessage {
goal: float
}
export MyMessageSchema = z.object({
goal: z.number()
})
I have tried ts-to-zod but there are some issues that would need to be solved first (chief among them, imports do not work: https://github.com/fabien0102/ts-to-zod?tab=readme-ov-file#non-zod-imports).
Anyway, I think this might be a common problem, so I wondered how other people solved it :)
Would appreciate any pointers!
you might need to use some validation library to ensure that the client json request conforms to the proto interface
Can you explain more about what you're passing around in these json requests? Are you passing around the object returned by MyMessage.toJson()? Or are you passing around the object returned by MyMessage.create()/MyMessage.fromJson()/MyMessage.fromBinary()? The provided TS interfaces are only going to represent the latter.
What I mean is: Let's say you have an REST API. The input to this API is a proto message. But it's a rest API (not gRPC) so the input it's not a proto, it's a json with arbitrary fields.
Many existing frameworks assume this, and allow you / force you to use validation on this json input (e.g. zod) to ensure that the (untrusted) user input is what you would expect it to be.
So while doing
try {
const parsed = MyMessage.fromJson(input)
}
catch {...}
might work in isolation, it does not play super well with the rest of the ecosystem that uses specific validation libraries.
Given that zod is very widespread, I thought maybe there was a way to generate a ZodSchema from MyMessage, so that one can integrate with frameworks expecting zod schemas.