Skip to content

Events ​

Introduction ​

Models announce what they are doing as they persist. You can listen for those moments to generate a slug before a row is inserted, write an audit record after it is updated, or stop a delete that breaks a rule. Listeners are plain functions registered on a model class; a set of listeners for one model can be grouped into an observer.

These are model lifecycle events. For application-level events with their own dispatcher, see Events.

The examples use this setup:

ts
import { Schema, sqliteConnection } from '@plinthjs/database'
import { ConnectionDataSource, Model } from '@plinthjs/orm'

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

await new Schema(db).create('posts', (table) => {
  table.id()
  table.string('title')
  table.string('slug').nullable()
  table.timestamps()
  table.softDeletes()
})

class Post extends Model {
  static override table = 'posts'
  static override fillable = ['title', 'slug']
  static override softDeletes = true
}

Available Events ​

A model fires these events, listed with the operation that fires them:

EventFires
saving, savedAround every save(), for both inserts and updates.
creating, createdAround the insert of a model that does not exist yet.
updating, updatedAround the update of a model that already exists.
deleting, deletedAround delete(), whether it is a soft or a hard delete.
restoring, restoredAround restore() on a soft deleted model.
forceDeleting, forceDeletedAround forceDelete(), which also fires deleting and deleted.

The "ing" events fire before the database write and can cancel it. The "ed" events fire after it and cannot.

The order for an insert is saving, creating, created, saved. For an update it is saving, updating, updated, saved. updating and updated fire only when the model has dirty attributes: saving an unchanged model fires saving and saved and nothing else.

touch() fires updating and updated with updated_at as the dirty attribute. forceDelete() fires forceDeleting, deleting, deleted and forceDeleted, in that order, and a false from either "ing" listener cancels it.

Listening for Events ​

Register a listener with Model.on(event, listener). The listener receives the model and may be async; it is awaited before the operation continues.

ts
Post.on('creating', async (post) => {
  console.log('about to insert', post.getAttribute('title'))
})

Post.on('created', (post) => {
  console.log('inserted with id', post.getKey())
})

await Post.create({ title: 'Hello World' })

Several listeners can be registered for the same event, and they run in the order they were registered. A subclass inherits the listeners of its parent classes: they run first (base class down to the concrete class), then the listeners registered on the subclass itself.

Changing the model in a listener ​

Changes made to the model in a "ing" listener are saved with it. This is the place for derived values:

ts
Post.on('saving', (post) => {
  if (!post.getAttribute('slug')) {
    const title = String(post.getAttribute('title'))
    post.setAttribute('slug', title.toLowerCase().replace(/\s+/g, '-'))
  }
})

const post = await Post.create({ title: 'Hello World' })
post.getAttribute('slug') // => 'hello-world'

In an updating listener, post.getDirty() shows the changes about to be written.

Cancelling Operations ​

Return false from a listener for saving, creating, updating, deleting or restoring to cancel the operation. Remaining listeners for that event are skipped. Returning false from an "ed" event has no effect.

ts
Post.on('deleting', (post) => post.getAttribute('title') !== 'Keep')

const keep = await Post.create({ title: 'Keep' })
await keep.delete() // => false
keep.trashed() // => false

What the caller sees when an operation is cancelled:

  • save() and update() resolve with the model, unchanged. After a cancelled insert, model.exists is still false.
  • Model.create() resolves with the unsaved model.
  • delete() resolves with false.
  • restore() resolves with the model, still trashed.
ts
Post.on('creating', () => false)

const post = await Post.create({ title: 'Blocked' })
post.exists // => false

A thrown error is different: it rejects the promise and aborts the operation, as any error would.

Observers ​

An observer groups listeners for one model. Pass an object whose keys are event names to Model.observe(), which registers each method as a listener. Keep one observer per concern, in its own file:

ts
import type { ModelObserver } from '@plinthjs/orm'

export const postObserver: ModelObserver<Post> = {
  creating(post) {
    post.setAttribute('slug', String(post.getAttribute('title')).toLowerCase())
  },
  updated(post) {
    console.log('post updated', post.getKey())
  },
  deleting(post) {
    return post.getAttribute('title') !== 'Keep'
  },
}

Post.observe(postObserver)

Register observers once at startup, for example from a service provider.

Muting Events ​

Model.flushEventListeners() removes every listener registered on that exact class. Listeners registered on a parent class are not removed by flushing a subclass. It is the way to start clean in tests, so that listeners from one test do not run in the next:

ts
import { afterEach } from 'vitest'

afterEach(() => {
  Post.flushEventListeners()
})

Gotchas ​

  • Events fire from model instance methods. Bulk builder operations (Post.where(...).update(...), .delete(), .forceDelete()) and upsert() do not fire events, because no model instance is involved. Load the models and call save() or delete() on each when you need the events.
  • pruneAll() deletes each model individually, so deleting and deleted fire for every pruned row (see Pruning Models).

Released under the MIT License.