Shared behavior
Write methods, callbacks, and scopes once, on your app’s base class.
At a glance
| To | Write, on ApplicationRecord |
|---|---|
| give every record a method | label() { … } |
| run a callback for every Model | this.beforeSave(…), in static {} |
| give every Model a scope | static newest = this.scope((q) => q.order(sql`…`)) |
| share behavior between only some Models | an abstract class between them and ApplicationRecord |
The Models
The examples use these Models, whose attributes come from their tables through the schema active-record schema generates:
import { Model, sql } from "@forestfuture/active-record";
import { schema } from "../db/schema";
// What's written on ApplicationRecord, every Model has.
export abstract class ApplicationRecord extends Model {
static override schema = schema;
static newest = this.scope((q) => q.order(sql`created_at DESC`));
label() {
return `${this.constructor.name} ${JSON.stringify(this.attributes())}`;
}
static {
this.beforeSave((record) => {
console.log(`Saving ${record.constructor.name}`); // before each Model's own callbacks
});
}
}import { ApplicationRecord } from "./application-record";
export class Product extends ApplicationRecord {}import { ApplicationRecord } from "./application-record";
// Shared by only the Models that extend it. It has no table of its own.
export abstract class Auditable extends ApplicationRecord {
static override abstract = true;
static {
this.afterSave((record) => {
console.log(`Saved ${record.constructor.name}`);
});
}
}import { Auditable } from "./auditable";
export class Invoice extends Auditable {}// Generated by `active-record schema` from migrations/ — don't edit.
// schema: 114ec35af314
import { defineSchema, type TableAttributes } from "@forestfuture/active-record";
import { d1 } from "@forestfuture/active-record/d1";
/** invoices — last changed by 0001_create_tables.sql */
export const invoices = {
id: { type: "string", null: false, generateId: true },
totalCents: { type: "integer", null: false },
createdAt: { type: "datetime", null: false },
} as const;
/** products — last changed by 0001_create_tables.sql */
export const products = {
id: { type: "string", null: false, generateId: true },
name: { type: "string", null: false },
createdAt: { type: "datetime", 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: {
invoices: { attributes: invoices, primaryKey: "id" },
products: { attributes: products, primaryKey: "id" },
},
models: { Invoice: "invoices", Product: "products" },
});
declare module "../models/invoice" {
interface Invoice extends TableAttributes<typeof invoices, (typeof Invoice)["attributes"]> {}
}
declare module "../models/product" {
interface Product extends TableAttributes<typeof products, (typeof Product)["attributes"]> {}
}CREATE TABLE products (
id TEXT PRIMARY KEY NOT NULL,
name TEXT NOT NULL,
created_at DATETIME NOT NULL
);
CREATE TABLE invoices (
id TEXT PRIMARY KEY NOT NULL,
total_cents INTEGER NOT NULL,
created_at DATETIME NOT NULL
);CREATE TABLE products (
id UUID PRIMARY KEY,
name TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL
);
CREATE TABLE invoices (
id UUID PRIMARY KEY,
total_cents INTEGER NOT NULL,
created_at TIMESTAMPTZ NOT NULL
);Sharing methods, callbacks, and scopes
Write them on ApplicationRecord, in src/models/application-record.ts, and every Model has them, as Product does:
import { class ProductProduct } from "./models/product";
const const lamp: Productlamp = await class ProductProduct.create<typeof Product>(this: typeof Product, attributes?: Partial<AttributeProperties<OverriddenSpecs<{
readonly id: {
readonly type: "string";
readonly null: false;
readonly generateId: true;
};
readonly name: {
readonly type: "string";
readonly null: false;
};
readonly createdAt: {
readonly type: "datetime";
readonly null: false;
};
}, Readonly<Record<string, false | AttributeOverride>> | undefined>>> | undefined, init?: Init<Product> | 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({ name?: string | undefinedname: "Lamp" }); // logs "Saving Product"
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 lamp: Productlamp.ApplicationRecord.label(): stringlabel()); // Product {"id":"…","name":"Lamp","createdAt":"…"}
const const newest: Product | nullnewest = await class ProductProduct.ApplicationRecord.newest: <typeof Product>(this: typeof Product) => Relation<Product, ScopesOf<typeof Product>> & ScopeMethods<Product, ScopesOf<typeof Product>>newest().Relation<Product, ScopesOf<typeof Product>>.first(): Promise<Product | null>The first record by this Relation's order, or by primary key if it has none.first(); // the shared scope, on productsEach is shared like this:
On ApplicationRecord |
Every Model |
|---|---|
A method, such as label() |
has it, on every record |
| A static method | has it, on the Model |
A callback, in static {} |
runs it, before the Model’s own callbacks of that kind |
A scope, static newest = this.scope(…) |
has it, as Product.newest() and on its Relations |
static override onQuery |
logs its queries (see Logging) |
A Model can replace a shared method or scope by declaring one of the same name.
Writing for every table
Inside ApplicationRecord, this is a record of any Model. It has every record method, such as save() and attributes(), but no attributes, since those differ from table to table:
- Read attributes through
this.attributes(), aslabel()does. - Write shared scopes with
sqlfragments, asnewestdoes, since they run on each Model’s own table. - Validations name attributes, so they belong on each Model. Put shared checks in a callback instead.
ApplicationRecord has no table of its own, so db.model(ApplicationRecord) throws InvalidModel. Once a Model has been used, ApplicationRecord is sealed with it, so request code can’t add callbacks to every Model.
Sharing behavior between some Models
To share behavior between only some Models, put it on a class between them and ApplicationRecord, marked abstract, as Auditable is:
import { class InvoiceInvoice } from "./models/invoice";
await class InvoiceInvoice.create<typeof Invoice>(this: typeof Invoice, attributes?: Partial<AttributeProperties<OverriddenSpecs<{
readonly id: {
readonly type: "string";
readonly null: false;
readonly generateId: true;
};
readonly totalCents: {
readonly type: "integer";
readonly null: false;
};
readonly createdAt: {
readonly type: "datetime";
readonly null: false;
};
}, Readonly<Record<string, false | AttributeOverride>> | undefined>>> | undefined, init?: Init<Invoice> | 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({ totalCents?: number | undefinedtotalCents: 1200 }); // logs "Saving Invoice", then "Saved Invoice"Auditable has no table. Each class that extends it has its own, so Invoice reads and writes invoices.
Sharing across databases
Each database has its own base class, such as DbRecord and LogsRecord, holding its own schema. To share behavior across all of them, write it on one abstract class extending Model, and extend that class in each base class’s file:
import { Model } from "@forestfuture/active-record";
import { schema } from "../db/LOGS";
export abstract class AppRecord extends Model {
label() {
return `${this.constructor.name} ${JSON.stringify(this.attributes())}`;
}
}
export abstract class LogsRecord extends AppRecord {
static override schema = schema;
}
See Multiple databases.