Skip to main content

🧙‍♂️ Casting Custom Fields

Need something special? Cascade lets you define your own custom casts for any field! Perfect for special data types, encryption, or anything unique to your app. 🛠️

🏗️ How to Make a Custom Cast

Just use a function in your casts property:

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

export class User extends Model {
public static collection = "users";
protected casts: Casts = {
// Custom cast for uppercase names
name: (value) => (typeof value === "string" ? value.toUpperCase() : value),
};
}

♻️ Reusable Casts

Make your custom cast reusable:

src/casts/uppercase.ts
export function uppercase(value) {
return typeof value === "string" ? value.toUpperCase() : value;
}
src/models/user.ts
import { uppercase } from "../casts/uppercase";

protected casts: Casts = {
name: uppercase,
};

🧙‍♂️ Pro Tip: Use for Encryption!

Custom casts are perfect for encrypting/decrypting fields on the fly.

src/casts/encrypt.ts
import { encrypt, decrypt } from "../utils/crypto";

export function encrypted(value, direction) {
return direction === "get" ? decrypt(value) : encrypt(value);
}

⚠️ Gotchas

  • Your cast function receives the value (and sometimes direction: "get" or "set").
  • Always handle undefined and null values gracefully.
info

Custom casts make your models super flexible. Use them for anything the built-in casts can't handle!


🌟 What's Next?