Skip to content

Mutators and Casts ​

Introduction ​

Databases store plain values: integers for booleans, strings for JSON and dates. Casts convert a column between its stored form and the type you want to work with, in both directions, so user.getAttribute('is_admin') is a boolean even though SQLite stores 1. Accessors compute attribute values from other attributes, and appended attributes include them in serialized output.

The examples use this table and connection:

ts
import { Schema, sqliteConnection } from '@plinthjs/database'
import { ConnectionDataSource, Model, encryptedCast, enumCast } from '@plinthjs/orm'
import type { Cast, CastType } from '@plinthjs/orm'

const db = sqliteConnection()
Model.connection = db
Model.dataSource = new ConnectionDataSource(db)

await new Schema(db).create('accounts', (table) => {
  table.id()
  table.string('first_name')
  table.string('last_name')
  table.string('email')
  table.string('password').nullable()
  table.boolean('is_admin').default(false)
  table.string('role').default('member')
  table.text('settings').nullable()
  table.text('secret').nullable()
  table.dateTime('verified_at').nullable()
  table.integer('logins').default(0)
  table.timestamps()
})

Attribute Casting ​

Declare casts in the static casts map, keyed by column. Annotate it as Record<string, CastType> so the literal names type-check:

ts
class Account extends Model {
  static override table = 'accounts'
  static override fillable = [
    'first_name',
    'last_name',
    'email',
    'password',
    'is_admin',
    'role',
    'settings',
    'secret',
    'verified_at',
    'logins',
  ]
  static override casts: Record<string, CastType> = {
    is_admin: 'boolean',
    settings: 'json',
    verified_at: 'datetime',
    logins: 'int',
  }
}

Casts apply in two places:

  • On read, getAttribute() converts the stored value to the cast type.
  • On write, setAttribute() (and so fill(), create() and update()) converts the value to its stored form. The model keeps the stored form in its attribute bag and sends it to the database as is.
ts
const account = await Account.create({
  first_name: 'Ann',
  last_name: 'Lee',
  email: 'ann@example.com',
  is_admin: true,
  settings: { theme: 'dark' },
  verified_at: new Date('2026-01-01T00:00:00Z'),
  logins: '3',
})

account.getRawAttribute('is_admin') // => 1
account.getAttribute('is_admin') // => true
account.getRawAttribute('settings') // => '{"theme":"dark"}'
account.getAttribute('settings') // => { theme: 'dark' }
account.getAttribute('verified_at') // => a Date
account.getAttribute('logins') // => 3

getRawAttribute() returns the stored value without casting. A null or undefined value passes through every built-in cast unchanged.

Built-in casts ​

CastRead givesStored as
'int', 'integer'a truncated integeran integer
'float', 'real'a numbera number
'boolean', 'bool'true or false1 or 0
'string'a stringa string
'json', 'array', 'object'the parsed valuea JSON string
'date', 'datetime'a Datean ISO 8601 string

The boolean cast understands 0, 1, '0', 'false' and the empty string as false. The JSON casts store a string as given (assuming you already serialized it) and serialize anything else with JSON.stringify. A JSON value that fails to parse is returned as the raw string.

The date casts accept a Date, an ISO string, or epoch milliseconds when reading.

Casts and dirty tracking ​

Dirty tracking compares stored values, and compares objects structurally. Assigning an equal JSON value is not a change:

ts
const found = (await Account.find(account.getKey()))!

found.setAttribute('settings', { theme: 'dark' })
found.isDirty('settings') // => false

found.setAttribute('settings', { theme: 'light' })
found.isDirty('settings') // => true

Enum casts ​

enumCast(values) restricts a column to a fixed set of values. Reading a stored value that is not in the set gives null; writing one throws:

ts
enum Role {
  Member = 'member',
  Admin = 'admin',
}

class Employee extends Model {
  static override table = 'accounts'
  static override fillable = ['role']
  static override casts: Record<string, CastType> = {
    role: enumCast(Object.values(Role)),
  }
}

const employee = new Employee({ role: 'admin' })
employee.getAttribute('role') // => 'admin'

employee.setAttribute('role', 'boss')
// throws: Invalid enum value [boss]; expected one of: member, admin.

Encrypted casts ​

encryptedCast(encrypter) encrypts a column at rest. The stored value is ciphertext and reading decrypts it. Pass an Encrypter from @plinthjs/encryption, or any object with encrypt(value) and decrypt(payload).

ts
import { Encrypter } from '@plinthjs/encryption'

const encrypter = new Encrypter(Encrypter.generateKey())

class Vault extends Model {
  static override table = 'accounts'
  static override fillable = ['first_name', 'last_name', 'email', 'secret']
  static override casts: Record<string, CastType> = {
    secret: encryptedCast(encrypter),
  }
}

const vault = await Vault.create({
  first_name: 'A',
  last_name: 'B',
  email: 'a@b.c',
  secret: 'token',
})
vault.getRawAttribute('secret') // => a base64 ciphertext
vault.getAttribute('secret') // => 'token'

Keep the key in configuration (see Encryption); losing it makes the column unreadable. You cannot query on an encrypted column, since each encryption produces different ciphertext.

Custom casts ​

A custom cast is an object with a get and a set function. get turns the stored value into the in-memory value; set turns an in-memory value into the stored one. Both also receive the model. Because set runs for every write, a custom cast is also how you write a mutator.

ts
const cents: Cast = {
  get: (value) => Number(value) / 100,
  set: (value) => Math.round(Number(value) * 100),
}

const lowercase: Cast = {
  get: (value) => value,
  set: (value) => (typeof value === 'string' ? value.toLowerCase().trim() : value),
}

class Product extends Model {
  static override table = 'products'
  static override fillable = ['price', 'sku']
  static override casts: Record<string, CastType> = { price: cents, sku: lowercase }
}

const product = new Product({ price: 12.5, sku: '  ABC-1 ' })
product.getRawAttribute('price') // => 1250
product.getAttribute('price') // => 12.5
product.getAttribute('sku') // => 'abc-1'

Custom casts must handle null themselves, since the null pass-through only applies to the built-in names.

Accessors ​

An accessor computes a value when you read an attribute. Define a method named get<StudlyName>Attribute, where the name is the attribute name in studly case (full_name becomes FullName). getAttribute() calls it before any cast or raw value:

ts
class Person extends Model {
  static override table = 'accounts'
  static override fillable = ['first_name', 'last_name']

  getFullNameAttribute(): string {
    return `${this.getRawAttribute('first_name')} ${this.getRawAttribute('last_name')}`
  }
}

const person = new Person({ first_name: 'Ann', last_name: 'Lee' })
person.getAttribute('full_name') // => 'Ann Lee'

Inside an accessor, read the underlying columns with getRawAttribute(). Calling getAttribute() with the accessor's own name would recurse.

An accessor can also override the value of a real column. Accessors are plain method calls with no property sugar, so read them with getAttribute('name'), not person.full_name.

Mutators ​

A mutator transforms a value as it is written. Define a method named set<StudlyName>Attribute(value). setAttribute() calls it before any cast, and stores the value it returns:

ts
class Subscriber extends Model {
  static override table = 'accounts'
  static override fillable = ['email']

  setEmailAttribute(value: unknown): string {
    return String(value).toLowerCase().trim()
  }
}

new Subscriber({ email: ' ANN@Example.com ' }).getAttribute('email') // => 'ann@example.com'

fill(), create() and update() all route through setAttribute(), so the mutator covers mass assignment too. Models hydrated from the database skip mutators, since the stored value is already in its stored form.

Return the value to store; do not call setAttribute() with the same key inside the mutator, which would recurse. A mutator that returns undefined stores nothing for its own key, which lets it write other attributes itself:

ts
class Article extends Model {
  static override table = 'posts'
  static override fillable = ['title']

  setTitleAttribute(value: unknown): undefined {
    this.$attributes['title'] = String(value)
    this.$attributes['slug'] = String(value).toLowerCase().replaceAll(' ', '-')
    return undefined
  }
}

A custom cast set, or overriding setAttribute(), still works and is the better choice when one transformation should apply to a column everywhere.

Appending Accessors ​

Computed attributes are not part of a model's serialized output unless you list them in appends. Each name is resolved with getAttribute(), so it needs an accessor:

ts
class AppendedPerson extends Model {
  static override table = 'accounts'
  static override fillable = ['first_name', 'last_name']
  static override appends = ['full_name']

  getFullNameAttribute(): string {
    return `${this.getRawAttribute('first_name')} ${this.getRawAttribute('last_name')}`
  }
}

new AppendedPerson({ first_name: 'Ann', last_name: 'Lee' }).toJSON()
// => { first_name: 'Ann', last_name: 'Lee', full_name: 'Ann Lee' }

See Serialization for how appends interacts with hidden and visible.

When a model is serialized, an accessor is applied to its stored column the same way, whether or not the model declares casts, so an accessor that overrides a real column changes the JSON output too.

Mass Assignment and Attribute Handling ​

Attributes enter a model in three ways, each with different rules:

  • new Model(attrs), fill(), create() and update() honor fillable and guarded, then apply casts. Guarded keys are dropped silently.
  • forceFill() skips the mass assignment guard but still applies casts.
  • setAttribute() writes one key with its cast and does not check the guard.
  • Models loaded from the database are hydrated raw: the guard is skipped, no casts run on load, and the values are treated as the clean baseline for dirty tracking.

getKey() returns the primary key, and setRawAttributes(attrs) replaces the whole bag without casting, which is useful in tests.

ts
const a = new Account({ first_name: 'x', not_a_column: 1 })
a.getRawAttribute('first_name') // => 'x'
a.getRawAttribute('not_a_column') // => undefined (not in fillable)

Released under the MIT License.