how to type dynamic where condition

i'd like to do something like
async function selectEventByCondition(condition) {
return db.query.events.findFirst({
where: condition,
with: {
exceptions: true,
},
})
}
async function selectEventByCondition(condition) {
return db.query.events.findFirst({
where: condition,
with: {
exceptions: true,
},
})
}
however the condition is any type in this case. does drizzle provide a type i can use? prisma has generated types that can be used in similar situations
5 Replies
Racks
Racks•2y ago
I think the idea is that you wouldn't bother wrapping the db.query.events.findFirst function. The type system can probably accomplish this but whats some examples of the condition(s) that will be passed in?
ewilliam
ewilliamOP•2y ago
example conditions: eq(events.id, id)) eq(events.slug, slug) and so on. not wrapping would be pretty repetitive. not a big deal maybe but hope there's a more elegant solution
Racks
Racks•2y ago
@ewilliam you'll need to add npm install --save type-fest But this may work:
type EventsCondition = Get<Parameters<(typeof db)["query"]["events"]["findFirst"]>[0], "where">
async function selectEventBycondition<T extends EventsCondition>(condition: T) {
return db.query.events.findFirst({where: condition})
}
type EventsCondition = Get<Parameters<(typeof db)["query"]["events"]["findFirst"]>[0], "where">
async function selectEventBycondition<T extends EventsCondition>(condition: T) {
return db.query.events.findFirst({where: condition})
}
Yea it does work 🙂 I'm actually going to use this in some of my stuff too… it is fantastic What it's doing is using TypeScript to lookup the type of db, then get the type of query.events.findFirst function's first argument. I couldn't figure out how to get access to the "where" key in the first argument without using type-fest. But type-fest is a type's only library and adds no bloat to bundles. You can make it more generic like this:
type Db = typeof db
type DbQuery = Db["query"]
type DbQueryWhere<K extends keyof DbQuery> = Get<Parameters<DbQuery[K]["findFirst"]>[0], "where">

function doTheThing<T extends DbQueryWhere<"events">>(where: T) {
return db.query.events.findFirst({
where
})
}
type Db = typeof db
type DbQuery = Db["query"]
type DbQueryWhere<K extends keyof DbQuery> = Get<Parameters<DbQuery[K]["findFirst"]>[0], "where">

function doTheThing<T extends DbQueryWhere<"events">>(where: T) {
return db.query.events.findFirst({
where
})
}
DiamondDragon
DiamondDragon•2y ago
This is cool. I’m going to copy into a util file as well
ewilliam
ewilliamOP•2y ago
thanks @Robert!

Did you find this page helpful?