A model

Music's albums live in an array. A datastore keeps them as records instead: objects the app can find, change and watch, so every page showing an album stays in step with it. Each kind of record is described by a model.

A model is a class that extends PuzzleModel with a static schema. Each field is built from Puzzle.string(), Puzzle.number(), Puzzle.boolean(), Puzzle.date(), Puzzle.array() or Puzzle.object(), and modifiers chain on:

  • .primary() marks the primary key, the field records are found by.
  • .required() makes a field mandatory.
  • .default(false) fills a field when a new record leaves it out.
  • .min(), .max() and .oneOf([...]) limit the values a field accepts.

The registry in models/index.js gives each model its type name, the string every store call takes: { album: Album } means store.findMany('album'). app.js hands the registry to PuzzleApp as models.

Your turn

  1. In album.js, add the fields Music needs: id as the primary key, a required title, a price number between 10 and 40, and an inPlaylist boolean that defaults to false.
  2. In models/index.js, import Album and register it as album.
  3. In app.js, import the registry from ./models/index.js and pass models to PuzzleApp.
static schema = {
  id: Puzzle.string().primary(),
  title: Puzzle.string().required(),
  price: Puzzle.number().min(10).max(40),
  inPlaylist: Puzzle.boolean().default(false),
  // …
};

Nothing in the preview changes yet. The store knows what an album looks like, but it holds none. The next lesson fills it.

Chapters