Skip to content
Esc
↑↓navigate↵open⌘Jpreview

Active Record

Active Record for Cloudflare Workers

Typed Models and queries, on D1 or Postgres.

npm install @forestfuture/active-record
pnpm add @forestfuture/active-record
yarn add @forestfuture/active-record
bun add @forestfuture/active-record
nub add @forestfuture/active-record
aube add @forestfuture/active-record

A Model and its queries

Use a Model in your Worker with no connection setup. It finds its database from its binding:

import { User } from "./models/user";

export default {
  async fetch(request: Request): Promise<Response> {
    // GET: the 20 newest active users, each with their posts.
    if (request.method === "GET") {
      const users = await User.active()
        .includes("posts") // loaded in one extra query, not one per user
        .order({ createdAt: "desc" })
        .limit(20)
        .toArray();
      return Response.json(users);
    }

    // POST: sign up a user with a first post, saved together.
    const { email } = await request.json<{ email: string }>();
    const user = User.build({ email });
    user.posts().build({ title: "Hello, world" });

    // save() validates and runs callbacks; false means it wasn't saved, and why is in errors.
    if (!(await user.save())) {
      return Response.json({ errors: user.errors.fullMessages() }, { status: 422 });
    }
    return Response.json(user, { status: 201 });
  },
} satisfies ExportedHandler<Env>;
import { hasMany } from "@forestfuture/active-record";
import { ApplicationRecord } from "./application-record";
import { Post } from "./post";

export class User extends ApplicationRecord {
  posts = hasMany(Post, { dependent: "destroy" }); // posts.user_id points here

  static active = this.scope((q) => q.where({ isActive: true }));

  static {
    this.validates("email", { presence: true, uniqueness: true });
    this.beforeSave((user) => {
      user.email = user.email.toLowerCase();
    });
  }
}
import { User } from "./models/user";

const admins = await User.where({ role: "admin", isActive: true }).toArray();

User.where({ role: null }); // role IS NULL
User.where({ role: ["admin", "editor"] }); // role IN (…), any number of values
import { User } from "./models/user";

const user = User.build({ email: "jane@example.com" });
if (await user.save()) {
  // saved: user.isPersisted() is true
} else {
  console.log(user.errors.fullMessages()); // ["Email has already been taken"]
}

const created = await User.create({ email: "sam@example.com" }); // saved, or not
await created.update({ isActive: false }); // true or false
import { batch } from "@forestfuture/active-record";
import { Article } from "./models/article";
import { Author } from "./models/author";

const authorId = crypto.randomUUID(); // generated in code, so the rows can point at it
await batch((b) => [
  b.insert(Author, { id: authorId, name: "Alex", email: "alex@example.com" }),
  b.insert(Article, { authorId, title: "Hello" }),
  b.updateAll(Article.where({ title: "Getting started" }), { authorId }), // Alex takes it over
]);
CREATE TABLE posts (
  id TEXT PRIMARY KEY NOT NULL,
  user_id TEXT NOT NULL REFERENCES users (id),
  title TEXT NOT NULL,
  published_at DATETIME,
  created_at DATETIME NOT NULL,
  updated_at DATETIME NOT NULL
);
CREATE INDEX index_posts_on_user_id ON posts (user_id);

Choose your database

What’s inside

Last updated on