Replies: 1 comment
|
The current Zod (v4) API allows you to define codecs for bidirectional transformations, such as bytes-to-UTF8 and UTF8-to-bytes, by specifying both decode and encode functions when creating a codec(1). However, there is no documented built-in method to automatically "reverse" or invert a codec (i.e., to swap the input/output schemas and the encode/decode functions in-place). To achieve the reverse transformation, you would need to manually define a new codec with the input and output schemas swapped and the encode/decode functions inverted: const utf8ToBytes = z.codec(
z.string(),
z.instanceof(Uint8Array),
{
decode: (str) => new TextEncoder().encode(str),
encode: (bytes) => new TextDecoder().decode(bytes),
}
);If you think a utility for inverting codecs would be helpful, implementing it as a PR would be a valuable contribution. There is no mention of such a feature in the current documentation(1), (2). 📚 Sources: Have another question? Just tag @inkeep. |
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
The docs show an example of
bytesToUtf8:Let's say one needs to do the reverse transform in a pipe (example), UTF-8 to bytes. It would be nice to have the ability to reverse/invert a codec, swapping the input & output schemas, and decode & encode function.
If that sounds like something useful, I'd be down to try implementing it in a PR.
All reactions