Active Record for Cloudflare Workers
Typed Models and queries, on D1 or Postgres.
npm install @forestfuture/active-recordpnpm add @forestfuture/active-recordyarn add @forestfuture/active-recordbun add @forestfuture/active-recordnub add @forestfuture/active-recordaube add @forestfuture/active-recordGet started
From an empty Worker to two related Models in about ten minutes.
Read the tutorial
Coming from Rails
What carries over from Rails, and what’s different.
See what’s different
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 valuesimport { 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 falseimport { 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
Cloudflare D1
Bind a D1 database, and read from nearby replicas with Sessions.
Use D1
Postgres
Connect through Hyperdrive in a Worker, or directly on Node.
Use Postgres
What’s inside
Models, declared once
Typed attributes come from your tables, camelCase in your code and snake_case in SQL, with defaults, timestamps, dates, and JSON converted both ways.
Lazy, composable queries
Conditions, ordering, pagination, scopes, and preloading with one query per association, never N+1. Hand-written SQL goes through a tagged template, so values are always bound.
A predictable lifecycle
save, create, update, and destroy run validations and callbacks in a predictable order,
with dirty tracking and dependent strategies. Methods that throw end in OrThrow.
Atomic batches
batch writes a set of statements and records all at once, or not at all, on D1 and on
Postgres. Keys generated in code let a whole graph save in one batch.
One API, two databases
Start on D1 and move to Postgres with your Models and code unchanged. Each adapter lists what works differently on its database.