Replies: 1 comment
-
I'm not sure my opinions count as idioms, but I would personally consider this as multiple steps, rather than a pipeline from If you keep it as a single pipelined schema, you'll want to update your example a bit: export const event = z
.string()
.nullable() // Needs `nullable` so that it doesn't fail on `null`
.transform(maybeString => { // just updated the name to be less certain about the stringiness
try {
return JSON.parse(maybeString);
} catch {
return null;
}
})
.refine(obj => typeof obj === 'object') // Do you really want this? It will fail on some valid JSON values like `42` or `true`
.transform(metric.parse); Some helper/util/core module defines the JSON stuff: const jsonStringSchema = z
.string()
.nullable()
.refine((maybeString) => {
try {
JSON.parse(maybeString);
return true;
} catch (err) {
return false;
}
})
.transform(JSON.parse); And then somewhere where you are handling these const parsedBody = jsonStringSchema.parse(event.body);
const metric = metric.parse(parsedBody); In my setup, the |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
👋 Love this library. Thank you so so much for all the amazing work.
I'm setting up an api endpoint that should validate incoming metrics. To do that, I've defined the following models:
In my APIGateWayHandler,
event.body
is eitherstring | null
. What I'd like to be able to do is define a model that will:validate that it's a string => call
JSON.parse
=> then try to parse that object withmetric
. Is there an idiomatic way to do that? This is what I've got so far (that I am unsure about because I don't thinktransforms
are supposed tothrow
), but hopefully this shows what I'm trying to do?Beta Was this translation helpful? Give feedback.
All reactions