24.7. An in-memory model layer with relations
Topics
This question is in
24. Build a small libraryA 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
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 recordA record is a plain object { id, ...fields }. { include } is optional everywhere: a list of relation names.
Requirements
creategives 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 ofdataisnull.- A key in
dataorchangesthat is not a declared field throwsUnknown field "<key>" on <model>.idis not a field: it is set by the database. - Every record returned is a copy, at every depth. Changing it, or changing the object passed to
createorupdate(nested objects and arrays included), never changes what is stored. findreturns the record with that id (ids compare exactly:"1"is not1), ornull.allreturns every record in id order.where(filter)returns, in id order, the records whose fields equal (===) every value infilter;idmay be used, and{}matches every record. A filter key that is not a field oridthrowsUnknown field "<key>" on <model>.updatemergeschangesinto the record (undefinedbecomesnull) and returns the new record. A missing record throwsNo <model> with id <id>.createandupdatecheck everybelongsTokey that is notnull: the other model must have a record with that id, or they throwNo <model> with id <id>(the other model's name). A failedcreateorupdatechanges nothing and uses no id.deleterefuses a record that a record of any model still refers to through abelongsTokey, withCannot delete <model> <id>: a <other> refers to it.includeadds each named relation to the returned copy: abelongsTorelation as the linked record (ornullwhen the key isnull), ahasManyrelation 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 throwsUnknown relation "<name>" on <model>, even when there are no records.- 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. db.modelwith a name that exists throwsModel "<model>" already exists.fieldsthat is not an array of strings throws aTypeErrorwith the messagefields must be an array of names, andfieldsthat contains"id"throws aTypeErrorwith the messageid is set by the database and cannot be a field. A model that throws is not defined.- Two databases never share models or records.
- Field and relation names are ordinary keys, whatever they are called. A field or relation named
__proto__,constructorortoStringis an own property of the returned record, with its value (ornull), increate,update,find,all,whereandinclude; it never changes the record's prototype, which is alwaysObject.prototype.
Examples
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 }] }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 reusedUser.where({ name: "Grace", email: null }); // [{ id: 2, name: "Grace", email: null }]
User.where({ nmae: "Grace" }); // throws Error: Unknown field "nmae" on UserEnvironment
- Plain JavaScript in a browser page; the tests call the global
createDatabasefromorm.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, awherefilter 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
- Where should each model's records and id counter live, and which data structure keeps them in id order?
- A
belongsTorelation and ahasManyrelation describe the same link from two sides. Which side holds the key, and which one doesdeleteneed to look at? - What must
createandupdatefinish 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