True Myth / standard-schema / asyncParserFor
Function: asyncParserFor()
asyncParserFor<
S
>(schema
):AsyncParserFor
<InferOutput
<S
>>
Create an asynchronous parser for unknown data to use with any library that implements Standard Schema (Zod, Arktype, Valibot, etc.).
The resulting parser will accept unknown
data and emit a Task
, which will be Resolved
if the schema successfully validates, or Rejected
with the Issue
s generated by the schema for invalid data.
If passed a parser that produces results synchronously, this function will lift it into a Task
.
Examples
With Zod:
import { asyncParserFor } from 'true-myth/standard-schema';
import * as z from 'zod';
interface Person {
name?: string | undefined;
age: number;
}
const parsePerson = asyncParserFor(z.object({
name: z.optional(z.string()),
// Define an async refinement so we have something to work with. This is a
// placeholder for some kind of *real* async validation you might do!
age: z.number().refine(async (val) => val >= 0),
}));
Other libraries that support async validation or transformation work similarly (but not all libraries support this).
Once you have a parser, you can simply call it with any value and then use the normal Task
APIs.
await parsePerson({ name: "Old!", age: 112 }).match({
Resolved: (person) => {
console.log(`${person.name ?? "someone"} is ${person.age} years old.`);
},
Rejected: (error) => {
console.error("Something is wrong!", ...error.issues);
}
});
Type Parameters
S
S
extends StandardSchemaV1
<unknown
, unknown
>
Parameters
schema
S
A Standard Schema-compatible schema that produces a result, possibly asynchronously.
Returns
AsyncParserFor
<InferOutput
<S
>>
A Task
that resolves to the output of the schema when it parses successfully and rejects with the StandardSchema
FailureResult
when it fails to parse.