create exportable types for frontend services

I feel like I'm missing something fundamental. I can create my Drizzle schema user = mysqlTable('user', {id: ....}); and use them in my queries to get data back. I want to return my result set to the frontend as {id: 1, ...} and strongly type the API return value. I thought that doing export type UserModel = InferModeltype<typeof user> would do that, but I get a type that looks like MySQLTableWithColumns.... instead of simply {id: number....}. What am I missing? I see how Drizzle keeps my queries type safe, but how can I leverage it to make sure consumers of my services use proper types? I feel like everyone is doing this, that it's super easy, and I'm just dumb right now.
10 Replies
tzezar
tzezar12mo ago
You want to provide types with your rest api response to the frontend? or do you want to provide validation for insert endpoints?
baronnoraz
baronnorazOP12mo ago
Both ideally, but I was speaking about types with my rest api to the frontend. I was also thinking that I could use drizzle-zod to validate - on the frontend and backend (when a request comes in), but I haven't gotten that far in my thinking. Right now, being able to give my frontend developers types/interfaces is the primary goal.
Angelelz
Angelelz12mo ago
You can import types to the front end no problem. It will get tree shaken by the compiler As long as it's just types
baronnoraz
baronnorazOP12mo ago
The problem is that the userSchema shows up as a type of MySQLTableWIthColumns... and not something simple like interface UserModel {id: number, ...}.
Angelelz
Angelelz12mo ago
Also, there's a new way to infer types: export type User = typeof user.$inferSelect
baronnoraz
baronnorazOP12mo ago
Interesting. I saw that, but I was using (insert) export type UserModel = InferModelType<typeof user, 'insert'> and it wasn't working, but when I switched to the $inferInsert it works great. Was the InferModelType just wrong?
Angelelz
Angelelz12mo ago
IDK where did you get that InferModelType Is that drizzle?
baronnoraz
baronnorazOP12mo ago
Yeah, the examples show using InferModel but in my IDE it said that was deprecated to use InferModelType, it's from drizzle-orm version 0.29.1
Angelelz
Angelelz12mo ago
I think you mean InferInsertModel
baronnoraz
baronnorazOP12mo ago
but.... as I look at the deprecation - yep dammit thanks - I'm a bone head. I appreciate the help. I can't believe that I looked at that wrong. I knew that I had to be doing something dumb.
Want results from more Discord servers?
Add your server