Searching Puzzle

Type to search Puzzle.

Data & Models

Define models with schema and validation, query and mutate the reactive store, and sync it with a server.

Puzzle's data layer has three parts:

  • Models define the shape of your data: fields, types, defaults, validation, computed properties, and business logic.
  • The store is an in-memory record manager with reactive subscriptions. It's how components read and write data.
  • Adapters (optional) say where a model's records live on a server. With server sync enabled, the store fetches what views read and saves what they change.

Records returned by the store are instances of your model class, so their getters work everywhere a record is read, templates included. Model methods are for your scripts: a template reads a record's fields and getters, and the only methods it calls are the built-in string, array, and number methods.

Defining a model

A model lives in app/models/ and extends PuzzleModel with a static schema built from the Puzzle field builders:

// models/todo.js
import { PuzzleModel, Puzzle } from '@magic-spells/puzzle';

export default class Todo extends PuzzleModel {
  static schema = {
    id:        Puzzle.string().primary(),
    text:      Puzzle.string().required().min(1, 'Todo text cannot be empty'),
    completed: Puzzle.boolean().default(false),
    createdAt: Puzzle.date().default(() => new Date()),
    updatedAt: Puzzle.date().default(() => new Date()),
  };
}

Three things to remember:

  1. The Puzzle builders are the only way to define fields. Don't hand-write raw descriptor objects.
  2. The class is the record. store.createRecord('todo', { text: 'Ship v1' }) returns a Todo instance, so anything on the class, getters and methods alike, is available on every record.
  3. Schemas are declarative. The store reads static schema to apply defaults and find the primary key; your class body stays plain JavaScript.

Schema builders

Types

BuilderField type
Puzzle.string()String
Puzzle.number()Number
Puzzle.boolean()Boolean
Puzzle.date()Date
Puzzle.array()Array
Puzzle.object()Object

Modifiers

Every modifier returns the builder, so they chain (Puzzle.string().required().min(1)):

ModifierMeaning
.primary()Marks the primary key; implies required.
.required(message?)Must be present (fails on undefined, null, '').
.default(value | () => value)Applied on createRecord when the field is absent.
.min(n, message?)Minimum: length for strings and arrays, value for numbers and dates.
.max(n, message?)Maximum: length for strings and arrays, value for numbers and dates.
.oneOf([...], message?)Value must be strictly one of the listed options.
.validate(fn, message?)Custom rule: fn(value) returns truthy for valid.

The optional message is the human-readable error shown when a rule fails; omit it for a default message naming the field.

Array and object defaults are deep-cloned per record, so literal defaults are safe too. The function form below also gives each record a fresh value:

static schema = {
  completed: Puzzle.boolean().default(false),          // same value every record
  createdAt: Puzzle.date().default(() => new Date()),  // fresh per record
  tags:      Puzzle.array().default(() => []),         // own array per record
};

Computed properties

Computed properties are plain getters on the model class, with no registration step. If it's a getter, it works anywhere a record is read, including templates:

export default class Todo extends PuzzleModel {
  static schema = { /* ... */ };

  get isActive() {
    return !this.completed;
  }

  get ageInDays() {
    return Math.floor((Date.now() - this.createdAt) / 86400000);
  }
}
{#for todo in todos}
  <li>
    <span>{ todo.text }</span>
    <small>{ date(todo.createdAt, 'short') }, { todo.ageInDays } days old</small>
  </li>
{/for}

Getters recompute on every read, so they always reflect current field values. Keep them cheap: heavy filtering and sorting belong in data().

Instance methods

Records are instances of your class, so business logic belongs on the model as ordinary methods. Inside a method, this is the record: read fields directly and mutate through this.update():

export default class Todo extends PuzzleModel {
  static schema = { /* ... */ };

  toggle() {
    return this.update({ completed: !this.completed, updatedAt: new Date() });
  }
}

update() returns the record and notifies subscribers, so any component that queried this record re-runs automatically. Calling it from a handler is a one-liner:

events = {
  toggleTodo: (todo) => { todo.toggle(); },
};

Always mutate through update(). Assigning a field directly (todo.completed = true) is never observed: nothing re-renders for it.

The model registry

Register models by name in models/index.js and hand them to PuzzleApp. The key you register under is the type string you pass to store methods:

// models/index.js
import Todo from './todo.js';

export const models = { todo: Todo };
export default models;
// app.js
import models from '@/models/index.js';

const app = new PuzzleApp({ target: '#app', routes, models });

Now 'todo' is a known type everywhere. By convention, registry keys are lowercase singular (todo, user, post). Static builds load models from app/models/index.js, so keep the registry there.

Querying the store

Access the store through this.ctx.store. The core methods:

MethodDescription
createRecord(type, data)Creates a record, applying schema defaults and validation. Returns the instance.
findMany(type, options?)Returns the type's records. options.filter narrows them with a predicate.
findOne(type, id)Returns a record by primary key, or null.
record.update(fields)Validates and merges fields, then notifies subscribers. Returns the record.
record.destroy()Removes the record locally and notifies subscribers.

Any query made inside data() auto-subscribes the component: when matching records change, data() re-runs and the view re-renders.

data(params, props) {
  const store = this.ctx.store;
  return {
    user:  store.findOne('user', params.id),   // single record by id
    posts: store.findMany('post'),             // all posts
  };
}

A quick filter can live in the template ({#for post in posts.filter(p => p.isPublished)}), but a list you sort, reuse, or compute over belongs in data(). findMany returns records in insertion order, so sort the result yourself:

data(params, props) {
  const published = this.ctx.store
    .findMany('post', { filter: (post) => post.isPublished })
    .sort((a, b) => new Date(b.publishedAt) - new Date(a.publishedAt));
  return { published, latest: published[0] ?? null };
}

Record identity ignores number/string spelling: findOne('todo', 7) and findOne('todo', '7') return the same record. That matters because route params are always strings while JSON payloads usually carry numbers, so findOne('post', params.id) is correct as written. Only numbers normalize, with no numeric parsing: '01' is not 1.

Validation

Validation rules are enforced at the local write boundary:

  • createRecord(type, data) validates after defaults are applied. On failure it throws PuzzleValidationError (exported from the package root) and writes nothing.
  • record.update(patch) validates only the fields in the patch. On failure it throws and leaves the record untouched.

For form UX, validate without throwing: Model.validate(data) (a pre-create check, defaults applied) and record.validate() (current field values) both return { valid, errors }, where errors is [{ field, rule, message }]:

events = {
  submit: (event) => {
    event.preventDefault();
    const patch = { name: this.getData().name, email: this.getData().email };
    const { valid, errors } = User.validate(patch);
    if (!valid) {
      this.setData('errors', errors);   // render them in the template
      return;
    }
    this.ctx.store.createRecord('user', patch);
  },
};

Or catch the throw directly:

try {
  this.ctx.store.createRecord('user', patch);
} catch (err) {
  if (err instanceof PuzzleValidationError) {
    this.setData('errors', err.errors);
  } else {
    throw err;
  }
}

A note on types: text inputs hand you strings. On a field declared number() or date(), a min or max rule fails a wrong-typed value with a type-mismatch message, so convert before writing (Number(input.value)). A two-way bound type="number" input already writes a number.

Relationships

Declare relationships as schema entries; they resolve as lazy, store-backed getters:

static schema = {
  id:       Puzzle.string().primary(),
  authorId: Puzzle.string(),
  author:   Puzzle.belongsTo('user'),    // → the user whose id is this.authorId
  comments: Puzzle.hasMany('comment'),   // → comments whose postId is this.id
};
  • Resolution is a live local lookup. post.author finds the user under post.authorId (null on a miss), and post.comments returns the matching comment records ([] when there are none) in insertion order. Nothing is cached or materialized.
  • The foreign key is inferred by convention: belongsTo uses <relationshipName>Id (author: reads authorId), and hasMany uses <ownerType>Id. Override with Puzzle.belongsTo('user', { key: 'writtenBy' }).
  • Relationships never fetch. A traversal is always local, so a 50-row list reading post.author can't become 50 requests. When a view needs a related record that may not be loaded yet, it asks for it with one more findOne on the foreign key.
  • Traverse in data() to subscribe. Reading a relationship inside data() subscribes the view like any query. Reading it only in the template shows current state but subscribes nothing, so return traversals from data():
data(params, props) {
  const post = this.ctx.store.findOne('post', params.id);
  return {
    post,
    author:   post ? post.author : null,                     // subscribes that user
    comments: post ? [...post.comments].sort(byDate) : [],   // subscribes 'comment'
  };
}

The reactive flow

The cycle behind everything above:

  1. A record changes (todo.update(...), createRecord, destroy).
  2. The store schedules a flush and notifies each subscribed view.
  3. Views re-run data(params, props), and the template diff applies DOM updates. A child that received the changed record as a prop re-renders too.

Keep data() a pure derivation: it can run several times per navigation. Don't copy store results into local state and mutate the copy; mutate the records through update() or another store path and let the store notify subscribers.

Server data

Server sync is opt-in. Give a model a static adapter that says where its records live, then pass the adapter capability to the app once:

// app/models/post.js
export default class Post extends PuzzleModel {
  static schema = { /* ... */ };
  static adapter = { endpoint: '/posts' };
}
// app/adapter.js
import { adapter } from '@magic-spells/puzzle/adapter';
export default adapter;

// app/app.js
import adapter from './adapter.js';

const app = new PuzzleApp({
  target: '#app',
  routes,
  models,
  adapter,
  apiURL: 'https://api.example.com',   // endpoints join onto this
});

endpoint is the REST shorthand: it generates the five standard requests (list, fetch one, create, update, delete) against apiURL + endpoint. An app that never passes adapter ships none of the network code, and a model with no adapter stays purely local.

The one rule

Server data comes from data(). findOne and findMany fetch what the store is missing, and a committed null means the record does not exist. There's no loading code to write, no load hook, and no seeding step:

data(params, props) {
  const store = this.ctx.store;
  const post = store.findOne('post', params.id);
  const author = post ? store.findOne('user', post.authorId) : null;
  return { post, author };
}

Land on that view with an empty store and it settles in rounds: the post misses and is fetched, then the author misses and is fetched, then both are present. The view renders once, fully populated. Nothing declares that the author depends on the post; the loop discovers it.

  • null is never "still loading". {#if post} … {:else} Not found {/if} needs no loaded flag. The previous page stays on screen until the new view commits, or a skeleton covers the wait.
  • Only a view's own data() fetches, through this.ctx.store. Reads in event handlers, model methods, and timers are local snapshots and never issue a request. A handler that needs fresh server data changes state and calls this.refresh().
  • Requests dedupe and cache for the session. Concurrent misses on the same record share one request. A successful no-options collection load makes later findMany(type) calls local. A missing-id lookup stays local only when the generated REST transport loaded the complete collection; a custom collection verb may return just one page, so a later missing id can still fetch. A 404 is remembered in a bounded session cache.
  • Only a 404 becomes null. A network error, a 5xx, or a malformed response fails the navigation and goes to the app's error view.
  • Prerendered builds fetch at build time. The build machine must reach the API, so give the app an absolute apiURL; an app-relative read fails the build with a message naming both fixes. See Static Builds.

Custom requests and API dialects

Override only the verbs your API does differently. The five verbs are loadMany, loadOne, create, update, and delete; each receives an enhanced fetch as its first argument, and may return parsed data or a standard Response:

static adapter = {
  endpoint: '/posts',

  // Different URL for the list, standard payload: Puzzle checks and parses it.
  loadMany: (fetch) => fetch('https://api.example.com/v2/posts'),

  // A custom method; call it through store.adapter('post').publish(id).
  async publish(fetch, id) {
    const res = await fetch(`https://api.example.com/v2/posts/${id}/publish`, { method: 'PATCH' });
    return res.json();
  },
};

// in an event handler
const post = store.upsert('post', await store.adapter('post').publish(id));

A custom loadOne reports "no such record" by returning a 404 response, which becomes the committed null. The supplied fetch runs the app's request hook and the fixtures mock; calling the global fetch instead bypasses both. Extra keys such as publish are custom methods you call yourself, through store.adapter(type), and store.upsert() merges what they return.

When every model speaks the same dialect, define it once with adapter.defaults(). App defaults receive an extra { type, endpoint } argument; the endpoint is the model's raw value, so a dialect in an app that sets apiURL adds it itself. A model's own function always wins over the default, which wins over the generated REST request:

// app/adapter.js: unwrap the same { data } envelope for every model
import { adapter } from '@magic-spells/puzzle/adapter';

export default adapter.defaults({
  async loadMany(fetch, options, { endpoint }) {
    const response = await fetch('https://api.example.com' + endpoint);
    return (await response.json()).data;
  },
});

To attach auth headers, set beforeRequest in the app config. Every adapter request runs through it, and it's synchronous by design, so refresh tokens outside the request path:

new PuzzleApp({
  target: '#app',
  routes,
  models,
  adapter,
  beforeRequest(init, { type, method, url }) {
    init.headers = { ...init.headers, Authorization: `Bearer ${currentToken()}` };
  },
});

Explicit loads

store.loadMany(type, options?) and store.loadOne(type, id) are escape hatches for use outside data(): a forced refresh from a click handler, or pagination. Pages accumulate in the store, and records with the same primary key merge. Calling them inside data() is redundant (the finds already fetch) and warns in development.

events = {
  reload: () => this.ctx.store.loadOne('post', this.params.id),   // force refresh
  nextPage: async () => {
    const page = this.getData().page + 1;
    await this.ctx.store.loadMany('post', { page });   // pages accumulate
    this.setData('page', page);
  },
};

Saving to the server

Local mutations (createRecord, update, destroy) stay local and instant. Syncing to the server is a separate, explicit verb using the same adapter:

MethodDescription
record.save()Validates the full record first (invalid rejects with no request), then creates a never-synced record or updates a synced one. The server's response merges back, except for fields edited while the request was in flight. A failed save keeps the local changes and rejects; retry by calling it again.
record.delete()Confirmed delete: sends the delete first, then removes the record locally on success. A never-synced record is simply removed; records loaded from the server are already synced. Distinct from record.destroy(), which stays local.
store.request(type, path, { method, body, headers })Custom-endpoint escape hatch: joins apiURL and the model's endpoint onto path, JSON in and out.
const todo = store.createRecord('todo', { text: 'Ship it' }); // local, instant
await todo.save();                  // POST (first save)
todo.update({ completed: true });   // local, instant
await todo.save();                  // PUT (now synced)
await todo.delete();                // DELETE, then local remove

A record's saves and deletes run one at a time, in order. A create or update response must be the record (with its primary key) or empty; anything else rejects. A failed request rejects with PuzzleAdapterError, exported from @magic-spells/puzzle/adapter, which carries .status, .statusText, and .body. A documented pattern is to wrap store.request in a model method:

publish() {
  return this._store.request('post', `/${this.id}/publish`, { method: 'POST' });
}

Fixtures and the mock adapter

Puzzle can generate fake records from your schemas and serve adapter requests from memory, so you can build against data before the API exists. Describe it in app/fixtures.js:

// app/fixtures.js
export default {
  seed: 42,                                   // deterministic generated data
  mock: { post: { latency: 150 } },           // serve 'post' requests from memory
  setup(app) {
    app.store.seed('post', 12);               // 12 posts generated from the schema
  },
};

Run puzzle dev --fixtures or puzzle build --fixtures to wire it in. Without the flag nothing imports the module, so fixtures can never reach a production bundle. Generated records respect default, oneOf, min, and max, and the mock serves the real request paths with optional latency and failure rates, which makes skeletons and error handling easy to exercise. In tests, import installFixtures from @magic-spells/puzzle/testing.

Next