How can I re-use table validators?
If I define types in my table in my schema, how can I use them in functions and get the types?
10 Replies
Thanks for posting in <#1088161997662724167>.
Reminder: If you have a Convex Pro account, use the Convex Dashboard to file support tickets.
- Provide context: What are you trying to achieve, what is the end-user interaction, what are you seeing? (full error message, command output, etc.)
- Use search.convex.dev to search Docs, Stack, and Discord all at once.
- Ask in the <#1228095053885476985> channel to get a response from <@1072591948499664996>.
- Avoid tagging staff unless specifically instructed.
Thank you!
If you define your table like:
Then you can do:
@CabalDAO ^
attention: schema.tables.users.validator.fields wouldnt have _id and _creationtime etc. so if you are validating data that have those fields it will fail.
Thanks that's helpful, but I don't seem to be able to spread a v.object into another v.object like so:
And then separately when just creating the table it doesn't let me do the following:
Im not sure what you trying to do, but remove the v-object on both...because in both example you would get same result...
...Base.fields
will be able to spread in
You can get tab-completion on all the validator types - they're quite nice! You can get .members
on unions, e.g.
also getting values out of literals, etc.Please read this page:
https://stack.convex.dev/argument-validation-without-repetition
Argument Validation without Repetition
A few more advanced techniques & helpers to further reduce duplication and accelerate your Convex workflow.
I'm not sure this is the question you are asking, but in my Convex queries, mutations and helper functions I referred table entry types with the generated DataModel imported from _generated folder like so:
export const withStorageImage = async (
ctx: GenericQueryCtx<DataModel>,
user: DataModel['users']['document'] | null
): Promise<DataModel['users']['document'] | null> => {
[...]
const url = await ctx.storage.getUrl(user.image as Id<'_storage'>);
[...]
return user;
};
And the validator run-time equivalent is
schema.tables.users.validator
- which has .fields
if the table is an object, or .members
if it's a union of objects
I should update that article with the newer ways of accessing validators 👆sounds like a great idea 😄