zod-extended
v1.0.5
Published
Do more with your Zod schemas.
Downloads
2
Readme
Zod Extended
Do more with your Zod schemas.
npm add zod-x
API
zx(schema)
Resolve
Resolve/computed fields according to a parent object.
Description
The resolve
functionality aims to make "field-resolution" or "computed fields" simple in Zod. Computed or resolved fields enable deriving new fields based on existing object fields. A common use case for computed fields is collecting relation data.
⚠️ This requires using .parseAsync() to parse schema
Usage
First define a "resolveable" field on an object.
// Schema of resolved type
const Photo = z.object({
src: z.string(),
width: z.number(),
height: z.number()
})
const User = z.object({
id: z.string(),
photoId; z.string(),
// Add a resolved field
Photo: zx(Photo).resolve(async (parent) => {
return db.photo.findUnique({
where: { id: parent.photoId }
})
})
})
By default these resolvers won't ever be run, and the computed fields never populated, until you wrap a schema in the .resolved()
function.
// Upon .parseAsync(), the resolved fields will be appended to the resulting value.
const UserWithResolved = zx.resolved(User);
By moving this relation data-fetching to the application boundary, we can easily include and exclude relation data, without altering our business logic in our functions.