Hey guys, quick question, I have an
Hey guys, quick question, I have an query with some args, i want to pass as an arg a convex object, i don't want to specifically set all of its properties as arguments like : name: v.string(), age: v.number() and so on, is there a way to infer the object type and set the argument type to it?
Thanks!
6 Replies
Hey @Idan - thanks for the question.
Check out this page https://docs.convex.dev/functions/args-validation
You can leave out the args from query/mutation/action, and then typescript will (try to) infer the type.
We wouldn't recommend it, because you'll lose out on some of the security benefits regarding malicious (or accidental incorrect input) highlighted on that docs page.
I hear you that it's a little bit verbose - noting that down as feedback, but hopefully it's not that bad.
Argument Validation | Convex Developer Hub
Argument validators ensure that queries,
@nipunn Thank you for the response,
That will just make it much less secure, It seems odd that there is not a way to infer the type of a document that is already have been created and already have a type. like for example when using the DOC<"products"> type for a type of a product object
You can reuse the validator from your schema.ts in an argument validator . But you might have to add the
_id
and _creationTime
. I don't know if we have an automated way to do that@Lee Can you provide an example?
lets say i have this product:
products: defineTable({
title: v.string(),
description: v.optional(v.string()),
marketplace: v.string(),
coverImage: v.string(),
addedBy: v.string(),
url: v.string(),
price: v.number(),
currency: v.string(),
numberOfReviews: v.number(),
rating: v.number(),
})
In this args of a query I've created i want to pass a product instead of an coverImage:
args: { coverImage: v.string() },
Thank you
You can
export const productType = {title: v.string(), etc}
and in the schema do defineTable(productType)
and in the arg validator do args: { product: {...productType, _id: v.id("products"), _creationTime: v.number()}}
got it, thank you!