1 | import isPlainObject from 'lodash.isplainobject';
|
2 | import isFunction from 'lodash.isfunction';
|
3 | import mapValues from 'lodash.mapvalues';
|
4 | import uniq from 'lodash.uniq';
|
5 | import flatten from 'lodash.flatten';
|
6 | import '@miragejs/pretender-node-polyfill/before';
|
7 | import Pretender from 'pretender';
|
8 | import '@miragejs/pretender-node-polyfill/after';
|
9 | import { camelize as camelize$1, dasherize as dasherize$1, underscore as underscore$1, capitalize as capitalize$1, singularize, pluralize } from 'inflected';
|
10 | import lowerFirst from 'lodash.lowerfirst';
|
11 | import isEqual from 'lodash.isequal';
|
12 | import map from 'lodash.map';
|
13 | import cloneDeep from 'lodash.clonedeep';
|
14 | import invokeMap from 'lodash.invokemap';
|
15 | import compact from 'lodash.compact';
|
16 | import has from 'lodash.has';
|
17 | import values from 'lodash.values';
|
18 | import isEmpty from 'lodash.isempty';
|
19 | import get from 'lodash.get';
|
20 | import uniqBy from 'lodash.uniqby';
|
21 | import forIn from 'lodash.forin';
|
22 | import pick from 'lodash.pick';
|
23 | import assign from 'lodash.assign';
|
24 | import find from 'lodash.find';
|
25 | import isInteger from 'lodash.isinteger';
|
26 |
|
27 | function _typeof(obj) {
|
28 | if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
|
29 | _typeof = function (obj) {
|
30 | return typeof obj;
|
31 | };
|
32 | } else {
|
33 | _typeof = function (obj) {
|
34 | return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
|
35 | };
|
36 | }
|
37 |
|
38 | return _typeof(obj);
|
39 | }
|
40 |
|
41 | function _classCallCheck(instance, Constructor) {
|
42 | if (!(instance instanceof Constructor)) {
|
43 | throw new TypeError("Cannot call a class as a function");
|
44 | }
|
45 | }
|
46 |
|
47 | function _defineProperties(target, props) {
|
48 | for (var i = 0; i < props.length; i++) {
|
49 | var descriptor = props[i];
|
50 | descriptor.enumerable = descriptor.enumerable || false;
|
51 | descriptor.configurable = true;
|
52 | if ("value" in descriptor) descriptor.writable = true;
|
53 | Object.defineProperty(target, descriptor.key, descriptor);
|
54 | }
|
55 | }
|
56 |
|
57 | function _createClass(Constructor, protoProps, staticProps) {
|
58 | if (protoProps) _defineProperties(Constructor.prototype, protoProps);
|
59 | if (staticProps) _defineProperties(Constructor, staticProps);
|
60 | return Constructor;
|
61 | }
|
62 |
|
63 | function _defineProperty(obj, key, value) {
|
64 | if (key in obj) {
|
65 | Object.defineProperty(obj, key, {
|
66 | value: value,
|
67 | enumerable: true,
|
68 | configurable: true,
|
69 | writable: true
|
70 | });
|
71 | } else {
|
72 | obj[key] = value;
|
73 | }
|
74 |
|
75 | return obj;
|
76 | }
|
77 |
|
78 | function _inherits(subClass, superClass) {
|
79 | if (typeof superClass !== "function" && superClass !== null) {
|
80 | throw new TypeError("Super expression must either be null or a function");
|
81 | }
|
82 |
|
83 | subClass.prototype = Object.create(superClass && superClass.prototype, {
|
84 | constructor: {
|
85 | value: subClass,
|
86 | writable: true,
|
87 | configurable: true
|
88 | }
|
89 | });
|
90 | if (superClass) _setPrototypeOf(subClass, superClass);
|
91 | }
|
92 |
|
93 | function _getPrototypeOf(o) {
|
94 | _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
|
95 | return o.__proto__ || Object.getPrototypeOf(o);
|
96 | };
|
97 | return _getPrototypeOf(o);
|
98 | }
|
99 |
|
100 | function _setPrototypeOf(o, p) {
|
101 | _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
|
102 | o.__proto__ = p;
|
103 | return o;
|
104 | };
|
105 |
|
106 | return _setPrototypeOf(o, p);
|
107 | }
|
108 |
|
109 | function isNativeReflectConstruct() {
|
110 | if (typeof Reflect === "undefined" || !Reflect.construct) return false;
|
111 | if (Reflect.construct.sham) return false;
|
112 | if (typeof Proxy === "function") return true;
|
113 |
|
114 | try {
|
115 | Date.prototype.toString.call(Reflect.construct(Date, [], function () {}));
|
116 | return true;
|
117 | } catch (e) {
|
118 | return false;
|
119 | }
|
120 | }
|
121 |
|
122 | function _construct(Parent, args, Class) {
|
123 | if (isNativeReflectConstruct()) {
|
124 | _construct = Reflect.construct;
|
125 | } else {
|
126 | _construct = function _construct(Parent, args, Class) {
|
127 | var a = [null];
|
128 | a.push.apply(a, args);
|
129 | var Constructor = Function.bind.apply(Parent, a);
|
130 | var instance = new Constructor();
|
131 | if (Class) _setPrototypeOf(instance, Class.prototype);
|
132 | return instance;
|
133 | };
|
134 | }
|
135 |
|
136 | return _construct.apply(null, arguments);
|
137 | }
|
138 |
|
139 | function _assertThisInitialized(self) {
|
140 | if (self === void 0) {
|
141 | throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
|
142 | }
|
143 |
|
144 | return self;
|
145 | }
|
146 |
|
147 | function _possibleConstructorReturn(self, call) {
|
148 | if (call && (typeof call === "object" || typeof call === "function")) {
|
149 | return call;
|
150 | }
|
151 |
|
152 | return _assertThisInitialized(self);
|
153 | }
|
154 |
|
155 | function _slicedToArray(arr, i) {
|
156 | return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest();
|
157 | }
|
158 |
|
159 | function _toConsumableArray(arr) {
|
160 | return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread();
|
161 | }
|
162 |
|
163 | function _arrayWithoutHoles(arr) {
|
164 | if (Array.isArray(arr)) {
|
165 | for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];
|
166 |
|
167 | return arr2;
|
168 | }
|
169 | }
|
170 |
|
171 | function _arrayWithHoles(arr) {
|
172 | if (Array.isArray(arr)) return arr;
|
173 | }
|
174 |
|
175 | function _iterableToArray(iter) {
|
176 | if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter);
|
177 | }
|
178 |
|
179 | function _iterableToArrayLimit(arr, i) {
|
180 | if (!(Symbol.iterator in Object(arr) || Object.prototype.toString.call(arr) === "[object Arguments]")) {
|
181 | return;
|
182 | }
|
183 |
|
184 | var _arr = [];
|
185 | var _n = true;
|
186 | var _d = false;
|
187 | var _e = undefined;
|
188 |
|
189 | try {
|
190 | for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
|
191 | _arr.push(_s.value);
|
192 |
|
193 | if (i && _arr.length === i) break;
|
194 | }
|
195 | } catch (err) {
|
196 | _d = true;
|
197 | _e = err;
|
198 | } finally {
|
199 | try {
|
200 | if (!_n && _i["return"] != null) _i["return"]();
|
201 | } finally {
|
202 | if (_d) throw _e;
|
203 | }
|
204 | }
|
205 |
|
206 | return _arr;
|
207 | }
|
208 |
|
209 | function _nonIterableSpread() {
|
210 | throw new TypeError("Invalid attempt to spread non-iterable instance");
|
211 | }
|
212 |
|
213 | function _nonIterableRest() {
|
214 | throw new TypeError("Invalid attempt to destructure non-iterable instance");
|
215 | }
|
216 |
|
217 |
|
218 |
|
219 |
|
220 |
|
221 |
|
222 | function referenceSort (edges) {
|
223 | var nodes = uniq(flatten(edges));
|
224 | var cursor = nodes.length;
|
225 | var sorted = new Array(cursor);
|
226 | var visited = {};
|
227 | var i = cursor;
|
228 |
|
229 | var visit = function visit(node, i, predecessors) {
|
230 | if (predecessors.indexOf(node) >= 0) {
|
231 | throw new Error("Cyclic dependency in properties ".concat(JSON.stringify(predecessors)));
|
232 | }
|
233 |
|
234 | if (visited[i]) {
|
235 | return;
|
236 | } else {
|
237 | visited[i] = true;
|
238 | }
|
239 |
|
240 | var outgoing = edges.filter(function (edge) {
|
241 | return edge && edge[0] === node;
|
242 | });
|
243 | i = outgoing.length;
|
244 |
|
245 | if (i) {
|
246 | var preds = predecessors.concat(node);
|
247 |
|
248 | do {
|
249 | var pair = outgoing[--i];
|
250 | var child = pair[1];
|
251 |
|
252 | if (child) {
|
253 | visit(child, nodes.indexOf(child), preds);
|
254 | }
|
255 | } while (i);
|
256 | }
|
257 |
|
258 | sorted[--cursor] = node;
|
259 | };
|
260 |
|
261 | while (i--) {
|
262 | if (!visited[i]) {
|
263 | visit(nodes[i], i, []);
|
264 | }
|
265 | }
|
266 |
|
267 | return sorted.reverse();
|
268 | }
|
269 |
|
270 | var Factory = function Factory() {
|
271 | this.build = function (sequence) {
|
272 | var _this = this;
|
273 |
|
274 | var object = {};
|
275 | var topLevelAttrs = Object.assign({}, this.attrs);
|
276 | delete topLevelAttrs.afterCreate;
|
277 | Object.keys(topLevelAttrs).forEach(function (attr) {
|
278 | if (Factory.isTrait.call(_this, attr)) {
|
279 | delete topLevelAttrs[attr];
|
280 | }
|
281 | });
|
282 | var keys = sortAttrs(topLevelAttrs, sequence);
|
283 | keys.forEach(function (key) {
|
284 | var buildAttrs, _buildSingleValue;
|
285 |
|
286 | buildAttrs = function buildAttrs(attrs) {
|
287 | return mapValues(attrs, _buildSingleValue);
|
288 | };
|
289 |
|
290 | _buildSingleValue = function buildSingleValue(value) {
|
291 | if (Array.isArray(value)) {
|
292 | return value.map(_buildSingleValue);
|
293 | } else if (isPlainObject(value)) {
|
294 | return buildAttrs(value);
|
295 | } else if (isFunction(value)) {
|
296 | return value.call(topLevelAttrs, sequence);
|
297 | } else {
|
298 | return value;
|
299 | }
|
300 | };
|
301 |
|
302 | var value = topLevelAttrs[key];
|
303 |
|
304 | if (isFunction(value)) {
|
305 | object[key] = value.call(object, sequence);
|
306 | } else {
|
307 | object[key] = _buildSingleValue(value);
|
308 | }
|
309 | });
|
310 | return object;
|
311 | };
|
312 | };
|
313 |
|
314 | Factory.extend = function (attrs) {
|
315 |
|
316 | var newAttrs = Object.assign({}, this.attrs, attrs);
|
317 |
|
318 | var Subclass = function Subclass() {
|
319 | this.attrs = newAttrs;
|
320 | Factory.call(this);
|
321 | };
|
322 |
|
323 |
|
324 | Subclass.extend = Factory.extend;
|
325 | Subclass.extractAfterCreateCallbacks = Factory.extractAfterCreateCallbacks;
|
326 | Subclass.isTrait = Factory.isTrait;
|
327 |
|
328 | Subclass.attrs = newAttrs;
|
329 | return Subclass;
|
330 | };
|
331 |
|
332 | Factory.extractAfterCreateCallbacks = function () {
|
333 | var _this2 = this;
|
334 |
|
335 | var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
|
336 | traits = _ref.traits;
|
337 |
|
338 | var afterCreateCallbacks = [];
|
339 | var attrs = this.attrs || {};
|
340 | var traitCandidates;
|
341 |
|
342 | if (attrs.afterCreate) {
|
343 | afterCreateCallbacks.push(attrs.afterCreate);
|
344 | }
|
345 |
|
346 | if (Array.isArray(traits)) {
|
347 | traitCandidates = traits;
|
348 | } else {
|
349 | traitCandidates = Object.keys(attrs);
|
350 | }
|
351 |
|
352 | traitCandidates.filter(function (attr) {
|
353 | return _this2.isTrait(attr) && attrs[attr].extension.afterCreate;
|
354 | }).forEach(function (attr) {
|
355 | afterCreateCallbacks.push(attrs[attr].extension.afterCreate);
|
356 | });
|
357 | return afterCreateCallbacks;
|
358 | };
|
359 |
|
360 | Factory.isTrait = function (attrName) {
|
361 | var attrs = this.attrs;
|
362 | return isPlainObject(attrs[attrName]) && attrs[attrName].__isTrait__ === true;
|
363 | };
|
364 |
|
365 | function sortAttrs(attrs, sequence) {
|
366 | var Temp = function Temp() {};
|
367 |
|
368 | var obj = new Temp();
|
369 | var refs = [];
|
370 | var property;
|
371 | Object.keys(attrs).forEach(function (key) {
|
372 | var value;
|
373 | Object.defineProperty(obj.constructor.prototype, key, {
|
374 | get: function get() {
|
375 | refs.push([property, key]);
|
376 | return value;
|
377 | },
|
378 | set: function set(newValue) {
|
379 | value = newValue;
|
380 | },
|
381 | enumerable: false,
|
382 | configurable: true
|
383 | });
|
384 | });
|
385 | Object.keys(attrs).forEach(function (key) {
|
386 | var value = attrs[key];
|
387 |
|
388 | if (typeof value !== "function") {
|
389 | obj[key] = value;
|
390 | }
|
391 | });
|
392 | Object.keys(attrs).forEach(function (key) {
|
393 | var value = attrs[key];
|
394 | property = key;
|
395 |
|
396 | if (typeof value === "function") {
|
397 | obj[key] = value.call(obj, sequence);
|
398 | }
|
399 |
|
400 | refs.push([key]);
|
401 | });
|
402 | return referenceSort(refs);
|
403 | }
|
404 |
|
405 | function isNumber(n) {
|
406 | return (+n).toString() === n.toString();
|
407 | }
|
408 |
|
409 |
|
410 |
|
411 |
|
412 |
|
413 |
|
414 |
|
415 |
|
416 |
|
417 |
|
418 |
|
419 |
|
420 |
|
421 |
|
422 |
|
423 |
|
424 |
|
425 |
|
426 |
|
427 | var IdentityManager =
|
428 |
|
429 | function () {
|
430 | function IdentityManager() {
|
431 | _classCallCheck(this, IdentityManager);
|
432 |
|
433 | this._nextId = 1;
|
434 | this._ids = {};
|
435 | }
|
436 | |
437 |
|
438 |
|
439 |
|
440 |
|
441 |
|
442 |
|
443 | _createClass(IdentityManager, [{
|
444 | key: "get",
|
445 | value: function get() {
|
446 | return this._nextId;
|
447 | }
|
448 | |
449 |
|
450 |
|
451 |
|
452 |
|
453 |
|
454 |
|
455 |
|
456 | }, {
|
457 | key: "set",
|
458 | value: function set(uniqueIdentifier) {
|
459 | if (this._ids[uniqueIdentifier]) {
|
460 | throw new Error("Attempting to use the ID ".concat(uniqueIdentifier, ", but it's already been used"));
|
461 | }
|
462 |
|
463 | if (isNumber(uniqueIdentifier) && +uniqueIdentifier >= this._nextId) {
|
464 | this._nextId = +uniqueIdentifier + 1;
|
465 | }
|
466 |
|
467 | this._ids[uniqueIdentifier] = true;
|
468 | }
|
469 | |
470 |
|
471 |
|
472 |
|
473 |
|
474 |
|
475 | }, {
|
476 | key: "inc",
|
477 | value: function inc() {
|
478 | var nextValue = this.get() + 1;
|
479 | this._nextId = nextValue;
|
480 | return nextValue;
|
481 | }
|
482 | |
483 |
|
484 |
|
485 |
|
486 |
|
487 |
|
488 |
|
489 | }, {
|
490 | key: "fetch",
|
491 | value: function fetch() {
|
492 | var id = this.get();
|
493 | this._ids[id] = true;
|
494 | this.inc();
|
495 | return id.toString();
|
496 | }
|
497 | |
498 |
|
499 |
|
500 |
|
501 |
|
502 |
|
503 | }, {
|
504 | key: "reset",
|
505 | value: function reset() {
|
506 | this._nextId = 1;
|
507 | this._ids = {};
|
508 | }
|
509 | }]);
|
510 |
|
511 | return IdentityManager;
|
512 | }();
|
513 |
|
514 |
|
515 |
|
516 |
|
517 | var association = function association() {
|
518 | var __isAssociation__ = true;
|
519 |
|
520 | for (var _len = arguments.length, traitsAndOverrides = new Array(_len), _key = 0; _key < _len; _key++) {
|
521 | traitsAndOverrides[_key] = arguments[_key];
|
522 | }
|
523 |
|
524 | return {
|
525 | __isAssociation__: __isAssociation__,
|
526 | traitsAndOverrides: traitsAndOverrides
|
527 | };
|
528 | };
|
529 |
|
530 | var trait = function trait(extension) {
|
531 | var __isTrait__ = true;
|
532 | return {
|
533 | extension: extension,
|
534 | __isTrait__: __isTrait__
|
535 | };
|
536 | };
|
537 |
|
538 | var warn = console.warn;
|
539 |
|
540 |
|
541 |
|
542 |
|
543 |
|
544 |
|
545 |
|
546 |
|
547 |
|
548 |
|
549 |
|
550 |
|
551 |
|
552 |
|
553 |
|
554 | var Response =
|
555 |
|
556 | function () {
|
557 | function Response(code) {
|
558 | var headers = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
|
559 | var data = arguments.length > 2 ? arguments[2] : undefined;
|
560 |
|
561 | _classCallCheck(this, Response);
|
562 |
|
563 | this.code = code;
|
564 | this.headers = headers;
|
565 |
|
566 | if (code === 204) {
|
567 | if (data !== undefined && data !== "") {
|
568 | warn("Mirage: One of your route handlers is returning a custom\n 204 Response that has data, but this is a violation of the HTTP spec\n and could lead to unexpected behavior. 204 responses should have no\n content (an empty string) as their body.");
|
569 | } else {
|
570 | this.data = "";
|
571 | }
|
572 |
|
573 | } else if ((data === undefined || data === "") && !Object.prototype.hasOwnProperty.call(this.headers, "Content-Type")) {
|
574 | this.data = {};
|
575 | } else {
|
576 | this.data = data;
|
577 | }
|
578 |
|
579 |
|
580 | if (code !== 204 && !Object.prototype.hasOwnProperty.call(this.headers, "Content-Type")) {
|
581 | this.headers["Content-Type"] = "application/json";
|
582 | }
|
583 | }
|
584 |
|
585 | _createClass(Response, [{
|
586 | key: "toRackResponse",
|
587 | value: function toRackResponse() {
|
588 | return [this.code, this.headers, this.data];
|
589 | }
|
590 | }]);
|
591 |
|
592 | return Response;
|
593 | }();
|
594 |
|
595 | var camelizeCache = {};
|
596 | var dasherizeCache = {};
|
597 | var underscoreCache = {};
|
598 | var capitalizeCache = {};
|
599 |
|
600 |
|
601 |
|
602 |
|
603 |
|
604 | function camelize(word) {
|
605 | if (typeof camelizeCache[word] !== "string") {
|
606 | var camelizedWord = camelize$1(underscore(word), false);
|
607 | |
608 |
|
609 |
|
610 |
|
611 |
|
612 |
|
613 |
|
614 |
|
615 |
|
616 | var camelized = camelizedWord.split("/").map(lowerFirst).join("/");
|
617 | camelizeCache[word] = camelized;
|
618 | }
|
619 |
|
620 | return camelizeCache[word];
|
621 | }
|
622 |
|
623 |
|
624 |
|
625 |
|
626 |
|
627 | function dasherize(word) {
|
628 | if (typeof dasherizeCache[word] !== "string") {
|
629 | var dasherized = dasherize$1(underscore(word));
|
630 |
|
631 | dasherizeCache[word] = dasherized;
|
632 | }
|
633 |
|
634 | return dasherizeCache[word];
|
635 | }
|
636 | function underscore(word) {
|
637 | if (typeof underscoreCache[word] !== "string") {
|
638 | var underscored = underscore$1(word);
|
639 |
|
640 | underscoreCache[word] = underscored;
|
641 | }
|
642 |
|
643 | return underscoreCache[word];
|
644 | }
|
645 | function capitalize(word) {
|
646 | if (typeof capitalizeCache[word] !== "string") {
|
647 | var capitalized = capitalize$1(word);
|
648 |
|
649 | capitalizeCache[word] = capitalized;
|
650 | }
|
651 |
|
652 | return capitalizeCache[word];
|
653 | }
|
654 |
|
655 |
|
656 |
|
657 |
|
658 |
|
659 | function isAssociation (object) {
|
660 | return isPlainObject(object) && object.__isAssociation__ === true;
|
661 | }
|
662 |
|
663 |
|
664 | var errorProps = ["description", "fileName", "lineNumber", "message", "name", "number", "stack"];
|
665 |
|
666 |
|
667 |
|
668 |
|
669 | function assert(bool, text) {
|
670 | if (typeof bool === "string" && !text) {
|
671 |
|
672 | throw new MirageError(bool);
|
673 | }
|
674 |
|
675 | if (!bool) {
|
676 |
|
677 | throw new MirageError(text.replace(/^ +/gm, "") || "Assertion failed");
|
678 | }
|
679 | }
|
680 |
|
681 |
|
682 |
|
683 |
|
684 |
|
685 |
|
686 | function MirageError(message, stack) {
|
687 | var tmp = Error(message);
|
688 |
|
689 | if (stack) {
|
690 | tmp.stack = stack;
|
691 | }
|
692 |
|
693 | for (var idx = 0; idx < errorProps.length; idx++) {
|
694 | var prop = errorProps[idx];
|
695 |
|
696 | if (["description", "message", "stack"].indexOf(prop) > -1) {
|
697 | this[prop] = "Mirage: ".concat(tmp[prop]);
|
698 | } else {
|
699 | this[prop] = tmp[prop];
|
700 | }
|
701 | }
|
702 | }
|
703 | MirageError.prototype = Object.create(Error.prototype);
|
704 |
|
705 |
|
706 |
|
707 |
|
708 |
|
709 |
|
710 |
|
711 |
|
712 |
|
713 | var Association =
|
714 |
|
715 | function () {
|
716 | function Association(modelName, opts) {
|
717 | _classCallCheck(this, Association);
|
718 |
|
719 | if (_typeof(modelName) === "object") {
|
720 |
|
721 | this.modelName = undefined;
|
722 | this.opts = modelName;
|
723 | } else {
|
724 |
|
725 |
|
726 | this.modelName = modelName ? dasherize(modelName) : "";
|
727 | this.opts = opts || {};
|
728 | }
|
729 |
|
730 |
|
731 | this.key = "";
|
732 |
|
733 | this.ownerModelName = "";
|
734 | }
|
735 | |
736 |
|
737 |
|
738 |
|
739 |
|
740 |
|
741 |
|
742 |
|
743 | _createClass(Association, [{
|
744 | key: "setSchema",
|
745 | value: function setSchema(schema) {
|
746 | this.schema = schema;
|
747 | }
|
748 | |
749 |
|
750 |
|
751 |
|
752 |
|
753 |
|
754 |
|
755 | }, {
|
756 | key: "isReflexive",
|
757 | value: function isReflexive() {
|
758 | var isExplicitReflexive = !!(this.modelName === this.ownerModelName && this.opts.inverse);
|
759 | var isImplicitReflexive = !!(this.opts.inverse === undefined && this.ownerModelName === this.modelName);
|
760 | return isExplicitReflexive || isImplicitReflexive;
|
761 | }
|
762 | }, {
|
763 | key: "isPolymorphic",
|
764 | get: function get() {
|
765 | return this.opts.polymorphic;
|
766 | }
|
767 | |
768 |
|
769 |
|
770 |
|
771 | }, {
|
772 | key: "identifier",
|
773 | get: function get() {
|
774 | throw new Error("Subclasses of Association must implement a getter for identifier");
|
775 | }
|
776 | }]);
|
777 |
|
778 | return Association;
|
779 | }();
|
780 |
|
781 | var identifierCache = {};
|
782 |
|
783 |
|
784 |
|
785 |
|
786 |
|
787 |
|
788 |
|
789 |
|
790 |
|
791 |
|
792 | var BelongsTo =
|
793 |
|
794 | function (_Association) {
|
795 | _inherits(BelongsTo, _Association);
|
796 |
|
797 | function BelongsTo() {
|
798 | _classCallCheck(this, BelongsTo);
|
799 |
|
800 | return _possibleConstructorReturn(this, _getPrototypeOf(BelongsTo).apply(this, arguments));
|
801 | }
|
802 |
|
803 | _createClass(BelongsTo, [{
|
804 | key: "getForeignKeyArray",
|
805 |
|
806 | |
807 |
|
808 |
|
809 |
|
810 |
|
811 |
|
812 | value: function getForeignKeyArray() {
|
813 | return [camelize(this.ownerModelName), this.getForeignKey()];
|
814 | }
|
815 | |
816 |
|
817 |
|
818 |
|
819 |
|
820 |
|
821 | }, {
|
822 | key: "getForeignKey",
|
823 | value: function getForeignKey() {
|
824 |
|
825 | if (typeof identifierCache[this.key] !== "string") {
|
826 | var foreignKey = "".concat(camelize(this.key), "Id");
|
827 | identifierCache[this.key] = foreignKey;
|
828 | }
|
829 |
|
830 | return identifierCache[this.key];
|
831 | }
|
832 | |
833 |
|
834 |
|
835 |
|
836 |
|
837 |
|
838 |
|
839 |
|
840 |
|
841 |
|
842 |
|
843 | }, {
|
844 | key: "addMethodsToModelClass",
|
845 | value: function addMethodsToModelClass(ModelClass, key) {
|
846 | var modelPrototype = ModelClass.prototype;
|
847 | var association = this;
|
848 | var foreignKey = this.getForeignKey();
|
849 |
|
850 | var associationHash = _defineProperty({}, key, this);
|
851 |
|
852 | modelPrototype.belongsToAssociations = Object.assign(modelPrototype.belongsToAssociations, associationHash);
|
853 |
|
854 | Object.keys(modelPrototype.belongsToAssociations).forEach(function (key) {
|
855 | var value = modelPrototype.belongsToAssociations[key];
|
856 | modelPrototype.belongsToAssociationFks[value.getForeignKey()] = value;
|
857 | });
|
858 |
|
859 | this.schema.addDependentAssociation(this, this.modelName);
|
860 |
|
861 |
|
862 | modelPrototype.associationKeys.add(key);
|
863 | modelPrototype.associationIdKeys.add(foreignKey);
|
864 | Object.defineProperty(modelPrototype, foreignKey, {
|
865 | |
866 |
|
867 |
|
868 |
|
869 | get: function get() {
|
870 | this._tempAssociations = this._tempAssociations || {};
|
871 | var tempParent = this._tempAssociations[key];
|
872 | var id;
|
873 |
|
874 | if (tempParent === null) {
|
875 | id = null;
|
876 | } else {
|
877 | if (association.isPolymorphic) {
|
878 | if (tempParent) {
|
879 | id = {
|
880 | id: tempParent.id,
|
881 | type: tempParent.modelName
|
882 | };
|
883 | } else {
|
884 | id = this.attrs[foreignKey];
|
885 | }
|
886 | } else {
|
887 | if (tempParent) {
|
888 | id = tempParent.id;
|
889 | } else {
|
890 | id = this.attrs[foreignKey];
|
891 | }
|
892 | }
|
893 | }
|
894 |
|
895 | return id;
|
896 | },
|
897 |
|
898 | |
899 |
|
900 |
|
901 |
|
902 | set: function set(id) {
|
903 | var tempParent;
|
904 |
|
905 | if (id === null) {
|
906 | tempParent = null;
|
907 | } else if (id !== undefined) {
|
908 | if (association.isPolymorphic) {
|
909 | assert(_typeof(id) === "object", "You're setting an ID on the polymorphic association '".concat(association.key, "' but you didn't pass in an object. Polymorphic IDs need to be in the form { type, id }."));
|
910 | tempParent = association.schema[association.schema.toCollectionName(id.type)].find(id.id);
|
911 | } else {
|
912 | tempParent = association.schema[association.schema.toCollectionName(association.modelName)].find(id);
|
913 | assert(tempParent, "Couldn't find ".concat(association.modelName, " with id = ").concat(id));
|
914 | }
|
915 | }
|
916 |
|
917 | this[key] = tempParent;
|
918 | }
|
919 | });
|
920 | Object.defineProperty(modelPrototype, key, {
|
921 | |
922 |
|
923 |
|
924 |
|
925 | get: function get() {
|
926 | this._tempAssociations = this._tempAssociations || {};
|
927 | var tempParent = this._tempAssociations[key];
|
928 | var foreignKeyId = this[foreignKey];
|
929 | var model = null;
|
930 |
|
931 | if (tempParent) {
|
932 | model = tempParent;
|
933 | } else if (foreignKeyId !== null) {
|
934 | if (association.isPolymorphic) {
|
935 | model = association.schema[association.schema.toCollectionName(foreignKeyId.type)].find(foreignKeyId.id);
|
936 | } else {
|
937 | model = association.schema[association.schema.toCollectionName(association.modelName)].find(foreignKeyId);
|
938 | }
|
939 | }
|
940 |
|
941 | return model;
|
942 | },
|
943 |
|
944 | |
945 |
|
946 |
|
947 |
|
948 |
|
949 |
|
950 |
|
951 |
|
952 |
|
953 |
|
954 |
|
955 |
|
956 | set: function set(model) {
|
957 | this._tempAssociations = this._tempAssociations || {};
|
958 | this._tempAssociations[key] = model;
|
959 |
|
960 | if (model && model.hasInverseFor(association)) {
|
961 | var inverse = model.inverseFor(association);
|
962 | model.associate(this, inverse);
|
963 | }
|
964 | }
|
965 | });
|
966 | |
967 |
|
968 |
|
969 |
|
970 |
|
971 |
|
972 | modelPrototype["new".concat(capitalize(key))] = function () {
|
973 | var modelName, attrs;
|
974 |
|
975 | if (association.isPolymorphic) {
|
976 | modelName = arguments.length <= 0 ? undefined : arguments[0];
|
977 | attrs = arguments.length <= 1 ? undefined : arguments[1];
|
978 | } else {
|
979 | modelName = association.modelName;
|
980 | attrs = arguments.length <= 0 ? undefined : arguments[0];
|
981 | }
|
982 |
|
983 | var parent = association.schema[association.schema.toCollectionName(modelName)]["new"](attrs);
|
984 | this[key] = parent;
|
985 | return parent;
|
986 | };
|
987 | |
988 |
|
989 |
|
990 |
|
991 |
|
992 |
|
993 |
|
994 | modelPrototype["create".concat(capitalize(key))] = function () {
|
995 | var modelName, attrs;
|
996 |
|
997 | if (association.isPolymorphic) {
|
998 | modelName = arguments.length <= 0 ? undefined : arguments[0];
|
999 | attrs = arguments.length <= 1 ? undefined : arguments[1];
|
1000 | } else {
|
1001 | modelName = association.modelName;
|
1002 | attrs = arguments.length <= 0 ? undefined : arguments[0];
|
1003 | }
|
1004 |
|
1005 | var parent = association.schema[association.schema.toCollectionName(modelName)].create(attrs);
|
1006 | this[key] = parent;
|
1007 | this.save();
|
1008 | return parent.reload();
|
1009 | };
|
1010 | }
|
1011 | |
1012 |
|
1013 |
|
1014 |
|
1015 |
|
1016 |
|
1017 | }, {
|
1018 | key: "disassociateAllDependentsFromTarget",
|
1019 | value: function disassociateAllDependentsFromTarget(model) {
|
1020 | var _this = this;
|
1021 |
|
1022 | var owner = this.ownerModelName;
|
1023 | var fk;
|
1024 |
|
1025 | if (this.isPolymorphic) {
|
1026 | fk = {
|
1027 | type: model.modelName,
|
1028 | id: model.id
|
1029 | };
|
1030 | } else {
|
1031 | fk = model.id;
|
1032 | }
|
1033 |
|
1034 | var dependents = this.schema[this.schema.toCollectionName(owner)].where(function (potentialOwner) {
|
1035 | var id = potentialOwner[_this.getForeignKey()];
|
1036 |
|
1037 | if (!id) {
|
1038 | return false;
|
1039 | }
|
1040 |
|
1041 | if (_typeof(id) === "object") {
|
1042 | return id.type === fk.type && id.id === fk.id;
|
1043 | } else {
|
1044 | return id === fk;
|
1045 | }
|
1046 | });
|
1047 | dependents.models.forEach(function (dependent) {
|
1048 | dependent.disassociate(model, _this);
|
1049 | dependent.save();
|
1050 | });
|
1051 | }
|
1052 | }, {
|
1053 | key: "identifier",
|
1054 | get: function get() {
|
1055 | if (typeof identifierCache[this.key] !== "string") {
|
1056 | var identifier = "".concat(camelize(this.key), "Id");
|
1057 | identifierCache[this.key] = identifier;
|
1058 | }
|
1059 |
|
1060 | return identifierCache[this.key];
|
1061 | }
|
1062 | }]);
|
1063 |
|
1064 | return BelongsTo;
|
1065 | }(Association);
|
1066 |
|
1067 | function duplicate(data) {
|
1068 | if (Array.isArray(data)) {
|
1069 | return data.map(duplicate);
|
1070 | } else {
|
1071 | return Object.assign({}, data);
|
1072 | }
|
1073 | }
|
1074 |
|
1075 |
|
1076 |
|
1077 |
|
1078 |
|
1079 |
|
1080 |
|
1081 |
|
1082 |
|
1083 |
|
1084 |
|
1085 |
|
1086 |
|
1087 |
|
1088 |
|
1089 |
|
1090 |
|
1091 |
|
1092 |
|
1093 |
|
1094 |
|
1095 |
|
1096 | var DbCollection =
|
1097 |
|
1098 | function () {
|
1099 | function DbCollection(name, initialData, IdentityManager) {
|
1100 | _classCallCheck(this, DbCollection);
|
1101 |
|
1102 | this.name = name;
|
1103 | this._records = [];
|
1104 | this.identityManager = new IdentityManager();
|
1105 |
|
1106 | if (initialData) {
|
1107 | this.insert(initialData);
|
1108 | }
|
1109 | }
|
1110 | |
1111 |
|
1112 |
|
1113 |
|
1114 |
|
1115 |
|
1116 |
|
1117 |
|
1118 | _createClass(DbCollection, [{
|
1119 | key: "all",
|
1120 | value: function all() {
|
1121 | return duplicate(this._records);
|
1122 | }
|
1123 | |
1124 |
|
1125 |
|
1126 |
|
1127 |
|
1128 |
|
1129 |
|
1130 |
|
1131 |
|
1132 |
|
1133 |
|
1134 |
|
1135 |
|
1136 |
|
1137 |
|
1138 |
|
1139 |
|
1140 |
|
1141 |
|
1142 | }, {
|
1143 | key: "insert",
|
1144 | value: function insert(data) {
|
1145 | var _this = this;
|
1146 |
|
1147 | if (!Array.isArray(data)) {
|
1148 | return this._insertRecord(data);
|
1149 | } else {
|
1150 | return map(data, function (attrs) {
|
1151 | return _this._insertRecord(attrs);
|
1152 | });
|
1153 | }
|
1154 | }
|
1155 | |
1156 |
|
1157 |
|
1158 |
|
1159 |
|
1160 |
|
1161 |
|
1162 |
|
1163 |
|
1164 |
|
1165 |
|
1166 |
|
1167 |
|
1168 |
|
1169 |
|
1170 | }, {
|
1171 | key: "find",
|
1172 | value: function find(ids) {
|
1173 | if (Array.isArray(ids)) {
|
1174 | var records = this._findRecords(ids).filter(Boolean).map(duplicate);
|
1175 |
|
1176 |
|
1177 | return records;
|
1178 | } else {
|
1179 | var record = this._findRecord(ids);
|
1180 |
|
1181 | if (!record) {
|
1182 | return null;
|
1183 | }
|
1184 |
|
1185 |
|
1186 | return duplicate(record);
|
1187 | }
|
1188 | }
|
1189 | |
1190 |
|
1191 |
|
1192 |
|
1193 |
|
1194 |
|
1195 |
|
1196 |
|
1197 |
|
1198 |
|
1199 |
|
1200 |
|
1201 |
|
1202 | }, {
|
1203 | key: "findBy",
|
1204 | value: function findBy(query) {
|
1205 | var record = this._findRecordBy(query);
|
1206 |
|
1207 | if (!record) {
|
1208 | return null;
|
1209 | }
|
1210 |
|
1211 |
|
1212 | return duplicate(record);
|
1213 | }
|
1214 | |
1215 |
|
1216 |
|
1217 |
|
1218 |
|
1219 |
|
1220 |
|
1221 |
|
1222 |
|
1223 |
|
1224 |
|
1225 |
|
1226 |
|
1227 | }, {
|
1228 | key: "where",
|
1229 | value: function where(query) {
|
1230 | return this._findRecordsWhere(query).map(duplicate);
|
1231 | }
|
1232 | |
1233 |
|
1234 |
|
1235 |
|
1236 |
|
1237 |
|
1238 |
|
1239 |
|
1240 |
|
1241 |
|
1242 |
|
1243 |
|
1244 |
|
1245 |
|
1246 |
|
1247 |
|
1248 |
|
1249 |
|
1250 |
|
1251 |
|
1252 |
|
1253 |
|
1254 |
|
1255 |
|
1256 |
|
1257 |
|
1258 |
|
1259 |
|
1260 |
|
1261 |
|
1262 |
|
1263 |
|
1264 |
|
1265 | }, {
|
1266 | key: "firstOrCreate",
|
1267 | value: function firstOrCreate(query) {
|
1268 | var attributesForCreate = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
|
1269 | var queryResult = this.where(query);
|
1270 |
|
1271 | var _queryResult = _slicedToArray(queryResult, 1),
|
1272 | record = _queryResult[0];
|
1273 |
|
1274 | if (record) {
|
1275 | return record;
|
1276 | } else {
|
1277 | var mergedAttributes = Object.assign(attributesForCreate, query);
|
1278 | var createdRecord = this.insert(mergedAttributes);
|
1279 | return createdRecord;
|
1280 | }
|
1281 | }
|
1282 | |
1283 |
|
1284 |
|
1285 |
|
1286 |
|
1287 |
|
1288 |
|
1289 |
|
1290 |
|
1291 |
|
1292 |
|
1293 |
|
1294 |
|
1295 |
|
1296 |
|
1297 |
|
1298 |
|
1299 |
|
1300 |
|
1301 |
|
1302 | }, {
|
1303 | key: "update",
|
1304 | value: function update(target, attrs) {
|
1305 | var _this2 = this;
|
1306 |
|
1307 | var records;
|
1308 |
|
1309 | if (typeof attrs === "undefined") {
|
1310 | attrs = target;
|
1311 | var changedRecords = [];
|
1312 |
|
1313 | this._records.forEach(function (record) {
|
1314 | var oldRecord = Object.assign({}, record);
|
1315 |
|
1316 | _this2._updateRecord(record, attrs);
|
1317 |
|
1318 | if (!isEqual(oldRecord, record)) {
|
1319 | changedRecords.push(record);
|
1320 | }
|
1321 | });
|
1322 |
|
1323 | return changedRecords;
|
1324 | } else if (typeof target === "number" || typeof target === "string") {
|
1325 | var id = target;
|
1326 |
|
1327 | var record = this._findRecord(id);
|
1328 |
|
1329 | this._updateRecord(record, attrs);
|
1330 |
|
1331 | return record;
|
1332 | } else if (Array.isArray(target)) {
|
1333 | var ids = target;
|
1334 | records = this._findRecords(ids);
|
1335 | records.forEach(function (record) {
|
1336 | _this2._updateRecord(record, attrs);
|
1337 | });
|
1338 | return records;
|
1339 | } else if (_typeof(target) === "object") {
|
1340 | var query = target;
|
1341 | records = this._findRecordsWhere(query);
|
1342 | records.forEach(function (record) {
|
1343 | _this2._updateRecord(record, attrs);
|
1344 | });
|
1345 | return records;
|
1346 | }
|
1347 | }
|
1348 | |
1349 |
|
1350 |
|
1351 |
|
1352 |
|
1353 |
|
1354 |
|
1355 |
|
1356 |
|
1357 |
|
1358 |
|
1359 |
|
1360 |
|
1361 |
|
1362 |
|
1363 |
|
1364 |
|
1365 | }, {
|
1366 | key: "remove",
|
1367 | value: function remove(target) {
|
1368 | var _this3 = this;
|
1369 |
|
1370 | var records;
|
1371 |
|
1372 | if (typeof target === "undefined") {
|
1373 | this._records = [];
|
1374 | this.identityManager.reset();
|
1375 | } else if (typeof target === "number" || typeof target === "string") {
|
1376 | var record = this._findRecord(target);
|
1377 |
|
1378 | var index = this._records.indexOf(record);
|
1379 |
|
1380 | this._records.splice(index, 1);
|
1381 | } else if (Array.isArray(target)) {
|
1382 | records = this._findRecords(target);
|
1383 | records.forEach(function (record) {
|
1384 | var index = _this3._records.indexOf(record);
|
1385 |
|
1386 | _this3._records.splice(index, 1);
|
1387 | });
|
1388 | } else if (_typeof(target) === "object") {
|
1389 | records = this._findRecordsWhere(target);
|
1390 | records.forEach(function (record) {
|
1391 | var index = _this3._records.indexOf(record);
|
1392 |
|
1393 | _this3._records.splice(index, 1);
|
1394 | });
|
1395 | }
|
1396 | }
|
1397 | |
1398 |
|
1399 |
|
1400 |
|
1401 |
|
1402 |
|
1403 | |
1404 |
|
1405 |
|
1406 |
|
1407 |
|
1408 |
|
1409 |
|
1410 | }, {
|
1411 | key: "_findRecord",
|
1412 | value: function _findRecord(id) {
|
1413 | id = id.toString();
|
1414 | return this._records.find(function (obj) {
|
1415 | return obj.id === id;
|
1416 | });
|
1417 | }
|
1418 | |
1419 |
|
1420 |
|
1421 |
|
1422 |
|
1423 |
|
1424 |
|
1425 | }, {
|
1426 | key: "_findRecordBy",
|
1427 | value: function _findRecordBy(query) {
|
1428 | return this._findRecordsWhere(query)[0];
|
1429 | }
|
1430 | |
1431 |
|
1432 |
|
1433 |
|
1434 |
|
1435 |
|
1436 |
|
1437 | }, {
|
1438 | key: "_findRecords",
|
1439 | value: function _findRecords(ids) {
|
1440 | return ids.map(this._findRecord, this);
|
1441 | }
|
1442 | |
1443 |
|
1444 |
|
1445 |
|
1446 |
|
1447 |
|
1448 |
|
1449 | }, {
|
1450 | key: "_findRecordsWhere",
|
1451 | value: function _findRecordsWhere(query) {
|
1452 | var records = this._records;
|
1453 |
|
1454 | function defaultQueryFunction(record) {
|
1455 | var keys = Object.keys(query);
|
1456 | return keys.every(function (key) {
|
1457 | return String(record[key]) === String(query[key]);
|
1458 | });
|
1459 | }
|
1460 |
|
1461 | var queryFunction = _typeof(query) === "object" ? defaultQueryFunction : query;
|
1462 | return records.filter(queryFunction);
|
1463 | }
|
1464 | |
1465 |
|
1466 |
|
1467 |
|
1468 |
|
1469 |
|
1470 |
|
1471 | }, {
|
1472 | key: "_insertRecord",
|
1473 | value: function _insertRecord(data) {
|
1474 | var attrs = duplicate(data);
|
1475 |
|
1476 | if (attrs && (attrs.id === undefined || attrs.id === null)) {
|
1477 | attrs.id = this.identityManager.fetch(attrs);
|
1478 | } else {
|
1479 | attrs.id = attrs.id.toString();
|
1480 | this.identityManager.set(attrs.id);
|
1481 | }
|
1482 |
|
1483 | this._records.push(attrs);
|
1484 |
|
1485 | return duplicate(attrs);
|
1486 | }
|
1487 | |
1488 |
|
1489 |
|
1490 |
|
1491 |
|
1492 |
|
1493 |
|
1494 |
|
1495 | }, {
|
1496 | key: "_updateRecord",
|
1497 | value: function _updateRecord(record, attrs) {
|
1498 | var targetId = attrs && Object.prototype.hasOwnProperty.call(attrs, "id") ? attrs.id.toString() : null;
|
1499 | var currentId = record.id;
|
1500 |
|
1501 | if (targetId && currentId !== targetId) {
|
1502 | throw new Error("Updating the ID of a record is not permitted");
|
1503 | }
|
1504 |
|
1505 | for (var attr in attrs) {
|
1506 | if (attr === "id") {
|
1507 | continue;
|
1508 | }
|
1509 |
|
1510 | record[attr] = attrs[attr];
|
1511 | }
|
1512 | }
|
1513 | }]);
|
1514 |
|
1515 | return DbCollection;
|
1516 | }();
|
1517 |
|
1518 |
|
1519 |
|
1520 |
|
1521 |
|
1522 |
|
1523 |
|
1524 |
|
1525 |
|
1526 |
|
1527 |
|
1528 |
|
1529 |
|
1530 |
|
1531 |
|
1532 |
|
1533 |
|
1534 | var Db =
|
1535 |
|
1536 | function () {
|
1537 | function Db(initialData, identityManagers) {
|
1538 | _classCallCheck(this, Db);
|
1539 |
|
1540 | this._collections = [];
|
1541 | this.registerIdentityManagers(identityManagers);
|
1542 |
|
1543 | if (initialData) {
|
1544 | this.loadData(initialData);
|
1545 | }
|
1546 | }
|
1547 | |
1548 |
|
1549 |
|
1550 |
|
1551 |
|
1552 |
|
1553 |
|
1554 |
|
1555 |
|
1556 |
|
1557 |
|
1558 |
|
1559 |
|
1560 |
|
1561 |
|
1562 |
|
1563 |
|
1564 |
|
1565 | _createClass(Db, [{
|
1566 | key: "loadData",
|
1567 | value: function loadData(data) {
|
1568 | for (var key in data) {
|
1569 | this.createCollection(key, cloneDeep(data[key]));
|
1570 | }
|
1571 | }
|
1572 | |
1573 |
|
1574 |
|
1575 |
|
1576 |
|
1577 |
|
1578 |
|
1579 |
|
1580 |
|
1581 | }, {
|
1582 | key: "dump",
|
1583 | value: function dump() {
|
1584 | return this._collections.reduce(function (data, collection) {
|
1585 | data[collection.name] = collection.all();
|
1586 | return data;
|
1587 | }, {});
|
1588 | }
|
1589 | |
1590 |
|
1591 |
|
1592 |
|
1593 |
|
1594 |
|
1595 |
|
1596 |
|
1597 | }, {
|
1598 | key: "createCollection",
|
1599 | value: function createCollection(name, initialData) {
|
1600 | if (!this[name]) {
|
1601 | var _IdentityManager = this.identityManagerFor(name);
|
1602 |
|
1603 | var newCollection = new DbCollection(name, initialData, _IdentityManager);
|
1604 |
|
1605 |
|
1606 | Object.defineProperty(this, name, {
|
1607 | get: function get() {
|
1608 | var recordsCopy = newCollection.all();
|
1609 | ["insert", "find", "findBy", "where", "update", "remove", "firstOrCreate"].forEach(function (method) {
|
1610 | recordsCopy[method] = function () {
|
1611 | return newCollection[method].apply(newCollection, arguments);
|
1612 | };
|
1613 | });
|
1614 | return recordsCopy;
|
1615 | }
|
1616 | });
|
1617 |
|
1618 |
|
1619 |
|
1620 | Object.defineProperty(this, "_".concat(name), {
|
1621 | get: function get() {
|
1622 | var recordsCopy = [];
|
1623 | ["insert", "find", "findBy", "where", "update", "remove", "firstOrCreate"].forEach(function (method) {
|
1624 | recordsCopy[method] = function () {
|
1625 | return newCollection[method].apply(newCollection, arguments);
|
1626 | };
|
1627 | });
|
1628 | return recordsCopy;
|
1629 | }
|
1630 | });
|
1631 |
|
1632 | this._collections.push(newCollection);
|
1633 | } else if (initialData) {
|
1634 | this[name].insert(initialData);
|
1635 | }
|
1636 |
|
1637 | return this;
|
1638 | }
|
1639 | |
1640 |
|
1641 |
|
1642 |
|
1643 |
|
1644 |
|
1645 |
|
1646 | }, {
|
1647 | key: "createCollections",
|
1648 | value: function createCollections() {
|
1649 | var _this = this;
|
1650 |
|
1651 | for (var _len = arguments.length, collections = new Array(_len), _key = 0; _key < _len; _key++) {
|
1652 | collections[_key] = arguments[_key];
|
1653 | }
|
1654 |
|
1655 | collections.forEach(function (c) {
|
1656 | return _this.createCollection(c);
|
1657 | });
|
1658 | }
|
1659 | |
1660 |
|
1661 |
|
1662 |
|
1663 |
|
1664 |
|
1665 | }, {
|
1666 | key: "emptyData",
|
1667 | value: function emptyData() {
|
1668 | this._collections.forEach(function (c) {
|
1669 | return c.remove();
|
1670 | });
|
1671 | }
|
1672 | |
1673 |
|
1674 |
|
1675 |
|
1676 |
|
1677 |
|
1678 |
|
1679 | }, {
|
1680 | key: "identityManagerFor",
|
1681 | value: function identityManagerFor(name) {
|
1682 | return this._identityManagers[this._container.inflector.singularize(name)] || this._identityManagers.application || IdentityManager;
|
1683 | }
|
1684 | |
1685 |
|
1686 |
|
1687 |
|
1688 |
|
1689 |
|
1690 | }, {
|
1691 | key: "registerIdentityManagers",
|
1692 | value: function registerIdentityManagers(identityManagers) {
|
1693 | this._identityManagers = identityManagers || {};
|
1694 | }
|
1695 | }]);
|
1696 |
|
1697 | return Db;
|
1698 | }();
|
1699 |
|
1700 |
|
1701 |
|
1702 |
|
1703 |
|
1704 |
|
1705 |
|
1706 |
|
1707 |
|
1708 |
|
1709 |
|
1710 |
|
1711 |
|
1712 |
|
1713 |
|
1714 |
|
1715 |
|
1716 |
|
1717 | var Collection =
|
1718 |
|
1719 | function () {
|
1720 | function Collection(modelName) {
|
1721 | var models = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
|
1722 |
|
1723 | _classCallCheck(this, Collection);
|
1724 |
|
1725 | assert(modelName && typeof modelName === "string", "You must pass a `modelName` into a Collection");
|
1726 | |
1727 |
|
1728 |
|
1729 |
|
1730 |
|
1731 |
|
1732 |
|
1733 |
|
1734 |
|
1735 |
|
1736 |
|
1737 |
|
1738 | this.modelName = modelName;
|
1739 | |
1740 |
|
1741 |
|
1742 |
|
1743 |
|
1744 |
|
1745 |
|
1746 |
|
1747 |
|
1748 |
|
1749 |
|
1750 |
|
1751 |
|
1752 |
|
1753 |
|
1754 |
|
1755 |
|
1756 |
|
1757 |
|
1758 | this.models = models;
|
1759 | }
|
1760 | |
1761 |
|
1762 |
|
1763 |
|
1764 |
|
1765 |
|
1766 |
|
1767 |
|
1768 |
|
1769 |
|
1770 |
|
1771 | _createClass(Collection, [{
|
1772 | key: "update",
|
1773 |
|
1774 | |
1775 |
|
1776 |
|
1777 |
|
1778 |
|
1779 |
|
1780 |
|
1781 |
|
1782 |
|
1783 |
|
1784 |
|
1785 |
|
1786 | value: function update() {
|
1787 | for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
|
1788 | args[_key] = arguments[_key];
|
1789 | }
|
1790 |
|
1791 | invokeMap.apply(void 0, [this.models, "update"].concat(args));
|
1792 | return this;
|
1793 | }
|
1794 | |
1795 |
|
1796 |
|
1797 |
|
1798 |
|
1799 |
|
1800 |
|
1801 |
|
1802 |
|
1803 |
|
1804 |
|
1805 |
|
1806 | }, {
|
1807 | key: "save",
|
1808 | value: function save() {
|
1809 | invokeMap(this.models, "save");
|
1810 | return this;
|
1811 | }
|
1812 | |
1813 |
|
1814 |
|
1815 |
|
1816 |
|
1817 |
|
1818 |
|
1819 |
|
1820 |
|
1821 |
|
1822 |
|
1823 |
|
1824 | }, {
|
1825 | key: "reload",
|
1826 | value: function reload() {
|
1827 | invokeMap(this.models, "reload");
|
1828 | return this;
|
1829 | }
|
1830 | |
1831 |
|
1832 |
|
1833 |
|
1834 |
|
1835 |
|
1836 |
|
1837 |
|
1838 |
|
1839 |
|
1840 |
|
1841 | }, {
|
1842 | key: "destroy",
|
1843 | value: function destroy() {
|
1844 | invokeMap(this.models, "destroy");
|
1845 | return this;
|
1846 | }
|
1847 | |
1848 |
|
1849 |
|
1850 |
|
1851 |
|
1852 |
|
1853 |
|
1854 |
|
1855 |
|
1856 |
|
1857 |
|
1858 |
|
1859 |
|
1860 | }, {
|
1861 | key: "add",
|
1862 | value: function add(model) {
|
1863 | this.models.push(model);
|
1864 | return this;
|
1865 | }
|
1866 | |
1867 |
|
1868 |
|
1869 |
|
1870 |
|
1871 |
|
1872 |
|
1873 |
|
1874 |
|
1875 |
|
1876 |
|
1877 |
|
1878 |
|
1879 |
|
1880 |
|
1881 | }, {
|
1882 | key: "remove",
|
1883 | value: function remove(model) {
|
1884 | var match = this.models.find(function (m) {
|
1885 | return m.toString() === model.toString();
|
1886 | });
|
1887 |
|
1888 | if (match) {
|
1889 | var i = this.models.indexOf(match);
|
1890 | this.models.splice(i, 1);
|
1891 | }
|
1892 |
|
1893 | return this;
|
1894 | }
|
1895 | |
1896 |
|
1897 |
|
1898 |
|
1899 |
|
1900 |
|
1901 |
|
1902 |
|
1903 |
|
1904 |
|
1905 |
|
1906 |
|
1907 |
|
1908 |
|
1909 |
|
1910 |
|
1911 |
|
1912 |
|
1913 |
|
1914 |
|
1915 |
|
1916 | }, {
|
1917 | key: "includes",
|
1918 | value: function includes(model) {
|
1919 | return this.models.some(function (m) {
|
1920 | return m.toString() === model.toString();
|
1921 | });
|
1922 | }
|
1923 | |
1924 |
|
1925 |
|
1926 |
|
1927 |
|
1928 |
|
1929 |
|
1930 |
|
1931 |
|
1932 |
|
1933 |
|
1934 | }, {
|
1935 | key: "filter",
|
1936 | value: function filter(f) {
|
1937 | var filteredModels = this.models.filter(f);
|
1938 | return new Collection(this.modelName, filteredModels);
|
1939 | }
|
1940 | |
1941 |
|
1942 |
|
1943 |
|
1944 |
|
1945 |
|
1946 |
|
1947 |
|
1948 |
|
1949 |
|
1950 |
|
1951 |
|
1952 |
|
1953 | }, {
|
1954 | key: "sort",
|
1955 | value: function sort(f) {
|
1956 | var sortedModels = this.models.concat().sort(f);
|
1957 | return new Collection(this.modelName, sortedModels);
|
1958 | }
|
1959 | |
1960 |
|
1961 |
|
1962 |
|
1963 |
|
1964 |
|
1965 |
|
1966 |
|
1967 |
|
1968 |
|
1969 |
|
1970 |
|
1971 | }, {
|
1972 | key: "slice",
|
1973 | value: function slice() {
|
1974 | var _this$models;
|
1975 |
|
1976 | var slicedModels = (_this$models = this.models).slice.apply(_this$models, arguments);
|
1977 |
|
1978 | return new Collection(this.modelName, slicedModels);
|
1979 | }
|
1980 | |
1981 |
|
1982 |
|
1983 |
|
1984 |
|
1985 |
|
1986 |
|
1987 |
|
1988 |
|
1989 |
|
1990 |
|
1991 |
|
1992 | }, {
|
1993 | key: "mergeCollection",
|
1994 | value: function mergeCollection(collection) {
|
1995 | this.models = this.models.concat(collection.models);
|
1996 | return this;
|
1997 | }
|
1998 | |
1999 |
|
2000 |
|
2001 |
|
2002 |
|
2003 |
|
2004 |
|
2005 |
|
2006 |
|
2007 |
|
2008 | }, {
|
2009 | key: "toString",
|
2010 | value: function toString() {
|
2011 | return "collection:".concat(this.modelName, "(").concat(this.models.map(function (m) {
|
2012 | return m.id;
|
2013 | }).join(","), ")");
|
2014 | }
|
2015 | }, {
|
2016 | key: "length",
|
2017 | get: function get() {
|
2018 | return this.models.length;
|
2019 | }
|
2020 | }]);
|
2021 |
|
2022 | return Collection;
|
2023 | }();
|
2024 |
|
2025 |
|
2026 |
|
2027 |
|
2028 |
|
2029 |
|
2030 |
|
2031 |
|
2032 |
|
2033 |
|
2034 |
|
2035 |
|
2036 |
|
2037 |
|
2038 |
|
2039 | var PolymorphicCollection =
|
2040 |
|
2041 | function () {
|
2042 | function PolymorphicCollection() {
|
2043 | var models = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
|
2044 |
|
2045 | _classCallCheck(this, PolymorphicCollection);
|
2046 |
|
2047 | this.models = models;
|
2048 | }
|
2049 | |
2050 |
|
2051 |
|
2052 |
|
2053 |
|
2054 |
|
2055 |
|
2056 |
|
2057 |
|
2058 | _createClass(PolymorphicCollection, [{
|
2059 | key: "update",
|
2060 |
|
2061 | |
2062 |
|
2063 |
|
2064 |
|
2065 |
|
2066 |
|
2067 |
|
2068 |
|
2069 | value: function update() {
|
2070 | for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
|
2071 | args[_key] = arguments[_key];
|
2072 | }
|
2073 |
|
2074 | invokeMap.apply(void 0, [this.models, "update"].concat(args));
|
2075 | return this;
|
2076 | }
|
2077 | |
2078 |
|
2079 |
|
2080 |
|
2081 |
|
2082 |
|
2083 |
|
2084 | }, {
|
2085 | key: "destroy",
|
2086 | value: function destroy() {
|
2087 | invokeMap(this.models, "destroy");
|
2088 | return this;
|
2089 | }
|
2090 | |
2091 |
|
2092 |
|
2093 |
|
2094 |
|
2095 |
|
2096 |
|
2097 | }, {
|
2098 | key: "save",
|
2099 | value: function save() {
|
2100 | invokeMap(this.models, "save");
|
2101 | return this;
|
2102 | }
|
2103 | |
2104 |
|
2105 |
|
2106 |
|
2107 |
|
2108 |
|
2109 |
|
2110 | }, {
|
2111 | key: "reload",
|
2112 | value: function reload() {
|
2113 | invokeMap(this.models, "reload");
|
2114 | return this;
|
2115 | }
|
2116 | |
2117 |
|
2118 |
|
2119 |
|
2120 |
|
2121 |
|
2122 |
|
2123 |
|
2124 | }, {
|
2125 | key: "add",
|
2126 | value: function add(model) {
|
2127 | this.models.push(model);
|
2128 | return this;
|
2129 | }
|
2130 | |
2131 |
|
2132 |
|
2133 |
|
2134 |
|
2135 |
|
2136 |
|
2137 |
|
2138 | }, {
|
2139 | key: "remove",
|
2140 | value: function remove(model) {
|
2141 | var match = this.models.find(function (m) {
|
2142 | return isEqual(m.attrs, model.attrs);
|
2143 | });
|
2144 |
|
2145 | if (match) {
|
2146 | var i = this.models.indexOf(match);
|
2147 | this.models.splice(i, 1);
|
2148 | }
|
2149 |
|
2150 | return this;
|
2151 | }
|
2152 | |
2153 |
|
2154 |
|
2155 |
|
2156 |
|
2157 |
|
2158 |
|
2159 |
|
2160 | }, {
|
2161 | key: "includes",
|
2162 | value: function includes(model) {
|
2163 | return this.models.some(function (m) {
|
2164 | return isEqual(m.attrs, model.attrs);
|
2165 | });
|
2166 | }
|
2167 | |
2168 |
|
2169 |
|
2170 |
|
2171 |
|
2172 |
|
2173 |
|
2174 | }, {
|
2175 | key: "filter",
|
2176 | value: function filter(f) {
|
2177 | var filteredModels = this.models.filter(f);
|
2178 | return new PolymorphicCollection(filteredModels);
|
2179 | }
|
2180 | |
2181 |
|
2182 |
|
2183 |
|
2184 |
|
2185 |
|
2186 |
|
2187 | }, {
|
2188 | key: "sort",
|
2189 | value: function sort(f) {
|
2190 | var sortedModels = this.models.concat().sort(f);
|
2191 | return new PolymorphicCollection(sortedModels);
|
2192 | }
|
2193 | |
2194 |
|
2195 |
|
2196 |
|
2197 |
|
2198 |
|
2199 |
|
2200 |
|
2201 | }, {
|
2202 | key: "slice",
|
2203 | value: function slice() {
|
2204 | var _this$models;
|
2205 |
|
2206 | var slicedModels = (_this$models = this.models).slice.apply(_this$models, arguments);
|
2207 |
|
2208 | return new PolymorphicCollection(slicedModels);
|
2209 | }
|
2210 | |
2211 |
|
2212 |
|
2213 |
|
2214 |
|
2215 |
|
2216 |
|
2217 | }, {
|
2218 | key: "mergeCollection",
|
2219 | value: function mergeCollection(collection) {
|
2220 | this.models = this.models.concat(collection.models);
|
2221 | return this;
|
2222 | }
|
2223 | |
2224 |
|
2225 |
|
2226 |
|
2227 |
|
2228 |
|
2229 |
|
2230 | }, {
|
2231 | key: "toString",
|
2232 | value: function toString() {
|
2233 | return "collection:".concat(this.modelName, "(").concat(this.models.map(function (m) {
|
2234 | return m.id;
|
2235 | }).join(","), ")");
|
2236 | }
|
2237 | }, {
|
2238 | key: "length",
|
2239 | get: function get() {
|
2240 | return this.models.length;
|
2241 | }
|
2242 | }]);
|
2243 |
|
2244 | return PolymorphicCollection;
|
2245 | }();
|
2246 |
|
2247 | var identifierCache$1 = {};
|
2248 |
|
2249 |
|
2250 |
|
2251 |
|
2252 |
|
2253 |
|
2254 |
|
2255 |
|
2256 | var HasMany =
|
2257 |
|
2258 | function (_Association) {
|
2259 | _inherits(HasMany, _Association);
|
2260 |
|
2261 | function HasMany() {
|
2262 | _classCallCheck(this, HasMany);
|
2263 |
|
2264 | return _possibleConstructorReturn(this, _getPrototypeOf(HasMany).apply(this, arguments));
|
2265 | }
|
2266 |
|
2267 | _createClass(HasMany, [{
|
2268 | key: "getForeignKeyArray",
|
2269 |
|
2270 | |
2271 |
|
2272 |
|
2273 |
|
2274 |
|
2275 |
|
2276 | value: function getForeignKeyArray() {
|
2277 | return [camelize(this.ownerModelName), this.getForeignKey()];
|
2278 | }
|
2279 | |
2280 |
|
2281 |
|
2282 |
|
2283 |
|
2284 |
|
2285 | }, {
|
2286 | key: "getForeignKey",
|
2287 | value: function getForeignKey() {
|
2288 |
|
2289 | if (typeof identifierCache$1[this.key] !== "string") {
|
2290 | var foreignKey = "".concat(this._container.inflector.singularize(camelize(this.key)), "Ids");
|
2291 | identifierCache$1[this.key] = foreignKey;
|
2292 | }
|
2293 |
|
2294 | return identifierCache$1[this.key];
|
2295 | }
|
2296 | |
2297 |
|
2298 |
|
2299 |
|
2300 |
|
2301 |
|
2302 |
|
2303 |
|
2304 |
|
2305 |
|
2306 |
|
2307 | }, {
|
2308 | key: "addMethodsToModelClass",
|
2309 | value: function addMethodsToModelClass(ModelClass, key) {
|
2310 | var modelPrototype = ModelClass.prototype;
|
2311 | var association = this;
|
2312 | var foreignKey = this.getForeignKey();
|
2313 |
|
2314 | var associationHash = _defineProperty({}, key, this);
|
2315 |
|
2316 | modelPrototype.hasManyAssociations = Object.assign(modelPrototype.hasManyAssociations, associationHash);
|
2317 |
|
2318 | Object.keys(modelPrototype.hasManyAssociations).forEach(function (key) {
|
2319 | var value = modelPrototype.hasManyAssociations[key];
|
2320 | modelPrototype.hasManyAssociationFks[value.getForeignKey()] = value;
|
2321 | });
|
2322 |
|
2323 | this.schema.addDependentAssociation(this, this.modelName);
|
2324 |
|
2325 |
|
2326 | modelPrototype.associationKeys.add(key);
|
2327 | modelPrototype.associationIdKeys.add(foreignKey);
|
2328 | Object.defineProperty(modelPrototype, foreignKey, {
|
2329 | |
2330 |
|
2331 |
|
2332 |
|
2333 | get: function get() {
|
2334 | this._tempAssociations = this._tempAssociations || {};
|
2335 | var tempChildren = this._tempAssociations[key];
|
2336 | var ids = [];
|
2337 |
|
2338 | if (tempChildren) {
|
2339 | if (association.isPolymorphic) {
|
2340 | ids = tempChildren.models.map(function (model) {
|
2341 | return {
|
2342 | type: model.modelName,
|
2343 | id: model.id
|
2344 | };
|
2345 | });
|
2346 | } else {
|
2347 | ids = tempChildren.models.map(function (model) {
|
2348 | return model.id;
|
2349 | });
|
2350 | }
|
2351 | } else {
|
2352 | ids = this.attrs[foreignKey] || [];
|
2353 | }
|
2354 |
|
2355 | return ids;
|
2356 | },
|
2357 |
|
2358 | |
2359 |
|
2360 |
|
2361 |
|
2362 | set: function set(ids) {
|
2363 | var tempChildren;
|
2364 |
|
2365 | if (ids === null) {
|
2366 | tempChildren = [];
|
2367 | } else if (ids !== undefined) {
|
2368 | assert(Array.isArray(ids), "You must pass an array in when setting ".concat(foreignKey, " on ").concat(this));
|
2369 |
|
2370 | if (association.isPolymorphic) {
|
2371 | assert(ids.every(function (el) {
|
2372 | return _typeof(el) === "object" && _typeof(el.type) !== undefined && _typeof(el.id) !== undefined;
|
2373 | }), "You must pass in an array of polymorphic identifiers (objects of shape { type, id }) when setting ".concat(foreignKey, " on ").concat(this));
|
2374 | var models = ids.map(function (_ref) {
|
2375 | var type = _ref.type,
|
2376 | id = _ref.id;
|
2377 | return association.schema[association.schema.toCollectionName(type)].find(id);
|
2378 | });
|
2379 | tempChildren = new PolymorphicCollection(models);
|
2380 | } else {
|
2381 | tempChildren = association.schema[association.schema.toCollectionName(association.modelName)].find(ids);
|
2382 | }
|
2383 | }
|
2384 |
|
2385 | this[key] = tempChildren;
|
2386 | }
|
2387 | });
|
2388 | Object.defineProperty(modelPrototype, key, {
|
2389 | |
2390 |
|
2391 |
|
2392 |
|
2393 | get: function get() {
|
2394 | this._tempAssociations = this._tempAssociations || {};
|
2395 | var collection = null;
|
2396 |
|
2397 | if (this._tempAssociations[key]) {
|
2398 | collection = this._tempAssociations[key];
|
2399 | } else {
|
2400 | if (association.isPolymorphic) {
|
2401 | if (this[foreignKey]) {
|
2402 | var polymorphicIds = this[foreignKey];
|
2403 | var models = polymorphicIds.map(function (_ref2) {
|
2404 | var type = _ref2.type,
|
2405 | id = _ref2.id;
|
2406 | return association.schema[association.schema.toCollectionName(type)].find(id);
|
2407 | });
|
2408 | collection = new PolymorphicCollection(models);
|
2409 | } else {
|
2410 | collection = new PolymorphicCollection(association.modelName);
|
2411 | }
|
2412 | } else {
|
2413 | if (this[foreignKey]) {
|
2414 | collection = association.schema[association.schema.toCollectionName(association.modelName)].find(this[foreignKey]);
|
2415 | } else {
|
2416 | collection = new Collection(association.modelName);
|
2417 | }
|
2418 | }
|
2419 |
|
2420 | this._tempAssociations[key] = collection;
|
2421 | }
|
2422 |
|
2423 | return collection;
|
2424 | },
|
2425 |
|
2426 | |
2427 |
|
2428 |
|
2429 |
|
2430 | set: function set(models) {
|
2431 | var _this = this;
|
2432 |
|
2433 | if (models instanceof Collection || models instanceof PolymorphicCollection) {
|
2434 | models = models.models;
|
2435 | }
|
2436 |
|
2437 | models = models ? compact(models) : [];
|
2438 | this._tempAssociations = this._tempAssociations || {};
|
2439 | var collection;
|
2440 |
|
2441 | if (association.isPolymorphic) {
|
2442 | collection = new PolymorphicCollection(models);
|
2443 | } else {
|
2444 | collection = new Collection(association.modelName, models);
|
2445 | }
|
2446 |
|
2447 | this._tempAssociations[key] = collection;
|
2448 | models.forEach(function (model) {
|
2449 | if (model.hasInverseFor(association)) {
|
2450 | var inverse = model.inverseFor(association);
|
2451 | model.associate(_this, inverse);
|
2452 | }
|
2453 | });
|
2454 | }
|
2455 | });
|
2456 | |
2457 |
|
2458 |
|
2459 |
|
2460 |
|
2461 | modelPrototype["new".concat(capitalize(camelize(this._container.inflector.singularize(association.key))))] = function () {
|
2462 | var modelName, attrs;
|
2463 |
|
2464 | if (association.isPolymorphic) {
|
2465 | modelName = arguments.length <= 0 ? undefined : arguments[0];
|
2466 | attrs = arguments.length <= 1 ? undefined : arguments[1];
|
2467 | } else {
|
2468 | modelName = association.modelName;
|
2469 | attrs = arguments.length <= 0 ? undefined : arguments[0];
|
2470 | }
|
2471 |
|
2472 | var child = association.schema[association.schema.toCollectionName(modelName)]["new"](attrs);
|
2473 | var children = this[key].models;
|
2474 | children.push(child);
|
2475 | this[key] = children;
|
2476 | return child;
|
2477 | };
|
2478 | |
2479 |
|
2480 |
|
2481 |
|
2482 |
|
2483 |
|
2484 |
|
2485 |
|
2486 |
|
2487 | modelPrototype["create".concat(capitalize(camelize(this._container.inflector.singularize(association.key))))] = function () {
|
2488 | var modelName, attrs;
|
2489 |
|
2490 | if (association.isPolymorphic) {
|
2491 | modelName = arguments.length <= 0 ? undefined : arguments[0];
|
2492 | attrs = arguments.length <= 1 ? undefined : arguments[1];
|
2493 | } else {
|
2494 | modelName = association.modelName;
|
2495 | attrs = arguments.length <= 0 ? undefined : arguments[0];
|
2496 | }
|
2497 |
|
2498 | var child = association.schema[association.schema.toCollectionName(modelName)].create(attrs);
|
2499 | var children = this[key].models;
|
2500 | children.push(child);
|
2501 | this[key] = children;
|
2502 | this.save();
|
2503 | return child.reload();
|
2504 | };
|
2505 | }
|
2506 | |
2507 |
|
2508 |
|
2509 |
|
2510 |
|
2511 |
|
2512 | }, {
|
2513 | key: "disassociateAllDependentsFromTarget",
|
2514 | value: function disassociateAllDependentsFromTarget(model) {
|
2515 | var _this2 = this;
|
2516 |
|
2517 | var owner = this.ownerModelName;
|
2518 | var fk;
|
2519 |
|
2520 | if (this.isPolymorphic) {
|
2521 | fk = {
|
2522 | type: model.modelName,
|
2523 | id: model.id
|
2524 | };
|
2525 | } else {
|
2526 | fk = model.id;
|
2527 | }
|
2528 |
|
2529 | var dependents = this.schema[this.schema.toCollectionName(owner)].where(function (potentialOwner) {
|
2530 | var currentIds = potentialOwner[_this2.getForeignKey()];
|
2531 |
|
2532 |
|
2533 | return currentIds && currentIds.find(function (id) {
|
2534 | if (_typeof(id) === "object") {
|
2535 | return id.type === fk.type && id.id === fk.id;
|
2536 | } else {
|
2537 | return id === fk;
|
2538 | }
|
2539 | });
|
2540 | });
|
2541 | dependents.models.forEach(function (dependent) {
|
2542 | dependent.disassociate(model, _this2);
|
2543 | dependent.save();
|
2544 | });
|
2545 | }
|
2546 | }, {
|
2547 | key: "identifier",
|
2548 | get: function get() {
|
2549 | if (typeof identifierCache$1[this.key] !== "string") {
|
2550 | var identifier = "".concat(camelize(this._container.inflector.singularize(this.key)), "Ids");
|
2551 | identifierCache$1[this.key] = identifier;
|
2552 | }
|
2553 |
|
2554 | return identifierCache$1[this.key];
|
2555 | }
|
2556 | }]);
|
2557 |
|
2558 | return HasMany;
|
2559 | }(Association);
|
2560 |
|
2561 | var pathModelClassCache = {};
|
2562 |
|
2563 |
|
2564 |
|
2565 |
|
2566 | var BaseRouteHandler =
|
2567 |
|
2568 | function () {
|
2569 | function BaseRouteHandler() {
|
2570 | _classCallCheck(this, BaseRouteHandler);
|
2571 | }
|
2572 |
|
2573 | _createClass(BaseRouteHandler, [{
|
2574 | key: "getModelClassFromPath",
|
2575 | value: function getModelClassFromPath(fullPath) {
|
2576 | if (!fullPath) {
|
2577 | return;
|
2578 | }
|
2579 |
|
2580 | if (typeof pathModelClassCache[fullPath] !== "string") {
|
2581 | var path = fullPath.split("/");
|
2582 | var lastPath;
|
2583 |
|
2584 | for (var i = path.length - 1; i >= 0; i--) {
|
2585 | var segment = path[i];
|
2586 |
|
2587 | if (segment.length && segment[0] !== ":") {
|
2588 | lastPath = segment;
|
2589 | break;
|
2590 | }
|
2591 | }
|
2592 |
|
2593 | pathModelClassCache[fullPath] = dasherize(camelize(this._container.inflector.singularize(lastPath)));
|
2594 | }
|
2595 |
|
2596 | return pathModelClassCache[fullPath];
|
2597 | }
|
2598 | }, {
|
2599 | key: "_getIdForRequest",
|
2600 | value: function _getIdForRequest(request, jsonApiDoc) {
|
2601 | var id;
|
2602 |
|
2603 | if (request && request.params && request.params.id) {
|
2604 | id = request.params.id;
|
2605 | } else if (jsonApiDoc && jsonApiDoc.data && jsonApiDoc.data.id) {
|
2606 | id = jsonApiDoc.data.id;
|
2607 | }
|
2608 |
|
2609 | return id;
|
2610 | }
|
2611 | }, {
|
2612 | key: "_getJsonApiDocForRequest",
|
2613 | value: function _getJsonApiDocForRequest(request, modelName) {
|
2614 | var body;
|
2615 |
|
2616 | if (request && request.requestBody) {
|
2617 | body = JSON.parse(request.requestBody);
|
2618 | }
|
2619 |
|
2620 | return this.serializerOrRegistry.normalize(body, modelName);
|
2621 | }
|
2622 | }, {
|
2623 | key: "_getAttrsForRequest",
|
2624 | value: function _getAttrsForRequest(request, modelName) {
|
2625 | var _this = this;
|
2626 |
|
2627 | var json = this._getJsonApiDocForRequest(request, modelName);
|
2628 |
|
2629 | var id = this._getIdForRequest(request, json);
|
2630 |
|
2631 | var attrs = {};
|
2632 | assert(json.data && (json.data.attributes || json.data.type || json.data.relationships), "You're using a shorthand or #normalizedRequestAttrs, but your serializer's normalize function did not return a valid JSON:API document. Consult the docs for the normalize hook on the Serializer class.");
|
2633 |
|
2634 | if (json.data.attributes) {
|
2635 | attrs = Object.keys(json.data.attributes).reduce(function (sum, key) {
|
2636 | sum[camelize(key)] = json.data.attributes[key];
|
2637 | return sum;
|
2638 | }, {});
|
2639 | }
|
2640 |
|
2641 | if (json.data.relationships) {
|
2642 | Object.keys(json.data.relationships).forEach(function (relationshipName) {
|
2643 | var relationship = json.data.relationships[relationshipName];
|
2644 |
|
2645 | var modelClass = _this.schema.modelClassFor(modelName);
|
2646 |
|
2647 | var association = modelClass.associationFor(camelize(relationshipName));
|
2648 | var valueForRelationship;
|
2649 | assert(association, "You're passing the relationship '".concat(relationshipName, "' to the '").concat(modelName, "' model via a ").concat(request.method, " to '").concat(request.url, "', but you did not define the '").concat(relationshipName, "' association on the '").concat(modelName, "' model."));
|
2650 |
|
2651 | if (association.isPolymorphic) {
|
2652 | valueForRelationship = relationship.data;
|
2653 | } else if (association instanceof HasMany) {
|
2654 | valueForRelationship = relationship.data && relationship.data.map(function (rel) {
|
2655 | return rel.id;
|
2656 | });
|
2657 | } else {
|
2658 | valueForRelationship = relationship.data && relationship.data.id;
|
2659 | }
|
2660 |
|
2661 | attrs[association.identifier] = valueForRelationship;
|
2662 | }, {});
|
2663 | }
|
2664 |
|
2665 | if (id) {
|
2666 | attrs.id = id;
|
2667 | }
|
2668 |
|
2669 | return attrs;
|
2670 | }
|
2671 | }, {
|
2672 | key: "_getAttrsForFormRequest",
|
2673 | value: function _getAttrsForFormRequest(_ref) {
|
2674 | var requestBody = _ref.requestBody;
|
2675 | var attrs;
|
2676 | var urlEncodedParts = [];
|
2677 | assert(requestBody && typeof requestBody === "string", "You're using the helper method #normalizedFormData, but the request body is empty or not a valid url encoded string.");
|
2678 | urlEncodedParts = requestBody.split("&");
|
2679 | attrs = urlEncodedParts.reduce(function (a, urlEncodedPart) {
|
2680 | var _urlEncodedPart$split = urlEncodedPart.split("="),
|
2681 | _urlEncodedPart$split2 = _slicedToArray(_urlEncodedPart$split, 2),
|
2682 | key = _urlEncodedPart$split2[0],
|
2683 | value = _urlEncodedPart$split2[1];
|
2684 |
|
2685 | a[key] = decodeURIComponent(value.replace(/\+/g, " "));
|
2686 | return a;
|
2687 | }, {});
|
2688 | return attrs;
|
2689 | }
|
2690 | }]);
|
2691 |
|
2692 | return BaseRouteHandler;
|
2693 | }();
|
2694 |
|
2695 |
|
2696 |
|
2697 |
|
2698 |
|
2699 | var FunctionRouteHandler =
|
2700 |
|
2701 | function (_BaseRouteHandler) {
|
2702 | _inherits(FunctionRouteHandler, _BaseRouteHandler);
|
2703 |
|
2704 | function FunctionRouteHandler(schema, serializerOrRegistry, userFunction, path, server) {
|
2705 | var _this;
|
2706 |
|
2707 | _classCallCheck(this, FunctionRouteHandler);
|
2708 |
|
2709 | _this = _possibleConstructorReturn(this, _getPrototypeOf(FunctionRouteHandler).call(this, server));
|
2710 | _this.schema = schema;
|
2711 | _this.serializerOrRegistry = serializerOrRegistry;
|
2712 | _this.userFunction = userFunction;
|
2713 | _this.path = path;
|
2714 | return _this;
|
2715 | }
|
2716 |
|
2717 | _createClass(FunctionRouteHandler, [{
|
2718 | key: "handle",
|
2719 | value: function handle(request) {
|
2720 | return this.userFunction(this.schema, request);
|
2721 | }
|
2722 | }, {
|
2723 | key: "setRequest",
|
2724 | value: function setRequest(request) {
|
2725 | this.request = request;
|
2726 | }
|
2727 | }, {
|
2728 | key: "serialize",
|
2729 | value: function serialize(response, serializerType) {
|
2730 | var serializer;
|
2731 |
|
2732 | if (serializerType) {
|
2733 | serializer = this.serializerOrRegistry.serializerFor(serializerType, {
|
2734 | explicit: true
|
2735 | });
|
2736 | } else {
|
2737 | serializer = this.serializerOrRegistry;
|
2738 | }
|
2739 |
|
2740 | return serializer.serialize(response, this.request);
|
2741 | }
|
2742 | }, {
|
2743 | key: "normalizedRequestAttrs",
|
2744 | value: function normalizedRequestAttrs() {
|
2745 | var modelName = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
|
2746 | var path = this.path,
|
2747 | request = this.request,
|
2748 | requestHeaders = this.request.requestHeaders;
|
2749 | var attrs;
|
2750 | var lowerCaseHeaders = {};
|
2751 |
|
2752 | for (var header in requestHeaders) {
|
2753 | lowerCaseHeaders[header.toLowerCase()] = requestHeaders[header];
|
2754 | }
|
2755 |
|
2756 | if (/x-www-form-urlencoded/.test(lowerCaseHeaders["content-type"])) {
|
2757 | attrs = this._getAttrsForFormRequest(request);
|
2758 | } else {
|
2759 | if (modelName) {
|
2760 | assert(dasherize(modelName) === modelName, "You called normalizedRequestAttrs('".concat(modelName, "'), but normalizedRequestAttrs was intended to be used with the dasherized version of the model type. Please change this to normalizedRequestAttrs('").concat(dasherize(modelName), "')."));
|
2761 | } else {
|
2762 | modelName = this.getModelClassFromPath(path);
|
2763 | }
|
2764 |
|
2765 | assert(this.schema.hasModelForModelName(modelName), "You're using a shorthand or the #normalizedRequestAttrs helper but the detected model of '".concat(modelName, "' does not exist. You might need to pass in the correct modelName as the first argument to #normalizedRequestAttrs."));
|
2766 | attrs = this._getAttrsForRequest(request, modelName);
|
2767 | }
|
2768 |
|
2769 | return attrs;
|
2770 | }
|
2771 | }]);
|
2772 |
|
2773 | return FunctionRouteHandler;
|
2774 | }(BaseRouteHandler);
|
2775 |
|
2776 |
|
2777 |
|
2778 |
|
2779 | var ObjectRouteHandler =
|
2780 |
|
2781 | function () {
|
2782 | function ObjectRouteHandler(schema, serializerOrRegistry, object) {
|
2783 | _classCallCheck(this, ObjectRouteHandler);
|
2784 |
|
2785 | this.schema = schema;
|
2786 | this.serializerOrRegistry = serializerOrRegistry;
|
2787 | this.object = object;
|
2788 | }
|
2789 |
|
2790 | _createClass(ObjectRouteHandler, [{
|
2791 | key: "handle",
|
2792 | value: function handle()
|
2793 | /* request */
|
2794 | {
|
2795 | return this.object;
|
2796 | }
|
2797 | }]);
|
2798 |
|
2799 | return ObjectRouteHandler;
|
2800 | }();
|
2801 |
|
2802 |
|
2803 |
|
2804 |
|
2805 |
|
2806 | var BaseShorthandRouteHandler =
|
2807 |
|
2808 | function (_BaseRouteHandler) {
|
2809 | _inherits(BaseShorthandRouteHandler, _BaseRouteHandler);
|
2810 |
|
2811 | function BaseShorthandRouteHandler(schema, serializerOrRegistry, shorthand, path) {
|
2812 | var _this;
|
2813 |
|
2814 | var options = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {};
|
2815 |
|
2816 | _classCallCheck(this, BaseShorthandRouteHandler);
|
2817 |
|
2818 | _this = _possibleConstructorReturn(this, _getPrototypeOf(BaseShorthandRouteHandler).call(this));
|
2819 | shorthand = shorthand || _this.getModelClassFromPath(path);
|
2820 | _this.schema = schema;
|
2821 | _this.serializerOrRegistry = serializerOrRegistry;
|
2822 | _this.shorthand = shorthand;
|
2823 | _this.options = options;
|
2824 | var type = Array.isArray(shorthand) ? "array" : _typeof(shorthand);
|
2825 |
|
2826 | if (type === "string") {
|
2827 | var modelClass = _this.schema[_this.schema.toCollectionName(shorthand)];
|
2828 |
|
2829 | _this.handle = function (request) {
|
2830 | return _this.handleStringShorthand(request, modelClass);
|
2831 | };
|
2832 | } else if (type === "array") {
|
2833 | var modelClasses = shorthand.map(function (modelName) {
|
2834 | return _this.schema[_this.schema.toCollectionName(modelName)];
|
2835 | });
|
2836 |
|
2837 | _this.handle = function (request) {
|
2838 | return _this.handleArrayShorthand(request, modelClasses);
|
2839 | };
|
2840 | }
|
2841 |
|
2842 | return _this;
|
2843 | }
|
2844 |
|
2845 |
|
2846 |
|
2847 |
|
2848 |
|
2849 |
|
2850 |
|
2851 |
|
2852 | return BaseShorthandRouteHandler;
|
2853 | }(BaseRouteHandler);
|
2854 |
|
2855 |
|
2856 |
|
2857 |
|
2858 |
|
2859 | var GetShorthandRouteHandler =
|
2860 |
|
2861 | function (_BaseShorthandRouteHa) {
|
2862 | _inherits(GetShorthandRouteHandler, _BaseShorthandRouteHa);
|
2863 |
|
2864 | function GetShorthandRouteHandler() {
|
2865 | _classCallCheck(this, GetShorthandRouteHandler);
|
2866 |
|
2867 | return _possibleConstructorReturn(this, _getPrototypeOf(GetShorthandRouteHandler).apply(this, arguments));
|
2868 | }
|
2869 |
|
2870 | _createClass(GetShorthandRouteHandler, [{
|
2871 | key: "handleStringShorthand",
|
2872 |
|
2873 | |
2874 |
|
2875 |
|
2876 |
|
2877 |
|
2878 |
|
2879 | value: function handleStringShorthand(request, modelClass) {
|
2880 | var modelName = this.shorthand;
|
2881 | var camelizedModelName = camelize(modelName);
|
2882 | assert(modelClass, "The route handler for ".concat(request.url, " is trying to access the ").concat(camelizedModelName, " model, but that model doesn't exist."));
|
2883 |
|
2884 | var id = this._getIdForRequest(request);
|
2885 |
|
2886 | if (id) {
|
2887 | var model = modelClass.find(id);
|
2888 |
|
2889 | if (!model) {
|
2890 | return new Response(404);
|
2891 | } else {
|
2892 | return model;
|
2893 | }
|
2894 | } else if (this.options.coalesce) {
|
2895 | var ids = this.serializerOrRegistry.getCoalescedIds(request, camelizedModelName);
|
2896 |
|
2897 | if (ids) {
|
2898 | return modelClass.find(ids);
|
2899 | }
|
2900 | }
|
2901 |
|
2902 | return modelClass.all();
|
2903 | }
|
2904 | |
2905 |
|
2906 |
|
2907 |
|
2908 |
|
2909 | }, {
|
2910 | key: "handleArrayShorthand",
|
2911 | value: function handleArrayShorthand(request, modelClasses) {
|
2912 | var keys = this.shorthand;
|
2913 |
|
2914 | var id = this._getIdForRequest(request);
|
2915 | |
2916 |
|
2917 |
|
2918 |
|
2919 |
|
2920 |
|
2921 |
|
2922 |
|
2923 |
|
2924 | assert(!id || this._container.inflector.singularize(keys[0]) !== keys[0], "It looks like you're using the \"Single record with\n related records\" version of the array shorthand, in addition to opting\n in to the model layer. This shorthand was made when there was no\n serializer layer. Now that you're using models, please ensure your\n relationships are defined, and create a serializer for the parent\n model, adding the relationships there.");
|
2925 | return modelClasses.map(function (modelClass) {
|
2926 | return modelClass.all();
|
2927 | });
|
2928 | }
|
2929 | }]);
|
2930 |
|
2931 | return GetShorthandRouteHandler;
|
2932 | }(BaseShorthandRouteHandler);
|
2933 |
|
2934 |
|
2935 |
|
2936 |
|
2937 |
|
2938 | var PostShorthandRouteHandler =
|
2939 |
|
2940 | function (_BaseShorthandRouteHa) {
|
2941 | _inherits(PostShorthandRouteHandler, _BaseShorthandRouteHa);
|
2942 |
|
2943 | function PostShorthandRouteHandler() {
|
2944 | _classCallCheck(this, PostShorthandRouteHandler);
|
2945 |
|
2946 | return _possibleConstructorReturn(this, _getPrototypeOf(PostShorthandRouteHandler).apply(this, arguments));
|
2947 | }
|
2948 |
|
2949 | _createClass(PostShorthandRouteHandler, [{
|
2950 | key: "handleStringShorthand",
|
2951 |
|
2952 | |
2953 |
|
2954 |
|
2955 |
|
2956 |
|
2957 | value: function handleStringShorthand(request, modelClass) {
|
2958 | var modelName = this.shorthand;
|
2959 | var camelizedModelName = camelize(modelName);
|
2960 | assert(modelClass, "The route handler for ".concat(request.url, " is trying to access the ").concat(camelizedModelName, " model, but that model doesn't exist."));
|
2961 |
|
2962 | var attrs = this._getAttrsForRequest(request, modelClass.camelizedModelName);
|
2963 |
|
2964 | return modelClass.create(attrs);
|
2965 | }
|
2966 | }]);
|
2967 |
|
2968 | return PostShorthandRouteHandler;
|
2969 | }(BaseShorthandRouteHandler);
|
2970 |
|
2971 |
|
2972 |
|
2973 |
|
2974 |
|
2975 | var PutShorthandRouteHandler =
|
2976 |
|
2977 | function (_BaseShorthandRouteHa) {
|
2978 | _inherits(PutShorthandRouteHandler, _BaseShorthandRouteHa);
|
2979 |
|
2980 | function PutShorthandRouteHandler() {
|
2981 | _classCallCheck(this, PutShorthandRouteHandler);
|
2982 |
|
2983 | return _possibleConstructorReturn(this, _getPrototypeOf(PutShorthandRouteHandler).apply(this, arguments));
|
2984 | }
|
2985 |
|
2986 | _createClass(PutShorthandRouteHandler, [{
|
2987 | key: "handleStringShorthand",
|
2988 |
|
2989 | |
2990 |
|
2991 |
|
2992 |
|
2993 | value: function handleStringShorthand(request, modelClass) {
|
2994 | var modelName = this.shorthand;
|
2995 | var camelizedModelName = camelize(modelName);
|
2996 | assert(modelClass, "The route handler for ".concat(request.url, " is trying to access the ").concat(camelizedModelName, " model, but that model doesn't exist."));
|
2997 |
|
2998 | var id = this._getIdForRequest(request);
|
2999 |
|
3000 | var model = modelClass.find(id);
|
3001 |
|
3002 | if (!model) {
|
3003 | return new Response(404);
|
3004 | }
|
3005 |
|
3006 | var attrs = this._getAttrsForRequest(request, modelClass.camelizedModelName);
|
3007 |
|
3008 | return model.update(attrs);
|
3009 | }
|
3010 | }]);
|
3011 |
|
3012 | return PutShorthandRouteHandler;
|
3013 | }(BaseShorthandRouteHandler);
|
3014 |
|
3015 |
|
3016 |
|
3017 |
|
3018 |
|
3019 | var DeleteShorthandRouteHandler =
|
3020 |
|
3021 | function (_BaseShorthandRouteHa) {
|
3022 | _inherits(DeleteShorthandRouteHandler, _BaseShorthandRouteHa);
|
3023 |
|
3024 | function DeleteShorthandRouteHandler() {
|
3025 | _classCallCheck(this, DeleteShorthandRouteHandler);
|
3026 |
|
3027 | return _possibleConstructorReturn(this, _getPrototypeOf(DeleteShorthandRouteHandler).apply(this, arguments));
|
3028 | }
|
3029 |
|
3030 | _createClass(DeleteShorthandRouteHandler, [{
|
3031 | key: "handleStringShorthand",
|
3032 |
|
3033 | |
3034 |
|
3035 |
|
3036 |
|
3037 |
|
3038 | value: function handleStringShorthand(request, modelClass) {
|
3039 | var modelName = this.shorthand;
|
3040 | var camelizedModelName = camelize(modelName);
|
3041 | assert(modelClass, "The route handler for ".concat(request.url, " is trying to access the ").concat(camelizedModelName, " model, but that model doesn't exist."));
|
3042 |
|
3043 | var id = this._getIdForRequest(request);
|
3044 |
|
3045 | var model = modelClass.find(id);
|
3046 |
|
3047 | if (!model) {
|
3048 | return new Response(404);
|
3049 | }
|
3050 |
|
3051 | model.destroy();
|
3052 | }
|
3053 | |
3054 |
|
3055 |
|
3056 |
|
3057 |
|
3058 |
|
3059 |
|
3060 | }, {
|
3061 | key: "handleArrayShorthand",
|
3062 | value: function handleArrayShorthand(request, modelClasses) {
|
3063 | var _this = this;
|
3064 |
|
3065 | var id = this._getIdForRequest(request);
|
3066 |
|
3067 | var parent = modelClasses[0].find(id);
|
3068 | var childTypes = modelClasses.slice(1).map(function (modelClass) {
|
3069 | return _this._container.inflector.pluralize(modelClass.camelizedModelName);
|
3070 | });
|
3071 |
|
3072 | childTypes.forEach(function (type) {
|
3073 | return parent[type].destroy();
|
3074 | });
|
3075 | parent.destroy();
|
3076 | }
|
3077 | }]);
|
3078 |
|
3079 | return DeleteShorthandRouteHandler;
|
3080 | }(BaseShorthandRouteHandler);
|
3081 |
|
3082 |
|
3083 |
|
3084 |
|
3085 |
|
3086 | var HeadShorthandRouteHandler =
|
3087 |
|
3088 | function (_BaseShorthandRouteHa) {
|
3089 | _inherits(HeadShorthandRouteHandler, _BaseShorthandRouteHa);
|
3090 |
|
3091 | function HeadShorthandRouteHandler() {
|
3092 | _classCallCheck(this, HeadShorthandRouteHandler);
|
3093 |
|
3094 | return _possibleConstructorReturn(this, _getPrototypeOf(HeadShorthandRouteHandler).apply(this, arguments));
|
3095 | }
|
3096 |
|
3097 | _createClass(HeadShorthandRouteHandler, [{
|
3098 | key: "handleStringShorthand",
|
3099 |
|
3100 | |
3101 |
|
3102 |
|
3103 |
|
3104 |
|
3105 |
|
3106 | value: function handleStringShorthand(request, modelClass) {
|
3107 | var modelName = this.shorthand;
|
3108 | var camelizedModelName = camelize(modelName);
|
3109 | assert(modelClass, "The route handler for ".concat(request.url, " is trying to access the ").concat(camelizedModelName, " model, but that model doesn't exist."));
|
3110 |
|
3111 | var id = this._getIdForRequest(request);
|
3112 |
|
3113 | if (id) {
|
3114 | var model = modelClass.find(id);
|
3115 |
|
3116 | if (!model) {
|
3117 | return new Response(404);
|
3118 | } else {
|
3119 | return new Response(204);
|
3120 | }
|
3121 | } else if (this.options.coalesce && request.queryParams && request.queryParams.ids) {
|
3122 | var _model = modelClass.find(request.queryParams.ids);
|
3123 |
|
3124 | if (!_model) {
|
3125 | return new Response(404);
|
3126 | } else {
|
3127 | return new Response(204);
|
3128 | }
|
3129 | } else {
|
3130 | return new Response(204);
|
3131 | }
|
3132 | }
|
3133 | }]);
|
3134 |
|
3135 | return HeadShorthandRouteHandler;
|
3136 | }(BaseShorthandRouteHandler);
|
3137 |
|
3138 | var DEFAULT_CODES = {
|
3139 | get: 200,
|
3140 | put: 204,
|
3141 | post: 201,
|
3142 | "delete": 204
|
3143 | };
|
3144 |
|
3145 | function createHandler(_ref) {
|
3146 | var verb = _ref.verb,
|
3147 | schema = _ref.schema,
|
3148 | serializerOrRegistry = _ref.serializerOrRegistry,
|
3149 | path = _ref.path,
|
3150 | rawHandler = _ref.rawHandler,
|
3151 | options = _ref.options;
|
3152 | var handler;
|
3153 | var args = [schema, serializerOrRegistry, rawHandler, path, options];
|
3154 |
|
3155 | var type = _typeof(rawHandler);
|
3156 |
|
3157 | if (type === "function") {
|
3158 | handler = _construct(FunctionRouteHandler, args);
|
3159 | } else if (type === "object" && rawHandler) {
|
3160 | handler = _construct(ObjectRouteHandler, args);
|
3161 | } else if (verb === "get") {
|
3162 | handler = _construct(GetShorthandRouteHandler, args);
|
3163 | } else if (verb === "post") {
|
3164 | handler = _construct(PostShorthandRouteHandler, args);
|
3165 | } else if (verb === "put" || verb === "patch") {
|
3166 | handler = _construct(PutShorthandRouteHandler, args);
|
3167 | } else if (verb === "delete") {
|
3168 | handler = _construct(DeleteShorthandRouteHandler, args);
|
3169 | } else if (verb === "head") {
|
3170 | handler = _construct(HeadShorthandRouteHandler, args);
|
3171 | }
|
3172 |
|
3173 | return handler;
|
3174 | }
|
3175 |
|
3176 |
|
3177 |
|
3178 |
|
3179 |
|
3180 | var RouteHandler =
|
3181 |
|
3182 | function () {
|
3183 | function RouteHandler(_ref2) {
|
3184 | var schema = _ref2.schema,
|
3185 | verb = _ref2.verb,
|
3186 | rawHandler = _ref2.rawHandler,
|
3187 | customizedCode = _ref2.customizedCode,
|
3188 | options = _ref2.options,
|
3189 | path = _ref2.path,
|
3190 | serializerOrRegistry = _ref2.serializerOrRegistry;
|
3191 |
|
3192 | _classCallCheck(this, RouteHandler);
|
3193 |
|
3194 | this.verb = verb;
|
3195 | this.customizedCode = customizedCode;
|
3196 | this.serializerOrRegistry = serializerOrRegistry;
|
3197 | this.handler = createHandler({
|
3198 | verb: verb,
|
3199 | schema: schema,
|
3200 | path: path,
|
3201 | serializerOrRegistry: serializerOrRegistry,
|
3202 | rawHandler: rawHandler,
|
3203 | options: options
|
3204 | });
|
3205 | }
|
3206 |
|
3207 | _createClass(RouteHandler, [{
|
3208 | key: "handle",
|
3209 | value: function handle(request) {
|
3210 | var _this = this;
|
3211 |
|
3212 | return this._getMirageResponseForRequest(request).then(function (mirageResponse) {
|
3213 | return _this.serialize(mirageResponse, request);
|
3214 | }).then(function (serializedMirageResponse) {
|
3215 | return serializedMirageResponse.toRackResponse();
|
3216 | });
|
3217 | }
|
3218 | }, {
|
3219 | key: "_getMirageResponseForRequest",
|
3220 | value: function _getMirageResponseForRequest(request) {
|
3221 | var result;
|
3222 |
|
3223 | try {
|
3224 | |
3225 |
|
3226 |
|
3227 |
|
3228 | if (this.handler instanceof FunctionRouteHandler) {
|
3229 | this.handler.setRequest(request);
|
3230 | }
|
3231 |
|
3232 | result = this.handler.handle(request);
|
3233 | } catch (e) {
|
3234 | if (e instanceof MirageError) {
|
3235 | result = new Response(500, {}, e);
|
3236 | } else {
|
3237 | var message = e.message || e;
|
3238 | result = new Response(500, {}, {
|
3239 | message: message,
|
3240 | stack: "Mirage: Your ".concat(request.method, " handler for the url ").concat(request.url, " threw an error:\n\n").concat(e.stack || e)
|
3241 | });
|
3242 | }
|
3243 | }
|
3244 |
|
3245 | return this._toMirageResponse(result);
|
3246 | }
|
3247 | }, {
|
3248 | key: "_toMirageResponse",
|
3249 | value: function _toMirageResponse(result) {
|
3250 | var _this2 = this;
|
3251 |
|
3252 | var mirageResponse;
|
3253 | return new Promise(function (resolve, reject) {
|
3254 | Promise.resolve(result).then(function (response) {
|
3255 | if (response instanceof Response) {
|
3256 | mirageResponse = result;
|
3257 | } else {
|
3258 | var code = _this2._getCodeForResponse(response);
|
3259 |
|
3260 | mirageResponse = new Response(code, {}, response);
|
3261 | }
|
3262 |
|
3263 | resolve(mirageResponse);
|
3264 | })["catch"](reject);
|
3265 | });
|
3266 | }
|
3267 | }, {
|
3268 | key: "_getCodeForResponse",
|
3269 | value: function _getCodeForResponse(response) {
|
3270 | var code;
|
3271 |
|
3272 | if (this.customizedCode) {
|
3273 | code = this.customizedCode;
|
3274 | } else {
|
3275 | code = DEFAULT_CODES[this.verb];
|
3276 |
|
3277 | if (code === 204 && response !== undefined && response !== "") {
|
3278 | code = 200;
|
3279 | }
|
3280 | }
|
3281 |
|
3282 | return code;
|
3283 | }
|
3284 | }, {
|
3285 | key: "serialize",
|
3286 | value: function serialize(mirageResponse, request) {
|
3287 | mirageResponse.data = this.serializerOrRegistry.serialize(mirageResponse.data, request);
|
3288 | return mirageResponse;
|
3289 | }
|
3290 | }]);
|
3291 |
|
3292 | return RouteHandler;
|
3293 | }();
|
3294 |
|
3295 |
|
3296 |
|
3297 |
|
3298 |
|
3299 | function extend(protoProps, staticProps) {
|
3300 | var Child =
|
3301 |
|
3302 | function (_this) {
|
3303 | _inherits(Child, _this);
|
3304 |
|
3305 | function Child() {
|
3306 | var _getPrototypeOf2;
|
3307 |
|
3308 | var _this2;
|
3309 |
|
3310 | _classCallCheck(this, Child);
|
3311 |
|
3312 | for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
|
3313 | args[_key] = arguments[_key];
|
3314 | }
|
3315 |
|
3316 | _this2 = _possibleConstructorReturn(this, (_getPrototypeOf2 = _getPrototypeOf(Child)).call.apply(_getPrototypeOf2, [this].concat(args)));
|
3317 |
|
3318 |
|
3319 | if (protoProps && has(protoProps, "constructor")) {
|
3320 | var _protoProps$construct;
|
3321 |
|
3322 | (_protoProps$construct = protoProps.constructor).call.apply(_protoProps$construct, [_assertThisInitialized(_this2)].concat(args));
|
3323 | }
|
3324 |
|
3325 | return _this2;
|
3326 | }
|
3327 |
|
3328 | return Child;
|
3329 | }(this);
|
3330 |
|
3331 |
|
3332 | Object.assign(Child, this, staticProps);
|
3333 |
|
3334 |
|
3335 | if (protoProps) {
|
3336 | Object.assign(Child.prototype, protoProps);
|
3337 | }
|
3338 |
|
3339 | return Child;
|
3340 | }
|
3341 |
|
3342 |
|
3343 |
|
3344 |
|
3345 |
|
3346 |
|
3347 |
|
3348 |
|
3349 |
|
3350 |
|
3351 |
|
3352 |
|
3353 |
|
3354 |
|
3355 |
|
3356 |
|
3357 |
|
3358 |
|
3359 |
|
3360 |
|
3361 |
|
3362 |
|
3363 |
|
3364 |
|
3365 |
|
3366 |
|
3367 |
|
3368 |
|
3369 |
|
3370 |
|
3371 |
|
3372 |
|
3373 |
|
3374 |
|
3375 |
|
3376 |
|
3377 |
|
3378 |
|
3379 |
|
3380 |
|
3381 |
|
3382 |
|
3383 |
|
3384 |
|
3385 |
|
3386 |
|
3387 | var Model =
|
3388 |
|
3389 | function () {
|
3390 |
|
3391 |
|
3392 | |
3393 |
|
3394 |
|
3395 |
|
3396 |
|
3397 |
|
3398 | function Model(schema, modelName, attrs, fks) {
|
3399 | var _this = this;
|
3400 |
|
3401 | _classCallCheck(this, Model);
|
3402 |
|
3403 | assert(schema, "A model requires a schema");
|
3404 | assert(modelName, "A model requires a modelName");
|
3405 | this._schema = schema;
|
3406 | this.modelName = modelName;
|
3407 | this.fks = fks || [];
|
3408 | |
3409 |
|
3410 |
|
3411 |
|
3412 |
|
3413 |
|
3414 |
|
3415 |
|
3416 |
|
3417 |
|
3418 |
|
3419 | this.attrs = {};
|
3420 | attrs = attrs || {};
|
3421 |
|
3422 | this.fks.forEach(function (fk) {
|
3423 | _this.attrs[fk] = attrs[fk] !== undefined ? attrs[fk] : null;
|
3424 | });
|
3425 | Object.keys(attrs).forEach(function (name) {
|
3426 | var value = attrs[name];
|
3427 |
|
3428 | _this._validateAttr(name, value);
|
3429 |
|
3430 | _this._setupAttr(name, value);
|
3431 |
|
3432 | _this._setupRelationship(name, value);
|
3433 | });
|
3434 | return this;
|
3435 | }
|
3436 | |
3437 |
|
3438 |
|
3439 |
|
3440 |
|
3441 |
|
3442 |
|
3443 |
|
3444 |
|
3445 |
|
3446 |
|
3447 |
|
3448 |
|
3449 |
|
3450 |
|
3451 |
|
3452 | _createClass(Model, [{
|
3453 | key: "save",
|
3454 | value: function save() {
|
3455 | var collection = this._schema.toInternalCollectionName(this.modelName);
|
3456 |
|
3457 | if (this.isNew()) {
|
3458 |
|
3459 | this.attrs = this._schema.db[collection].insert(this.attrs);
|
3460 |
|
3461 | this._definePlainAttribute("id");
|
3462 | } else {
|
3463 | this._schema.isSaving[this.toString()] = true;
|
3464 |
|
3465 | this._schema.db[collection].update(this.attrs.id, this.attrs);
|
3466 | }
|
3467 |
|
3468 | this._saveAssociations();
|
3469 |
|
3470 | this._schema.isSaving[this.toString()] = false;
|
3471 | return this;
|
3472 | }
|
3473 | |
3474 |
|
3475 |
|
3476 |
|
3477 |
|
3478 |
|
3479 |
|
3480 |
|
3481 |
|
3482 |
|
3483 |
|
3484 |
|
3485 |
|
3486 |
|
3487 |
|
3488 |
|
3489 |
|
3490 | }, {
|
3491 | key: "update",
|
3492 | value: function update(key, val) {
|
3493 | var attrs;
|
3494 |
|
3495 | if (key == null) {
|
3496 | return this;
|
3497 | }
|
3498 |
|
3499 | if (_typeof(key) === "object") {
|
3500 | attrs = key;
|
3501 | } else {
|
3502 | (attrs = {})[key] = val;
|
3503 | }
|
3504 |
|
3505 | Object.keys(attrs).forEach(function (attr) {
|
3506 | if (!this.associationKeys.has(attr) && !this.associationIdKeys.has(attr)) {
|
3507 | this._definePlainAttribute(attr);
|
3508 | }
|
3509 |
|
3510 | this[attr] = attrs[attr];
|
3511 | }, this);
|
3512 | this.save();
|
3513 | return this;
|
3514 | }
|
3515 | |
3516 |
|
3517 |
|
3518 |
|
3519 |
|
3520 |
|
3521 |
|
3522 |
|
3523 |
|
3524 |
|
3525 | }, {
|
3526 | key: "destroy",
|
3527 | value: function destroy() {
|
3528 | if (this.isSaved()) {
|
3529 | this._disassociateFromDependents();
|
3530 |
|
3531 | var collection = this._schema.toInternalCollectionName(this.modelName);
|
3532 |
|
3533 | this._schema.db[collection].remove(this.attrs.id);
|
3534 | }
|
3535 | }
|
3536 | |
3537 |
|
3538 |
|
3539 |
|
3540 |
|
3541 |
|
3542 |
|
3543 |
|
3544 |
|
3545 |
|
3546 |
|
3547 |
|
3548 |
|
3549 |
|
3550 |
|
3551 | }, {
|
3552 | key: "isNew",
|
3553 | value: function isNew() {
|
3554 | var hasDbRecord = false;
|
3555 | var hasId = this.attrs.id !== undefined && this.attrs.id !== null;
|
3556 |
|
3557 | if (hasId) {
|
3558 | var collectionName = this._schema.toInternalCollectionName(this.modelName);
|
3559 |
|
3560 | var record = this._schema.db[collectionName].find(this.attrs.id);
|
3561 |
|
3562 | if (record) {
|
3563 | hasDbRecord = true;
|
3564 | }
|
3565 | }
|
3566 |
|
3567 | return !hasDbRecord;
|
3568 | }
|
3569 | |
3570 |
|
3571 |
|
3572 |
|
3573 |
|
3574 |
|
3575 |
|
3576 | }, {
|
3577 | key: "isSaved",
|
3578 | value: function isSaved() {
|
3579 | return !this.isNew();
|
3580 | }
|
3581 | |
3582 |
|
3583 |
|
3584 |
|
3585 |
|
3586 |
|
3587 |
|
3588 |
|
3589 |
|
3590 |
|
3591 |
|
3592 |
|
3593 |
|
3594 |
|
3595 |
|
3596 | }, {
|
3597 | key: "reload",
|
3598 | value: function reload() {
|
3599 | if (this.id) {
|
3600 | var collection = this._schema.toInternalCollectionName(this.modelName);
|
3601 |
|
3602 | var attrs = this._schema.db[collection].find(this.id);
|
3603 |
|
3604 | Object.keys(attrs).filter(function (attr) {
|
3605 | return attr !== "id";
|
3606 | }).forEach(function (attr) {
|
3607 | this.attrs[attr] = attrs[attr];
|
3608 | }, this);
|
3609 | }
|
3610 |
|
3611 |
|
3612 | this._tempAssociations = {};
|
3613 | return this;
|
3614 | }
|
3615 | }, {
|
3616 | key: "toJSON",
|
3617 | value: function toJSON() {
|
3618 | return this.attrs;
|
3619 | }
|
3620 | |
3621 |
|
3622 |
|
3623 |
|
3624 |
|
3625 |
|
3626 |
|
3627 |
|
3628 | }, {
|
3629 | key: "associationFor",
|
3630 | value: function associationFor(key) {
|
3631 | return this._schema.associationsFor(this.modelName)[key];
|
3632 | }
|
3633 | |
3634 |
|
3635 |
|
3636 |
|
3637 |
|
3638 |
|
3639 |
|
3640 |
|
3641 |
|
3642 |
|
3643 |
|
3644 |
|
3645 |
|
3646 |
|
3647 |
|
3648 |
|
3649 |
|
3650 |
|
3651 |
|
3652 |
|
3653 |
|
3654 |
|
3655 |
|
3656 |
|
3657 |
|
3658 |
|
3659 |
|
3660 |
|
3661 |
|
3662 |
|
3663 |
|
3664 |
|
3665 |
|
3666 |
|
3667 |
|
3668 | }, {
|
3669 | key: "inverseFor",
|
3670 | value: function inverseFor(association) {
|
3671 | return this._explicitInverseFor(association) || this._implicitInverseFor(association);
|
3672 | }
|
3673 | |
3674 |
|
3675 |
|
3676 |
|
3677 |
|
3678 |
|
3679 | }, {
|
3680 | key: "_explicitInverseFor",
|
3681 | value: function _explicitInverseFor(association) {
|
3682 | this._checkForMultipleExplicitInverses(association);
|
3683 |
|
3684 | var associations = this._schema.associationsFor(this.modelName);
|
3685 |
|
3686 | var inverse = association.opts.inverse;
|
3687 | var candidate = inverse ? associations[inverse] : null;
|
3688 | var matchingPolymorphic = candidate && candidate.isPolymorphic;
|
3689 | var matchingInverse = candidate && candidate.modelName === association.ownerModelName;
|
3690 | var candidateInverse = candidate && candidate.opts.inverse;
|
3691 |
|
3692 | if (candidateInverse && candidate.opts.inverse !== association.key) {
|
3693 | assert(false, "You specified an inverse of ".concat(inverse, " for ").concat(association.key, ", but it does not match ").concat(candidate.modelName, " ").concat(candidate.key, "'s inverse"));
|
3694 | }
|
3695 |
|
3696 | return matchingPolymorphic || matchingInverse ? candidate : null;
|
3697 | }
|
3698 | |
3699 |
|
3700 |
|
3701 |
|
3702 |
|
3703 |
|
3704 |
|
3705 |
|
3706 | }, {
|
3707 | key: "_checkForMultipleExplicitInverses",
|
3708 | value: function _checkForMultipleExplicitInverses(association) {
|
3709 | var associations = this._schema.associationsFor(this.modelName);
|
3710 |
|
3711 | var matchingExplicitInverses = Object.keys(associations).filter(function (key) {
|
3712 | var candidate = associations[key];
|
3713 | var modelMatches = association.ownerModelName === candidate.modelName;
|
3714 | var inverseKeyMatches = association.key === candidate.opts.inverse;
|
3715 | return modelMatches && inverseKeyMatches;
|
3716 | });
|
3717 | assert(matchingExplicitInverses.length <= 1, "The ".concat(this.modelName, " model has defined multiple explicit inverse associations for the ").concat(association.ownerModelName, ".").concat(association.key, " association."));
|
3718 | }
|
3719 | |
3720 |
|
3721 |
|
3722 |
|
3723 |
|
3724 |
|
3725 |
|
3726 | }, {
|
3727 | key: "_implicitInverseFor",
|
3728 | value: function _implicitInverseFor(association) {
|
3729 | var _this2 = this;
|
3730 |
|
3731 | var associations = this._schema.associationsFor(this.modelName);
|
3732 |
|
3733 | var modelName = association.ownerModelName;
|
3734 | return values(associations).filter(function (candidate) {
|
3735 | return candidate.modelName === modelName;
|
3736 | }).reduce(function (inverse, candidate) {
|
3737 | var candidateInverse = candidate.opts.inverse;
|
3738 | var candidateIsImplicitInverse = candidateInverse === undefined;
|
3739 | var candidateIsExplicitInverse = candidateInverse === association.key;
|
3740 | var candidateMatches = candidateIsImplicitInverse || candidateIsExplicitInverse;
|
3741 |
|
3742 | if (candidateMatches) {
|
3743 |
|
3744 | assert(!inverse, "The ".concat(_this2.modelName, " model has multiple possible inverse associations for the ").concat(association.ownerModelName, ".").concat(association.key, " association."));
|
3745 | inverse = candidate;
|
3746 | }
|
3747 |
|
3748 | return inverse;
|
3749 | }, null);
|
3750 | }
|
3751 | |
3752 |
|
3753 |
|
3754 |
|
3755 |
|
3756 |
|
3757 |
|
3758 |
|
3759 |
|
3760 |
|
3761 |
|
3762 | }, {
|
3763 | key: "hasInverseFor",
|
3764 | value: function hasInverseFor(association) {
|
3765 | return !!this.inverseFor(association);
|
3766 | }
|
3767 | |
3768 |
|
3769 |
|
3770 |
|
3771 |
|
3772 |
|
3773 |
|
3774 | }, {
|
3775 | key: "alreadyAssociatedWith",
|
3776 | value: function alreadyAssociatedWith(model, association) {
|
3777 | var key = association.key;
|
3778 | var associatedModelOrCollection = this[key];
|
3779 |
|
3780 | if (associatedModelOrCollection && model) {
|
3781 | if (associatedModelOrCollection instanceof Model) {
|
3782 | if (associatedModelOrCollection.isSaved() && model.isSaved()) {
|
3783 | return associatedModelOrCollection.toString() === model.toString();
|
3784 | } else {
|
3785 | return associatedModelOrCollection === model;
|
3786 | }
|
3787 | } else {
|
3788 | return associatedModelOrCollection.includes(model);
|
3789 | }
|
3790 | }
|
3791 | }
|
3792 | }, {
|
3793 | key: "associate",
|
3794 | value: function associate(model, association) {
|
3795 | if (this.alreadyAssociatedWith(model, association)) {
|
3796 | return;
|
3797 | }
|
3798 |
|
3799 | var key = association.key;
|
3800 |
|
3801 | if (association instanceof HasMany) {
|
3802 | if (!this[key].includes(model)) {
|
3803 | this[key].add(model);
|
3804 | }
|
3805 | } else {
|
3806 | this[key] = model;
|
3807 | }
|
3808 | }
|
3809 | }, {
|
3810 | key: "disassociate",
|
3811 | value: function disassociate(model, association) {
|
3812 | var fk = association.getForeignKey();
|
3813 |
|
3814 | if (association instanceof HasMany) {
|
3815 | var i;
|
3816 |
|
3817 | if (association.isPolymorphic) {
|
3818 | var found = this[fk].find(function (_ref) {
|
3819 | var type = _ref.type,
|
3820 | id = _ref.id;
|
3821 | return type === model.modelName && id === model.id;
|
3822 | });
|
3823 | i = found && this[fk].indexOf(found);
|
3824 | } else {
|
3825 | i = this[fk].map(function (key) {
|
3826 | return key.toString();
|
3827 | }).indexOf(model.id.toString());
|
3828 | }
|
3829 |
|
3830 | if (i > -1) {
|
3831 | this.attrs[fk].splice(i, 1);
|
3832 | }
|
3833 | } else {
|
3834 | this.attrs[fk] = null;
|
3835 | }
|
3836 | }
|
3837 | |
3838 |
|
3839 |
|
3840 |
|
3841 | }, {
|
3842 | key: "_setupAttr",
|
3843 |
|
3844 |
|
3845 | |
3846 |
|
3847 |
|
3848 |
|
3849 |
|
3850 |
|
3851 |
|
3852 |
|
3853 |
|
3854 | value: function _setupAttr(attr, value) {
|
3855 | var isAssociation = this.associationKeys.has(attr) || this.associationIdKeys.has(attr);
|
3856 |
|
3857 | if (!isAssociation) {
|
3858 | this.attrs[attr] = value;
|
3859 |
|
3860 | this._definePlainAttribute(attr);
|
3861 | }
|
3862 | }
|
3863 | |
3864 |
|
3865 |
|
3866 |
|
3867 |
|
3868 |
|
3869 |
|
3870 |
|
3871 | }, {
|
3872 | key: "_definePlainAttribute",
|
3873 | value: function _definePlainAttribute(attr) {
|
3874 |
|
3875 | var existingProperty = Object.getOwnPropertyDescriptor(this, attr);
|
3876 |
|
3877 | if (existingProperty && existingProperty.get) {
|
3878 | return;
|
3879 | }
|
3880 |
|
3881 |
|
3882 | if (!Object.prototype.hasOwnProperty.call(this.attrs, attr)) {
|
3883 | this.attrs[attr] = null;
|
3884 | }
|
3885 |
|
3886 |
|
3887 | Object.defineProperty(this, attr, {
|
3888 | get: function get() {
|
3889 | return this.attrs[attr];
|
3890 | },
|
3891 | set: function set(val) {
|
3892 | this.attrs[attr] = val;
|
3893 | return this;
|
3894 | }
|
3895 | });
|
3896 | }
|
3897 | |
3898 |
|
3899 |
|
3900 |
|
3901 |
|
3902 |
|
3903 |
|
3904 |
|
3905 |
|
3906 |
|
3907 |
|
3908 |
|
3909 |
|
3910 | }, {
|
3911 | key: "_setupRelationship",
|
3912 | value: function _setupRelationship(attr, value) {
|
3913 | var isFk = this.associationIdKeys.has(attr) || this.fks.includes(attr);
|
3914 | var isAssociation = this.associationKeys.has(attr);
|
3915 |
|
3916 | if (isFk) {
|
3917 | if (value !== undefined && value !== null) {
|
3918 | this._validateForeignKeyExistsInDatabase(attr, value);
|
3919 | }
|
3920 |
|
3921 | this.attrs[attr] = value;
|
3922 | }
|
3923 |
|
3924 | if (isAssociation) {
|
3925 | this[attr] = value;
|
3926 | }
|
3927 | }
|
3928 | |
3929 |
|
3930 |
|
3931 |
|
3932 |
|
3933 |
|
3934 | }, {
|
3935 | key: "_validateAttr",
|
3936 | value: function _validateAttr(key, value) {
|
3937 |
|
3938 | {
|
3939 | if (this.associationKeys.has(key)) {
|
3940 | var association = this.associationFor(key);
|
3941 | var isNull = value === null;
|
3942 |
|
3943 | if (association instanceof HasMany) {
|
3944 | var isCollection = value instanceof Collection || value instanceof PolymorphicCollection;
|
3945 | var isArrayOfModels = Array.isArray(value) && value.every(function (item) {
|
3946 | return item instanceof Model;
|
3947 | });
|
3948 | assert(isCollection || isArrayOfModels || isNull, "You're trying to create a ".concat(this.modelName, " model and you passed in \"").concat(value, "\" under the ").concat(key, " key, but that key is a HasMany relationship. You must pass in a Collection, PolymorphicCollection, array of Models, or null."));
|
3949 | } else if (association instanceof BelongsTo) {
|
3950 | assert(value instanceof Model || isNull, "You're trying to create a ".concat(this.modelName, " model and you passed in \"").concat(value, "\" under the ").concat(key, " key, but that key is a BelongsTo relationship. You must pass in a Model or null."));
|
3951 | }
|
3952 | }
|
3953 | }
|
3954 |
|
3955 | {
|
3956 | if (this.associationIdKeys.has(key)) {
|
3957 | if (key.endsWith("Ids")) {
|
3958 | var isArray = Array.isArray(value);
|
3959 |
|
3960 | var _isNull = value === null;
|
3961 |
|
3962 | assert(isArray || _isNull, "You're trying to create a ".concat(this.modelName, " model and you passed in \"").concat(value, "\" under the ").concat(key, " key, but that key is a foreign key for a HasMany relationship. You must pass in an array of ids or null."));
|
3963 | }
|
3964 | }
|
3965 | }
|
3966 |
|
3967 | {
|
3968 | var isModelOrCollection = value instanceof Model || value instanceof Collection || value instanceof PolymorphicCollection;
|
3969 |
|
3970 | var _isArrayOfModels = Array.isArray(value) && value.length && value.every(function (item) {
|
3971 | return item instanceof Model;
|
3972 | });
|
3973 |
|
3974 | if (isModelOrCollection || _isArrayOfModels) {
|
3975 | var modelOrCollection = value;
|
3976 | assert(this.associationKeys.has(key), "You're trying to create a ".concat(this.modelName, " model and you passed in a ").concat(modelOrCollection.toString(), " under the ").concat(key, " key, but you haven't defined that key as an association on your model."));
|
3977 | }
|
3978 | }
|
3979 | }
|
3980 | |
3981 |
|
3982 |
|
3983 |
|
3984 |
|
3985 |
|
3986 |
|
3987 |
|
3988 |
|
3989 |
|
3990 | }, {
|
3991 | key: "_validateForeignKeyExistsInDatabase",
|
3992 | value: function _validateForeignKeyExistsInDatabase(foreignKeyName, foreignKeys) {
|
3993 | var _this3 = this;
|
3994 |
|
3995 | if (Array.isArray(foreignKeys)) {
|
3996 | var association = this.hasManyAssociationFks[foreignKeyName];
|
3997 | var found;
|
3998 |
|
3999 | if (association.isPolymorphic) {
|
4000 | found = foreignKeys.map(function (_ref2) {
|
4001 | var type = _ref2.type,
|
4002 | id = _ref2.id;
|
4003 | return _this3._schema.db[_this3._schema.toInternalCollectionName(type)].find(id);
|
4004 | });
|
4005 | found = compact(found);
|
4006 | } else {
|
4007 | found = this._schema.db[this._schema.toInternalCollectionName(association.modelName)].find(foreignKeys);
|
4008 | }
|
4009 |
|
4010 | var foreignKeyLabel = association.isPolymorphic ? foreignKeys.map(function (fk) {
|
4011 | return "".concat(fk.type, ":").concat(fk.id);
|
4012 | }).join(",") : foreignKeys;
|
4013 | assert(found.length === foreignKeys.length, "You're instantiating a ".concat(this.modelName, " that has a ").concat(foreignKeyName, " of ").concat(foreignKeyLabel, ", but some of those records don't exist in the database."));
|
4014 | } else {
|
4015 | var _association = this.belongsToAssociationFks[foreignKeyName];
|
4016 |
|
4017 | var _found;
|
4018 |
|
4019 | if (_association.isPolymorphic) {
|
4020 | _found = this._schema.db[this._schema.toInternalCollectionName(foreignKeys.type)].find(foreignKeys.id);
|
4021 | } else {
|
4022 | _found = this._schema.db[this._schema.toInternalCollectionName(_association.modelName)].find(foreignKeys);
|
4023 | }
|
4024 |
|
4025 | var _foreignKeyLabel = _association.isPolymorphic ? "".concat(foreignKeys.type, ":").concat(foreignKeys.id) : foreignKeys;
|
4026 |
|
4027 | assert(_found, "You're instantiating a ".concat(this.modelName, " that has a ").concat(foreignKeyName, " of ").concat(_foreignKeyLabel, ", but that record doesn't exist in the database."));
|
4028 | }
|
4029 | }
|
4030 | |
4031 |
|
4032 |
|
4033 |
|
4034 |
|
4035 |
|
4036 |
|
4037 |
|
4038 | }, {
|
4039 | key: "_saveAssociations",
|
4040 | value: function _saveAssociations() {
|
4041 | this._saveBelongsToAssociations();
|
4042 |
|
4043 | this._saveHasManyAssociations();
|
4044 | }
|
4045 | }, {
|
4046 | key: "_saveBelongsToAssociations",
|
4047 | value: function _saveBelongsToAssociations() {
|
4048 | var _this4 = this;
|
4049 |
|
4050 | values(this.belongsToAssociations).forEach(function (association) {
|
4051 | _this4._disassociateFromOldInverses(association);
|
4052 |
|
4053 | _this4._saveNewAssociates(association);
|
4054 |
|
4055 | _this4._associateWithNewInverses(association);
|
4056 | });
|
4057 | }
|
4058 | }, {
|
4059 | key: "_saveHasManyAssociations",
|
4060 | value: function _saveHasManyAssociations() {
|
4061 | var _this5 = this;
|
4062 |
|
4063 | values(this.hasManyAssociations).forEach(function (association) {
|
4064 | _this5._disassociateFromOldInverses(association);
|
4065 |
|
4066 | _this5._saveNewAssociates(association);
|
4067 |
|
4068 | _this5._associateWithNewInverses(association);
|
4069 | });
|
4070 | }
|
4071 | }, {
|
4072 | key: "_disassociateFromOldInverses",
|
4073 | value: function _disassociateFromOldInverses(association) {
|
4074 | if (association instanceof HasMany) {
|
4075 | this._disassociateFromHasManyInverses(association);
|
4076 | } else if (association instanceof BelongsTo) {
|
4077 | this._disassociateFromBelongsToInverse(association);
|
4078 | }
|
4079 | }
|
4080 |
|
4081 | }, {
|
4082 | key: "_disassociateFromHasManyInverses",
|
4083 | value: function _disassociateFromHasManyInverses(association) {
|
4084 | var _this6 = this;
|
4085 |
|
4086 | var key = association.key;
|
4087 | var fk = association.getForeignKey();
|
4088 | var tempAssociation = this._tempAssociations && this._tempAssociations[key];
|
4089 | var associateIds = this.attrs[fk];
|
4090 |
|
4091 | if (tempAssociation && associateIds) {
|
4092 | var models;
|
4093 |
|
4094 | if (association.isPolymorphic) {
|
4095 | models = associateIds.map(function (_ref3) {
|
4096 | var type = _ref3.type,
|
4097 | id = _ref3.id;
|
4098 | return _this6._schema[_this6._schema.toCollectionName(type)].find(id);
|
4099 | });
|
4100 | } else {
|
4101 |
|
4102 | models = this._schema[this._schema.toCollectionName(association.modelName)].find(associateIds || []).models;
|
4103 | }
|
4104 |
|
4105 | models.filter(function (associate) {
|
4106 | return (
|
4107 | !associate.isSaving &&
|
4108 | !tempAssociation.includes(associate) && associate.hasInverseFor(association)
|
4109 | );
|
4110 | }).forEach(function (associate) {
|
4111 | var inverse = associate.inverseFor(association);
|
4112 | associate.disassociate(_this6, inverse);
|
4113 | associate.save();
|
4114 | });
|
4115 | }
|
4116 | }
|
4117 | |
4118 |
|
4119 |
|
4120 |
|
4121 |
|
4122 |
|
4123 |
|
4124 |
|
4125 |
|
4126 |
|
4127 |
|
4128 |
|
4129 |
|
4130 |
|
4131 | }, {
|
4132 | key: "_disassociateFromBelongsToInverse",
|
4133 | value: function _disassociateFromBelongsToInverse(association) {
|
4134 | var key = association.key;
|
4135 | var fk = association.getForeignKey();
|
4136 | var tempAssociation = this._tempAssociations && this._tempAssociations[key];
|
4137 | var associateId = this.attrs[fk];
|
4138 |
|
4139 | if (tempAssociation !== undefined && associateId) {
|
4140 | var associate;
|
4141 |
|
4142 | if (association.isPolymorphic) {
|
4143 | associate = this._schema[this._schema.toCollectionName(associateId.type)].find(associateId.id);
|
4144 | } else {
|
4145 | associate = this._schema[this._schema.toCollectionName(association.modelName)].find(associateId);
|
4146 | }
|
4147 |
|
4148 | if (associate.hasInverseFor(association)) {
|
4149 | var inverse = associate.inverseFor(association);
|
4150 | associate.disassociate(this, inverse);
|
4151 |
|
4152 | associate._updateInDb(associate.attrs);
|
4153 | }
|
4154 | }
|
4155 | }
|
4156 |
|
4157 | }, {
|
4158 | key: "_disassociateFromDependents",
|
4159 | value: function _disassociateFromDependents() {
|
4160 | var _this7 = this;
|
4161 |
|
4162 | this._schema.dependentAssociationsFor(this.modelName).forEach(function (association) {
|
4163 | association.disassociateAllDependentsFromTarget(_this7);
|
4164 | });
|
4165 | }
|
4166 | }, {
|
4167 | key: "_saveNewAssociates",
|
4168 | value: function _saveNewAssociates(association) {
|
4169 | var key = association.key;
|
4170 | var fk = association.getForeignKey();
|
4171 | var tempAssociate = this._tempAssociations && this._tempAssociations[key];
|
4172 |
|
4173 | if (tempAssociate !== undefined) {
|
4174 | this.__isSavingNewChildren = true;
|
4175 | delete this._tempAssociations[key];
|
4176 |
|
4177 | if (tempAssociate instanceof Collection) {
|
4178 | tempAssociate.models.filter(function (model) {
|
4179 | return !model.isSaving;
|
4180 | }).forEach(function (child) {
|
4181 | child.save();
|
4182 | });
|
4183 |
|
4184 | this._updateInDb(_defineProperty({}, fk, tempAssociate.models.map(function (child) {
|
4185 | return child.id;
|
4186 | })));
|
4187 | } else if (tempAssociate instanceof PolymorphicCollection) {
|
4188 | tempAssociate.models.filter(function (model) {
|
4189 | return !model.isSaving;
|
4190 | }).forEach(function (child) {
|
4191 | child.save();
|
4192 | });
|
4193 |
|
4194 | this._updateInDb(_defineProperty({}, fk, tempAssociate.models.map(function (child) {
|
4195 | return {
|
4196 | type: child.modelName,
|
4197 | id: child.id
|
4198 | };
|
4199 | })));
|
4200 | } else {
|
4201 |
|
4202 | if (tempAssociate === null) {
|
4203 | this._updateInDb(_defineProperty({}, fk, null));
|
4204 |
|
4205 | } else if (this.equals(tempAssociate)) {
|
4206 | this._updateInDb(_defineProperty({}, fk, this.id));
|
4207 |
|
4208 | } else if (!tempAssociate.isSaving) {
|
4209 |
|
4210 | tempAssociate.save();
|
4211 |
|
4212 | this._syncTempAssociations(tempAssociate);
|
4213 |
|
4214 | var fkValue;
|
4215 |
|
4216 | if (association.isPolymorphic) {
|
4217 | fkValue = {
|
4218 | id: tempAssociate.id,
|
4219 | type: tempAssociate.modelName
|
4220 | };
|
4221 | } else {
|
4222 | fkValue = tempAssociate.id;
|
4223 | }
|
4224 |
|
4225 | this._updateInDb(_defineProperty({}, fk, fkValue));
|
4226 | }
|
4227 | }
|
4228 |
|
4229 | this.__isSavingNewChildren = false;
|
4230 | }
|
4231 | }
|
4232 | |
4233 |
|
4234 |
|
4235 |
|
4236 |
|
4237 |
|
4238 |
|
4239 |
|
4240 |
|
4241 |
|
4242 |
|
4243 |
|
4244 | }, {
|
4245 | key: "_associateWithNewInverses",
|
4246 | value: function _associateWithNewInverses(association) {
|
4247 | var _this8 = this;
|
4248 |
|
4249 | if (!this.__isSavingNewChildren) {
|
4250 | var modelOrCollection = this[association.key];
|
4251 |
|
4252 | if (modelOrCollection instanceof Model) {
|
4253 | this._associateModelWithInverse(modelOrCollection, association);
|
4254 | } else if (modelOrCollection instanceof Collection || modelOrCollection instanceof PolymorphicCollection) {
|
4255 | modelOrCollection.models.forEach(function (model) {
|
4256 | _this8._associateModelWithInverse(model, association);
|
4257 | });
|
4258 | }
|
4259 |
|
4260 | delete this._tempAssociations[association.key];
|
4261 | }
|
4262 | }
|
4263 | }, {
|
4264 | key: "_associateModelWithInverse",
|
4265 | value: function _associateModelWithInverse(model, association) {
|
4266 | var _this9 = this;
|
4267 |
|
4268 | if (model.hasInverseFor(association)) {
|
4269 | var inverse = model.inverseFor(association);
|
4270 | var inverseFk = inverse.getForeignKey();
|
4271 | var ownerId = this.id;
|
4272 |
|
4273 | if (inverse instanceof BelongsTo) {
|
4274 | var newId;
|
4275 |
|
4276 | if (inverse.isPolymorphic) {
|
4277 | newId = {
|
4278 | type: this.modelName,
|
4279 | id: ownerId
|
4280 | };
|
4281 | } else {
|
4282 | newId = ownerId;
|
4283 | }
|
4284 |
|
4285 | this._schema.db[this._schema.toInternalCollectionName(model.modelName)].update(model.id, _defineProperty({}, inverseFk, newId));
|
4286 | } else {
|
4287 | var inverseCollection = this._schema.db[this._schema.toInternalCollectionName(model.modelName)];
|
4288 |
|
4289 | var currentIdsForInverse = inverseCollection.find(model.id)[inverse.getForeignKey()] || [];
|
4290 | var newIdsForInverse = Object.assign([], currentIdsForInverse);
|
4291 |
|
4292 | var _newId, alreadyAssociatedWith;
|
4293 |
|
4294 | if (inverse.isPolymorphic) {
|
4295 | _newId = {
|
4296 | type: this.modelName,
|
4297 | id: ownerId
|
4298 | };
|
4299 | alreadyAssociatedWith = newIdsForInverse.some(function (key) {
|
4300 | return key.type == _this9.modelName && key.id == ownerId;
|
4301 | });
|
4302 | } else {
|
4303 | _newId = ownerId;
|
4304 | alreadyAssociatedWith = newIdsForInverse.includes(ownerId);
|
4305 | }
|
4306 |
|
4307 | if (!alreadyAssociatedWith) {
|
4308 | newIdsForInverse.push(_newId);
|
4309 | }
|
4310 |
|
4311 | inverseCollection.update(model.id, _defineProperty({}, inverseFk, newIdsForInverse));
|
4312 | }
|
4313 | }
|
4314 | }
|
4315 |
|
4316 |
|
4317 | }, {
|
4318 | key: "_updateInDb",
|
4319 | value: function _updateInDb(attrs) {
|
4320 | this.attrs = this._schema.db[this._schema.toInternalCollectionName(this.modelName)].update(this.attrs.id, attrs);
|
4321 | }
|
4322 | |
4323 |
|
4324 |
|
4325 |
|
4326 |
|
4327 |
|
4328 |
|
4329 |
|
4330 |
|
4331 | }, {
|
4332 | key: "_syncTempAssociations",
|
4333 | value: function _syncTempAssociations(tempAssociate) {
|
4334 | var _this10 = this;
|
4335 |
|
4336 | Object.keys(this._tempAssociations).forEach(function (key) {
|
4337 | if (_this10._tempAssociations[key] && _this10._tempAssociations[key].toString() === tempAssociate.toString()) {
|
4338 | _this10._tempAssociations[key] = tempAssociate;
|
4339 | }
|
4340 | });
|
4341 | }
|
4342 | |
4343 |
|
4344 |
|
4345 |
|
4346 |
|
4347 |
|
4348 |
|
4349 |
|
4350 |
|
4351 |
|
4352 |
|
4353 | }, {
|
4354 | key: "toString",
|
4355 | value: function toString() {
|
4356 | var idLabel = this.id ? "(".concat(this.id, ")") : "";
|
4357 | return "model:".concat(this.modelName).concat(idLabel);
|
4358 | }
|
4359 | |
4360 |
|
4361 |
|
4362 |
|
4363 |
|
4364 |
|
4365 |
|
4366 |
|
4367 |
|
4368 | }, {
|
4369 | key: "equals",
|
4370 | value: function equals(model) {
|
4371 | return this.toString() === model.toString();
|
4372 | }
|
4373 | }, {
|
4374 | key: "isSaving",
|
4375 | get: function get() {
|
4376 | return this._schema.isSaving[this.toString()];
|
4377 | }
|
4378 | }]);
|
4379 |
|
4380 | return Model;
|
4381 | }();
|
4382 |
|
4383 | Model.extend = extend;
|
4384 |
|
4385 | Model.findBelongsToAssociation = function (associationType) {
|
4386 | return this.prototype.belongsToAssociations[associationType];
|
4387 | };
|
4388 |
|
4389 |
|
4390 |
|
4391 |
|
4392 |
|
4393 |
|
4394 |
|
4395 |
|
4396 |
|
4397 |
|
4398 |
|
4399 |
|
4400 |
|
4401 |
|
4402 |
|
4403 |
|
4404 |
|
4405 |
|
4406 |
|
4407 |
|
4408 |
|
4409 |
|
4410 |
|
4411 |
|
4412 |
|
4413 |
|
4414 |
|
4415 |
|
4416 |
|
4417 |
|
4418 |
|
4419 |
|
4420 |
|
4421 |
|
4422 |
|
4423 |
|
4424 |
|
4425 |
|
4426 |
|
4427 |
|
4428 |
|
4429 |
|
4430 |
|
4431 |
|
4432 |
|
4433 |
|
4434 |
|
4435 |
|
4436 |
|
4437 |
|
4438 |
|
4439 |
|
4440 |
|
4441 |
|
4442 |
|
4443 |
|
4444 |
|
4445 |
|
4446 |
|
4447 |
|
4448 |
|
4449 |
|
4450 |
|
4451 |
|
4452 |
|
4453 |
|
4454 |
|
4455 |
|
4456 |
|
4457 |
|
4458 |
|
4459 |
|
4460 |
|
4461 |
|
4462 |
|
4463 |
|
4464 |
|
4465 |
|
4466 |
|
4467 |
|
4468 |
|
4469 |
|
4470 |
|
4471 |
|
4472 |
|
4473 |
|
4474 |
|
4475 |
|
4476 |
|
4477 |
|
4478 |
|
4479 |
|
4480 |
|
4481 | var Serializer =
|
4482 |
|
4483 | function () {
|
4484 | function Serializer(registry, type) {
|
4485 | var request = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
|
4486 |
|
4487 | _classCallCheck(this, Serializer);
|
4488 |
|
4489 | this.registry = registry;
|
4490 | this.type = type;
|
4491 | this.request = request;
|
4492 | |
4493 |
|
4494 |
|
4495 |
|
4496 |
|
4497 |
|
4498 |
|
4499 |
|
4500 |
|
4501 |
|
4502 |
|
4503 |
|
4504 |
|
4505 |
|
4506 |
|
4507 |
|
4508 |
|
4509 |
|
4510 |
|
4511 |
|
4512 |
|
4513 |
|
4514 |
|
4515 |
|
4516 |
|
4517 |
|
4518 |
|
4519 |
|
4520 | this.attrs = this.attrs || undefined;
|
4521 |
|
4522 | |
4523 |
|
4524 |
|
4525 |
|
4526 |
|
4527 |
|
4528 |
|
4529 |
|
4530 |
|
4531 |
|
4532 |
|
4533 |
|
4534 |
|
4535 |
|
4536 |
|
4537 |
|
4538 |
|
4539 |
|
4540 |
|
4541 |
|
4542 |
|
4543 |
|
4544 |
|
4545 |
|
4546 |
|
4547 |
|
4548 |
|
4549 |
|
4550 |
|
4551 |
|
4552 |
|
4553 |
|
4554 |
|
4555 |
|
4556 |
|
4557 |
|
4558 |
|
4559 |
|
4560 |
|
4561 |
|
4562 |
|
4563 |
|
4564 |
|
4565 |
|
4566 |
|
4567 |
|
4568 |
|
4569 |
|
4570 |
|
4571 |
|
4572 |
|
4573 |
|
4574 |
|
4575 |
|
4576 |
|
4577 |
|
4578 |
|
4579 |
|
4580 |
|
4581 |
|
4582 |
|
4583 |
|
4584 |
|
4585 |
|
4586 |
|
4587 |
|
4588 |
|
4589 | this.include = this.include || [];
|
4590 |
|
4591 | |
4592 |
|
4593 |
|
4594 |
|
4595 |
|
4596 |
|
4597 |
|
4598 |
|
4599 |
|
4600 |
|
4601 |
|
4602 |
|
4603 |
|
4604 |
|
4605 |
|
4606 |
|
4607 |
|
4608 |
|
4609 |
|
4610 |
|
4611 |
|
4612 |
|
4613 |
|
4614 |
|
4615 |
|
4616 |
|
4617 |
|
4618 |
|
4619 |
|
4620 |
|
4621 |
|
4622 | this.root = this.root || undefined;
|
4623 |
|
4624 | |
4625 |
|
4626 |
|
4627 |
|
4628 |
|
4629 |
|
4630 |
|
4631 |
|
4632 |
|
4633 |
|
4634 |
|
4635 |
|
4636 |
|
4637 |
|
4638 |
|
4639 |
|
4640 |
|
4641 |
|
4642 |
|
4643 |
|
4644 |
|
4645 |
|
4646 |
|
4647 |
|
4648 |
|
4649 |
|
4650 |
|
4651 |
|
4652 |
|
4653 |
|
4654 |
|
4655 |
|
4656 |
|
4657 |
|
4658 |
|
4659 |
|
4660 |
|
4661 |
|
4662 |
|
4663 |
|
4664 | this.embed = this.embed || undefined;
|
4665 |
|
4666 | |
4667 |
|
4668 |
|
4669 |
|
4670 |
|
4671 |
|
4672 |
|
4673 |
|
4674 |
|
4675 |
|
4676 | this.serializeIds = this.serializeIds || undefined;
|
4677 | }
|
4678 | |
4679 |
|
4680 |
|
4681 |
|
4682 |
|
4683 |
|
4684 |
|
4685 |
|
4686 |
|
4687 |
|
4688 |
|
4689 |
|
4690 |
|
4691 |
|
4692 |
|
4693 |
|
4694 |
|
4695 |
|
4696 | _createClass(Serializer, [{
|
4697 | key: "serialize",
|
4698 | value: function serialize(primaryResource
|
4699 | /* , request */
|
4700 | ) {
|
4701 | return this.buildPayload(primaryResource);
|
4702 | }
|
4703 | |
4704 |
|
4705 |
|
4706 |
|
4707 |
|
4708 |
|
4709 |
|
4710 |
|
4711 |
|
4712 | }, {
|
4713 | key: "normalize",
|
4714 | value: function normalize(json) {
|
4715 | return json;
|
4716 | }
|
4717 | }, {
|
4718 | key: "buildPayload",
|
4719 | value: function buildPayload(primaryResource, toInclude, didSerialize, json) {
|
4720 | if (!primaryResource && isEmpty(toInclude)) {
|
4721 | return json;
|
4722 | } else if (primaryResource) {
|
4723 | var _this$getHashForPrima = this.getHashForPrimaryResource(primaryResource),
|
4724 | _this$getHashForPrima2 = _slicedToArray(_this$getHashForPrima, 2),
|
4725 | resourceHash = _this$getHashForPrima2[0],
|
4726 | newIncludes = _this$getHashForPrima2[1];
|
4727 |
|
4728 | var newDidSerialize = this.isCollection(primaryResource) ? primaryResource.models : [primaryResource];
|
4729 | return this.buildPayload(undefined, newIncludes, newDidSerialize, resourceHash);
|
4730 | } else {
|
4731 | var nextIncludedResource = toInclude.shift();
|
4732 |
|
4733 | var _this$getHashForInclu = this.getHashForIncludedResource(nextIncludedResource),
|
4734 | _this$getHashForInclu2 = _slicedToArray(_this$getHashForInclu, 2),
|
4735 | _resourceHash = _this$getHashForInclu2[0],
|
4736 | _newIncludes = _this$getHashForInclu2[1];
|
4737 |
|
4738 | var newToInclude = _newIncludes.filter(function (resource) {
|
4739 | return !didSerialize.map(function (m) {
|
4740 | return m.toString();
|
4741 | }).includes(resource.toString());
|
4742 | }).concat(toInclude);
|
4743 |
|
4744 | var _newDidSerialize = (this.isCollection(nextIncludedResource) ? nextIncludedResource.models : [nextIncludedResource]).concat(didSerialize);
|
4745 |
|
4746 | var newJson = this.mergePayloads(json, _resourceHash);
|
4747 | return this.buildPayload(undefined, newToInclude, _newDidSerialize, newJson);
|
4748 | }
|
4749 | }
|
4750 | }, {
|
4751 | key: "getHashForPrimaryResource",
|
4752 | value: function getHashForPrimaryResource(resource) {
|
4753 | var _this$getHashForResou = this.getHashForResource(resource),
|
4754 | _this$getHashForResou2 = _slicedToArray(_this$getHashForResou, 2),
|
4755 | hash = _this$getHashForResou2[0],
|
4756 | addToIncludes = _this$getHashForResou2[1];
|
4757 |
|
4758 | var hashWithRoot;
|
4759 |
|
4760 | if (this.root) {
|
4761 | assert(!(resource instanceof PolymorphicCollection), "The base Serializer class cannot serialize a top-level PolymorphicCollection when root is true, since PolymorphicCollections have no type.");
|
4762 | var serializer = this.serializerFor(resource.modelName);
|
4763 | var rootKey = serializer.keyForResource(resource);
|
4764 | hashWithRoot = _defineProperty({}, rootKey, hash);
|
4765 | } else {
|
4766 | hashWithRoot = hash;
|
4767 | }
|
4768 |
|
4769 | return [hashWithRoot, addToIncludes];
|
4770 | }
|
4771 | }, {
|
4772 | key: "getHashForIncludedResource",
|
4773 | value: function getHashForIncludedResource(resource) {
|
4774 | var hashWithRoot, addToIncludes;
|
4775 |
|
4776 | if (resource instanceof PolymorphicCollection) {
|
4777 | hashWithRoot = {};
|
4778 | addToIncludes = resource.models;
|
4779 | } else {
|
4780 | var serializer = this.serializerFor(resource.modelName);
|
4781 |
|
4782 | var _serializer$getHashFo = serializer.getHashForResource(resource),
|
4783 | _serializer$getHashFo2 = _slicedToArray(_serializer$getHashFo, 2),
|
4784 | hash = _serializer$getHashFo2[0],
|
4785 | newModels = _serializer$getHashFo2[1];
|
4786 |
|
4787 |
|
4788 | var rootKey = serializer.keyForRelationship(resource.modelName);
|
4789 | hashWithRoot = Array.isArray(hash) ? _defineProperty({}, rootKey, hash) : _defineProperty({}, rootKey, [hash]);
|
4790 | addToIncludes = newModels;
|
4791 | }
|
4792 |
|
4793 | return [hashWithRoot, addToIncludes];
|
4794 | }
|
4795 | }, {
|
4796 | key: "getHashForResource",
|
4797 | value: function getHashForResource(resource) {
|
4798 | var _this = this;
|
4799 |
|
4800 | var removeForeignKeys = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
|
4801 | var didSerialize = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
|
4802 | var lookupSerializer = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
|
4803 | var hash, serializer;
|
4804 |
|
4805 | if (!lookupSerializer) {
|
4806 | serializer = this;
|
4807 | }
|
4808 |
|
4809 |
|
4810 |
|
4811 | if (lookupSerializer && resource.modelName) {
|
4812 | serializer = this.serializerFor(resource.modelName);
|
4813 | }
|
4814 |
|
4815 | if (this.isModel(resource)) {
|
4816 | hash = serializer._hashForModel(resource, removeForeignKeys, didSerialize);
|
4817 | } else {
|
4818 | hash = resource.models.map(function (m) {
|
4819 | var modelSerializer = serializer;
|
4820 |
|
4821 | if (!modelSerializer) {
|
4822 |
|
4823 | modelSerializer = _this.serializerFor(m.modelName);
|
4824 | }
|
4825 |
|
4826 | return modelSerializer._hashForModel(m, removeForeignKeys, didSerialize);
|
4827 | });
|
4828 | }
|
4829 |
|
4830 | if (this.embed) {
|
4831 | return [hash, []];
|
4832 | } else {
|
4833 | var addToIncludes = uniqBy(compact(flatten(serializer.getKeysForIncluded().map(function (key) {
|
4834 | if (_this.isCollection(resource)) {
|
4835 | return resource.models.map(function (m) {
|
4836 | return m[key];
|
4837 | });
|
4838 | } else {
|
4839 | return resource[key];
|
4840 | }
|
4841 | }))), function (m) {
|
4842 | return m.toString();
|
4843 | });
|
4844 | return [hash, addToIncludes];
|
4845 | }
|
4846 | }
|
4847 | |
4848 |
|
4849 |
|
4850 |
|
4851 |
|
4852 |
|
4853 |
|
4854 |
|
4855 |
|
4856 |
|
4857 |
|
4858 |
|
4859 |
|
4860 |
|
4861 |
|
4862 |
|
4863 |
|
4864 |
|
4865 |
|
4866 |
|
4867 |
|
4868 |
|
4869 |
|
4870 |
|
4871 |
|
4872 | }, {
|
4873 | key: "mergePayloads",
|
4874 | value: function mergePayloads(json, resourceHash) {
|
4875 | var newJson;
|
4876 |
|
4877 | var _Object$keys = Object.keys(resourceHash),
|
4878 | _Object$keys2 = _slicedToArray(_Object$keys, 1),
|
4879 | resourceHashKey = _Object$keys2[0];
|
4880 |
|
4881 | if (json[resourceHashKey]) {
|
4882 | newJson = json;
|
4883 | newJson[resourceHashKey] = json[resourceHashKey].concat(resourceHash[resourceHashKey]);
|
4884 | } else {
|
4885 | newJson = Object.assign(json, resourceHash);
|
4886 | }
|
4887 |
|
4888 | return newJson;
|
4889 | }
|
4890 | }, {
|
4891 | key: "keyForResource",
|
4892 | value: function keyForResource(resource) {
|
4893 | var modelName = resource.modelName;
|
4894 | return this.isModel(resource) ? this.keyForModel(modelName) : this.keyForCollection(modelName);
|
4895 | }
|
4896 | |
4897 |
|
4898 |
|
4899 |
|
4900 |
|
4901 |
|
4902 |
|
4903 |
|
4904 |
|
4905 |
|
4906 |
|
4907 |
|
4908 |
|
4909 |
|
4910 |
|
4911 |
|
4912 |
|
4913 |
|
4914 |
|
4915 |
|
4916 |
|
4917 |
|
4918 |
|
4919 |
|
4920 |
|
4921 |
|
4922 |
|
4923 |
|
4924 |
|
4925 |
|
4926 |
|
4927 |
|
4928 |
|
4929 |
|
4930 | }, {
|
4931 | key: "keyForModel",
|
4932 | value: function keyForModel(modelName) {
|
4933 | return camelize(modelName);
|
4934 | }
|
4935 | |
4936 |
|
4937 |
|
4938 |
|
4939 |
|
4940 |
|
4941 |
|
4942 |
|
4943 |
|
4944 |
|
4945 |
|
4946 |
|
4947 |
|
4948 |
|
4949 |
|
4950 |
|
4951 |
|
4952 |
|
4953 |
|
4954 |
|
4955 |
|
4956 |
|
4957 |
|
4958 |
|
4959 |
|
4960 |
|
4961 |
|
4962 |
|
4963 |
|
4964 |
|
4965 |
|
4966 |
|
4967 |
|
4968 |
|
4969 |
|
4970 |
|
4971 |
|
4972 |
|
4973 |
|
4974 |
|
4975 |
|
4976 | }, {
|
4977 | key: "keyForCollection",
|
4978 | value: function keyForCollection(modelName) {
|
4979 | return this._container.inflector.pluralize(this.keyForModel(modelName));
|
4980 | }
|
4981 | }, {
|
4982 | key: "_hashForModel",
|
4983 | value: function _hashForModel(model, removeForeignKeys) {
|
4984 | var _this2 = this;
|
4985 |
|
4986 | var didSerialize = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
|
4987 |
|
4988 | var attrs = this._attrsForModel(model);
|
4989 |
|
4990 | if (removeForeignKeys) {
|
4991 | model.fks.forEach(function (fk) {
|
4992 | delete attrs[fk];
|
4993 | });
|
4994 | }
|
4995 |
|
4996 | if (this.embed) {
|
4997 | var newDidSerialize = Object.assign({}, didSerialize);
|
4998 | newDidSerialize[model.modelName] = newDidSerialize[model.modelName] || {};
|
4999 | newDidSerialize[model.modelName][model.id] = true;
|
5000 | this.getKeysForIncluded().forEach(function (key) {
|
5001 | var associatedResource = model[key];
|
5002 |
|
5003 | if (associatedResource && !get(newDidSerialize, "".concat(associatedResource.modelName, ".").concat(associatedResource.id))) {
|
5004 | var _this2$getHashForReso = _this2.getHashForResource(associatedResource, true, newDidSerialize, true),
|
5005 | _this2$getHashForReso2 = _slicedToArray(_this2$getHashForReso, 1),
|
5006 | associatedResourceHash = _this2$getHashForReso2[0];
|
5007 |
|
5008 | var formattedKey = _this2.keyForEmbeddedRelationship(key);
|
5009 |
|
5010 | attrs[formattedKey] = associatedResourceHash;
|
5011 |
|
5012 | if (_this2.isModel(associatedResource)) {
|
5013 | var fk = "".concat(camelize(key), "Id");
|
5014 | delete attrs[fk];
|
5015 | }
|
5016 | }
|
5017 | });
|
5018 | return attrs;
|
5019 | } else {
|
5020 | return this._maybeAddAssociationIds(model, attrs);
|
5021 | }
|
5022 | }
|
5023 | |
5024 |
|
5025 |
|
5026 |
|
5027 |
|
5028 |
|
5029 |
|
5030 | }, {
|
5031 | key: "_attrsForModel",
|
5032 | value: function _attrsForModel(model) {
|
5033 | var attrs = {};
|
5034 |
|
5035 | if (this.attrs) {
|
5036 | attrs = this.attrs.reduce(function (memo, attr) {
|
5037 | memo[attr] = model[attr];
|
5038 | return memo;
|
5039 | }, {});
|
5040 | } else {
|
5041 | attrs = Object.assign(attrs, model.attrs);
|
5042 | }
|
5043 |
|
5044 |
|
5045 | model.fks.forEach(function (key) {
|
5046 | return delete attrs[key];
|
5047 | });
|
5048 | return this._formatAttributeKeys(attrs);
|
5049 | }
|
5050 | |
5051 |
|
5052 |
|
5053 |
|
5054 |
|
5055 |
|
5056 |
|
5057 |
|
5058 | }, {
|
5059 | key: "_maybeAddAssociationIds",
|
5060 | value: function _maybeAddAssociationIds(model, attrs) {
|
5061 | var _this3 = this;
|
5062 |
|
5063 | var newHash = Object.assign({}, attrs);
|
5064 |
|
5065 | if (this.serializeIds === "always") {
|
5066 | model.associationKeys.forEach(function (key) {
|
5067 | var resource = model[key];
|
5068 | var association = model.associationFor(key);
|
5069 |
|
5070 | if (_this3.isCollection(resource)) {
|
5071 | var formattedKey = _this3.keyForRelationshipIds(key);
|
5072 |
|
5073 | newHash[formattedKey] = model["".concat(_this3._container.inflector.singularize(key), "Ids")];
|
5074 | } else if (_this3.isModel(resource) && association.isPolymorphic) {
|
5075 | var formattedTypeKey = _this3.keyForPolymorphicForeignKeyType(key);
|
5076 |
|
5077 | var formattedIdKey = _this3.keyForPolymorphicForeignKeyId(key);
|
5078 |
|
5079 | newHash[formattedTypeKey] = model["".concat(key, "Id")].type;
|
5080 | newHash[formattedIdKey] = model["".concat(key, "Id")].id;
|
5081 | } else if (resource) {
|
5082 | var _formattedKey = _this3.keyForForeignKey(key);
|
5083 |
|
5084 | newHash[_formattedKey] = model["".concat(key, "Id")];
|
5085 | }
|
5086 | });
|
5087 | } else if (this.serializeIds === "included") {
|
5088 | this.getKeysForIncluded().forEach(function (key) {
|
5089 | var resource = model[key];
|
5090 | var association = model.associationFor(key);
|
5091 |
|
5092 | if (_this3.isCollection(resource)) {
|
5093 | var formattedKey = _this3.keyForRelationshipIds(key);
|
5094 |
|
5095 | newHash[formattedKey] = model["".concat(_this3._container.inflector.singularize(key), "Ids")];
|
5096 | } else if (_this3.isModel(resource) && association.isPolymorphic) {
|
5097 | var formattedTypeKey = _this3.keyForPolymorphicForeignKeyType(key);
|
5098 |
|
5099 | var formattedIdKey = _this3.keyForPolymorphicForeignKeyId(key);
|
5100 |
|
5101 | newHash[formattedTypeKey] = model["".concat(key, "Id")].type;
|
5102 | newHash[formattedIdKey] = model["".concat(key, "Id")].id;
|
5103 | } else if (_this3.isModel(resource)) {
|
5104 | var _formattedKey2 = _this3.keyForForeignKey(key);
|
5105 |
|
5106 | newHash[_formattedKey2] = model["".concat(key, "Id")];
|
5107 | }
|
5108 | });
|
5109 | }
|
5110 |
|
5111 | return newHash;
|
5112 | }
|
5113 | |
5114 |
|
5115 |
|
5116 |
|
5117 |
|
5118 |
|
5119 |
|
5120 |
|
5121 |
|
5122 |
|
5123 |
|
5124 |
|
5125 |
|
5126 |
|
5127 |
|
5128 |
|
5129 |
|
5130 |
|
5131 |
|
5132 |
|
5133 |
|
5134 |
|
5135 |
|
5136 |
|
5137 |
|
5138 |
|
5139 |
|
5140 |
|
5141 |
|
5142 |
|
5143 |
|
5144 |
|
5145 |
|
5146 |
|
5147 |
|
5148 | }, {
|
5149 | key: "keyForAttribute",
|
5150 | value: function keyForAttribute(attr) {
|
5151 | return attr;
|
5152 | }
|
5153 | |
5154 |
|
5155 |
|
5156 |
|
5157 |
|
5158 |
|
5159 |
|
5160 |
|
5161 |
|
5162 |
|
5163 |
|
5164 |
|
5165 |
|
5166 |
|
5167 |
|
5168 |
|
5169 |
|
5170 |
|
5171 |
|
5172 |
|
5173 |
|
5174 |
|
5175 |
|
5176 |
|
5177 |
|
5178 |
|
5179 |
|
5180 |
|
5181 |
|
5182 |
|
5183 |
|
5184 | }, {
|
5185 | key: "keyForRelationship",
|
5186 | value: function keyForRelationship(modelName) {
|
5187 | return camelize(this._container.inflector.pluralize(modelName));
|
5188 | }
|
5189 | |
5190 |
|
5191 |
|
5192 |
|
5193 |
|
5194 |
|
5195 |
|
5196 | }, {
|
5197 | key: "keyForEmbeddedRelationship",
|
5198 | value: function keyForEmbeddedRelationship(attributeName) {
|
5199 | return camelize(attributeName);
|
5200 | }
|
5201 | |
5202 |
|
5203 |
|
5204 |
|
5205 |
|
5206 |
|
5207 |
|
5208 |
|
5209 |
|
5210 |
|
5211 |
|
5212 |
|
5213 |
|
5214 |
|
5215 |
|
5216 |
|
5217 |
|
5218 |
|
5219 |
|
5220 |
|
5221 |
|
5222 |
|
5223 |
|
5224 |
|
5225 |
|
5226 |
|
5227 |
|
5228 |
|
5229 |
|
5230 |
|
5231 |
|
5232 |
|
5233 |
|
5234 |
|
5235 |
|
5236 |
|
5237 |
|
5238 |
|
5239 | }, {
|
5240 | key: "keyForRelationshipIds",
|
5241 | value: function keyForRelationshipIds(relationshipName) {
|
5242 | return "".concat(this._container.inflector.singularize(camelize(relationshipName)), "Ids");
|
5243 | }
|
5244 | |
5245 |
|
5246 |
|
5247 |
|
5248 |
|
5249 |
|
5250 |
|
5251 |
|
5252 |
|
5253 |
|
5254 |
|
5255 |
|
5256 |
|
5257 |
|
5258 |
|
5259 |
|
5260 |
|
5261 |
|
5262 |
|
5263 |
|
5264 |
|
5265 |
|
5266 |
|
5267 |
|
5268 |
|
5269 |
|
5270 |
|
5271 |
|
5272 |
|
5273 |
|
5274 |
|
5275 |
|
5276 |
|
5277 |
|
5278 |
|
5279 |
|
5280 |
|
5281 | }, {
|
5282 | key: "keyForForeignKey",
|
5283 | value: function keyForForeignKey(relationshipName) {
|
5284 | return "".concat(camelize(relationshipName), "Id");
|
5285 | }
|
5286 | |
5287 |
|
5288 |
|
5289 |
|
5290 |
|
5291 |
|
5292 |
|
5293 |
|
5294 |
|
5295 |
|
5296 |
|
5297 |
|
5298 |
|
5299 |
|
5300 |
|
5301 |
|
5302 |
|
5303 |
|
5304 |
|
5305 |
|
5306 |
|
5307 |
|
5308 |
|
5309 |
|
5310 |
|
5311 |
|
5312 | }, {
|
5313 | key: "keyForPolymorphicForeignKeyId",
|
5314 | value: function keyForPolymorphicForeignKeyId(relationshipName) {
|
5315 | return "".concat(camelize(relationshipName), "Id");
|
5316 | }
|
5317 | |
5318 |
|
5319 |
|
5320 |
|
5321 |
|
5322 |
|
5323 |
|
5324 |
|
5325 |
|
5326 |
|
5327 |
|
5328 |
|
5329 |
|
5330 |
|
5331 |
|
5332 |
|
5333 |
|
5334 |
|
5335 |
|
5336 |
|
5337 |
|
5338 |
|
5339 |
|
5340 |
|
5341 |
|
5342 |
|
5343 | }, {
|
5344 | key: "keyForPolymorphicForeignKeyType",
|
5345 | value: function keyForPolymorphicForeignKeyType(relationshipName) {
|
5346 | return "".concat(camelize(relationshipName), "Type");
|
5347 | }
|
5348 | |
5349 |
|
5350 |
|
5351 |
|
5352 |
|
5353 |
|
5354 |
|
5355 |
|
5356 | }, {
|
5357 | key: "isModel",
|
5358 | value: function isModel(object) {
|
5359 | return object instanceof Model;
|
5360 | }
|
5361 | |
5362 |
|
5363 |
|
5364 |
|
5365 |
|
5366 |
|
5367 |
|
5368 |
|
5369 | }, {
|
5370 | key: "isCollection",
|
5371 | value: function isCollection(object) {
|
5372 | return object instanceof Collection || object instanceof PolymorphicCollection;
|
5373 | }
|
5374 | |
5375 |
|
5376 |
|
5377 |
|
5378 |
|
5379 |
|
5380 |
|
5381 |
|
5382 | }, {
|
5383 | key: "isModelOrCollection",
|
5384 | value: function isModelOrCollection(object) {
|
5385 | return this.isModel(object) || this.isCollection(object);
|
5386 | }
|
5387 | |
5388 |
|
5389 |
|
5390 |
|
5391 |
|
5392 |
|
5393 |
|
5394 | }, {
|
5395 | key: "serializerFor",
|
5396 | value: function serializerFor(type) {
|
5397 | return this.registry.serializerFor(type);
|
5398 | }
|
5399 | }, {
|
5400 | key: "getKeysForIncluded",
|
5401 | value: function getKeysForIncluded() {
|
5402 | return isFunction(this.include) ? this.include(this.request) : this.include;
|
5403 | }
|
5404 | |
5405 |
|
5406 |
|
5407 |
|
5408 |
|
5409 |
|
5410 |
|
5411 | }, {
|
5412 | key: "_formatAttributeKeys",
|
5413 |
|
5414 | |
5415 |
|
5416 |
|
5417 |
|
5418 |
|
5419 |
|
5420 | value: function _formatAttributeKeys(attrs) {
|
5421 | var formattedAttrs = {};
|
5422 |
|
5423 | for (var key in attrs) {
|
5424 | var formattedKey = this.keyForAttribute(key);
|
5425 | formattedAttrs[formattedKey] = attrs[key];
|
5426 | }
|
5427 |
|
5428 | return formattedAttrs;
|
5429 | }
|
5430 | }, {
|
5431 | key: "getCoalescedIds",
|
5432 | value: function getCoalescedIds()
|
5433 | /* request */
|
5434 | {}
|
5435 | }, {
|
5436 | key: "schema",
|
5437 | get: function get() {
|
5438 | return this.registry.schema;
|
5439 | }
|
5440 | }]);
|
5441 |
|
5442 | return Serializer;
|
5443 | }();
|
5444 |
|
5445 |
|
5446 | Serializer.prototype.include = [];
|
5447 | Serializer.prototype.root = true;
|
5448 | Serializer.prototype.embed = false;
|
5449 | Serializer.prototype.serializeIds = "included";
|
5450 |
|
5451 | Serializer.extend = extend;
|
5452 |
|
5453 |
|
5454 |
|
5455 |
|
5456 |
|
5457 |
|
5458 |
|
5459 |
|
5460 |
|
5461 | var JSONAPISerializer =
|
5462 |
|
5463 | function (_Serializer) {
|
5464 | _inherits(JSONAPISerializer, _Serializer);
|
5465 |
|
5466 | function JSONAPISerializer() {
|
5467 | var _this;
|
5468 |
|
5469 | _classCallCheck(this, JSONAPISerializer);
|
5470 |
|
5471 | _this = _possibleConstructorReturn(this, _getPrototypeOf(JSONAPISerializer).apply(this, arguments));
|
5472 | |
5473 |
|
5474 |
|
5475 |
|
5476 |
|
5477 |
|
5478 |
|
5479 |
|
5480 |
|
5481 |
|
5482 |
|
5483 |
|
5484 |
|
5485 |
|
5486 |
|
5487 |
|
5488 |
|
5489 |
|
5490 |
|
5491 |
|
5492 |
|
5493 |
|
5494 |
|
5495 |
|
5496 |
|
5497 |
|
5498 |
|
5499 |
|
5500 |
|
5501 |
|
5502 |
|
5503 |
|
5504 |
|
5505 |
|
5506 |
|
5507 |
|
5508 |
|
5509 |
|
5510 |
|
5511 |
|
5512 |
|
5513 |
|
5514 |
|
5515 |
|
5516 |
|
5517 |
|
5518 |
|
5519 |
|
5520 |
|
5521 |
|
5522 |
|
5523 |
|
5524 |
|
5525 |
|
5526 |
|
5527 |
|
5528 |
|
5529 |
|
5530 |
|
5531 |
|
5532 |
|
5533 |
|
5534 |
|
5535 | _this.alwaysIncludeLinkageData = _this.alwaysIncludeLinkageData || undefined;
|
5536 |
|
5537 | return _this;
|
5538 | }
|
5539 |
|
5540 |
|
5541 | _createClass(JSONAPISerializer, [{
|
5542 | key: "keyForModel",
|
5543 | value: function keyForModel(modelName) {
|
5544 | return dasherize(modelName);
|
5545 | }
|
5546 |
|
5547 | }, {
|
5548 | key: "keyForCollection",
|
5549 | value: function keyForCollection(modelName) {
|
5550 | return dasherize(modelName);
|
5551 | }
|
5552 | |
5553 |
|
5554 |
|
5555 |
|
5556 |
|
5557 |
|
5558 |
|
5559 |
|
5560 |
|
5561 |
|
5562 |
|
5563 |
|
5564 |
|
5565 |
|
5566 |
|
5567 |
|
5568 |
|
5569 |
|
5570 |
|
5571 |
|
5572 | }, {
|
5573 | key: "keyForAttribute",
|
5574 | value: function keyForAttribute(attr) {
|
5575 | return dasherize(attr);
|
5576 | }
|
5577 | |
5578 |
|
5579 |
|
5580 |
|
5581 |
|
5582 |
|
5583 |
|
5584 |
|
5585 |
|
5586 |
|
5587 |
|
5588 |
|
5589 |
|
5590 |
|
5591 |
|
5592 |
|
5593 |
|
5594 |
|
5595 |
|
5596 |
|
5597 |
|
5598 |
|
5599 |
|
5600 |
|
5601 |
|
5602 | }, {
|
5603 | key: "keyForRelationship",
|
5604 | value: function keyForRelationship(key) {
|
5605 | return dasherize(key);
|
5606 | }
|
5607 | |
5608 |
|
5609 |
|
5610 |
|
5611 |
|
5612 |
|
5613 |
|
5614 |
|
5615 |
|
5616 |
|
5617 |
|
5618 |
|
5619 |
|
5620 |
|
5621 |
|
5622 |
|
5623 |
|
5624 |
|
5625 |
|
5626 | }, {
|
5627 | key: "links",
|
5628 | value: function links() {}
|
5629 | }, {
|
5630 | key: "getHashForPrimaryResource",
|
5631 | value: function getHashForPrimaryResource(resource) {
|
5632 | this._createRequestedIncludesGraph(resource);
|
5633 |
|
5634 | var resourceHash = this.getHashForResource(resource);
|
5635 | var hashWithRoot = {
|
5636 | data: resourceHash
|
5637 | };
|
5638 | var addToIncludes = this.getAddToIncludesForResource(resource);
|
5639 | return [hashWithRoot, addToIncludes];
|
5640 | }
|
5641 | }, {
|
5642 | key: "getHashForIncludedResource",
|
5643 | value: function getHashForIncludedResource(resource) {
|
5644 | var serializer = this.serializerFor(resource.modelName);
|
5645 | var hash = serializer.getHashForResource(resource);
|
5646 | var hashWithRoot = {
|
5647 | included: this.isModel(resource) ? [hash] : hash
|
5648 | };
|
5649 | var addToIncludes = [];
|
5650 |
|
5651 | if (!this.hasQueryParamIncludes()) {
|
5652 | addToIncludes = this.getAddToIncludesForResource(resource);
|
5653 | }
|
5654 |
|
5655 | return [hashWithRoot, addToIncludes];
|
5656 | }
|
5657 | }, {
|
5658 | key: "getHashForResource",
|
5659 | value: function getHashForResource(resource) {
|
5660 | var _this2 = this;
|
5661 |
|
5662 | var hash;
|
5663 |
|
5664 | if (this.isModel(resource)) {
|
5665 | hash = this.getResourceObjectForModel(resource);
|
5666 | } else {
|
5667 | hash = resource.models.map(function (m) {
|
5668 | return _this2.getResourceObjectForModel(m);
|
5669 | });
|
5670 | }
|
5671 |
|
5672 | return hash;
|
5673 | }
|
5674 | |
5675 |
|
5676 |
|
5677 |
|
5678 | }, {
|
5679 | key: "getAddToIncludesForResource",
|
5680 | value: function getAddToIncludesForResource(resource) {
|
5681 | var relationshipPaths;
|
5682 |
|
5683 | if (this.hasQueryParamIncludes()) {
|
5684 | relationshipPaths = this.request.queryParams.include.split(",");
|
5685 | } else {
|
5686 | var serializer = this.serializerFor(resource.modelName);
|
5687 | relationshipPaths = serializer.getKeysForIncluded();
|
5688 | }
|
5689 |
|
5690 | return this.getAddToIncludesForResourceAndPaths(resource, relationshipPaths);
|
5691 | }
|
5692 | }, {
|
5693 | key: "getAddToIncludesForResourceAndPaths",
|
5694 | value: function getAddToIncludesForResourceAndPaths(resource, relationshipPaths) {
|
5695 | var _this3 = this;
|
5696 |
|
5697 | var includes = [];
|
5698 | relationshipPaths.forEach(function (path) {
|
5699 | var relationshipNames = path.split(".");
|
5700 |
|
5701 | var newIncludes = _this3.getIncludesForResourceAndPath.apply(_this3, [resource].concat(_toConsumableArray(relationshipNames)));
|
5702 |
|
5703 | includes.push(newIncludes);
|
5704 | });
|
5705 | return uniqBy(compact(flatten(includes)), function (m) {
|
5706 | return m.toString();
|
5707 | });
|
5708 | }
|
5709 | }, {
|
5710 | key: "getIncludesForResourceAndPath",
|
5711 | value: function getIncludesForResourceAndPath(resource) {
|
5712 | var _this4 = this;
|
5713 |
|
5714 | for (var _len = arguments.length, names = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
|
5715 | names[_key - 1] = arguments[_key];
|
5716 | }
|
5717 |
|
5718 | var nameForCurrentResource = camelize(names.shift());
|
5719 | var includes = [];
|
5720 | var modelsToAdd = [];
|
5721 |
|
5722 | if (this.isModel(resource)) {
|
5723 | var relationship = resource[nameForCurrentResource];
|
5724 |
|
5725 | if (this.isModel(relationship)) {
|
5726 | modelsToAdd = [relationship];
|
5727 | } else if (this.isCollection(relationship)) {
|
5728 | modelsToAdd = relationship.models;
|
5729 | }
|
5730 | } else {
|
5731 | resource.models.forEach(function (model) {
|
5732 | var relationship = model[nameForCurrentResource];
|
5733 |
|
5734 | if (_this4.isModel(relationship)) {
|
5735 | modelsToAdd.push(relationship);
|
5736 | } else if (_this4.isCollection(relationship)) {
|
5737 | modelsToAdd = modelsToAdd.concat(relationship.models);
|
5738 | }
|
5739 | });
|
5740 | }
|
5741 |
|
5742 | includes = includes.concat(modelsToAdd);
|
5743 |
|
5744 | if (names.length) {
|
5745 | modelsToAdd.forEach(function (model) {
|
5746 | includes = includes.concat(_this4.getIncludesForResourceAndPath.apply(_this4, [model].concat(names)));
|
5747 | });
|
5748 | }
|
5749 |
|
5750 | return includes;
|
5751 | }
|
5752 | }, {
|
5753 | key: "getResourceObjectForModel",
|
5754 | value: function getResourceObjectForModel(model) {
|
5755 | var attrs = this._attrsForModel(model, true);
|
5756 |
|
5757 | delete attrs.id;
|
5758 | var hash = {
|
5759 | type: this.typeKeyForModel(model),
|
5760 | id: model.id,
|
5761 | attributes: attrs
|
5762 | };
|
5763 | return this._maybeAddRelationshipsToResourceObjectForModel(hash, model);
|
5764 | }
|
5765 | }, {
|
5766 | key: "_maybeAddRelationshipsToResourceObjectForModel",
|
5767 | value: function _maybeAddRelationshipsToResourceObjectForModel(hash, model) {
|
5768 | var _this5 = this;
|
5769 |
|
5770 | var relationships = {};
|
5771 | model.associationKeys.forEach(function (key) {
|
5772 | var relationship = model[key];
|
5773 |
|
5774 | var relationshipKey = _this5.keyForRelationship(key);
|
5775 |
|
5776 | var relationshipHash = {};
|
5777 |
|
5778 | if (_this5.hasLinksForRelationship(model, key)) {
|
5779 | var serializer = _this5.serializerFor(model.modelName);
|
5780 |
|
5781 | var links = serializer.links(model);
|
5782 | relationshipHash.links = links[key];
|
5783 | }
|
5784 |
|
5785 | if (_this5.alwaysIncludeLinkageData || _this5.shouldIncludeLinkageData(key, model) || _this5._relationshipIsIncludedForModel(key, model)) {
|
5786 | var data = null;
|
5787 |
|
5788 | if (_this5.isModel(relationship)) {
|
5789 | data = {
|
5790 | type: _this5.typeKeyForModel(relationship),
|
5791 | id: relationship.id
|
5792 | };
|
5793 | } else if (_this5.isCollection(relationship)) {
|
5794 | data = relationship.models.map(function (model) {
|
5795 | return {
|
5796 | type: _this5.typeKeyForModel(model),
|
5797 | id: model.id
|
5798 | };
|
5799 | });
|
5800 | }
|
5801 |
|
5802 | relationshipHash.data = data;
|
5803 | }
|
5804 |
|
5805 | if (!isEmpty(relationshipHash)) {
|
5806 | relationships[relationshipKey] = relationshipHash;
|
5807 | }
|
5808 | });
|
5809 |
|
5810 | if (!isEmpty(relationships)) {
|
5811 | hash.relationships = relationships;
|
5812 | }
|
5813 |
|
5814 | return hash;
|
5815 | }
|
5816 | }, {
|
5817 | key: "hasLinksForRelationship",
|
5818 | value: function hasLinksForRelationship(model, relationshipKey) {
|
5819 | var serializer = this.serializerFor(model.modelName);
|
5820 | var links = serializer.links && serializer.links(model);
|
5821 | return links && links[relationshipKey] != null;
|
5822 | }
|
5823 | |
5824 |
|
5825 |
|
5826 |
|
5827 |
|
5828 | }, {
|
5829 | key: "_relationshipIsIncludedForModel",
|
5830 | value: function _relationshipIsIncludedForModel(relationshipKey, model) {
|
5831 | if (this.hasQueryParamIncludes()) {
|
5832 | var graph = this.request._includesGraph;
|
5833 |
|
5834 | var graphKey = this._graphKeyForModel(model);
|
5835 |
|
5836 |
|
5837 | var graphResource;
|
5838 |
|
5839 | if (graph.data[graphKey]) {
|
5840 | graphResource = graph.data[graphKey];
|
5841 | } else if (graph.included[this._container.inflector.pluralize(model.modelName)]) {
|
5842 | graphResource = graph.included[this._container.inflector.pluralize(model.modelName)][graphKey];
|
5843 | }
|
5844 |
|
5845 |
|
5846 | return graphResource && graphResource.relationships && Object.prototype.hasOwnProperty.call(graphResource.relationships, dasherize(relationshipKey));
|
5847 | } else {
|
5848 | var relationshipPaths = this.getKeysForIncluded();
|
5849 | return relationshipPaths.includes(relationshipKey);
|
5850 | }
|
5851 | }
|
5852 | |
5853 |
|
5854 |
|
5855 |
|
5856 |
|
5857 |
|
5858 |
|
5859 | }, {
|
5860 | key: "_createRequestedIncludesGraph",
|
5861 | value: function _createRequestedIncludesGraph(primaryResource) {
|
5862 | var _this6 = this;
|
5863 | var graph = {
|
5864 | data: {}
|
5865 | };
|
5866 |
|
5867 | if (this.isModel(primaryResource)) {
|
5868 | var primaryResourceKey = this._graphKeyForModel(primaryResource);
|
5869 |
|
5870 | graph.data[primaryResourceKey] = {};
|
5871 |
|
5872 | this._addPrimaryModelToRequestedIncludesGraph(graph, primaryResource);
|
5873 | } else if (this.isCollection(primaryResource)) {
|
5874 | primaryResource.models.forEach(function (model) {
|
5875 | var primaryResourceKey = _this6._graphKeyForModel(model);
|
5876 |
|
5877 | graph.data[primaryResourceKey] = {};
|
5878 |
|
5879 | _this6._addPrimaryModelToRequestedIncludesGraph(graph, model);
|
5880 | });
|
5881 | }
|
5882 |
|
5883 |
|
5884 |
|
5885 | this.request._includesGraph = graph;
|
5886 | }
|
5887 | }, {
|
5888 | key: "_addPrimaryModelToRequestedIncludesGraph",
|
5889 | value: function _addPrimaryModelToRequestedIncludesGraph(graph, model) {
|
5890 | var _this7 = this;
|
5891 |
|
5892 | if (this.hasQueryParamIncludes()) {
|
5893 | var graphKey = this._graphKeyForModel(model);
|
5894 |
|
5895 | var queryParamIncludes = this.getQueryParamIncludes();
|
5896 | queryParamIncludes.split(",").forEach(function (includesPath) {
|
5897 |
|
5898 | graph.data[graphKey].relationships = graph.data[graphKey].relationships || {};
|
5899 | var relationshipKeys = includesPath.split(".").map(dasherize);
|
5900 | var relationshipKey = relationshipKeys[0];
|
5901 | var graphRelationshipKey = relationshipKey;
|
5902 | var normalizedRelationshipKey = camelize(relationshipKey);
|
5903 | var hasAssociation = model.associationKeys.has(normalizedRelationshipKey);
|
5904 | assert(hasAssociation, "You tried to include \"".concat(relationshipKey, "\" with ").concat(model, " but no association named \"").concat(normalizedRelationshipKey, "\" is defined on the model."));
|
5905 | var relationship = model[normalizedRelationshipKey];
|
5906 | var relationshipData;
|
5907 |
|
5908 | if (_this7.isModel(relationship)) {
|
5909 | relationshipData = _this7._graphKeyForModel(relationship);
|
5910 | } else if (_this7.isCollection(relationship)) {
|
5911 | relationshipData = relationship.models.map(_this7._graphKeyForModel);
|
5912 | } else {
|
5913 | relationshipData = null;
|
5914 | }
|
5915 |
|
5916 | graph.data[graphKey].relationships[graphRelationshipKey] = relationshipData;
|
5917 |
|
5918 | if (relationship) {
|
5919 | _this7._addResourceToRequestedIncludesGraph(graph, relationship, relationshipKeys.slice(1));
|
5920 | }
|
5921 | });
|
5922 | }
|
5923 | }
|
5924 | }, {
|
5925 | key: "_addResourceToRequestedIncludesGraph",
|
5926 | value: function _addResourceToRequestedIncludesGraph(graph, resource, relationshipNames) {
|
5927 | var _this8 = this;
|
5928 |
|
5929 | graph.included = graph.included || {};
|
5930 | var models = this.isCollection(resource) ? resource.models : [resource];
|
5931 | models.forEach(function (model) {
|
5932 | var collectionName = _this8._container.inflector.pluralize(model.modelName);
|
5933 |
|
5934 | graph.included[collectionName] = graph.included[collectionName] || {};
|
5935 |
|
5936 | _this8._addModelToRequestedIncludesGraph(graph, model, relationshipNames);
|
5937 | });
|
5938 | }
|
5939 | }, {
|
5940 | key: "_addModelToRequestedIncludesGraph",
|
5941 | value: function _addModelToRequestedIncludesGraph(graph, model, relationshipNames) {
|
5942 | var collectionName = this._container.inflector.pluralize(model.modelName);
|
5943 |
|
5944 | var resourceKey = this._graphKeyForModel(model);
|
5945 |
|
5946 | graph.included[collectionName][resourceKey] = graph.included[collectionName][resourceKey] || {};
|
5947 |
|
5948 | if (relationshipNames.length) {
|
5949 | this._addResourceRelationshipsToRequestedIncludesGraph(graph, collectionName, resourceKey, model, relationshipNames);
|
5950 | }
|
5951 | }
|
5952 | |
5953 |
|
5954 |
|
5955 |
|
5956 | }, {
|
5957 | key: "_addResourceRelationshipsToRequestedIncludesGraph",
|
5958 | value: function _addResourceRelationshipsToRequestedIncludesGraph(graph, collectionName, resourceKey, model, relationshipNames) {
|
5959 | graph.included[collectionName][resourceKey].relationships = graph.included[collectionName][resourceKey].relationships || {};
|
5960 | var relationshipName = relationshipNames[0];
|
5961 | var relationship = model[camelize(relationshipName)];
|
5962 | var relationshipData;
|
5963 |
|
5964 | if (this.isModel(relationship)) {
|
5965 | relationshipData = this._graphKeyForModel(relationship);
|
5966 | } else if (this.isCollection(relationship)) {
|
5967 | relationshipData = relationship.models.map(this._graphKeyForModel);
|
5968 | }
|
5969 |
|
5970 | graph.included[collectionName][resourceKey].relationships[relationshipName] = relationshipData;
|
5971 |
|
5972 | if (relationship) {
|
5973 | this._addResourceToRequestedIncludesGraph(graph, relationship, relationshipNames.slice(1));
|
5974 | }
|
5975 | }
|
5976 | }, {
|
5977 | key: "_graphKeyForModel",
|
5978 | value: function _graphKeyForModel(model) {
|
5979 | return "".concat(model.modelName, ":").concat(model.id);
|
5980 | }
|
5981 | }, {
|
5982 | key: "getQueryParamIncludes",
|
5983 | value: function getQueryParamIncludes() {
|
5984 | return get(this, "request.queryParams.include");
|
5985 | }
|
5986 | }, {
|
5987 | key: "hasQueryParamIncludes",
|
5988 | value: function hasQueryParamIncludes() {
|
5989 | return !!this.getQueryParamIncludes();
|
5990 | }
|
5991 | |
5992 |
|
5993 |
|
5994 |
|
5995 |
|
5996 |
|
5997 |
|
5998 |
|
5999 |
|
6000 |
|
6001 |
|
6002 |
|
6003 |
|
6004 |
|
6005 |
|
6006 |
|
6007 |
|
6008 | }, {
|
6009 | key: "typeKeyForModel",
|
6010 | value: function typeKeyForModel(model) {
|
6011 | return dasherize(this._container.inflector.pluralize(model.modelName));
|
6012 | }
|
6013 | }, {
|
6014 | key: "getCoalescedIds",
|
6015 | value: function getCoalescedIds(request) {
|
6016 | var ids = request.queryParams && request.queryParams["filter[id]"];
|
6017 |
|
6018 | if (typeof ids === "string") {
|
6019 | return ids.split(",");
|
6020 | }
|
6021 |
|
6022 | return ids;
|
6023 | }
|
6024 | |
6025 |
|
6026 |
|
6027 |
|
6028 |
|
6029 |
|
6030 |
|
6031 |
|
6032 |
|
6033 |
|
6034 |
|
6035 |
|
6036 |
|
6037 |
|
6038 |
|
6039 |
|
6040 |
|
6041 |
|
6042 |
|
6043 | }, {
|
6044 | key: "shouldIncludeLinkageData",
|
6045 | value: function shouldIncludeLinkageData(relationshipKey, model) {
|
6046 | return false;
|
6047 | }
|
6048 | }]);
|
6049 |
|
6050 | return JSONAPISerializer;
|
6051 | }(Serializer);
|
6052 |
|
6053 | JSONAPISerializer.prototype.alwaysIncludeLinkageData = false;
|
6054 |
|
6055 |
|
6056 |
|
6057 |
|
6058 |
|
6059 | var SerializerRegistry =
|
6060 |
|
6061 | function () {
|
6062 | function SerializerRegistry(schema) {
|
6063 | var serializerMap = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
|
6064 |
|
6065 | _classCallCheck(this, SerializerRegistry);
|
6066 |
|
6067 | this.schema = schema;
|
6068 | this._serializerMap = serializerMap;
|
6069 | }
|
6070 |
|
6071 | _createClass(SerializerRegistry, [{
|
6072 | key: "normalize",
|
6073 | value: function normalize(payload, modelName) {
|
6074 | return this.serializerFor(modelName).normalize(payload);
|
6075 | }
|
6076 | }, {
|
6077 | key: "serialize",
|
6078 | value: function serialize(response, request) {
|
6079 | var _this = this;
|
6080 |
|
6081 | this.request = request;
|
6082 |
|
6083 | if (this._isModelOrCollection(response)) {
|
6084 | var serializer = this.serializerFor(response.modelName);
|
6085 | return serializer.serialize(response, request);
|
6086 | } else if (Array.isArray(response) && response.some(this._isCollection)) {
|
6087 | return response.reduce(function (json, collection) {
|
6088 | var serializer = _this.serializerFor(collection.modelName);
|
6089 |
|
6090 | if (serializer.embed) {
|
6091 | json[_this._container.inflector.pluralize(collection.modelName)] = serializer.serialize(collection, request);
|
6092 | } else {
|
6093 | json = Object.assign(json, serializer.serialize(collection, request));
|
6094 | }
|
6095 |
|
6096 | return json;
|
6097 | }, {});
|
6098 | } else {
|
6099 | return response;
|
6100 | }
|
6101 | }
|
6102 | }, {
|
6103 | key: "serializerFor",
|
6104 | value: function serializerFor(type) {
|
6105 | var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
|
6106 | _ref$explicit = _ref.explicit,
|
6107 | explicit = _ref$explicit === void 0 ? false : _ref$explicit;
|
6108 |
|
6109 | var SerializerForResponse = type && this._serializerMap && this._serializerMap[camelize(type)];
|
6110 |
|
6111 | if (explicit) {
|
6112 | assert(!!SerializerForResponse, "You passed in ".concat(type, " as an explicit serializer type but that serializer doesn't exist."));
|
6113 | } else {
|
6114 | SerializerForResponse = SerializerForResponse || this._serializerMap.application || Serializer;
|
6115 | assert(!SerializerForResponse || SerializerForResponse.prototype.embed || SerializerForResponse.prototype.root || new SerializerForResponse() instanceof JSONAPISerializer, "You cannot have a serializer that sideloads (embed: false) and disables the root (root: false).");
|
6116 | }
|
6117 |
|
6118 | return new SerializerForResponse(this, type, this.request);
|
6119 | }
|
6120 | }, {
|
6121 | key: "_isModel",
|
6122 | value: function _isModel(object) {
|
6123 | return object instanceof Model;
|
6124 | }
|
6125 | }, {
|
6126 | key: "_isCollection",
|
6127 | value: function _isCollection(object) {
|
6128 | return object instanceof Collection || object instanceof PolymorphicCollection;
|
6129 | }
|
6130 | }, {
|
6131 | key: "_isModelOrCollection",
|
6132 | value: function _isModelOrCollection(object) {
|
6133 | return this._isModel(object) || this._isCollection(object);
|
6134 | }
|
6135 | }, {
|
6136 | key: "registerSerializers",
|
6137 | value: function registerSerializers(newSerializerMaps) {
|
6138 | var currentSerializerMap = this._serializerMap || {};
|
6139 | this._serializerMap = Object.assign(currentSerializerMap, newSerializerMaps);
|
6140 | }
|
6141 | }, {
|
6142 | key: "getCoalescedIds",
|
6143 | value: function getCoalescedIds(request, modelName) {
|
6144 | return this.serializerFor(modelName).getCoalescedIds(request);
|
6145 | }
|
6146 | }]);
|
6147 |
|
6148 | return SerializerRegistry;
|
6149 | }();
|
6150 |
|
6151 | var collectionNameCache = {};
|
6152 | var internalCollectionNameCache = {};
|
6153 | var modelNameCache = {};
|
6154 |
|
6155 |
|
6156 |
|
6157 |
|
6158 |
|
6159 |
|
6160 |
|
6161 |
|
6162 |
|
6163 |
|
6164 |
|
6165 |
|
6166 |
|
6167 |
|
6168 |
|
6169 |
|
6170 |
|
6171 |
|
6172 |
|
6173 |
|
6174 |
|
6175 |
|
6176 |
|
6177 |
|
6178 | var Schema =
|
6179 |
|
6180 | function () {
|
6181 | function Schema(db) {
|
6182 | var modelsMap = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
|
6183 |
|
6184 | _classCallCheck(this, Schema);
|
6185 |
|
6186 | assert(db, "A schema requires a db");
|
6187 | |
6188 |
|
6189 |
|
6190 |
|
6191 |
|
6192 |
|
6193 |
|
6194 | this.db = db;
|
6195 | this._registry = {};
|
6196 | this._dependentAssociations = {
|
6197 | polymorphic: []
|
6198 | };
|
6199 | this.registerModels(modelsMap);
|
6200 | this.isSaving = {};
|
6201 | }
|
6202 | |
6203 |
|
6204 |
|
6205 |
|
6206 |
|
6207 |
|
6208 |
|
6209 |
|
6210 | _createClass(Schema, [{
|
6211 | key: "registerModels",
|
6212 | value: function registerModels() {
|
6213 | var _this = this;
|
6214 |
|
6215 | var hash = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
|
6216 | forIn(hash, function (model, key) {
|
6217 | _this.registerModel(key, hash[key]);
|
6218 | });
|
6219 | }
|
6220 | |
6221 |
|
6222 |
|
6223 |
|
6224 |
|
6225 |
|
6226 |
|
6227 |
|
6228 | }, {
|
6229 | key: "registerModel",
|
6230 | value: function registerModel(type, ModelClass) {
|
6231 | var _this2 = this;
|
6232 |
|
6233 | var camelizedModelName = camelize(type);
|
6234 | var modelName = dasherize(camelizedModelName);
|
6235 |
|
6236 | ModelClass = ModelClass.extend();
|
6237 |
|
6238 |
|
6239 | this._registry[camelizedModelName] = this._registry[camelizedModelName] || {
|
6240 | "class": null,
|
6241 | foreignKeys: []
|
6242 | };
|
6243 |
|
6244 | this._registry[camelizedModelName]["class"] = ModelClass;
|
6245 |
|
6246 | ModelClass.prototype._schema = this;
|
6247 | ModelClass.prototype.modelName = modelName;
|
6248 |
|
6249 | ModelClass.prototype.hasManyAssociations = {};
|
6250 |
|
6251 | ModelClass.prototype.hasManyAssociationFks = {};
|
6252 |
|
6253 | ModelClass.prototype.belongsToAssociations = {};
|
6254 |
|
6255 | ModelClass.prototype.belongsToAssociationFks = {};
|
6256 |
|
6257 | ModelClass.prototype.associationKeys = new Set();
|
6258 |
|
6259 | ModelClass.prototype.associationIdKeys = new Set();
|
6260 |
|
6261 | ModelClass.prototype.dependentAssociations = [];
|
6262 |
|
6263 | var fksAddedFromThisModel = {};
|
6264 |
|
6265 | for (var associationProperty in ModelClass.prototype) {
|
6266 | if (ModelClass.prototype[associationProperty] instanceof Association) {
|
6267 | var association = ModelClass.prototype[associationProperty];
|
6268 | association.key = associationProperty;
|
6269 | association.modelName = association.modelName || this.toModelName(associationProperty);
|
6270 | association.ownerModelName = modelName;
|
6271 | association.setSchema(this);
|
6272 |
|
6273 |
|
6274 | var _association$getForei = association.getForeignKeyArray(),
|
6275 | _association$getForei2 = _slicedToArray(_association$getForei, 2),
|
6276 | fkHolder = _association$getForei2[0],
|
6277 | fk = _association$getForei2[1];
|
6278 |
|
6279 | fksAddedFromThisModel[fkHolder] = fksAddedFromThisModel[fkHolder] || [];
|
6280 | assert(!fksAddedFromThisModel[fkHolder].includes(fk), "Your '".concat(type, "' model definition has multiple possible inverse relationships of type '").concat(fkHolder, "'. Please use explicit inverses."));
|
6281 | fksAddedFromThisModel[fkHolder].push(fk);
|
6282 |
|
6283 | this._addForeignKeyToRegistry(fkHolder, fk);
|
6284 |
|
6285 |
|
6286 | association.addMethodsToModelClass(ModelClass, associationProperty);
|
6287 | }
|
6288 | }
|
6289 |
|
6290 |
|
6291 | var collection = this.toCollectionName(modelName);
|
6292 |
|
6293 | if (!this.db[collection]) {
|
6294 | this.db.createCollection(collection);
|
6295 | }
|
6296 |
|
6297 |
|
6298 | this[collection] = {
|
6299 | camelizedModelName: camelizedModelName,
|
6300 | "new": function _new(attrs) {
|
6301 | return _this2["new"](camelizedModelName, attrs);
|
6302 | },
|
6303 | create: function create(attrs) {
|
6304 | return _this2.create(camelizedModelName, attrs);
|
6305 | },
|
6306 | all: function all(attrs) {
|
6307 | return _this2.all(camelizedModelName, attrs);
|
6308 | },
|
6309 | find: function find(attrs) {
|
6310 | return _this2.find(camelizedModelName, attrs);
|
6311 | },
|
6312 | findBy: function findBy(attrs) {
|
6313 | return _this2.findBy(camelizedModelName, attrs);
|
6314 | },
|
6315 | findOrCreateBy: function findOrCreateBy(attrs) {
|
6316 | return _this2.findOrCreateBy(camelizedModelName, attrs);
|
6317 | },
|
6318 | where: function where(attrs) {
|
6319 | return _this2.where(camelizedModelName, attrs);
|
6320 | },
|
6321 | none: function none(attrs) {
|
6322 | return _this2.none(camelizedModelName, attrs);
|
6323 | },
|
6324 | first: function first(attrs) {
|
6325 | return _this2.first(camelizedModelName, attrs);
|
6326 | }
|
6327 | };
|
6328 | return this;
|
6329 | }
|
6330 | |
6331 |
|
6332 |
|
6333 |
|
6334 |
|
6335 |
|
6336 |
|
6337 | }, {
|
6338 | key: "modelFor",
|
6339 | value: function modelFor(type) {
|
6340 | return this._registry[type];
|
6341 | }
|
6342 | |
6343 |
|
6344 |
|
6345 |
|
6346 |
|
6347 |
|
6348 |
|
6349 |
|
6350 |
|
6351 |
|
6352 |
|
6353 |
|
6354 |
|
6355 |
|
6356 | }, {
|
6357 | key: "new",
|
6358 | value: function _new(type, attrs) {
|
6359 | return this._instantiateModel(dasherize(type), attrs);
|
6360 | }
|
6361 | |
6362 |
|
6363 |
|
6364 |
|
6365 |
|
6366 |
|
6367 |
|
6368 |
|
6369 |
|
6370 |
|
6371 |
|
6372 |
|
6373 |
|
6374 |
|
6375 | }, {
|
6376 | key: "create",
|
6377 | value: function create(type, attrs) {
|
6378 | return this["new"](type, attrs).save();
|
6379 | }
|
6380 | |
6381 |
|
6382 |
|
6383 |
|
6384 |
|
6385 |
|
6386 |
|
6387 |
|
6388 |
|
6389 |
|
6390 |
|
6391 | }, {
|
6392 | key: "all",
|
6393 | value: function all(type) {
|
6394 | var collection = this.collectionForType(type);
|
6395 | return this._hydrate(collection, dasherize(type));
|
6396 | }
|
6397 | |
6398 |
|
6399 |
|
6400 |
|
6401 |
|
6402 |
|
6403 |
|
6404 | }, {
|
6405 | key: "none",
|
6406 | value: function none(type) {
|
6407 | return this._hydrate([], dasherize(type));
|
6408 | }
|
6409 | |
6410 |
|
6411 |
|
6412 |
|
6413 |
|
6414 |
|
6415 |
|
6416 |
|
6417 |
|
6418 |
|
6419 |
|
6420 |
|
6421 | }, {
|
6422 | key: "find",
|
6423 | value: function find(type, ids) {
|
6424 | var collection = this.collectionForType(type);
|
6425 | var records = collection.find(ids);
|
6426 |
|
6427 | if (Array.isArray(ids)) {
|
6428 | assert(records.length === ids.length, "Couldn't find all ".concat(this._container.inflector.pluralize(type), " with ids: (").concat(ids.join(","), ") (found ").concat(records.length, " results, but was looking for ").concat(ids.length, ")"));
|
6429 | }
|
6430 |
|
6431 | return this._hydrate(records, dasherize(type));
|
6432 | }
|
6433 | |
6434 |
|
6435 |
|
6436 |
|
6437 |
|
6438 |
|
6439 |
|
6440 |
|
6441 |
|
6442 |
|
6443 |
|
6444 |
|
6445 | }, {
|
6446 | key: "findBy",
|
6447 | value: function findBy(type, query) {
|
6448 | var collection = this.collectionForType(type);
|
6449 | var record = collection.findBy(query);
|
6450 | return this._hydrate(record, dasherize(type));
|
6451 | }
|
6452 | |
6453 |
|
6454 |
|
6455 |
|
6456 |
|
6457 |
|
6458 |
|
6459 |
|
6460 |
|
6461 |
|
6462 |
|
6463 |
|
6464 | }, {
|
6465 | key: "findOrCreateBy",
|
6466 | value: function findOrCreateBy(type, attrs) {
|
6467 | var collection = this.collectionForType(type);
|
6468 | var record = collection.findBy(attrs);
|
6469 | var model;
|
6470 |
|
6471 | if (!record) {
|
6472 | model = this.create(type, attrs);
|
6473 | } else {
|
6474 | model = this._hydrate(record, dasherize(type));
|
6475 | }
|
6476 |
|
6477 | return model;
|
6478 | }
|
6479 | |
6480 |
|
6481 |
|
6482 |
|
6483 |
|
6484 |
|
6485 |
|
6486 |
|
6487 |
|
6488 |
|
6489 |
|
6490 |
|
6491 |
|
6492 |
|
6493 | }, {
|
6494 | key: "where",
|
6495 | value: function where(type, query) {
|
6496 | var collection = this.collectionForType(type);
|
6497 | var records = collection.where(query);
|
6498 | return this._hydrate(records, dasherize(type));
|
6499 | }
|
6500 | |
6501 |
|
6502 |
|
6503 |
|
6504 |
|
6505 |
|
6506 |
|
6507 |
|
6508 |
|
6509 |
|
6510 |
|
6511 | }, {
|
6512 | key: "first",
|
6513 | value: function first(type) {
|
6514 | var collection = this.collectionForType(type);
|
6515 | var record = collection[0];
|
6516 | return this._hydrate(record, dasherize(type));
|
6517 | }
|
6518 | |
6519 |
|
6520 |
|
6521 |
|
6522 |
|
6523 |
|
6524 |
|
6525 | }, {
|
6526 | key: "modelClassFor",
|
6527 | value: function modelClassFor(modelName) {
|
6528 | var model = this._registry[camelize(modelName)];
|
6529 |
|
6530 | assert(model, "Model not registered: ".concat(modelName));
|
6531 | return model["class"].prototype;
|
6532 | }
|
6533 | |
6534 |
|
6535 |
|
6536 |
|
6537 |
|
6538 |
|
6539 |
|
6540 |
|
6541 |
|
6542 |
|
6543 |
|
6544 |
|
6545 |
|
6546 |
|
6547 |
|
6548 |
|
6549 |
|
6550 |
|
6551 |
|
6552 |
|
6553 | }, {
|
6554 | key: "addDependentAssociation",
|
6555 | value: function addDependentAssociation(association, modelName) {
|
6556 | if (association.isPolymorphic) {
|
6557 | this._dependentAssociations.polymorphic.push(association);
|
6558 | } else {
|
6559 | this._dependentAssociations[modelName] = this._dependentAssociations[modelName] || [];
|
6560 |
|
6561 | this._dependentAssociations[modelName].push(association);
|
6562 | }
|
6563 | }
|
6564 | }, {
|
6565 | key: "dependentAssociationsFor",
|
6566 | value: function dependentAssociationsFor(modelName) {
|
6567 | var directDependents = this._dependentAssociations[modelName] || [];
|
6568 | var polymorphicAssociations = this._dependentAssociations.polymorphic || [];
|
6569 | return directDependents.concat(polymorphicAssociations);
|
6570 | }
|
6571 | }, {
|
6572 | key: "associationsFor",
|
6573 | value: function associationsFor(modelName) {
|
6574 | var modelClass = this.modelClassFor(modelName);
|
6575 | return Object.assign({}, modelClass.belongsToAssociations, modelClass.hasManyAssociations);
|
6576 | }
|
6577 | }, {
|
6578 | key: "hasModelForModelName",
|
6579 | value: function hasModelForModelName(modelName) {
|
6580 | return this.modelFor(camelize(modelName));
|
6581 | }
|
6582 | |
6583 |
|
6584 |
|
6585 |
|
6586 | |
6587 |
|
6588 |
|
6589 |
|
6590 |
|
6591 |
|
6592 |
|
6593 | }, {
|
6594 | key: "collectionForType",
|
6595 | value: function collectionForType(type) {
|
6596 | var collection = this.toCollectionName(type);
|
6597 | assert(this.db[collection], "You're trying to find model(s) of type ".concat(type, " but this collection doesn't exist in the database."));
|
6598 | return this.db[collection];
|
6599 | }
|
6600 | }, {
|
6601 | key: "toCollectionName",
|
6602 | value: function toCollectionName(type) {
|
6603 | if (typeof collectionNameCache[type] !== "string") {
|
6604 | var modelName = dasherize(type);
|
6605 | var collectionName = camelize(this._container.inflector.pluralize(modelName));
|
6606 | collectionNameCache[type] = collectionName;
|
6607 | }
|
6608 |
|
6609 | return collectionNameCache[type];
|
6610 | }
|
6611 |
|
6612 |
|
6613 | }, {
|
6614 | key: "toInternalCollectionName",
|
6615 | value: function toInternalCollectionName(type) {
|
6616 | if (typeof internalCollectionNameCache[type] !== "string") {
|
6617 | var internalCollectionName = "_".concat(this.toCollectionName(type));
|
6618 | internalCollectionNameCache[type] = internalCollectionName;
|
6619 | }
|
6620 |
|
6621 | return internalCollectionNameCache[type];
|
6622 | }
|
6623 | }, {
|
6624 | key: "toModelName",
|
6625 | value: function toModelName(type) {
|
6626 | if (typeof modelNameCache[type] !== "string") {
|
6627 | var dasherized = dasherize(type);
|
6628 |
|
6629 | var modelName = this._container.inflector.singularize(dasherized);
|
6630 |
|
6631 | modelNameCache[type] = modelName;
|
6632 | }
|
6633 |
|
6634 | return modelNameCache[type];
|
6635 | }
|
6636 | |
6637 |
|
6638 |
|
6639 |
|
6640 |
|
6641 |
|
6642 |
|
6643 |
|
6644 | }, {
|
6645 | key: "_addForeignKeyToRegistry",
|
6646 | value: function _addForeignKeyToRegistry(type, fk) {
|
6647 | this._registry[type] = this._registry[type] || {
|
6648 | "class": null,
|
6649 | foreignKeys: []
|
6650 | };
|
6651 | var fks = this._registry[type].foreignKeys;
|
6652 |
|
6653 | if (!fks.includes(fk)) {
|
6654 | fks.push(fk);
|
6655 | }
|
6656 | }
|
6657 | |
6658 |
|
6659 |
|
6660 |
|
6661 |
|
6662 |
|
6663 |
|
6664 |
|
6665 | }, {
|
6666 | key: "_instantiateModel",
|
6667 | value: function _instantiateModel(modelName, attrs) {
|
6668 | var ModelClass = this._modelFor(modelName);
|
6669 |
|
6670 | var fks = this._foreignKeysFor(modelName);
|
6671 |
|
6672 | return new ModelClass(this, modelName, attrs, fks);
|
6673 | }
|
6674 | |
6675 |
|
6676 |
|
6677 |
|
6678 |
|
6679 |
|
6680 |
|
6681 | }, {
|
6682 | key: "_modelFor",
|
6683 | value: function _modelFor(modelName) {
|
6684 | return this._registry[camelize(modelName)]["class"];
|
6685 | }
|
6686 | |
6687 |
|
6688 |
|
6689 |
|
6690 |
|
6691 |
|
6692 |
|
6693 | }, {
|
6694 | key: "_foreignKeysFor",
|
6695 | value: function _foreignKeysFor(modelName) {
|
6696 | return this._registry[camelize(modelName)].foreignKeys;
|
6697 | }
|
6698 | |
6699 |
|
6700 |
|
6701 |
|
6702 |
|
6703 |
|
6704 |
|
6705 |
|
6706 |
|
6707 |
|
6708 |
|
6709 | }, {
|
6710 | key: "_hydrate",
|
6711 | value: function _hydrate(records, modelName) {
|
6712 | if (Array.isArray(records)) {
|
6713 | var models = records.map(function (record) {
|
6714 | return this._instantiateModel(modelName, record);
|
6715 | }, this);
|
6716 | return new Collection(modelName, models);
|
6717 | } else if (records) {
|
6718 | return this._instantiateModel(modelName, records);
|
6719 | } else {
|
6720 | return null;
|
6721 | }
|
6722 | }
|
6723 | }]);
|
6724 |
|
6725 | return Schema;
|
6726 | }();
|
6727 |
|
6728 | var classes = {
|
6729 | Db: Db,
|
6730 | Association: Association,
|
6731 | RouteHandler: RouteHandler,
|
6732 | BaseRouteHandler: BaseRouteHandler,
|
6733 | Serializer: Serializer,
|
6734 | SerializerRegistry: SerializerRegistry,
|
6735 | Schema: Schema
|
6736 | };
|
6737 | var defaultInflector = {
|
6738 | singularize: singularize,
|
6739 | pluralize: pluralize
|
6740 | };
|
6741 |
|
6742 |
|
6743 |
|
6744 |
|
6745 |
|
6746 |
|
6747 |
|
6748 |
|
6749 | var Container =
|
6750 |
|
6751 | function () {
|
6752 | function Container() {
|
6753 | _classCallCheck(this, Container);
|
6754 |
|
6755 | this.inflector = defaultInflector;
|
6756 | }
|
6757 |
|
6758 | _createClass(Container, [{
|
6759 | key: "register",
|
6760 | value: function register(key, value) {
|
6761 | this[key] = value;
|
6762 | }
|
6763 | }, {
|
6764 | key: "create",
|
6765 | value: function create(className) {
|
6766 | var Class = classes[className];
|
6767 | Class.prototype._container = this;
|
6768 |
|
6769 | for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
|
6770 | args[_key - 1] = arguments[_key];
|
6771 | }
|
6772 |
|
6773 | return _construct(Class, args);
|
6774 | }
|
6775 | }]);
|
6776 |
|
6777 | return Container;
|
6778 | }();
|
6779 |
|
6780 |
|
6781 |
|
6782 |
|
6783 |
|
6784 |
|
6785 |
|
6786 |
|
6787 |
|
6788 | var defaultContainer = new Container();
|
6789 | Db.prototype._container = defaultContainer;
|
6790 | Association.prototype._container = defaultContainer;
|
6791 | BaseRouteHandler.prototype._container = defaultContainer;
|
6792 | RouteHandler.prototype._container = defaultContainer;
|
6793 | Serializer.prototype._container = defaultContainer;
|
6794 | SerializerRegistry.prototype._container = defaultContainer;
|
6795 | Schema.prototype._container = defaultContainer;
|
6796 |
|
6797 | var isPluralForModelCache = {};
|
6798 |
|
6799 |
|
6800 |
|
6801 |
|
6802 |
|
6803 |
|
6804 |
|
6805 |
|
6806 |
|
6807 | function createPretender(server) {
|
6808 | if (typeof window !== "undefined") {
|
6809 | return new Pretender(function () {
|
6810 | this.passthroughRequest = function (verb, path, request) {
|
6811 | if (server.shouldLog()) {
|
6812 | console.log("Mirage: Passthrough request for ".concat(verb.toUpperCase(), " ").concat(request.url));
|
6813 | }
|
6814 | };
|
6815 |
|
6816 | this.handledRequest = function (verb, path, request) {
|
6817 | if (server.shouldLog()) {
|
6818 | console.groupCollapsed("Mirage: [".concat(request.status, "] ").concat(verb.toUpperCase(), " ").concat(request.url));
|
6819 | var requestBody = request.requestBody,
|
6820 | responseText = request.responseText;
|
6821 | var loggedRequest, loggedResponse;
|
6822 |
|
6823 | try {
|
6824 | loggedRequest = JSON.parse(requestBody);
|
6825 | } catch (e) {
|
6826 | loggedRequest = requestBody;
|
6827 | }
|
6828 |
|
6829 | try {
|
6830 | loggedResponse = JSON.parse(responseText);
|
6831 | } catch (e) {
|
6832 | loggedResponse = responseText;
|
6833 | }
|
6834 |
|
6835 | console.groupCollapsed("Response");
|
6836 | console.log(loggedResponse);
|
6837 | console.groupEnd();
|
6838 | console.groupCollapsed("Request (data)");
|
6839 | console.log(loggedRequest);
|
6840 | console.groupEnd();
|
6841 | console.groupCollapsed("Request (raw)");
|
6842 | console.log(request);
|
6843 | console.groupEnd();
|
6844 | console.groupEnd();
|
6845 | }
|
6846 | };
|
6847 |
|
6848 | var originalCheckPassthrough = this.checkPassthrough;
|
6849 |
|
6850 | this.checkPassthrough = function (request) {
|
6851 | var shouldPassthrough = server.passthroughChecks.some(function (passthroughCheck) {
|
6852 | return passthroughCheck(request);
|
6853 | });
|
6854 |
|
6855 | if (shouldPassthrough) {
|
6856 | var url = request.url.includes("?") ? request.url.substr(0, request.url.indexOf("?")) : request.url;
|
6857 | this[request.method.toLowerCase()](url, this.passthrough);
|
6858 | }
|
6859 |
|
6860 | return originalCheckPassthrough.apply(this, arguments);
|
6861 | };
|
6862 |
|
6863 | this.unhandledRequest = function (verb, path) {
|
6864 | path = decodeURI(path);
|
6865 | assert("Your app tried to ".concat(verb, " '").concat(path, "', but there was no route defined to handle this request. Define a route for this endpoint in your routes() config. Did you forget to define a namespace?"));
|
6866 | };
|
6867 | }, {
|
6868 | trackRequests: server.shouldTrackRequests()
|
6869 | });
|
6870 | }
|
6871 | }
|
6872 |
|
6873 | var defaultRouteOptions = {
|
6874 | coalesce: false,
|
6875 | timing: undefined
|
6876 | };
|
6877 | var defaultInflector$1 = {
|
6878 | singularize: singularize,
|
6879 | pluralize: pluralize
|
6880 | };
|
6881 |
|
6882 |
|
6883 |
|
6884 |
|
6885 | var defaultPassthroughs = ["http://localhost:0/chromecheckurl",
|
6886 | "http://localhost:30820/socket.io",
|
6887 | function (request) {
|
6888 | return /.+\.hot-update.json$/.test(request.url);
|
6889 | }];
|
6890 |
|
6891 |
|
6892 |
|
6893 |
|
6894 |
|
6895 |
|
6896 |
|
6897 |
|
6898 |
|
6899 | function isOption(option) {
|
6900 | if (!option || _typeof(option) !== "object") {
|
6901 | return false;
|
6902 | }
|
6903 |
|
6904 | var allOptions = Object.keys(defaultRouteOptions);
|
6905 | var optionKeys = Object.keys(option);
|
6906 |
|
6907 | for (var i = 0; i < optionKeys.length; i++) {
|
6908 | var key = optionKeys[i];
|
6909 |
|
6910 | if (allOptions.indexOf(key) > -1) {
|
6911 | return true;
|
6912 | }
|
6913 | }
|
6914 |
|
6915 | return false;
|
6916 | }
|
6917 |
|
6918 |
|
6919 |
|
6920 |
|
6921 |
|
6922 |
|
6923 |
|
6924 |
|
6925 |
|
6926 |
|
6927 |
|
6928 |
|
6929 | function extractRouteArguments(args) {
|
6930 | var _args$splice = args.splice(-1),
|
6931 | _args$splice2 = _slicedToArray(_args$splice, 1),
|
6932 | lastArg = _args$splice2[0];
|
6933 |
|
6934 | if (isOption(lastArg)) {
|
6935 | lastArg = assign({}, defaultRouteOptions, lastArg);
|
6936 | } else {
|
6937 | args.push(lastArg);
|
6938 | lastArg = defaultRouteOptions;
|
6939 | }
|
6940 |
|
6941 | var t = 2 - args.length;
|
6942 |
|
6943 | while (t-- > 0) {
|
6944 | args.push(undefined);
|
6945 | }
|
6946 |
|
6947 | args.push(lastArg);
|
6948 | return args;
|
6949 | }
|
6950 |
|
6951 |
|
6952 |
|
6953 |
|
6954 |
|
6955 |
|
6956 |
|
6957 |
|
6958 |
|
6959 |
|
6960 | var Server =
|
6961 |
|
6962 | function () {
|
6963 | function Server() {
|
6964 | var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
|
6965 |
|
6966 | _classCallCheck(this, Server);
|
6967 |
|
6968 | this._container = new Container();
|
6969 | this.config(options);
|
6970 | |
6971 |
|
6972 |
|
6973 |
|
6974 |
|
6975 |
|
6976 | this.db = this.db || undefined;
|
6977 | |
6978 |
|
6979 |
|
6980 |
|
6981 |
|
6982 |
|
6983 | this.schema = this.schema || undefined;
|
6984 | }
|
6985 |
|
6986 | _createClass(Server, [{
|
6987 | key: "config",
|
6988 | value: function config() {
|
6989 | var _config = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
|
6990 |
|
6991 | this.passthroughChecks = this.passthroughChecks || [];
|
6992 | var didOverrideConfig = _config.environment && this.environment && this.environment !== _config.environment;
|
6993 | assert(!didOverrideConfig, "You cannot modify Mirage's environment once the server is created");
|
6994 | this.environment = _config.environment || this.environment || "development";
|
6995 |
|
6996 | if (_config.routes) {
|
6997 | assert(!_config.baseConfig, "The routes option is an alias for the baseConfig option. You can't pass both options into your server definition.");
|
6998 | _config.baseConfig = _config.routes;
|
6999 | }
|
7000 |
|
7001 | if (_config.seeds) {
|
7002 | assert(!_config.scenarios, "The seeds option is an alias for the scenarios.default option. You can't pass both options into your server definition.");
|
7003 | _config.scenarios = {
|
7004 | "default": _config.seeds
|
7005 | };
|
7006 | }
|
7007 |
|
7008 | this._config = _config;
|
7009 | |
7010 |
|
7011 |
|
7012 |
|
7013 |
|
7014 |
|
7015 |
|
7016 |
|
7017 |
|
7018 |
|
7019 |
|
7020 |
|
7021 |
|
7022 |
|
7023 |
|
7024 |
|
7025 |
|
7026 |
|
7027 |
|
7028 |
|
7029 |
|
7030 |
|
7031 |
|
7032 |
|
7033 |
|
7034 |
|
7035 |
|
7036 |
|
7037 |
|
7038 |
|
7039 |
|
7040 | this.namespace = this.namespace || _config.namespace || "";
|
7041 | |
7042 |
|
7043 |
|
7044 |
|
7045 | this.inflector = _config.inflector || defaultInflector$1;
|
7046 |
|
7047 | this._container.register("inflector", this.inflector);
|
7048 | |
7049 |
|
7050 |
|
7051 |
|
7052 |
|
7053 |
|
7054 |
|
7055 |
|
7056 |
|
7057 |
|
7058 |
|
7059 |
|
7060 |
|
7061 | this.urlPrefix = this.urlPrefix || _config.urlPrefix || "";
|
7062 | |
7063 |
|
7064 |
|
7065 |
|
7066 |
|
7067 |
|
7068 |
|
7069 |
|
7070 |
|
7071 |
|
7072 |
|
7073 |
|
7074 |
|
7075 |
|
7076 |
|
7077 |
|
7078 | this.timing = this.timing || _config.timing || 400;
|
7079 | |
7080 |
|
7081 |
|
7082 |
|
7083 |
|
7084 |
|
7085 |
|
7086 |
|
7087 |
|
7088 |
|
7089 |
|
7090 |
|
7091 |
|
7092 |
|
7093 |
|
7094 |
|
7095 |
|
7096 |
|
7097 |
|
7098 |
|
7099 |
|
7100 |
|
7101 |
|
7102 |
|
7103 |
|
7104 |
|
7105 |
|
7106 |
|
7107 |
|
7108 | this.logging = this.logging !== undefined ? this.logging : undefined;
|
7109 | this.testConfig = this.testConfig || undefined;
|
7110 | this.trackRequests = _config.trackRequests;
|
7111 |
|
7112 | this._defineRouteHandlerHelpers();
|
7113 |
|
7114 | if (this.db) {
|
7115 | this.db.registerIdentityManagers(_config.identityManagers);
|
7116 | } else {
|
7117 | this.db = this._container.create("Db", undefined, _config.identityManagers);
|
7118 | }
|
7119 |
|
7120 | if (this.schema) {
|
7121 | this.schema.registerModels(_config.models);
|
7122 | this.serializerOrRegistry.registerSerializers(_config.serializers || {});
|
7123 | } else {
|
7124 | this.schema = this._container.create("Schema", this.db, _config.models);
|
7125 | this.serializerOrRegistry = this._container.create("SerializerRegistry", this.schema, _config.serializers);
|
7126 | }
|
7127 |
|
7128 | var hasFactories = this._hasModulesOfType(_config, "factories");
|
7129 |
|
7130 | var hasDefaultScenario = _config.scenarios && Object.prototype.hasOwnProperty.call(_config.scenarios, "default");
|
7131 | var didOverridePretenderConfig = _config.trackRequests !== undefined && this.pretender;
|
7132 | assert(!didOverridePretenderConfig, "You cannot modify Pretender's request tracking once the server is created");
|
7133 | |
7134 |
|
7135 |
|
7136 |
|
7137 |
|
7138 |
|
7139 |
|
7140 |
|
7141 |
|
7142 |
|
7143 |
|
7144 |
|
7145 |
|
7146 |
|
7147 |
|
7148 |
|
7149 |
|
7150 | this.pretender = this.pretender || _config.pretender || createPretender(this);
|
7151 |
|
7152 | if (_config.baseConfig) {
|
7153 | this.loadConfig(_config.baseConfig);
|
7154 | }
|
7155 |
|
7156 | if (this.isTest()) {
|
7157 | if (_config.testConfig) {
|
7158 | this.loadConfig(_config.testConfig);
|
7159 | }
|
7160 |
|
7161 | if (typeof window !== "undefined") {
|
7162 | window.server = this;
|
7163 | }
|
7164 | }
|
7165 |
|
7166 | if (this.isTest() && hasFactories) {
|
7167 | this.loadFactories(_config.factories);
|
7168 | } else if (!this.isTest() && hasDefaultScenario) {
|
7169 | this.loadFactories(_config.factories);
|
7170 |
|
7171 | _config.scenarios["default"](this);
|
7172 | } else {
|
7173 | this.loadFixtures();
|
7174 | }
|
7175 |
|
7176 | var useDefaultPassthroughs = typeof _config.useDefaultPassthroughs !== "undefined" ? _config.useDefaultPassthroughs : true;
|
7177 |
|
7178 | if (useDefaultPassthroughs) {
|
7179 | this._configureDefaultPassthroughs();
|
7180 | }
|
7181 | }
|
7182 | |
7183 |
|
7184 |
|
7185 |
|
7186 |
|
7187 |
|
7188 |
|
7189 |
|
7190 |
|
7191 | }, {
|
7192 | key: "isTest",
|
7193 | value: function isTest() {
|
7194 | return this.environment === "test";
|
7195 | }
|
7196 | |
7197 |
|
7198 |
|
7199 |
|
7200 |
|
7201 |
|
7202 |
|
7203 |
|
7204 |
|
7205 | }, {
|
7206 | key: "shouldLog",
|
7207 | value: function shouldLog() {
|
7208 | return typeof this.logging !== "undefined" ? this.logging : !this.isTest();
|
7209 | }
|
7210 | |
7211 |
|
7212 |
|
7213 |
|
7214 |
|
7215 |
|
7216 |
|
7217 |
|
7218 |
|
7219 | }, {
|
7220 | key: "shouldTrackRequests",
|
7221 | value: function shouldTrackRequests() {
|
7222 | return Boolean(this.trackRequests);
|
7223 | }
|
7224 | |
7225 |
|
7226 |
|
7227 |
|
7228 |
|
7229 |
|
7230 |
|
7231 |
|
7232 |
|
7233 |
|
7234 | }, {
|
7235 | key: "loadConfig",
|
7236 | value: function loadConfig(config) {
|
7237 | config.call(this);
|
7238 | this.timing = this.isTest() ? 0 : this.timing || 0;
|
7239 | }
|
7240 | |
7241 |
|
7242 |
|
7243 |
|
7244 |
|
7245 |
|
7246 |
|
7247 |
|
7248 |
|
7249 |
|
7250 |
|
7251 |
|
7252 |
|
7253 |
|
7254 |
|
7255 |
|
7256 |
|
7257 |
|
7258 |
|
7259 |
|
7260 |
|
7261 |
|
7262 |
|
7263 |
|
7264 |
|
7265 |
|
7266 |
|
7267 |
|
7268 |
|
7269 |
|
7270 |
|
7271 |
|
7272 |
|
7273 |
|
7274 |
|
7275 |
|
7276 |
|
7277 |
|
7278 |
|
7279 |
|
7280 |
|
7281 |
|
7282 |
|
7283 | }, {
|
7284 | key: "passthrough",
|
7285 | value: function passthrough() {
|
7286 | var _this = this;
|
7287 |
|
7288 | for (var _len = arguments.length, paths = new Array(_len), _key = 0; _key < _len; _key++) {
|
7289 | paths[_key] = arguments[_key];
|
7290 | }
|
7291 |
|
7292 |
|
7293 |
|
7294 | if (typeof window !== "undefined") {
|
7295 | var verbs = ["get", "post", "put", "delete", "patch", "options", "head"];
|
7296 | var lastArg = paths[paths.length - 1];
|
7297 |
|
7298 | if (paths.length === 0) {
|
7299 | paths = ["/**", "/"];
|
7300 | } else if (Array.isArray(lastArg)) {
|
7301 | verbs = paths.pop();
|
7302 | }
|
7303 |
|
7304 | paths.forEach(function (path) {
|
7305 | if (typeof path === "function") {
|
7306 | _this.passthroughChecks.push(path);
|
7307 | } else {
|
7308 | verbs.forEach(function (verb) {
|
7309 | var fullPath = _this._getFullPath(path);
|
7310 |
|
7311 | _this.pretender[verb](fullPath, _this.pretender.passthrough);
|
7312 | });
|
7313 | }
|
7314 | });
|
7315 | }
|
7316 | }
|
7317 | |
7318 |
|
7319 |
|
7320 |
|
7321 |
|
7322 |
|
7323 |
|
7324 |
|
7325 |
|
7326 |
|
7327 |
|
7328 |
|
7329 |
|
7330 |
|
7331 |
|
7332 |
|
7333 |
|
7334 |
|
7335 |
|
7336 |
|
7337 |
|
7338 |
|
7339 |
|
7340 |
|
7341 |
|
7342 |
|
7343 |
|
7344 |
|
7345 |
|
7346 |
|
7347 | }, {
|
7348 | key: "loadFixtures",
|
7349 | value: function loadFixtures() {
|
7350 | var fixtures = this._config.fixtures;
|
7351 |
|
7352 | for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
|
7353 | args[_key2] = arguments[_key2];
|
7354 | }
|
7355 |
|
7356 | if (args.length) {
|
7357 | var camelizedArgs = args.map(camelize);
|
7358 | var missingKeys = camelizedArgs.filter(function (key) {
|
7359 | return !fixtures[key];
|
7360 | });
|
7361 |
|
7362 | if (missingKeys.length) {
|
7363 | throw new Error("Fixtures not found: ".concat(missingKeys.join(", ")));
|
7364 | }
|
7365 |
|
7366 | fixtures = pick.apply(void 0, [fixtures].concat(_toConsumableArray(camelizedArgs)));
|
7367 | }
|
7368 |
|
7369 | this.db.loadData(fixtures);
|
7370 | }
|
7371 | |
7372 |
|
7373 |
|
7374 |
|
7375 | |
7376 |
|
7377 |
|
7378 |
|
7379 |
|
7380 |
|
7381 |
|
7382 |
|
7383 |
|
7384 | }, {
|
7385 | key: "loadFactories",
|
7386 | value: function loadFactories() {
|
7387 | var _this2 = this;
|
7388 |
|
7389 | var factoryMap = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
|
7390 |
|
7391 | var currentFactoryMap = this._factoryMap || {};
|
7392 | this._factoryMap = assign(currentFactoryMap, factoryMap);
|
7393 |
|
7394 | Object.keys(factoryMap).forEach(function (type) {
|
7395 | var collectionName = _this2.schema.toCollectionName(type);
|
7396 |
|
7397 | _this2.db.createCollection(collectionName);
|
7398 | });
|
7399 | }
|
7400 | |
7401 |
|
7402 |
|
7403 |
|
7404 |
|
7405 |
|
7406 |
|
7407 |
|
7408 |
|
7409 | }, {
|
7410 | key: "factoryFor",
|
7411 | value: function factoryFor(type) {
|
7412 | var camelizedType = camelize(type);
|
7413 |
|
7414 | if (this._factoryMap && this._factoryMap[camelizedType]) {
|
7415 | return this._factoryMap[camelizedType];
|
7416 | }
|
7417 | }
|
7418 | }, {
|
7419 | key: "build",
|
7420 | value: function build(type) {
|
7421 | for (var _len3 = arguments.length, traitsAndOverrides = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {
|
7422 | traitsAndOverrides[_key3 - 1] = arguments[_key3];
|
7423 | }
|
7424 |
|
7425 | var traits = traitsAndOverrides.filter(function (arg) {
|
7426 | return arg && typeof arg === "string";
|
7427 | });
|
7428 | var overrides = find(traitsAndOverrides, function (arg) {
|
7429 | return isPlainObject(arg);
|
7430 | });
|
7431 | var camelizedType = camelize(type);
|
7432 |
|
7433 | this.factorySequences = this.factorySequences || {};
|
7434 | this.factorySequences[camelizedType] = this.factorySequences[camelizedType] + 1 || 0;
|
7435 | var OriginalFactory = this.factoryFor(type);
|
7436 |
|
7437 | if (OriginalFactory) {
|
7438 | OriginalFactory = OriginalFactory.extend({});
|
7439 | var attrs = OriginalFactory.attrs || {};
|
7440 |
|
7441 | this._validateTraits(traits, OriginalFactory, type);
|
7442 |
|
7443 | var mergedExtensions = this._mergeExtensions(attrs, traits, overrides);
|
7444 |
|
7445 | this._mapAssociationsFromAttributes(type, attrs, overrides);
|
7446 |
|
7447 | this._mapAssociationsFromAttributes(type, mergedExtensions);
|
7448 |
|
7449 | var Factory = OriginalFactory.extend(mergedExtensions);
|
7450 | var factory = new Factory();
|
7451 | var sequence = this.factorySequences[camelizedType];
|
7452 | return factory.build(sequence);
|
7453 | } else {
|
7454 | return overrides;
|
7455 | }
|
7456 | }
|
7457 | }, {
|
7458 | key: "buildList",
|
7459 | value: function buildList(type, amount) {
|
7460 | assert(isInteger(amount), "second argument has to be an integer, you passed: ".concat(_typeof(amount)));
|
7461 | var list = [];
|
7462 |
|
7463 | for (var _len4 = arguments.length, traitsAndOverrides = new Array(_len4 > 2 ? _len4 - 2 : 0), _key4 = 2; _key4 < _len4; _key4++) {
|
7464 | traitsAndOverrides[_key4 - 2] = arguments[_key4];
|
7465 | }
|
7466 |
|
7467 | var buildArgs = [type].concat(traitsAndOverrides);
|
7468 |
|
7469 | for (var i = 0; i < amount; i++) {
|
7470 | list.push(this.build.apply(this, buildArgs));
|
7471 | }
|
7472 |
|
7473 | return list;
|
7474 | }
|
7475 | |
7476 |
|
7477 |
|
7478 |
|
7479 |
|
7480 |
|
7481 |
|
7482 |
|
7483 |
|
7484 |
|
7485 |
|
7486 |
|
7487 |
|
7488 |
|
7489 |
|
7490 |
|
7491 |
|
7492 |
|
7493 |
|
7494 |
|
7495 |
|
7496 |
|
7497 |
|
7498 |
|
7499 |
|
7500 |
|
7501 |
|
7502 |
|
7503 |
|
7504 |
|
7505 |
|
7506 |
|
7507 |
|
7508 |
|
7509 |
|
7510 | }, {
|
7511 | key: "create",
|
7512 | value: function create(type) {
|
7513 | var _this3 = this;
|
7514 |
|
7515 | assert(this._modelOrFactoryExistsForType(type), "You called server.create('".concat(type, "') but no model or factory was found. Make sure you're passing in the singularized version of the model or factory name."));
|
7516 |
|
7517 |
|
7518 | for (var _len5 = arguments.length, options = new Array(_len5 > 1 ? _len5 - 1 : 0), _key5 = 1; _key5 < _len5; _key5++) {
|
7519 | options[_key5 - 1] = arguments[_key5];
|
7520 | }
|
7521 |
|
7522 | var traits = options.filter(function (arg) {
|
7523 | return arg && typeof arg === "string";
|
7524 | });
|
7525 | var overrides = find(options, function (arg) {
|
7526 | return isPlainObject(arg);
|
7527 | });
|
7528 | var collectionFromCreateList = find(options, function (arg) {
|
7529 | return arg && Array.isArray(arg);
|
7530 | });
|
7531 | var attrs = this.build.apply(this, [type].concat(_toConsumableArray(traits), [overrides]));
|
7532 | var modelOrRecord;
|
7533 |
|
7534 | if (this.schema && this.schema[this.schema.toCollectionName(type)]) {
|
7535 | var modelClass = this.schema[this.schema.toCollectionName(type)];
|
7536 | modelOrRecord = modelClass.create(attrs);
|
7537 | } else {
|
7538 | var collection, collectionName;
|
7539 |
|
7540 | if (collectionFromCreateList) {
|
7541 | collection = collectionFromCreateList;
|
7542 | } else {
|
7543 | collectionName = this.schema ? this.schema.toInternalCollectionName(type) : "_".concat(this.inflector.pluralize(type));
|
7544 | collection = this.db[collectionName];
|
7545 | }
|
7546 |
|
7547 | assert(collection, "You called server.create('".concat(type, "') but no model or factory was found."));
|
7548 | modelOrRecord = collection.insert(attrs);
|
7549 | }
|
7550 |
|
7551 | var OriginalFactory = this.factoryFor(type);
|
7552 |
|
7553 | if (OriginalFactory) {
|
7554 | OriginalFactory.extractAfterCreateCallbacks({
|
7555 | traits: traits
|
7556 | }).forEach(function (afterCreate) {
|
7557 | afterCreate(modelOrRecord, _this3);
|
7558 | });
|
7559 | }
|
7560 |
|
7561 | return modelOrRecord;
|
7562 | }
|
7563 | |
7564 |
|
7565 |
|
7566 |
|
7567 |
|
7568 |
|
7569 |
|
7570 |
|
7571 |
|
7572 |
|
7573 |
|
7574 |
|
7575 |
|
7576 |
|
7577 |
|
7578 |
|
7579 |
|
7580 |
|
7581 |
|
7582 |
|
7583 |
|
7584 |
|
7585 |
|
7586 |
|
7587 |
|
7588 |
|
7589 |
|
7590 |
|
7591 |
|
7592 |
|
7593 |
|
7594 | }, {
|
7595 | key: "createList",
|
7596 | value: function createList(type, amount) {
|
7597 | assert(this._modelOrFactoryExistsForType(type), "You called server.createList('".concat(type, "') but no model or factory was found. Make sure you're passing in the singularized version of the model or factory name."));
|
7598 | assert(isInteger(amount), "second argument has to be an integer, you passed: ".concat(_typeof(amount)));
|
7599 | var list = [];
|
7600 | var collectionName = this.schema ? this.schema.toInternalCollectionName(type) : "_".concat(this.inflector.pluralize(type));
|
7601 | var collection = this.db[collectionName];
|
7602 |
|
7603 | for (var _len6 = arguments.length, traitsAndOverrides = new Array(_len6 > 2 ? _len6 - 2 : 0), _key6 = 2; _key6 < _len6; _key6++) {
|
7604 | traitsAndOverrides[_key6 - 2] = arguments[_key6];
|
7605 | }
|
7606 |
|
7607 | var createArguments = [type].concat(traitsAndOverrides, [collection]);
|
7608 |
|
7609 | for (var i = 0; i < amount; i++) {
|
7610 | list.push(this.create.apply(this, createArguments));
|
7611 | }
|
7612 |
|
7613 | return list;
|
7614 | }
|
7615 | |
7616 |
|
7617 |
|
7618 |
|
7619 |
|
7620 |
|
7621 | }, {
|
7622 | key: "shutdown",
|
7623 | value: function shutdown() {
|
7624 | if (typeof window !== "undefined") {
|
7625 | this.pretender.shutdown();
|
7626 | }
|
7627 |
|
7628 | if (typeof window !== "undefined" && this.environment === "test") {
|
7629 | window.server = undefined;
|
7630 | }
|
7631 | }
|
7632 | }, {
|
7633 | key: "resource",
|
7634 | value: function resource(resourceName) {
|
7635 | var _this4 = this;
|
7636 |
|
7637 | var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
|
7638 | only = _ref.only,
|
7639 | except = _ref.except,
|
7640 | path = _ref.path;
|
7641 |
|
7642 | resourceName = this.inflector.pluralize(resourceName);
|
7643 | path = path || "/".concat(resourceName);
|
7644 | only = only || [];
|
7645 | except = except || [];
|
7646 |
|
7647 | if (only.length > 0 && except.length > 0) {
|
7648 | throw "cannot use both :only and :except options";
|
7649 | }
|
7650 |
|
7651 | var actionsMethodsAndsPathsMappings = {
|
7652 | index: {
|
7653 | methods: ["get"],
|
7654 | path: "".concat(path)
|
7655 | },
|
7656 | show: {
|
7657 | methods: ["get"],
|
7658 | path: "".concat(path, "/:id")
|
7659 | },
|
7660 | create: {
|
7661 | methods: ["post"],
|
7662 | path: "".concat(path)
|
7663 | },
|
7664 | update: {
|
7665 | methods: ["put", "patch"],
|
7666 | path: "".concat(path, "/:id")
|
7667 | },
|
7668 | "delete": {
|
7669 | methods: ["del"],
|
7670 | path: "".concat(path, "/:id")
|
7671 | }
|
7672 | };
|
7673 | var allActions = Object.keys(actionsMethodsAndsPathsMappings);
|
7674 | var actions = only.length > 0 && only || except.length > 0 && allActions.filter(function (action) {
|
7675 | return except.indexOf(action) === -1;
|
7676 | }) || allActions;
|
7677 | actions.forEach(function (action) {
|
7678 | var methodsWithPath = actionsMethodsAndsPathsMappings[action];
|
7679 | methodsWithPath.methods.forEach(function (method) {
|
7680 | return path === resourceName ? _this4[method](methodsWithPath.path) : _this4[method](methodsWithPath.path, resourceName);
|
7681 | });
|
7682 | });
|
7683 | }
|
7684 | |
7685 |
|
7686 |
|
7687 |
|
7688 |
|
7689 |
|
7690 | }, {
|
7691 | key: "_defineRouteHandlerHelpers",
|
7692 | value: function _defineRouteHandlerHelpers() {
|
7693 | var _this5 = this;
|
7694 |
|
7695 | [["get"], ["post"], ["put"], ["delete", "del"], ["patch"], ["head"], ["options"]].forEach(function (_ref2) {
|
7696 | var _ref3 = _slicedToArray(_ref2, 2),
|
7697 | verb = _ref3[0],
|
7698 | alias = _ref3[1];
|
7699 |
|
7700 | _this5[verb] = function (path) {
|
7701 | for (var _len7 = arguments.length, args = new Array(_len7 > 1 ? _len7 - 1 : 0), _key7 = 1; _key7 < _len7; _key7++) {
|
7702 | args[_key7 - 1] = arguments[_key7];
|
7703 | }
|
7704 |
|
7705 | var _extractRouteArgument = extractRouteArguments(args),
|
7706 | _extractRouteArgument2 = _slicedToArray(_extractRouteArgument, 3),
|
7707 | rawHandler = _extractRouteArgument2[0],
|
7708 | customizedCode = _extractRouteArgument2[1],
|
7709 | options = _extractRouteArgument2[2];
|
7710 |
|
7711 | return _this5._registerRouteHandler(verb, path, rawHandler, customizedCode, options);
|
7712 | };
|
7713 |
|
7714 | if (alias) {
|
7715 | _this5[alias] = _this5[verb];
|
7716 | }
|
7717 | });
|
7718 | }
|
7719 | }, {
|
7720 | key: "_serialize",
|
7721 | value: function _serialize(body) {
|
7722 | if (typeof body === "string") {
|
7723 | return body;
|
7724 | } else {
|
7725 | return JSON.stringify(body);
|
7726 | }
|
7727 | }
|
7728 | }, {
|
7729 | key: "_registerRouteHandler",
|
7730 | value: function _registerRouteHandler(verb, path, rawHandler, customizedCode, options) {
|
7731 | var _this6 = this;
|
7732 |
|
7733 | var routeHandler = this._container.create("RouteHandler", {
|
7734 | schema: this.schema,
|
7735 | verb: verb,
|
7736 | rawHandler: rawHandler,
|
7737 | customizedCode: customizedCode,
|
7738 | options: options,
|
7739 | path: path,
|
7740 | serializerOrRegistry: this.serializerOrRegistry
|
7741 | });
|
7742 |
|
7743 | var fullPath = this._getFullPath(path);
|
7744 |
|
7745 | var timing = options.timing !== undefined ? options.timing : function () {
|
7746 | return _this6.timing;
|
7747 | };
|
7748 |
|
7749 | if (this.pretender) {
|
7750 | return this.pretender[verb](fullPath, function (request) {
|
7751 | return routeHandler.handle(request).then(function (mirageResponse) {
|
7752 | var _mirageResponse = _slicedToArray(mirageResponse, 3),
|
7753 | code = _mirageResponse[0],
|
7754 | headers = _mirageResponse[1],
|
7755 | response = _mirageResponse[2];
|
7756 |
|
7757 | return [code, headers, _this6._serialize(response)];
|
7758 | });
|
7759 | }, timing);
|
7760 | }
|
7761 | }
|
7762 | |
7763 |
|
7764 |
|
7765 |
|
7766 |
|
7767 |
|
7768 | }, {
|
7769 | key: "_hasModulesOfType",
|
7770 | value: function _hasModulesOfType(modules, type) {
|
7771 | var modulesOfType = modules[type];
|
7772 | return modulesOfType ? Object.keys(modulesOfType).length > 0 : false;
|
7773 | }
|
7774 | |
7775 |
|
7776 |
|
7777 |
|
7778 |
|
7779 |
|
7780 |
|
7781 |
|
7782 | }, {
|
7783 | key: "_getFullPath",
|
7784 | value: function _getFullPath(path) {
|
7785 | path = path[0] === "/" ? path.slice(1) : path;
|
7786 | var fullPath = "";
|
7787 | var urlPrefix = this.urlPrefix ? this.urlPrefix.trim() : "";
|
7788 | var namespace = "";
|
7789 |
|
7790 | if (this.urlPrefix && this.namespace) {
|
7791 | if (this.namespace[0] === "/" && this.namespace[this.namespace.length - 1] === "/") {
|
7792 | namespace = this.namespace.substring(0, this.namespace.length - 1).substring(1);
|
7793 | }
|
7794 |
|
7795 | if (this.namespace[0] === "/" && this.namespace[this.namespace.length - 1] !== "/") {
|
7796 | namespace = this.namespace.substring(1);
|
7797 | }
|
7798 |
|
7799 | if (this.namespace[0] !== "/" && this.namespace[this.namespace.length - 1] === "/") {
|
7800 | namespace = this.namespace.substring(0, this.namespace.length - 1);
|
7801 | }
|
7802 |
|
7803 | if (this.namespace[0] !== "/" && this.namespace[this.namespace.length - 1] !== "/") {
|
7804 | namespace = this.namespace;
|
7805 | }
|
7806 | }
|
7807 |
|
7808 |
|
7809 | if (this.namespace && !this.urlPrefix) {
|
7810 | if (this.namespace[0] === "/" && this.namespace[this.namespace.length - 1] === "/") {
|
7811 | namespace = this.namespace.substring(0, this.namespace.length - 1);
|
7812 | }
|
7813 |
|
7814 | if (this.namespace[0] === "/" && this.namespace[this.namespace.length - 1] !== "/") {
|
7815 | namespace = this.namespace;
|
7816 | }
|
7817 |
|
7818 | if (this.namespace[0] !== "/" && this.namespace[this.namespace.length - 1] === "/") {
|
7819 | var namespaceSub = this.namespace.substring(0, this.namespace.length - 1);
|
7820 | namespace = "/".concat(namespaceSub);
|
7821 | }
|
7822 |
|
7823 | if (this.namespace[0] !== "/" && this.namespace[this.namespace.length - 1] !== "/") {
|
7824 | namespace = "/".concat(this.namespace);
|
7825 | }
|
7826 | }
|
7827 |
|
7828 |
|
7829 | if (!this.namespace) {
|
7830 | namespace = "";
|
7831 | }
|
7832 |
|
7833 |
|
7834 | if (/^https?:\/\//.test(path)) {
|
7835 | fullPath += path;
|
7836 | } else {
|
7837 |
|
7838 | if (urlPrefix.length) {
|
7839 | fullPath += urlPrefix[urlPrefix.length - 1] === "/" ? urlPrefix : "".concat(urlPrefix, "/");
|
7840 | }
|
7841 |
|
7842 |
|
7843 | fullPath += namespace;
|
7844 |
|
7845 | if (fullPath[fullPath.length - 1] !== "/") {
|
7846 | fullPath += "/";
|
7847 | }
|
7848 |
|
7849 |
|
7850 | fullPath += path;
|
7851 |
|
7852 |
|
7853 | if (!/^https?:\/\//.test(fullPath)) {
|
7854 | fullPath = "/".concat(fullPath);
|
7855 | fullPath = fullPath.replace(/\/+/g, "/");
|
7856 | }
|
7857 | }
|
7858 |
|
7859 | return fullPath;
|
7860 | }
|
7861 | |
7862 |
|
7863 |
|
7864 |
|
7865 |
|
7866 |
|
7867 | }, {
|
7868 | key: "_configureDefaultPassthroughs",
|
7869 | value: function _configureDefaultPassthroughs() {
|
7870 | var _this7 = this;
|
7871 |
|
7872 | defaultPassthroughs.forEach(function (passthroughUrl) {
|
7873 | _this7.passthrough(passthroughUrl);
|
7874 | });
|
7875 | }
|
7876 | |
7877 |
|
7878 |
|
7879 |
|
7880 |
|
7881 |
|
7882 | }, {
|
7883 | key: "_typeIsPluralForModel",
|
7884 | value: function _typeIsPluralForModel(typeOrCollectionName) {
|
7885 | if (typeof isPluralForModelCache[typeOrCollectionName] !== "boolean") {
|
7886 | var modelOrFactoryExists = this._modelOrFactoryExistsForTypeOrCollectionName(typeOrCollectionName);
|
7887 |
|
7888 | var isPlural = typeOrCollectionName === this.inflector.pluralize(typeOrCollectionName);
|
7889 | var isUncountable = this.inflector.singularize(typeOrCollectionName) === this.inflector.pluralize(typeOrCollectionName);
|
7890 | var isPluralForModel = isPlural && !isUncountable && modelOrFactoryExists;
|
7891 | isPluralForModelCache[typeOrCollectionName] = isPluralForModel;
|
7892 | }
|
7893 |
|
7894 | return isPluralForModelCache[typeOrCollectionName];
|
7895 | }
|
7896 | |
7897 |
|
7898 |
|
7899 |
|
7900 |
|
7901 |
|
7902 | }, {
|
7903 | key: "_modelOrFactoryExistsForType",
|
7904 | value: function _modelOrFactoryExistsForType(type) {
|
7905 | var modelExists = this.schema && this.schema.modelFor(camelize(type));
|
7906 | var dbCollectionExists = this.db[this.schema.toInternalCollectionName(type)];
|
7907 | return (modelExists || dbCollectionExists) && !this._typeIsPluralForModel(type);
|
7908 | }
|
7909 | |
7910 |
|
7911 |
|
7912 |
|
7913 |
|
7914 |
|
7915 | }, {
|
7916 | key: "_modelOrFactoryExistsForTypeOrCollectionName",
|
7917 | value: function _modelOrFactoryExistsForTypeOrCollectionName(typeOrCollectionName) {
|
7918 | var modelExists = this.schema && this.schema.modelFor(camelize(typeOrCollectionName));
|
7919 | var dbCollectionExists = this.db[this.schema.toInternalCollectionName(typeOrCollectionName)];
|
7920 | return modelExists || dbCollectionExists;
|
7921 | }
|
7922 | |
7923 |
|
7924 |
|
7925 |
|
7926 |
|
7927 |
|
7928 | }, {
|
7929 | key: "_validateTraits",
|
7930 | value: function _validateTraits(traits, factory, type) {
|
7931 | traits.forEach(function (traitName) {
|
7932 | if (!factory.isTrait(traitName)) {
|
7933 | throw new Error("'".concat(traitName, "' trait is not registered in '").concat(type, "' factory"));
|
7934 | }
|
7935 | });
|
7936 | }
|
7937 | |
7938 |
|
7939 |
|
7940 |
|
7941 |
|
7942 |
|
7943 | }, {
|
7944 | key: "_mergeExtensions",
|
7945 | value: function _mergeExtensions(attrs, traits, overrides) {
|
7946 | var allExtensions = traits.map(function (traitName) {
|
7947 | return attrs[traitName].extension;
|
7948 | });
|
7949 | allExtensions.push(overrides || {});
|
7950 | return allExtensions.reduce(function (accum, extension) {
|
7951 | return assign(accum, extension);
|
7952 | }, {});
|
7953 | }
|
7954 | |
7955 |
|
7956 |
|
7957 |
|
7958 |
|
7959 |
|
7960 | }, {
|
7961 | key: "_mapAssociationsFromAttributes",
|
7962 | value: function _mapAssociationsFromAttributes(modelName, attributes) {
|
7963 | var _this8 = this;
|
7964 |
|
7965 | var overrides = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
|
7966 | Object.keys(attributes || {}).filter(function (attr) {
|
7967 | return isAssociation(attributes[attr]);
|
7968 | }).forEach(function (attr) {
|
7969 | var modelClass = _this8.schema.modelClassFor(modelName);
|
7970 |
|
7971 | var association = modelClass.associationFor(attr);
|
7972 | assert(association && association instanceof BelongsTo, "You're using the `association` factory helper on the '".concat(attr, "' attribute of your ").concat(modelName, " factory, but that attribute is not a `belongsTo` association."));
|
7973 | var isSelfReferentialBelongsTo = association && association instanceof BelongsTo && association.modelName === modelName;
|
7974 | assert(!isSelfReferentialBelongsTo, "You're using the association() helper on your ".concat(modelName, " factory for ").concat(attr, ", which is a belongsTo self-referential relationship. You can't do this as it will lead to infinite recursion. You can move the helper inside of a trait and use it selectively."));
|
7975 | var isPolymorphic = association && association.opts && association.opts.polymorphic;
|
7976 | assert(!isPolymorphic, "You're using the association() helper on your ".concat(modelName, " factory for ").concat(attr, ", which is a polymorphic relationship. This is not currently supported."));
|
7977 | var factoryAssociation = attributes[attr];
|
7978 | var foreignKey = "".concat(camelize(attr), "Id");
|
7979 |
|
7980 | if (!overrides[attr]) {
|
7981 | attributes[foreignKey] = _this8.create.apply(_this8, [association.modelName].concat(_toConsumableArray(factoryAssociation.traitsAndOverrides))).id;
|
7982 | }
|
7983 |
|
7984 | delete attributes[attr];
|
7985 | });
|
7986 | }
|
7987 | }]);
|
7988 |
|
7989 | return Server;
|
7990 | }();
|
7991 |
|
7992 | var ActiveModelSerializer = Serializer.extend({
|
7993 | serializeIds: "always",
|
7994 | normalizeIds: true,
|
7995 | keyForModel: function keyForModel(type) {
|
7996 | return underscore(type);
|
7997 | },
|
7998 | keyForAttribute: function keyForAttribute(attr) {
|
7999 | return underscore(attr);
|
8000 | },
|
8001 | keyForRelationship: function keyForRelationship(type) {
|
8002 | return this._container.inflector.pluralize(underscore(type));
|
8003 | },
|
8004 | keyForEmbeddedRelationship: function keyForEmbeddedRelationship(attributeName) {
|
8005 | return underscore(attributeName);
|
8006 | },
|
8007 | keyForRelationshipIds: function keyForRelationshipIds(type) {
|
8008 | return "".concat(underscore(this._container.inflector.singularize(type)), "_ids");
|
8009 | },
|
8010 | keyForForeignKey: function keyForForeignKey(relationshipName) {
|
8011 | return "".concat(underscore(relationshipName), "_id");
|
8012 | },
|
8013 | keyForPolymorphicForeignKeyId: function keyForPolymorphicForeignKeyId(relationshipName) {
|
8014 | return "".concat(underscore(relationshipName), "_id");
|
8015 | },
|
8016 | keyForPolymorphicForeignKeyType: function keyForPolymorphicForeignKeyType(relationshipName) {
|
8017 | return "".concat(underscore(relationshipName), "_type");
|
8018 | },
|
8019 | normalize: function normalize(payload) {
|
8020 | var _this = this;
|
8021 |
|
8022 | var type = Object.keys(payload)[0];
|
8023 | var attrs = payload[type];
|
8024 | var modelName = camelize(type);
|
8025 | var modelClass = this.schema.modelClassFor(modelName);
|
8026 | var belongsToAssociations = modelClass.belongsToAssociations,
|
8027 | hasManyAssociations = modelClass.hasManyAssociations;
|
8028 | var belongsToKeys = Object.keys(belongsToAssociations);
|
8029 | var hasManyKeys = Object.keys(hasManyAssociations);
|
8030 | var jsonApiPayload = {
|
8031 | data: {
|
8032 | type: this._container.inflector.pluralize(type),
|
8033 | attributes: {}
|
8034 | }
|
8035 | };
|
8036 |
|
8037 | if (attrs.id) {
|
8038 | jsonApiPayload.data.id = attrs.id;
|
8039 | }
|
8040 |
|
8041 | var relationships = {};
|
8042 | Object.keys(attrs).forEach(function (key) {
|
8043 | if (key !== "id") {
|
8044 | if (_this.normalizeIds) {
|
8045 | if (belongsToKeys.includes(key)) {
|
8046 | var association = belongsToAssociations[key];
|
8047 | var associationModel = association.modelName;
|
8048 | relationships[dasherize(key)] = {
|
8049 | data: {
|
8050 | type: associationModel,
|
8051 | id: attrs[key]
|
8052 | }
|
8053 | };
|
8054 | } else if (hasManyKeys.includes(key)) {
|
8055 | var _association = hasManyAssociations[key];
|
8056 | var _associationModel = _association.modelName;
|
8057 | var data = attrs[key].map(function (id) {
|
8058 | return {
|
8059 | type: _associationModel,
|
8060 | id: id
|
8061 | };
|
8062 | });
|
8063 | relationships[dasherize(key)] = {
|
8064 | data: data
|
8065 | };
|
8066 | } else {
|
8067 | jsonApiPayload.data.attributes[dasherize(key)] = attrs[key];
|
8068 | }
|
8069 | } else {
|
8070 | jsonApiPayload.data.attributes[dasherize(key)] = attrs[key];
|
8071 | }
|
8072 | }
|
8073 | });
|
8074 |
|
8075 | if (Object.keys(relationships).length) {
|
8076 | jsonApiPayload.data.relationships = relationships;
|
8077 | }
|
8078 |
|
8079 | return jsonApiPayload;
|
8080 | },
|
8081 | getCoalescedIds: function getCoalescedIds(request) {
|
8082 | return request.queryParams && request.queryParams.ids;
|
8083 | }
|
8084 | });
|
8085 |
|
8086 | var restSerializer = ActiveModelSerializer.extend({
|
8087 | serializeIds: "always",
|
8088 | keyForModel: function keyForModel(type) {
|
8089 | return camelize(type);
|
8090 | },
|
8091 | keyForAttribute: function keyForAttribute(attr) {
|
8092 | return camelize(attr);
|
8093 | },
|
8094 | keyForRelationship: function keyForRelationship(type) {
|
8095 | return camelize(this._container.inflector.pluralize(type));
|
8096 | },
|
8097 | keyForEmbeddedRelationship: function keyForEmbeddedRelationship(attributeName) {
|
8098 | return camelize(attributeName);
|
8099 | },
|
8100 | keyForRelationshipIds: function keyForRelationshipIds(type) {
|
8101 | return camelize(this._container.inflector.pluralize(type));
|
8102 | },
|
8103 | keyForForeignKey: function keyForForeignKey(relationshipName) {
|
8104 | return camelize(this._container.inflector.singularize(relationshipName));
|
8105 | },
|
8106 | getCoalescedIds: function getCoalescedIds(request) {
|
8107 | return request.queryParams && request.queryParams.ids;
|
8108 | }
|
8109 | });
|
8110 |
|
8111 |
|
8112 |
|
8113 |
|
8114 |
|
8115 |
|
8116 | function uuid () {
|
8117 | return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) {
|
8118 | var r = Math.random() * 16 | 0;
|
8119 | var v = c === "x" ? r : r & 0x3 | 0x8;
|
8120 | return v.toString(16);
|
8121 | });
|
8122 | }
|
8123 |
|
8124 |
|
8125 |
|
8126 |
|
8127 |
|
8128 | function hasMany() {
|
8129 | for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
|
8130 | args[_key] = arguments[_key];
|
8131 | }
|
8132 |
|
8133 | return _construct(HasMany, args);
|
8134 | }
|
8135 |
|
8136 |
|
8137 |
|
8138 |
|
8139 |
|
8140 | function belongsTo() {
|
8141 | for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
|
8142 | args[_key2] = arguments[_key2];
|
8143 | }
|
8144 |
|
8145 | return _construct(BelongsTo, args);
|
8146 | }
|
8147 | var index = {
|
8148 | Factory: Factory,
|
8149 | Response: Response,
|
8150 | hasMany: hasMany,
|
8151 | belongsTo: belongsTo
|
8152 | };
|
8153 |
|
8154 | export default index;
|
8155 | export { ActiveModelSerializer, Collection, Factory, IdentityManager, JSONAPISerializer, Model, Response, restSerializer as RestSerializer, Serializer, Server, Db as _Db, DbCollection as _DbCollection, RouteHandler as _RouteHandler, SerializerRegistry as _SerializerRegistry, assert as _assert, Association as _ormAssociationsAssociation, BelongsTo as _ormAssociationsBelongsTo, HasMany as _ormAssociationsHasMany, PolymorphicCollection as _ormPolymorphicCollection, Schema as _ormSchema, BaseRouteHandler as _routeHandlersBase, FunctionRouteHandler as _routeHandlersFunction, ObjectRouteHandler as _routeHandlersObject, BaseShorthandRouteHandler as _routeHandlersShorthandsBase, DeleteShorthandRouteHandler as _routeHandlersShorthandsDelete, GetShorthandRouteHandler as _routeHandlersShorthandsGet, HeadShorthandRouteHandler as _routeHandlersShorthandsHead, PostShorthandRouteHandler as _routeHandlersShorthandsPost, PutShorthandRouteHandler as _routeHandlersShorthandsPut, extend as _utilsExtend, camelize as _utilsInflectorCamelize, capitalize as _utilsInflectorCapitalize, dasherize as _utilsInflectorDasherize, underscore as _utilsInflectorUnderscore, isAssociation as _utilsIsAssociation, referenceSort as _utilsReferenceSort, uuid as _utilsUuid, association, belongsTo, defaultPassthroughs, hasMany, trait };
|
8156 |
|