-
Notifications
You must be signed in to change notification settings - Fork 9
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Cast from an async sanitizer #42
Comments
Yes that is correct. Currently there is no notion of an async sanitizer in the library, but a PR would be greatly appreciated. In the meantime all you really need to do is await the result of |
I'm ok to make a PR. Would that be fine to add an |
That could also work, but it does not cover your use case. Your use case is a sanitizer that returns a promise, not a promise with a sanitizer. |
Hey @getlarge. I thought about your issue over the weekend and here is what I came up with: import { Result, SanitizerFailure, CastError } from "@restless/sanitizers";
export type AsyncSanitizer<T> = (value: unknown, path: string) => Promise<Result<SanitizerFailure[], T>>
export async function asyncCast<T>(value: unknown, sanitizer: AsyncSanitizer<T>, message?: string): Promise<T> {
const result = await sanitizer(value, '')
if (Result.isOk(result)) {
return result.ok
} else {
throw new CastError(result.error, message)
}
} You should be able to drop this code in your project and use it without issues. If however you wanted a function that takes a import { Sanitizer, cast } from "@restless/sanitizers";
export async function asyncCast<T>(value: unknown, sanitizer: Promise<Sanitizer<T>>, message?: string): Promise<T> {
return cast(value, await sanitizer, message)
} |
Hey @sz-piotr, sorry for the delay. You were right, the use case is a sanitizer that returns a promise. Thanks a lot for your snippet and your feedback. |
In fact my question was more to know if you would prefer a |
Here is my line of thinking. If async sanitizers were to be supported by default by the library this should be a bigger change, where all the other higher-order sanitizers like However since there are currently no async sanitizers in the library code I believe keeping the |
But since a user can create an async sanitizer maybe we can add an example or test to illustrate that case ? |
Hmm might be indeed useful once we have the notion of AsyncSanitizers somewhere in the library. If in the future we add this it will definitely be described in the readme. |
It seems it is not yet possible to use an async
sanitizer
function insidecast
, do i mistake ?If not, would it be possible to add support for this ?
Example
Sanitizer
Cast
The text was updated successfully, but these errors were encountered: