help with drizzle-zod with jsonb column

I have this table definition:
interface Address {
street: string
number: string
complement: string
neighborhood: string
city: string
state: string
zipcode: string
}

export const customerTable = pgTable("customer", {
id: text("id").primaryKey(),
userId: text("user_id")
.notNull()
.references(() => userTable.id),
addresses: jsonb("addresses").$type<Address[]>().notNull(),
})
interface Address {
street: string
number: string
complement: string
neighborhood: string
city: string
state: string
zipcode: string
}

export const customerTable = pgTable("customer", {
id: text("id").primaryKey(),
userId: text("user_id")
.notNull()
.references(() => userTable.id),
addresses: jsonb("addresses").$type<Address[]>().notNull(),
})
then I use drizzle-zod to create a type from that schema:
const tableSchema = createInsertSchema(customerTable)

export type Customer = z.infer<typeof tableSchema>
const tableSchema = createInsertSchema(customerTable)

export type Customer = z.infer<typeof tableSchema>
but the addresses property is a json type, not an array of Address. Is there a way to change that behavior?
No description
2 Replies
Rafael
Rafael12mo ago
It can't do that, the library and Zod only know about concrete information, and types aren't concrete. The only concrete information is Json. For custom columns, it uses z.any (https://github.com/drizzle-team/drizzle-orm/blob/main/drizzle-zod/src/index.ts#L205). But you can override it
const addressSchema = z.object({
...
})

type Address = z.infer<typeof addressSchema>

const tableSchema = createInsertSchema(customerTable, {
addresses: z.array(addressSchema)
})

export type Customer = z.infer<typeof tableSchema>
const addressSchema = z.object({
...
})

type Address = z.infer<typeof addressSchema>

const tableSchema = createInsertSchema(customerTable, {
addresses: z.array(addressSchema)
})

export type Customer = z.infer<typeof tableSchema>
Gabriel Lucena
Gabriel LucenaOP12mo ago
appreciate that, Rafael! thanks, man
Want results from more Discord servers?
Add your server