1 |
|
2 |
|
3 |
|
4 |
|
5 | 'use strict';
|
6 |
|
7 | const _ = require('lodash');
|
8 | const tc = require('colorette');
|
9 |
|
10 | module.exports = {
|
11 |
|
12 | saveConstraints: function(model, relatedData) {
|
13 | const data = {};
|
14 |
|
15 | if (
|
16 | relatedData &&
|
17 | !relatedData.isThrough() &&
|
18 | relatedData.type !== 'belongsToMany' &&
|
19 | relatedData.type !== 'belongsTo'
|
20 | ) {
|
21 | data[relatedData.key('foreignKey')] = relatedData.parentFk || model.get(relatedData.key('foreignKey'));
|
22 | if (relatedData.isMorph()) data[relatedData.key('morphKey')] = relatedData.key('morphValue');
|
23 | }
|
24 |
|
25 | return model.set(model.parse(data));
|
26 | },
|
27 |
|
28 |
|
29 |
|
30 | morphCandidate: function(candidates, morphValue) {
|
31 | const Target = _.find(candidates, (candidate) => candidate[1] === morphValue);
|
32 |
|
33 | if (!Target)
|
34 | throw new Error('The target polymorphic type "' + morphValue + '" is not one of the defined target types');
|
35 |
|
36 | return Target[0];
|
37 | },
|
38 |
|
39 |
|
40 |
|
41 |
|
42 |
|
43 |
|
44 | query: function(obj, args) {
|
45 |
|
46 | if (!obj._knex) {
|
47 | const tableName = _.result(obj, 'tableName');
|
48 | obj._knex = obj._builder(tableName);
|
49 | }
|
50 |
|
51 |
|
52 | if (args.length === 0) return obj._knex;
|
53 |
|
54 | const method = args[0];
|
55 |
|
56 | if (_.isFunction(method)) {
|
57 |
|
58 | method.call(obj._knex, obj._knex);
|
59 | } else if (_.isObject(method)) {
|
60 |
|
61 |
|
62 | for (const key in method) {
|
63 | const target = Array.isArray(method[key]) ? method[key] : [method[key]];
|
64 | obj._knex[key].apply(obj._knex, target);
|
65 | }
|
66 | } else {
|
67 |
|
68 |
|
69 | obj._knex[method].apply(obj._knex, args.slice(1));
|
70 | }
|
71 |
|
72 | return obj;
|
73 | },
|
74 |
|
75 | warn: function(msg) {
|
76 | console.log(tc.yellow(msg));
|
77 | },
|
78 |
|
79 | deprecate: function(a, b) {
|
80 | this.warn(a + ' has been deprecated, please use ' + b + ' instead');
|
81 | },
|
82 |
|
83 | orderBy: function(obj, sort, order) {
|
84 | let tableName;
|
85 | let idAttribute;
|
86 | let _sort;
|
87 |
|
88 | if (obj.model) {
|
89 | tableName = obj.model.prototype.tableName;
|
90 | idAttribute = obj.model.prototype.idAttribute || 'id';
|
91 | } else {
|
92 | tableName = obj.constructor.prototype.tableName;
|
93 | idAttribute = obj.constructor.prototype.idAttribute || 'id';
|
94 | }
|
95 |
|
96 | if (sort && sort.indexOf('-') === 0) {
|
97 | _sort = sort.slice(1);
|
98 | } else if (sort) {
|
99 | _sort = sort;
|
100 | } else {
|
101 | _sort = idAttribute;
|
102 | }
|
103 |
|
104 | const _order = order || (sort && sort.indexOf('-') === 0 ? 'DESC' : 'ASC');
|
105 |
|
106 | if (_sort.indexOf('.') === -1) {
|
107 | _sort = `${tableName}.${_sort}`;
|
108 | }
|
109 |
|
110 | return obj.query((qb) => {
|
111 | qb.orderBy(_sort, _order);
|
112 | });
|
113 | }
|
114 | };
|