couincouin007
couincouin007
Explore posts from servers
DTDrizzle Team
Created by couincouin007 on 12/18/2023 in #help
getPost() / getPosts() / ... what's your opinion? + any TS magician here :) ?
Hello! I was thinking of creating functions which will execute my queries, instead of putting all queries in my components. With that in place, I would be able to switch between Drizzle with any other query build / orm if I would like. To put it simply:
// lib/fetchers/post.ts
export async function getPost(id: Post["id"], options = {}): Promise<Post | undefined> {
const data = await db.query.post.findFirst({
where: eq(post.id, id),
...options
})

return data
}


// component.ts
export async function Component() {
const post = await getPost(1);

return <h1>{post.title}</h1>
}
// lib/fetchers/post.ts
export async function getPost(id: Post["id"], options = {}): Promise<Post | undefined> {
const data = await db.query.post.findFirst({
where: eq(post.id, id),
...options
})

return data
}


// component.ts
export async function Component() {
const post = await getPost(1);

return <h1>{post.title}</h1>
}
1. What do you think about this approach? i think it's convenient, abstraction does not seem overkilled, and I think it's quiet common, but I don't have seen it in tutorials / courses, but I think it's cleaner and more maintanable than putting queries everywhere in your code 2. I needed to add some types (id param + function return) to make it better to use, but I still don't know how or if it would be possible to type the options object which should take all params accepted in the findFirst method (such as columns, where...)
19 replies