Replies: 1 comment 2 replies
-
Zod 3.8 includes a new feature (preprocess) that might be helpful here. It's a little verbose since it requires validating the input as well, but that feels important anyway! import { z } from "./index";
const dbAccountSchema = z.object({
id: z.string(),
createdAt: z.date(),
cachedProfile: z
.object({
photos: z.array(z.object({ value: z.string() })).nullable(),
_json: z.object({ followerCount: z.number() }).nullable(),
})
.nullable(),
});
const preprocessTwitter = z.preprocess(
(raw) => {
const result = dbAccountSchema.parse(raw);
return {
id: result.id,
createdAt: result.createdAt,
photo: result.cachedProfile?.photos?.[0].value,
followers: result.cachedProfile?._json?.followerCount,
};
},
z.object({
id: z.string(),
createdAt: z.date(),
photo: z.string().nullable(),
followers: z.number().nullable(),
})
);
console.log(
preprocessTwitter.parse({
id: "abc",
createdAt: new Date(),
cachedProfile: {
photos: [{ value: "https://example.com" }],
_json: {
followerCount: 42,
},
},
})
); Output: {
id: 'abc',
createdAt: 2021-08-24T00:12:33.349Z,
photo: 'https://example.com',
followers: 42
} @colinhacks: is it ok for the processing function to throw like this (i.e. using |
Beta Was this translation helpful? Give feedback.
2 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Hey - I'm possibly missing an already available feature possibly enabled by the new transformations.
What I'm looking to achieve is a neat way to flatten a nested object and then validate it - for example:
There is a twitter account object in the db that has a
cachedProfile
json field storing the entire blob returned from passport-twitter. The row itself has it's ownid
andcreatedAt
fields. The entire object to be parsed may look something like this:I would like to parse and return a validated flattened version of the twitter profile.
The made-up getter function defines the mapping from the root object to the field. The function would be executed before validating it's resulting type.
I understand i can pre-transform and then validate with zod but is there a neater way like i'm describing above meaning there's one line for each attribute?
Maybe this a feature request instead.
Thanks
Beta Was this translation helpful? Give feedback.
All reactions