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

Custom types

Define an attribute type for a value the built-in types don’t hold, such as money.

At a glance

To Write
define a type stored as a built-in one defineType({ storedAs: "integer", cast, serialize, deserialize })
give a generated attribute the type static override attributes = { priceCents: money } as const
refuse a value throw from cast
query by the type’s values Product.where({ priceCents: new Money(500) })

The Models

The examples use these Models, whose attributes come from their tables through the schema active-record schema generates, with the types in src/types/:

import { money } from "../types/money";
import { ApplicationRecord } from "./application-record";

export class Product extends ApplicationRecord {
  static override attributes = {
    priceCents: money,
  } as const;
}
import { sizes } from "../types/sizes";
import { ApplicationRecord } from "./application-record";

export class Shirt extends ApplicationRecord {
  static override attributes = {
    sizes: { type: sizes, default: () => [] },
  } as const;
}
import { defineType } from "@forestfuture/active-record";

export class Money {
  readonly cents: number;

  constructor(cents: number) {
    this.cents = cents;
  }

  toString() {
    return `$${(this.cents / 100).toFixed(2)}`;
  }
}

export const money = defineType({
  storedAs: "integer",
  cast(input) {
    if (input instanceof Money) return input;
    if (Number.isSafeInteger(input)) return new Money(input as number);
    throw new TypeError("money is a Money or a whole number of cents");
  },
  serialize: (value) => value.cents,
  deserialize: (cents) => new Money(cents),
});
import { defineType } from "@forestfuture/active-record";

export const sizes = defineType({
  storedAs: "string",
  cast(input) {
    if (Array.isArray(input) && input.every((size) => typeof size === "string")) {
      return input as string[];
    }
    throw new TypeError("sizes are a list of strings");
  },
  serialize: (list) => list.join(","),
  deserialize: (text) => (text === "" ? [] : text.split(",")),
});
// Generated by `active-record schema` from migrations/ — don't edit.
// schema: b517af0d5b2a

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

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

/** shirts — last changed by 0001_create_tables.sql */
export const shirts = {
  id: { type: "string", null: false, generateId: true },
  name: { type: "string", null: false },
  sizes: { type: "string", null: false, default: () => "" },
} 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: {
    products: { attributes: products, primaryKey: "id" },
    shirts: { attributes: shirts, primaryKey: "id" },
  },
  models: { Product: "products", Shirt: "shirts" },
});

declare module "../models/product" {
  interface Product extends TableAttributes<typeof products, (typeof Product)["attributes"]> {}
}

declare module "../models/shirt" {
  interface Shirt extends TableAttributes<typeof shirts, (typeof Shirt)["attributes"]> {}
}
CREATE TABLE products (
  id TEXT PRIMARY KEY NOT NULL,
  name TEXT NOT NULL,
  price_cents INTEGER NOT NULL
);
CREATE TABLE shirts (
  id TEXT PRIMARY KEY NOT NULL,
  name TEXT NOT NULL,
  sizes TEXT NOT NULL DEFAULT ''
);
CREATE TABLE products (
  id UUID PRIMARY KEY,
  name TEXT NOT NULL,
  price_cents INTEGER NOT NULL
);
CREATE TABLE shirts (
  id UUID PRIMARY KEY,
  name TEXT NOT NULL,
  sizes TEXT NOT NULL DEFAULT ''
);

Defining a type

Define a type with defineType, naming the built-in type it’s stored as. This one keeps money as whole cents in an integer column:

import { defineType } from "@forestfuture/active-record";

export class Money {
  readonly cents: number;

  constructor(cents: number) {
    this.cents = cents;
  }

  toString() {
    return `$${(this.cents / 100).toFixed(2)}`;
  }
}

export const money = defineType({
  storedAs: "integer",
  cast(input) {
    if (input instanceof Money) return input;
    if (Number.isSafeInteger(input)) return new Money(input as number);
    throw new TypeError("money is a Money or a whole number of cents");
  },
  serialize: (value) => value.cents,
  deserialize: (cents) => new Money(cents),
});

A type has three functions:

Function Takes Returns
cast a value given to the attribute the type’s value, or throws
serialize the type’s value a value of the type it’s stored as
deserialize a value of the type it’s stored as the type’s value

The attribute’s TypeScript type is what cast returns, so Money here.

Using a type

Give the type to a generated attribute in static attributes, as Product does:

import { money } from "../types/money";
import { ApplicationRecord } from "./application-record";

export class Product extends ApplicationRecord {
  static override attributes = {
    priceCents: money,
  } as const;
}

Changing an attribute’s type drops its generated default, as any override of a type does. Give it a default if it needs one.

A Model that declares its attributes itself, with Model.define, takes the type in place of a type’s name: total: { type: money, null: false }.

Refusing values

Throw from cast for a value the type can’t hold. Assigning or permitting that value then throws a TypeError naming the Model and attribute, with your error as its cause:

import { class ProductProduct } from "./models/product";

class ProductProduct.
Model.permit<typeof Product, "priceCents">(this: typeof Product, input: unknown, ...names: "priceCents"[]): Partial<Pick<AttributeProperties<OverriddenSpecs<{
    readonly id: {
        readonly type: "string";
        readonly null: false;
        readonly generateId: true;
    };
    readonly name: {
        readonly type: "string";
        readonly null: false;
    };
    readonly priceCents: {
        readonly type: "integer";
        readonly null: false;
    };
}, {
    readonly priceCents: CustomType<Money, "integer">;
}>>, "priceCents">>
Only the named attributes of untrusted input (a JSON body, `FormData` or `URLSearchParams`): `User.create(User.permit(await request.json(), "email", "name"))`. Every other key is dropped, and each value is cast as assigning it would be.
permit
({ priceCents: stringpriceCents: "abc" }, "priceCents");
// TypeError: Product: "abc" isn't a valid value for "priceCents"

The same happens when deserialize throws for a stored value, and when serialize returns a value its stored type can’t hold. For a filtered attribute, the error has no cause, since yours may show the value.

Querying by a type

Conditions take the type’s values, and anything cast takes:

import { function gte<T>(value: T): Comparison<T>
`attribute >= value`: everything from `value` on.
gte
} from "@forestfuture/active-record";
import { class ProductProduct } from "./models/product"; import { class MoneyMoney } from "./types/money"; const const cheap: Product[]cheap = await class ProductProduct.where<typeof Product>(this: typeof Product, conditions: SafeSql | Conditions<Product>): Relation<Product, ScopesOf<typeof Product>>where({ priceCents?: Money | readonly Money[] | Comparison<Money> | undefinedpriceCents: new new Money(cents: number): MoneyMoney(500) }).Relation<Product, ScopesOf<typeof Product>>.toArray(): Promise<Product[]>toArray(); const const pricey: Product[]pricey = await class ProductProduct.where<typeof Product>(this: typeof Product, conditions: SafeSql | Conditions<Product>): Relation<Product, ScopesOf<typeof Product>>where({ priceCents?: Money | readonly Money[] | Comparison<Money> | undefinedpriceCents: gte<Money>(value: Money): Comparison<Money>
`attribute >= value`: everything from `value` on.
gte
(new new Money(cents: number): MoneyMoney(10_000)) })
.Relation<Product, ScopesOf<typeof Product>>.order(spec: SafeSql | OrderSpec<Product>): Relation<Product, ScopesOf<typeof Product>>
Sorts by each key in turn (`{ createdAt: "desc" }`, or `{ role: { direction: "asc", nulls: "last" } }`), or by an `sql` fragment expression. Repeated calls append.
order
({
priceCents?: OrderDirection | {
    direction: OrderDirection;
    nulls?: NullsPlacement;
} | undefined
priceCents
: "desc" })
.Relation<Product, ScopesOf<typeof Product>>.toArray(): Promise<Product[]>toArray();

Values compare and sort as their stored values do, so money sorts by cents. A value cast throws for matches nothing.

Changing values in place

A type can hold a value you change in place. This one keeps a list of sizes as text, and Shirt gives it to sizes:

import { defineType } from "@forestfuture/active-record";

export const sizes = defineType({
  storedAs: "string",
  cast(input) {
    if (Array.isArray(input) && input.every((size) => typeof size === "string")) {
      return input as string[];
    }
    throw new TypeError("sizes are a list of strings");
  },
  serialize: (list) => list.join(","),
  deserialize: (text) => (text === "" ? [] : text.split(",")),
});

Changes are found by comparing what serialize returns, so a size pushed onto the list is a change, and save() writes it:

import { class ShirtShirt } from "./models/shirt";

const const shirt: Shirtshirt = await class ShirtShirt.findByOrThrow<typeof Shirt>(this: typeof Shirt, conditions: SafeSql | Conditions<Shirt>): Promise<Shirt>
Like `findBy`, but throws `RecordNotFound` instead of returning null.
findByOrThrow
({ name?: string | readonly string[] | Comparison<string> | undefinedname: "Oxford" }); // sizes: ["S", "M"]
const shirt: Shirtshirt.sizes: string[]sizes.Array<string>.push(...items: string[]): number
Appends new elements to the end of an array, and returns the new length of the array.
@paramitems New elements to add to the array.
push
("XL");
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 shirt: Shirtshirt.Model.isChanged(): boolean
Whether any attribute differs from its value as last loaded or saved.
isChanged
()); // true
await const shirt: Shirtshirt.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
(); // writes "S,M,XL"

An equal value in another object, such as a new Money of the same cents, isn’t a change.

Last updated on