Skip to content
Active Record
Esc
↑↓navigate↵open⌘Jpreview
On this page

Callbacks

Run your code at points in a record’s lifecycle, such as before it’s validated or after it’s saved.

At a glance

To Write
run code before a record is validated this.beforeValidation((order) => { … })
run code only when a record is created beforeCreate, or beforeValidation(…, { on: "create" })
run code on both sides of a write this.aroundSave(async (order, next) => { await next() })
send an email once a record is created this.afterCreateCommit(async (user) => { … })
run code after touch() this.afterTouch(…)
run code when the database refuses a write this.afterRollback(…)
fill in a new record’s defaults this.afterInitialize(…)
stop a save or destroy throw abort("reason") in a before-callback

The Models

The examples use these Models, whose attributes come from their tables through the schema active-record schema generates. Each registers its callbacks in its static {} block, and mail.ts and cache.ts stand in for the app’s own services:

import { abort } from "@forestfuture/active-record";
import { sendShippedEmail } from "../mail";
import { ApplicationRecord } from "./application-record";

export class Order extends ApplicationRecord {
  static {
    this.beforeValidation((order) => {
      order.email = order.email.trim().toLowerCase();
    });
    this.beforeValidation(
      (order) => {
        order.placedAt = new Date();
      },
      { on: "create" },
    );
    this.beforeSave((order) => {
      if (order.isSuspended) throw abort("Orders can't change while suspended");
    });
    this.aroundSave(async (order, next) => {
      const started = Date.now();
      await next();
      console.log(`Saved order ${order.number} in ${Date.now() - started} ms`);
    });
    this.afterSave(async (order) => {
      if (order.hasSavedChangeTo("status", { to: "shipped" })) {
        await sendShippedEmail(order.email);
      }
    });
    this.afterRollback((order) => {
      console.log(`Order ${order.number} wasn't saved`);
    });
  }
}
import { sendWelcomeEmail } from "../mail";
import { ApplicationRecord } from "./application-record";

export class User extends ApplicationRecord {
  static {
    this.afterCreateCommit(async (user) => {
      await sendWelcomeEmail(user.email);
    });
  }
}
import { purgeCachedPage } from "../cache";
import { ApplicationRecord } from "./application-record";

export class Article extends ApplicationRecord {
  static {
    this.afterTouch(async (article) => {
      await purgeCachedPage(`/articles/${article.id}`);
    });
  }
}
import { ApplicationRecord } from "./application-record";

export class Invoice extends ApplicationRecord {
  static {
    this.afterInitialize((invoice) => {
      if (invoice.isNewRecord()) invoice.currency ??= invoice.country === "GB" ? "GBP" : "USD";
    });
    this.afterFind((invoice) => {
      // A record loaded with select() may leave totalCents out.
      if (invoice.hasAttribute("totalCents") && invoice.totalCents > 1_000_000) {
        console.log(`Large invoice ${invoice.id} loaded`);
      }
    });
  }
}
// The app's emails. Here they're logged, as a test's mailer would.
export async function sendWelcomeEmail(email: string): Promise<void> {
  console.log(`Welcome email to ${email}`);
}

export async function sendShippedEmail(email: string): Promise<void> {
  console.log(`Shipped email to ${email}`);
}
// The app's page cache. Here a purge is logged.
export async function purgeCachedPage(path: string): Promise<void> {
  console.log(`Purged ${path}`);
}
// Generated by `active-record schema` from migrations/ — don't edit.
// schema: 141262a87f5f

import { defineSchema, type TableAttributes } from "@forestfuture/active-record";
import { d1 } from "@forestfuture/active-record/d1";

/** articles — last changed by 0001_create_tables.sql */
export const articles = {
  id: { type: "string", null: false, generateId: true },
  title: { type: "string", null: false },
  updatedAt: "datetime",
} as const;

/** invoices — last changed by 0001_create_tables.sql */
export const invoices = {
  id: { type: "string", null: false, generateId: true },
  country: { type: "string", null: false },
  currency: "string",
  totalCents: { type: "integer", null: false, default: () => 0 },
} as const;

/** orders — last changed by 0001_create_tables.sql */
export const orders = {
  id: { type: "string", null: false, generateId: true },
  number: { type: "string", null: false },
  status: { type: "string", null: false, default: () => "pending" },
  email: { type: "string", null: false },
  totalCents: { type: "integer", null: false },
  isSuspended: { type: "boolean", null: false, default: () => false },
  placedAt: "datetime",
} as const;

/** users — last changed by 0001_create_tables.sql */
export const users = {
  id: { type: "string", null: false, generateId: true },
  email: { type: "string", null: false },
} as const;

/** The database's adapter and binding, its tables (with their primary keys), and the Models built on them. */
export const schema = defineSchema({
  adapter: d1({ binding: "DB" }),
  tables: {
    articles: { attributes: articles, primaryKey: "id" },
    invoices: { attributes: invoices, primaryKey: "id" },
    orders: { attributes: orders, primaryKey: "id" },
    users: { attributes: users, primaryKey: "id" },
  },
  models: { Article: "articles", Invoice: "invoices", Order: "orders", User: "users" },
});

declare module "../models/article" {
  interface Article extends TableAttributes<typeof articles, (typeof Article)["attributes"]> {}
}

declare module "../models/invoice" {
  interface Invoice extends TableAttributes<typeof invoices, (typeof Invoice)["attributes"]> {}
}

declare module "../models/order" {
  interface Order extends TableAttributes<typeof orders, (typeof Order)["attributes"]> {}
}

declare module "../models/user" {
  interface User extends TableAttributes<typeof users, (typeof User)["attributes"]> {}
}
CREATE TABLE orders (
  id TEXT PRIMARY KEY NOT NULL,
  number TEXT NOT NULL,
  status TEXT NOT NULL DEFAULT 'pending',
  email TEXT NOT NULL,
  total_cents INTEGER NOT NULL,
  is_suspended BOOLEAN NOT NULL DEFAULT FALSE,
  placed_at DATETIME
);
CREATE UNIQUE INDEX index_orders_on_number ON orders (number);
CREATE TABLE users (
  id TEXT PRIMARY KEY NOT NULL,
  email TEXT NOT NULL
);
CREATE TABLE articles (
  id TEXT PRIMARY KEY NOT NULL,
  title TEXT NOT NULL,
  updated_at DATETIME
);
CREATE TABLE invoices (
  id TEXT PRIMARY KEY NOT NULL,
  country TEXT NOT NULL,
  currency TEXT,
  total_cents INTEGER NOT NULL DEFAULT 0
);
CREATE TABLE orders (
  id UUID PRIMARY KEY,
  number TEXT NOT NULL,
  status TEXT NOT NULL DEFAULT 'pending',
  email TEXT NOT NULL,
  total_cents INTEGER NOT NULL,
  is_suspended BOOLEAN NOT NULL DEFAULT FALSE,
  placed_at TIMESTAMPTZ
);
CREATE UNIQUE INDEX index_orders_on_number ON orders (number);
CREATE TABLE users (
  id UUID PRIMARY KEY,
  email TEXT NOT NULL
);
CREATE TABLE articles (
  id UUID PRIMARY KEY,
  title TEXT NOT NULL,
  updated_at TIMESTAMPTZ
);
CREATE TABLE invoices (
  id UUID PRIMARY KEY,
  country TEXT NOT NULL,
  currency TEXT,
  total_cents INTEGER NOT NULL DEFAULT 0
);

Registering callbacks

Register callbacks in a Model’s static {} block, as Order does, and they run as the record is saved:

import { class OrderOrder } from "./models/order";

const const order: Orderorder = await class OrderOrder.
create<typeof Order>(this: typeof Order, attributes?: Partial<AttributeProperties<OverriddenSpecs<{
    readonly id: {
        readonly type: "string";
        readonly null: false;
        readonly generateId: true;
    };
    readonly number: {
        readonly type: "string";
        readonly null: false;
    };
    readonly status: {
        readonly type: "string";
        readonly null: false;
        readonly default: () => string;
    };
    readonly email: {
        readonly type: "string";
        readonly null: false;
    };
    readonly totalCents: {
        readonly type: "integer";
        readonly null: false;
    };
    readonly isSuspended: {
        readonly type: "boolean";
        readonly null: false;
        readonly default: () => boolean;
    };
    readonly placedAt: "datetime";
}, Readonly<Record<string, false | AttributeOverride>> | undefined>>> | undefined, init?: Init<...> | undefined): Promise<...>
Builds a record, awaits `init` with it if it's given, and saves it; resolves to it whether or not it was saved (check `isPersisted()`).
create
({
number?: string | undefinednumber: "1001", email?: string | undefinedemail: " Jane@Example.com ", totalCents?: number | undefinedtotalCents: 2500, }); var console: Consoleconsole.Console.log(...data: any[]): void (+1 overload)
The **`console.log()`** static method outputs a message to the console. [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)
log
(const order: Orderorder.email: stringemail); // "jane@example.com", from the first beforeValidation
var console: Consoleconsole.Console.log(...data: any[]): void (+1 overload)
The **`console.log()`** static method outputs a message to the console. [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)
log
(const order: Orderorder.placedAt: Date | nullplacedAt); // now, from the beforeValidation that runs on create
await const order: Orderorder.
Model.update(attributes: Partial<AttributeProperties<OverriddenSpecs<{
    readonly id: {
        readonly type: "string";
        readonly null: false;
        readonly generateId: true;
    };
    readonly number: {
        readonly type: "string";
        readonly null: false;
    };
    readonly status: {
        readonly type: "string";
        readonly null: false;
        readonly default: () => string;
    };
    readonly email: {
        readonly type: "string";
        readonly null: false;
    };
    readonly totalCents: {
        readonly type: "integer";
        readonly null: false;
    };
    readonly isSuspended: {
        readonly type: "boolean";
        readonly null: false;
        readonly default: () => boolean;
    };
    readonly placedAt: "datetime";
}, Readonly<Record<string, false | AttributeOverride>> | undefined>>>): Promise<boolean>
`assign` then `save`.
update
({ status?: string | undefinedstatus: "shipped" }); // afterSave sends the shipped email
  • Each callback receives the record, and may be async, except the callbacks for a record built or loaded.
  • Callbacks of one kind run in the order declared. A subclass runs its parent’s callbacks, then its own.
  • Pass on to beforeValidation or afterValidation to run it only in some validation contexts, as Order’s second beforeValidation does.

Callback order

Order Callback Runs abort()
Saving
1 beforeValidation Before the validators, on every save, and on isValid() Stops the save
2 afterValidation After the validators Stops the save
3 beforeSave Before every write, new or persisted Stops the save
4 aroundSave Its first part, before next() Stops the save
5 beforeCreate Before inserting a new record Stops the save
5 beforeUpdate Before updating a persisted record Stops the save
6 aroundCreate Its first part, before next() Stops the save
6 aroundUpdate Its first part, before next() Stops the save
The write Skipped when a persisted record has no changes
7 aroundCreate Its last part, once next() resolves Too late: AbortAfterPersistence
7 aroundUpdate Its last part, once next() resolves Too late: AbortAfterPersistence
8 afterCreate After inserting a new record Too late: AbortAfterPersistence
8 afterUpdate After updating a persisted record Too late: AbortAfterPersistence
9 aroundSave Its last part, once next() resolves Too late: AbortAfterPersistence
10 afterSave After every successful save Too late: AbortAfterPersistence
11 afterCommit Last, after every after-callback Too late: AbortAfterPersistence
11 afterCreateCommit Last, after inserting a new record Too late: AbortAfterPersistence
11 afterUpdateCommit Last, after updating a persisted record Too late: AbortAfterPersistence
11 afterSaveCommit Last, after every successful save Too late: AbortAfterPersistence
Destroying
1 beforeDestroy Before the dependent strategies and the DELETE Stops the destroy
2 aroundDestroy Its first part, before next() Stops the destroy
The delete With the dependents, in one batch
3 aroundDestroy Its last part, once next() resolves Too late: AbortAfterPersistence
4 afterDestroy After the record is destroyed Too late: AbortAfterPersistence
5 afterCommit Last, after every after-callback Too late: AbortAfterPersistence
5 afterDestroyCommit Last, after the record is destroyed Too late: AbortAfterPersistence
Touching
The write updatedAt, and any attributes named
1 afterTouch After touch() writes the record’s timestamps Too late: AbortAfterPersistence
2 afterCommit Last, when touch() wrote a row Too late: AbortAfterPersistence
2 afterUpdateCommit Last, when touch() wrote a row Too late: AbortAfterPersistence
2 afterSaveCommit Last, when touch() wrote a row Too late: AbortAfterPersistence
Refused
1 afterRollback When the database refuses the save or destroy Nothing to stop
Loading
1 afterFind After a record is loaded Nothing to stop
2 afterInitialize After a record is loaded, or built Nothing to stop

A save runs either the create pair or the update pair, never both.

  • After-callbacks run after every successful save, even one with no changes to write.
  • A before-callback that changes an attribute makes the record dirty, and the change is written.
  • An after-callback that changes an attribute leaves the record dirty. Nothing is written again.

Wrapping a save or destroy

An around callback runs code on both sides of a write, as Order’s aroundSave does. Call next() to run the rest of the save, and await it.

  • aroundSave runs after beforeSave. Its next() runs beforeCreate or beforeUpdate, the write, and afterCreate or afterUpdate. afterSave runs once the callback finishes.
  • aroundCreate, aroundUpdate, and aroundDestroy wrap only the write, between the matching before- and after-callbacks.
  • Several around callbacks of one kind nest. The first one declared is the outermost.

next() returns a promise with no value. It resolves once the database has kept the write. A save sends its writes together, so in a batch, every record’s first part runs before the batch is written. Then each record’s last part runs in turn.

Stopping a wrapped write

  • Not calling next() stops the save, as abort() does. save() resolves to false, and nothing is written.
  • An abort() before next() stops the save. After next(), the write has happened, so abort() throws AbortAfterPersistence.
  • When the database refuses the write, afterRollback runs, then next() rejects with the database’s error. The save throws it even if you catch it.
  • When the save ends without sending the write, next() rejects with the error the save ends with. That happens when another record in the save or batch is refused before the write is sent.
  • When an earlier record’s after-callback throws, the write is kept. This record’s after-callbacks are skipped, and next() rejects with that error.

To release something you hold during the write, put await next() in a try block, and release it in finally.

Running code after the commit

Register a commit callback, as User does, to run code once everything is written:

import { class UserUser } from "./models/user";

await class UserUser.
create<typeof User>(this: typeof User, attributes?: Partial<AttributeProperties<OverriddenSpecs<{
    readonly id: {
        readonly type: "string";
        readonly null: false;
        readonly generateId: true;
    };
    readonly email: {
        readonly type: "string";
        readonly null: false;
    };
}, Readonly<Record<string, false | AttributeOverride>> | undefined>>> | undefined, init?: Init<User> | undefined): Promise<User>
Builds a record, awaits `init` with it if it's given, and saves it; resolves to it whether or not it was saved (check `isPersisted()`).
create
({ email?: string | undefinedemail: "sam@example.com" }); // then afterCreateCommit sends the welcome email

Commit callbacks run last, after every after-callback of the save. In a batch, they wait for every record’s after-callbacks.

  • afterCommit runs after a create, an update, or a destroy.
  • afterCreateCommit, afterUpdateCommit, and afterDestroyCommit run after one kind of write. afterSaveCommit runs after a create or an update.
  • Commit callbacks of every kind run in the order you declared them.

Running code after a touch

afterTouch runs after touch() writes a record’s timestamps, as Article’s does:

import { class ArticleArticle } from "./models/article";

const const article: Articlearticle = await class ArticleArticle.findByOrThrow<typeof Article>(this: typeof Article, conditions: SafeSql | Conditions<Article>): Promise<Article>
Like `findBy`, but throws `RecordNotFound` instead of returning null.
findByOrThrow
({ title?: string | readonly string[] | Comparison<string> | undefinedtitle: "Hello" });
await const article: Articlearticle.AttributeWrites.touch<Article>(this: Article, ...args: TouchArguments<Article>): Promise<boolean>
Sets `updatedAt`, and the datetime attributes named, to now (or `{ time }`), straight to the row, with no validation or save callback. Resolves to whether there was a row to write. Inside its Model's `noTouching` block, it writes nothing (#496).
touch
(); // sets updatedAt, then afterTouch purges the cached page
  • No validation or save callback runs for a touch.
  • The commit callbacks for an update run after afterTouch: afterCommit, afterUpdateCommit, and afterSaveCommit. When the row is gone, only afterTouch runs.
  • savedChanges() holds only the touched attributes, so hasSavedChangeTo("email") is false in a touch’s callbacks.
  • A refused touch runs afterRollback, and the record stays as it was.

A belongsTo declared with touch touches its record the same way. Saving a comment can run its article’s afterTouch and commit callbacks.

touchAll and the counters’ touch option run no callbacks.

Handling a refused write

afterRollback runs when the database refuses a record’s save or destroy, as Order’s does for a number that’s taken:

import { class OrderOrder } from "./models/order";

const const order: Orderorder = class OrderOrder.
build<typeof Order>(this: typeof Order, attributes?: Partial<AttributeProperties<OverriddenSpecs<{
    readonly id: {
        readonly type: "string";
        readonly null: false;
        readonly generateId: true;
    };
    readonly number: {
        readonly type: "string";
        readonly null: false;
    };
    readonly status: {
        readonly type: "string";
        readonly null: false;
        readonly default: () => string;
    };
    readonly email: {
        readonly type: "string";
        readonly null: false;
    };
    readonly totalCents: {
        readonly type: "integer";
        readonly null: false;
    };
    readonly isSuspended: {
        readonly type: "boolean";
        readonly null: false;
        readonly default: () => boolean;
    };
    readonly placedAt: "datetime";
}, Readonly<Record<string, false | AttributeOverride>> | undefined>>> | undefined, init?: ((record: Order) => void) | undefined): Order
A new, unsaved record of this Relation's Model, handed to `init` first if it's given. Nothing awaits `init`, so one that returns a promise throws `TypeError`. Built through a hasMany, it joins the association, and saving the owner saves it too (autosave).
build
({ number?: string | undefinednumber: "1001", email?: string | undefinedemail: "sam@example.com", totalCents?: number | undefinedtotalCents: 900 });
await const order: Orderorder.Model.save(options?: SaveOptions): Promise<boolean>
Inserts a new record or updates a persisted one; `false` if it's invalid, a callback aborted, or a record it destroys refused (#37). `context` validates it in that context (`"signup"`), as `isValid(context)` does.
save
(); // throws RecordNotUnique, once afterRollback has logged "Order 1001 wasn't saved"
  • A constraint error refuses the record’s write, and the save then throws the constraint error.
  • In a batch, one refused write refuses them all, so afterRollback runs for every record in it.
  • A failed validation or an abort() sends nothing, so afterRollback doesn’t run.

The record keeps its unsaved state, and no after-callback or commit callback runs for it.

Running code when a record is built or loaded

afterInitialize runs for every record you build and every record you load, as Invoice’s fills in a new invoice’s currency. afterFind runs for every record you load, just before afterInitialize:

import { class InvoiceInvoice } from "./models/invoice";

const const invoice: Invoiceinvoice = class InvoiceInvoice.
build<typeof Invoice>(this: typeof Invoice, attributes?: Partial<AttributeProperties<OverriddenSpecs<{
    readonly id: {
        readonly type: "string";
        readonly null: false;
        readonly generateId: true;
    };
    readonly country: {
        readonly type: "string";
        readonly null: false;
    };
    readonly currency: "string";
    readonly totalCents: {
        readonly type: "integer";
        readonly null: false;
        readonly default: () => number;
    };
}, Readonly<Record<string, false | AttributeOverride>> | undefined>>> | undefined, init?: ((record: Invoice) => void) | undefined): Invoice
A new, unsaved record of this Relation's Model, handed to `init` first if it's given. Nothing awaits `init`, so one that returns a promise throws `TypeError`. Built through a hasMany, it joins the association, and saving the owner saves it too (autosave).
build
({ country?: string | undefinedcountry: "GB" });
var console: Consoleconsole.Console.log(...data: any[]): void (+1 overload)
The **`console.log()`** static method outputs a message to the console. [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)
log
(const invoice: Invoiceinvoice.currency: string | nullcurrency); // "GBP", from afterInitialize
  • build and create run afterInitialize after their init function, so it sees what init set. Building through a hasMany or hasOne runs it once the record points at its owner. Building through a through association runs the join record’s afterInitialize once it points at the record.
  • Every load runs afterFind, then afterInitialize: a query, an association read, a preload, and reload(). Preloaded associations aren’t attached yet when they run.
  • Saving a record runs neither, and neither does new Invoice().

Both callbacks run synchronously, since build can’t wait for them. An async one is a type error. An error thrown by either reaches the caller, and the query returns no records.

Handling partial records

A record loaded with select runs both callbacks too, and reading an attribute it left out throws MissingAttribute. Check with hasAttribute first, as Invoice’s afterFind does:

import { class InvoiceInvoice } from "./models/invoice";

const const invoices: Invoice[]invoices = await class InvoiceInvoice.select<typeof Invoice>(this: typeof Invoice, ...args: ("id" | "country" | "currency" | "totalCents")[]): Relation<Invoice, ScopesOf<typeof Invoice>>
Loads only these attributes (a partial record); the primary key is always loaded.
select
("id", "country").Relation<Invoice, ScopesOf<typeof Invoice>>.toArray(): Promise<Invoice[]>toArray(); // afterFind skips the total
const const large: Invoice[]large = await class InvoiceInvoice.where<typeof Invoice>(this: typeof Invoice, conditions: SafeSql | Conditions<Invoice>): Relation<Invoice, ScopesOf<typeof Invoice>>where({ country?: string | readonly string[] | Comparison<string> | undefinedcountry: "US" }).Relation<Invoice, ScopesOf<typeof Invoice>>.toArray(): Promise<Invoice[]>toArray(); // afterFind logs the large one

Stopping a save

Throw abort(reason) from a before-callback to stop a save or destroy, as Order’s beforeSave does for a suspended order:

import { class OrderOrder } from "./models/order";

const const order: Orderorder = await class OrderOrder.findByOrThrow<typeof Order>(this: typeof Order, conditions: SafeSql | Conditions<Order>): Promise<Order>
Like `findBy`, but throws `RecordNotFound` instead of returning null.
findByOrThrow
({ number?: string | readonly string[] | Comparison<string> | undefinednumber: "1002" }); // a suspended order
const order: Orderorder.totalCents: numbertotalCents = 0; await const order: Orderorder.Model.save(options?: SaveOptions): Promise<boolean>
Inserts a new record or updates a persisted one; `false` if it's invalid, a callback aborted, or a record it destroys refused (#37). `context` validates it in that context (`"signup"`), as `isValid(context)` does.
save
(); // false, and nothing is written
var console: Consoleconsole.Console.log(...data: any[]): void (+1 overload)
The **`console.log()`** static method outputs a message to the console. [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)
log
(const order: Orderorder.Model.abortReason: string | undefined
Why a callback last refused a save or destroy (`abort(reason)`); never copied into `errors`.
abortReason
); // "Orders can't change while suspended"
  • save() resolves to false and writes nothing. The record keeps its changes, and record.abortReason holds the reason.
  • saveOrThrow() throws RecordNotSaved with the reason.
  • destroy() resolves to false, and destroyOrThrow() throws RecordNotDestroyed.

Only abort() stops a save. Returning false does nothing, and any other error reaches the caller as it is.

Last updated on