Prototypes & Schemas
A prototype is an object that serves as a type: #[type] on an object makes it one. Instances get its fields as defaults and its functions as methods, and paired with #[schema(...)], a type can validate data too.
Declaring a Type
#[type]
Customer: {
str id: ''
str plan: 'free'
fn label() -> str {
`${self.id} (${self.plan})`
}
}
#[main]
fn main() {
const customer = new Customer { id: 'cus_1' };
pln(customer.label()); // plan comes from the type's default
pln(typename customer);
}new Customer { ... } creates an instance, with your values on top of the type's defaults. An object in the document can have a type too: Customer acme: { id: 'cus_2' }.
Constructors
A function marked #[constructor] runs on every instance created with new:
#[type]
Order: {
list items: []
#[constructor]
fn created() {
self.created_at = Time::now();
}
}
#[main]
fn main() {
const order = new Order {};
pln(order.created_at != null);
}Constructors run only with new. An object declared with a type in the document gets the type's fields and functions, but not a constructor call.
The Type Itself
<Customer> is a path to the type object. Calling a function on it runs with the type as self, which is how you write a static function, like a factory:
#[type]
Money: {
float amount: 0
str currency: 'USD'
#[static]
fn euros(amount: float) -> Money {
new Money { amount: amount, currency: 'EUR' }
}
fn label() -> str { `${self.amount} ${self.currency}` }
}
#[main]
fn main() {
pln(<Money>.euros(20).label());
}Inheritance
#[extends('Name')] makes a type build on another. It gets the parent's fields and functions, and can replace them:
#[type]
Plan: {
str name: 'plan'
float price: 0
fn describe() -> str { `${self.name}: ${self.monthly()}/mo` }
fn monthly() -> float { self.price }
}
#[type]
#[extends('Plan')]
AnnualPlan: {
fn monthly() -> float { (self.price / 12).round(2) }
}
#[main]
fn main() {
const plan = new AnnualPlan { name: 'pro annual', price: 120 };
pln(plan.describe()); // uses AnnualPlan's monthly()
pln(plan.monthly<Plan>()); // call the parent's version
pln(plan.instance_of('Plan'));
}The parent's constructor runs before the child's.
Types Inside Objects
Types can live inside objects, to keep a large document organized. Refer to one by a qualified name:
Geometry: {
#[type]
Point: {
float x: 0
float y: 0
fn length() -> float { Num::sqrt(self.x.pow(2) + self.y.pow(2)) }
}
}
#[main]
fn main() {
const p = new Geometry.Point { x: 3, y: 4 };
pln(p.length());
pln(<Geometry.Point>.y);
}A plain name like Point finds the nearest type with that name. A qualified name, Geometry.Point, is clearer when two types share a name, and it works from anywhere in the document.
Typed Fields Inside Types
A field whose type is another type casts what's assigned to it, filling in that type's defaults:
#[type]
Address: {
str city: ''
str country: 'US'
}
#[type]
Customer: {
str name: ''
Address address: {}
}
#[main]
fn main() {
const customer = new Customer { name: 'Ada', address: new { city: 'Boston' } };
pln(customer.address.country); // the default from Address
pln(typename customer.address);
}Validating with Schemas
A #[schema(...)] attribute on a type's field holds a function that checks a value. schemafy checks another object's fields against every rule, and returns whether they all pass:
#[type]
Signup: {
#[schema((target_val: str): bool => target_val != null && target_val.contains('@'))]
str email: ''
#[schema((target_val: int): bool => target_val != null && target_val >= 13)]
int age: 0
}
#[main]
fn main() {
const good = new { email: 'ada@example.com', age: 36 };
const bad = new { email: 'nope', age: 9 };
pln(<Signup>.schemafy(good));
pln(<Signup>.schemafy(bad));
}This is how to check data that comes from outside, like a request or a model's output, before using it.
A rule gets what it needs by parameter name: target_val is the value being checked. A rule can also ask for target (the object being checked), field (the field's name), and schema_val (the type's default for the field). A field that's missing is checked as null, so rules for required fields should reject null, as these do. #[schema_optional] skips the check when a value is null or missing.
Combining Rules
A list of functions runs in order, and every one has to pass:
fn not_empty(target_val: str) -> bool { target_val != null && target_val.len() > 0 }
#[type]
Contact: {
#[schema([self.not_empty, (target_val: str): bool => target_val.contains('@')])]
str email: ''
}
#[main]
fn main() {
pln(<Contact>.schemafy(new { email: '' }));
pln(<Contact>.schemafy(new { email: 'info@stof.dev' }));
}Checking Nested Objects
A bare #[schema] on a field that holds an object checks that object against the rules inside it:
#[type]
Order: {
#[schema]
shipping: {
#[schema((target_val: float): bool => target_val != null && target_val >= 0)]
cost: 0
}
}
#[main]
fn main() {
const order = new { shipping: new { cost: -5 } };
pln(<Order>.schemafy(order));
}Cleaning Up Instead of Rejecting
schemafy can fix the object instead of only reporting. remove_invalid = true deletes fields that fail, and remove_undefined = true deletes fields the type doesn't declare:
#[type]
Profile: {
#[schema((target_val: str): bool => target_val != null && target_val.len() <= 20)]
str name: ''
}
#[main]
fn main() {
const input = new { name: 'a name that is far too long', admin: true };
<Profile>.schemafy(input, remove_invalid = true, remove_undefined = true);
pln(stringify('json', input));
}Next, Attributes.