Skip to curriculum
Jump to the editor

24.7. An in-memory model layer with relations

Hard
Topics

This question is in

24. Build a small library
50–75 min

A model layer (an ORM) sits between code and stored data. Code says Post.find(1, { include: ["author"] }) instead of joining tables by hand, and the layer keeps the data consistent: ids are unique, a post cannot point at a user who does not exist, and a user with posts cannot simply vanish. Test doubles and offline-first apps often keep such a layer in memory, with no database at all.

Write createDatabase() in orm.js. It returns a database where you define models with fields and relations, then create, read, update and delete records.

Signature

JAVASCRIPT
function createDatabase() // returns { model }

const db = createDatabase();
const User = db.model("User", {
  fields: ["name", "email"],
  hasMany: { posts: { model: "Post", key: "authorId" } },     // Post.authorId holds a User id
});
const Post = db.model("Post", {
  fields: ["title", "authorId"],
  belongsTo: { author: { model: "User", key: "authorId" } },  // this Post's authorId
});

Model.create(data)                 // returns the new record
Model.find(id, { include })        // the record, or null
Model.all({ include })             // every record
Model.where(filter, { include })   // the records matching filter
Model.update(id, changes)          // returns the updated record
Model.delete(id)                   // true, or false when there was no such record

A record is a plain object { id, ...fields }. { include } is optional everywhere: a list of relation names.

Requirements

  1. create gives each record the next id of its model, starting at 1. Each model has its own counter, and an id is never given out twice, even after a delete. A field that is not an own key of data is null.
  2. A key in data or changes that is not a declared field throws Unknown field "<key>" on <model>. id is not a field: it is set by the database.
  3. Every record returned is a copy, at every depth. Changing it, or changing the object passed to create or update (nested objects and arrays included), never changes what is stored.
  4. find returns the record with that id (ids compare exactly: "1" is not 1), or null. all returns every record in id order.
  5. where(filter) returns, in id order, the records whose fields equal (===) every value in filter; id may be used, and {} matches every record. A filter key that is not a field or id throws Unknown field "<key>" on <model>.
  6. update merges changes into the record (undefined becomes null) and returns the new record. A missing record throws No <model> with id <id>.
  7. create and update check every belongsTo key that is not null: the other model must have a record with that id, or they throw No <model> with id <id> (the other model's name). A failed create or update changes nothing and uses no id.
  8. delete refuses a record that a record of any model still refers to through a belongsTo key, with Cannot delete <model> <id>: a <other> refers to it.
  9. include adds each named relation to the returned copy: a belongsTo relation as the linked record (or null when the key is null), a hasMany relation as a list of the linked records in id order ([] when there are none). Related records are copies, and nothing is stored. An unknown name throws Unknown relation "<name>" on <model>, even when there are no records.
  10. Relations name models by string, so models can be defined in any order. A relation to a model that was never defined throws Unknown model "<model>" when it is used.
  11. db.model with a name that exists throws Model "<model>" already exists. fields that is not an array of strings throws a TypeError with the message fields must be an array of names, and fields that contains "id" throws a TypeError with the message id is set by the database and cannot be a field. A model that throws is not defined.
  12. Two databases never share models or records.
  13. Field and relation names are ordinary keys, whatever they are called. A field or relation named __proto__, constructor or toString is an own property of the returned record, with its value (or null), in create, update, find, all, where and include; it never changes the record's prototype, which is always Object.prototype.

Examples

JAVASCRIPT
const ada = User.create({ name: "Ada" });          // { id: 1, name: "Ada", email: null }
Post.create({ title: "Hello", authorId: 1 });      // { id: 1, title: "Hello", authorId: 1 }
Post.create({ title: "Lost", authorId: 9 });       // throws Error: No User with id 9

Post.find(1, { include: ["author"] });
// { id: 1, title: "Hello", authorId: 1, author: { id: 1, name: "Ada", email: null } }
User.find(1, { include: ["posts"] });
// { id: 1, name: "Ada", email: null, posts: [{ id: 1, title: "Hello", authorId: 1 }] }
JAVASCRIPT
User.delete(1);  // throws Error: Cannot delete User 1: a Post refers to it
Post.delete(1);  // true
User.delete(1);  // true
User.delete(1);  // false
User.create({ name: "Grace" }).id; // 2: id 1 is never reused
JAVASCRIPT
User.where({ name: "Grace", email: null }); // [{ id: 2, name: "Grace", email: null }]
User.where({ nmae: "Grace" });              // throws Error: Unknown field "nmae" on User

Environment

  • Plain JavaScript in a browser page; the tests call the global createDatabase from orm.js. Nothing is saved between page loads.
  • Field values are data: strings, numbers, booleans, null, and plain objects and arrays of them (no functions). Because stored values are copies, a where filter value that is an object never equals (===) a stored one.
  • Nested includes (posts.comments), many-to-many relations, cascading deletes, transactions and indexes are out of scope.

Hints

  1. Where should each model's records and id counter live, and which data structure keeps them in id order?
  2. A belongsTo relation and a hasMany relation describe the same link from two sides. Which side holds the key, and which one does delete need to look at?
  3. What must create and update finish checking before they change anything?

The explanation comes with the course

A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.

  • Every line explained
  • The mistakes each test catches
  • Links to the lessons behind it
Back to the question
Loading the editor…