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

Getting started

Build a small blog’s users and posts on D1, from an empty Worker, in about ten minutes.

Prerequisites

You’ll need:

  • A Worker project with Wrangler. npm create cloudflare@latest makes one.

  • A D1 database bound as DB. Create one with npx wrangler d1 create my-app-db, then add the snippet it prints to your Wrangler config:

    {
      "d1_databases": [
        { "binding": "DB", "database_name": "my-app-db", "database_id": "<the id it printed>" },
      ],
    }
  • Node.js 22.13 or later, for the command line.

Installing Arbor

Install Arbor. Its D1 adapter comes with it:

npm install @forestfuture/arbor

Naming your database

Tell Arbor about your database:

npx arbor init

It writes arbor.jsonc, which names DB as a D1 database. Every arbor command reads it:

{
  "$schema": "./node_modules/@forestfuture/arbor/config-schema.json",
  "databases": {
    "DB": {
      "adapter": "d1",
    },
  },
}

Generating the Models

The generator writes a table’s migration and its Model in one step, like rails generate model. Generate users first, since each post belongs to a user:

npx arbor g model User 'email:string!:unique' 'isActive:boolean!=true'
npx arbor g model Post user:references 'title:string!' publishedAt:datetime

Each column is name:type. A ! makes it required, =true sets a default, :unique adds a unique index, and user:references links each post to a user. The quotes stop your shell from reading the !.

The generator writes these files:

File What it is
migrations/20261108090503_create_users.sql, 20261108090504_create_posts.sql The SQL that creates each table
src/db/schema.ts Every table’s columns, generated from the migrations. Don’t edit it.
src/models/application-record.ts Your app’s base class. It’s yours to edit.
src/models/user.ts, post.ts One Model per table

Here’s the migration for posts:

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);

Creating the tables

Apply the migrations to your local database:

npx arbor migrate

Use npx arbor migrate --remote when you deploy.

Adding behavior

A Model’s attributes come from the generated schema, so a Model only declares behavior. The generated Post already belongs to a user:

import { belongsTo } from "@forestfuture/arbor";
import { ApplicationRecord } from "./application-record";
import { User } from "./user";

export class Post extends ApplicationRecord {
  user = belongsTo(User);
}

The generated User is one line. Its table, users, comes from its class name:

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

export class User extends ApplicationRecord {}

Give it posts, a scope for active users, and rules for saving:

import { hasMany } from "@forestfuture/arbor";
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();
    });
  }
}
  • user.posts() finds the user’s posts, and dependent: "destroy" destroys them with the user.
  • User.active() finds active users.
  • validates and beforeSave run on every save. An invalid user isn’t saved, and user.errors says why.

Using the Models

Queries start from the Model. Each Model uses the DB binding, so there’s nothing to connect:

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>;
  • includes("posts") loads every user’s posts in one more query.
  • A post built with user.posts().build(…) is saved with its user, in one atomic batch.
  • save() resolves to false when validation fails.

Trying it

Start the Worker:

npx wrangler dev

In another terminal, sign up a user, then list the users:

curl -X POST http://localhost:8787 -d '{"email":"Ada@Example.com"}'
curl http://localhost:8787

The list includes Ada, with her email lowercased by beforeSave. Sign her up again, and you’ll get a 422 with ["Email has already been taken"].

Next steps

Last updated on