Loom Schema
Loom Schema is a lightweight toolkit for composing JSON Schema definitions in a fluent manner and validating data against those schemas. It uses AJV under the hood to perform validation, but abstracts away much of the complexity. You can define schemas for your data, then either compile and validate against them or export them as standard JSON Schemas.
Features
- Easy Schema Composition: Write and reuse fragments for strings, numbers, arrays, objects, etc.
- Built-in Validation: Any schema fragment can validate data directly, returning helpful errors if the validation fails.
- AJV Integration: Fine-tune validation with AJV’s options, custom keywords, or custom vocabularies.
- TypeScript-Friendly: Infer TypeScript types from your Loom schemas, ensuring that your data usage aligns with the rules you set.
Installation
bun install loom-schema
Basic Usage Example
import { object, string, number, Infer } from "loom-schema";
// Define a schema fragment for a user objectconst userSchema = object({ properties: { name: string({ minLength: 1 }), age: number({ minimum: 0 }), }, required: ["name", "age"],});
// Validate some dataasync function runExample() { const result = await userSchema.validate({ name: "Alice", age: 25 }); if (result.valid) { console.log("Data is valid!"); } else { console.error("Validation errors:", result.errors); }}
runExample();
// Infer TypeScript types from your schematype User = Infer<typeof userSchema>;
In the snippet above:
- We create a simple user schema describing an object with two properties (
name
andage
). - We call
.validate(...)
on the schema to check if a sample data object is valid. - We also demonstrate how to use the
Infer
utility type to derive a TypeScript type from our schema.
Continue to the API Reference for details on each helper function.