Search⌘ K

Model Code

Explore how to implement unidirectional non-functional associations in JavaScript models by coding add, remove, and set operations for multi-valued references. Understand deletion policies for related objects and learn how to create serialization functions to prepare objects for UI display and data storage. This lesson deepens your ability to manage object relationships and data persistence in a front-end app.

Code the add operation

For the multi-valued reference property Book::authors, we need to code the operations addAuthor and removeAuthor. Both operations accept one parameter, which denotes an author either by ID reference (the author ID as integer or string) or by an object reference.

The code of addAuthor is as follows:

Javascript (babel-node)
addAuthor(a) {
// a can be an ID reference or an object reference
const author_id = (typeof a !== "object") ? parseInt(a) : a.authorId;
const validationResult = Book.checkAuthor(author_id);
if (author_id && validationResult instanceof NoConstraintViolation) {
// add the new author reference
let key = String(author_id);
this._authors[key] = Author.instances[key];
} else {
throw validationResult;
}
}

Code the remove operation

In the removeAuthor method, the author reference is first checked and, if no constraint violation is detected, the corresponding entry in the map this._authors is deleted:

Javascript (babel-node)
removeAuthor(a) {
// a can be an ID reference or an object reference
const author_id = (typeof a !== "object") ?
parseInt(a) : a.authorId;
const validationResult = Book.checkAuthor(author_id);
if (validationResult instanceof NoConstraintViolation) {
// delete the author reference
delete this._authors[author_id];
} else {
throw validationResult;
}
}

Code the set operation

To assign an array of ID references, or a map of object references, to the property Book::authors, the method ...