import { schema } from "https://deno.land/x/fun@v2.0.0-alpha.6/schemable.ts";
A helper function to build a generic Schema that can be used with any Schemable.
Examples
Example 1
Example 1
import { schema, TypeOf } from "./schemable.ts";
import { SchemableDecoder } from "./decoder.ts";
import { SchemableRefinement } from "./refinement.ts";
import { SchemableJsonBuilder, print } from "./json_schema.ts";
import { pipe } from "./fn.ts";
const mySchema = schema(s => pipe(
s.struct({
name: s.string(),
age: s.number(),
}),
s.intersect(s.partial({
interests: s.array(s.string()),
}))
));
// Derive the type from the schema
type MySchema = TypeOf<typeof mySchema>;
const decode = mySchema(SchemableDecoder);
const refine = mySchema(SchemableRefinement);
const jsonSchema = mySchema(SchemableJsonBuilder);
const unknown1 = {
name: "Batman",
age: 45,
interests: ["crime fighting", "cake", "bats"],
};
const unknown2 = {
name: "Cthulhu",
interests: ["madness"],
};
const decoded1 = decode(unknown1); // Success!
const decoded2 = decode(unknown2); // Failure with info
const refine1 = refine(unknown1); // true
const refine2 = refine(unknown2); // false
const jsonSchemaString = pipe(
jsonSchema,
print,
json => JSON.stringify(json, null, 2),
); // Turns the jsonSchema into a prettified string