Skip to main content

๐Ÿ”ฎ Casting Data

Cascade makes sure your data is always the right typeโ€”no more surprises! Whether you want strings, numbers, booleans, dates, or even geo locations, Cascade has you covered. ๐Ÿง™โ€โ™‚๏ธ

๐Ÿงฐ How to Cast Dataโ€‹

Just define the casts property in your model:

src/models/user.ts
import { Model, Casts } from "@warlock.js/cascade";

export class User extends Model {
public static collection = "users";
protected casts: Casts = {
name: "string",
email: "string",
age: "number",
isActive: "boolean",
birthDate: "date",
};
}

๐Ÿท๏ธ Built-in Castsโ€‹

TypeDescription
stringCasts to a string
numberCasts to a number
int/integerCasts to an integer
floatCasts to a float
bool/booleanCasts to a boolean
dateCasts to a date
arrayCasts to an array
objectCasts to an object
any/mixedNo casting, keeps value as is
locationCasts to a geo location object
localizedStores as array of { localeCode, value } for multilingual fields
info

If a value is missing, Cascade uses a sensible default (e.g., "" for string, 0 for number, [] for array, etc.).

๐ŸŒ Geo Locationsโ€‹

Use the location cast for geo points:

src/models/user.ts
protected casts: Casts = {
location: "location",
};
src/app.ts
const user = await User.create({
location: { lat: 30.123, lng: 31.123 },
});
console.log(user.get("location")); // { type: "Point", coordinates: [30.123, 31.123] }

๐ŸŒ Localized Valuesโ€‹

Use the localized cast for multilingual fields:

src/models/user.ts
protected casts: Casts = {
bio: "localized",
};
src/app.ts
const user = await User.create({
bio: [
{ localeCode: "en", value: "English bio" },
{ localeCode: "ar", value: "Arabic bio" },
],
});

๐Ÿงฉ Built-in Custom Castsโ€‹

Embedding Models (๐Ÿš€ New & Improved!)โ€‹

You can now embed another model just by passing the model class directly:

src/models/post.ts
import { Category } from "./category";

protected casts: Casts = {
category: Category, // Just pass the model class!
};
Did you know?

You no longer need to use castModel(Category)โ€”just pass the model class directly! This is the new, recommended way. castModel is still supported for backward compatibility.

Pass the category id when creating a post, and Cascade will fetch and embed the category data for you!


๐ŸŒŸ What's Next?โ€‹