mikeysee
mikeysee7mo ago

Runtime validation using Convex Types

I asked the AI this but the answer wast very helpful unfortunately. Is there a way I can validate a type given a convex value so for example if I have:
const userValidator = v.object({
name: v.string(),
});
const userValidator = v.object({
name: v.string(),
});
I would like to validate that this:
validate(userValidator, { name: 123 })
validate(userValidator, { name: 123 })
Would throw an error because name is not of type string
6 Replies
Michal Srb
Michal Srb7mo ago
I don't think we have exposed the Rust implementation that powers argument and schema validation to JS. I'm curious, what's the use case? Do you want this on the backend or on the client? Is it needed because you're getting in more complex data through v.any()? convex-test does have a pure-JS implementation of the validation in its internals, so it could be pulled out. You could also use Zod, and then map from Zod to Convex validators with convex-helpers. https://stack.convex.dev/typescript-zod-function-validation
Zod with TypeScript for Server-side Validation and End-to-End Types
Use Zod with TypeScript for argument validation on your server functions allows you to both protect against invalid data, and define TypeScript types ...
mikeysee
mikeyseeOP7mo ago
Thanks for your reply Michael. My use-case is im parsing an RSS feed on the server which may have invalid data. I wanted to validate that data in a nice way. Yes I had thought of using Zod or io-ts or one of the others but I was hoping that I wouldnt have to pull in that dependency if its already built into Convex. Ill have a look at convex-test and see if it does the trick
Michal Srb
Michal Srb7mo ago
You'd have to vendor in the code from convex-test, at which point pulling in another dependency might be better (and Zod could give you more granular checks than Convex has).
mikeysee
mikeyseeOP7mo ago
I think this is the part that does the validation: https://github.com/get-convex/convex-test/blob/main/index.ts#L792
GitHub
convex-test/index.ts at main · get-convex/convex-test
Testing harness for pure-JS Convex tests. Contribute to get-convex/convex-test development by creating an account on GitHub.
mikeysee
mikeyseeOP7mo ago
The issue with pulling in Zod is that I would then have to write the validator for my type in two places, once in my fetch and parse function then second in my table schema (the parsed and validated data is inserted into the DB) that implementation in convex-test looks straight forward enough will need a bit of tweaking to convert from a convex value to a json or whatever but it looks like a pretty simple recursive function so should be easy enough
mikeysee
mikeyseeOP7mo ago
Incase anyone stumbles across this in the future, this seems to do the trick. Maybe I should submit it to convex-helpers ?