Replies: 1 comment 1 reply
-
|
Hey @alexd6631 I'm the middle of migrating from zod to TypeBox and I'm still getting the hang of things I agree the behaviors of parse in zod are great, I especially like zod's built in transform and pipe. I was looking at the Value methods and I'm going to take a guess and say they were designed in such a way that we can create our own version of parse. I only had a few minutes to whip up a first pass and here is what I got for stripping as well as adding in default properties. import { TSchema, Type as t } from "@sinclair/typebox";
import { Value } from "@sinclair/typebox/value";
const TbModel = t.Object({
id: t.Number({ default: 123 }),
message: t.String({ default: "hello world" }),
});
const { Diff, Create, Patch, Decode } = Value;
const Default = Create(TbModel);
const parse = <T extends TSchema>(model: T, value: Record<string, any>) => {
const edits = Diff(value, Default).filter((v) => v.type === "insert");
//we can strip by filtering on v.type ==="delete"
return Decode(model, Patch(value, edits));
};
describe("First iteration of a typebox parse using Value methods", () => {
test(" Parse empty object and return default values", () => {
const result = parse(TbModel, {});
expect(result.message).toBe("hello world");
expect(result.id).toBe(123);
});
test("Add in missing default values", () => {
const result = parse(TbModel, { message: "foo" });
expect(result?.id).toBeNumber();
expect(result?.message).toBeString();
expect(result.id).toBe(123);
expect(result.message).toBe("foo");
});
}); |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Hello,
I am considering moving from
zodtotypebox. My main motivations are the native JSON schema support and recursiveschema definition (I had to encode a tree structure, and generate a JSON schema for a yaml config file, and zod shown
its limit here).
I know the two libraries, while looking similar on the surface, have different design tradeoffs. I am looking for advice
on the best practices to mitigate the differences, or feedback from someone who has made the move from
zodbefore. Mymain usages of
zod, is to act as a boundary between my core, type-safe, logic and the external world (being itconfiguration files, payload validation, external API calls to services, etc ...)
One thing I really liked about Zod is the functional "Parse, don't validate" approach, and I am having a hard time going
back to the classical "validate" mindset.
While the native JSON schema approach will always lean on the validate approach, I was hoping
Value.DecodeandTransformwould be similar in behavior to zodparsemethod, but after a few tries, there are a few differences thatare putting me off :
Value.Decodeon aType.Objectwill not strip additional properties, whilez.object({...}).parse(data)will result in a new, clean object. I know this has been discussed before, andthe advice is to fix the data on the sender side, but I still find it convenient from some use cases. For instance let's
imagine I am parsing a large API response, or a CSV file in which I am only interested in a few fields, the ability to
parse and strip in one step, is really convenient. There is no explicitly way to enable this, but it seems feasible by
using
ajvdirectly.Value.Decodedoes not fill default values. Withzod, if I am adding a new property to an existing schema and provide adefault value, for retro compatibility reason, I can easily do it with the
.default(val)method.Typeboxseems tosupport a default option in schema, but it does not seem to honor it with
Value.Decode, which I find misleading.For default values, I tried the following workaround, but it did not work since transform are not applied when the field
data is not provided
I am considering reimplementing a
parseequivalent, using a custom ajv configuration to strip excess properties andadd defaults, followed by
Value.Decodeto apply transforms if necessary. But it feels a bit convoluted and I amwondering if something similar was not already implemented by typebox users or in a 3rd party library ?
Beta Was this translation helpful? Give feedback.
All reactions