Model Code
Let’s learn how to code the model.
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:
Press + to interact
addAuthor(a) {// a can be an ID reference or an object referenceconst 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 referencelet 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:
Press + to interact
removeAuthor(a) {// a can be an ID reference or an object referenceconst author_id = (typeof a !== "object") ?parseInt(a) : a.authorId;const validationResult = Book.checkAuthor(author_id);if (validationResult instanceof NoConstraintViolation) {// delete the author referencedelete 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 ...