cyremur
cyremur•2y ago

Types of function context and arguments

let's say I want to create a utility function that does a query inside a function like this:
async function loadGame(db, id) {
const game = (await db
.query("games")
.filter((q) => q.eq(q.field("_id"), id))
.unique()) ?? raise(`Game with id ${id} doesn't exist.`);
return game ;
}
async function loadGame(db, id) {
const game = (await db
.query("games")
.filter((q) => q.eq(q.field("_id"), id))
.unique()) ?? raise(`Game with id ${id} doesn't exist.`);
return game ;
}
what's the correct typing on db and id?
12 Replies
Michal Srb
Michal Srb•2y ago
You can go to the definition of query to see the context type. You can either use QueryCtx for the whole context type or DatabaseReader just for the db. IDs will be Id<"tableName"> exported from _generated/server. Feel free to post in the support channel with concrete questions, might be easier for other folks to find later.
cyremur
cyremurOP•2y ago
Oh yeah sorry
Michal Srb
Michal Srb•2y ago
No worries! Keep the feedback coming, we love it. This is a good question, and we should have better docs here (right now it only mentions the ID type): https://docs.convex.dev/typescript
TypeScript | Convex Developer Hub
Move faster with end-to-end type safety.
lee
lee•2y ago
btw your loadGame function might be easier to write with db.get(id) (drive by comment, feel free to ignore 😛 )
cyremur
cyremurOP•2y ago
oh yeah I had a legacy id field from my previous stack and then switched out to native convex ids yesterday and just went from id to _id
cyremur
cyremurOP•2y ago
but yeah reason for this question is
No description
cyremur
cyremurOP•2y ago
like vscode just tries to vomit the whole schema into the tooltip and I'm like... but what do I write as function arg type?
Michal Srb
Michal Srb•2y ago
Yeah, definitely not obvious! import {DatabaseWriter} from './_generated/server'
cyremur
cyremurOP•2y ago
My idea comes from client side though and currently comes in as args.id : v.string() Do I typecast that for db.get(id) or how can I make the function validate game ids? nvm rtfm
lee
lee•2y ago
i would type it as v.id("games") and do the cast client-side if necessary that way the server can validate that the id is actually valid and in the "games" table (otherwise, if you cast server-side, a rogue client could use this to get any document)
cyremur
cyremurOP•2y ago
I just hand the raw document row to the client with _id type as is is that bad practice?
lee
lee•2y ago
sounds fine to me 🙂

Did you find this page helpful?