Drizzle-zod Include Relations

Hello, I was wondering if drizzle-zod includes support for relations, and if so how I can include them. Thanks!
9 Replies
daniel
daniel2y ago
So far, I do not think so. I have added them manually myself.
shreddish
shreddish10mo ago
how were you manually adding them - are you typing out the complete zod definition or using drizzle-zod and appending onto the schema somehow?
volcanicislander
I am interested in accomplishing this as well
daniel
daniel9mo ago
I have a function which uses drizzle-zod then traverses the drizzle relations and uses zod's merge() function to expand the zod schema.
shreddish
shreddish9mo ago
Can you share it?
daniel
daniel9mo ago
Sure, though need to clean up slightly. I have some OpenAPI DTO annotation mixed in and it was a fiddle to get all going together.
pudgereyem
pudgereyem7mo ago
@danielsharvey I'm also looking into doing something similar. Would you mind sharing your approach?
Liam
LiamOP7mo ago
I did it like so if anyone needs it for future reference (cc @pudgereyem @shreddish )
const userValidator = createInsertSchema(users);

const userDataValidator = z.object({
data: createInsertSchema(data),
});

export const insertUserWithDataValidator = userValidator.merge(userDataValidator);
const userValidator = createInsertSchema(users);

const userDataValidator = z.object({
data: createInsertSchema(data),
});

export const insertUserWithDataValidator = userValidator.merge(userDataValidator);
You can also do it via extent, albeit with some wonky behaviours sometimes if you start adding in omits and what not
const userWithDataValidator = createInsertSchema(users).extend({
data: createInsertSchema(data)
});
const userWithDataValidator = createInsertSchema(users).extend({
data: createInsertSchema(data)
});
daniel
daniel7mo ago
Sorry for slow reply. My approach is similar to @Liam 's mentioned above, I've just written a generic function that utilises z.object() and createInsertSchema() based upon iterating (recursively) the Drizzle relations structures. I will share the code when I can but been swamped recently.
Want results from more Discord servers?
Add your server