Add an empty collection named _name_ to your database. Typically you won’t need to do this yourself, since collections are automatically created for any models you have defined. @method createCollection @param name @param initialData (optional) @public
(name, initialData)
| 81 | @public |
| 82 | */ |
| 83 | createCollection(name, initialData) { |
| 84 | if (!this[name]) { |
| 85 | let IdentityManager = this.identityManagerFor(name); |
| 86 | let newCollection = new DbCollection(name, initialData, IdentityManager); |
| 87 | |
| 88 | // Public API has a convenient array interface. It comes at the cost of |
| 89 | // returning a copy of all records to avoid accidental mutations. |
| 90 | Object.defineProperty(this, name, { |
| 91 | get() { |
| 92 | let recordsCopy = newCollection.all(); |
| 93 | |
| 94 | [ |
| 95 | "insert", |
| 96 | "find", |
| 97 | "findBy", |
| 98 | "where", |
| 99 | "update", |
| 100 | "remove", |
| 101 | "firstOrCreate", |
| 102 | ].forEach(function (method) { |
| 103 | recordsCopy[method] = function () { |
| 104 | return newCollection[method](...arguments); |
| 105 | }; |
| 106 | }); |
| 107 | |
| 108 | return recordsCopy; |
| 109 | }, |
| 110 | }); |
| 111 | |
| 112 | // Private API does not have the array interface. This means internally, only |
| 113 | // db-collection methods can be used. This is so records aren't copied redundantly |
| 114 | // internally, which leads to accidental O(n^2) operations (e.g., createList). |
| 115 | Object.defineProperty(this, `_${name}`, { |
| 116 | get() { |
| 117 | let recordsCopy = []; |
| 118 | |
| 119 | [ |
| 120 | "insert", |
| 121 | "find", |
| 122 | "findBy", |
| 123 | "where", |
| 124 | "update", |
| 125 | "remove", |
| 126 | "firstOrCreate", |
| 127 | ].forEach(function (method) { |
| 128 | recordsCopy[method] = function () { |
| 129 | return newCollection[method](...arguments); |
| 130 | }; |
| 131 | }); |
| 132 | |
| 133 | return recordsCopy; |
| 134 | }, |
| 135 | }); |
| 136 | |
| 137 | this._collections.push(newCollection); |
| 138 | } else if (initialData) { |
| 139 | this[name].insert(initialData); |
| 140 | } |
no test coverage detected