-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathdata-object-tag.js
More file actions
418 lines (393 loc) · 13.9 KB
/
data-object-tag.js
File metadata and controls
418 lines (393 loc) · 13.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
// MOST Web Framework 2.0 Codename Blueshift BSD-3-Clause license Copyright (c) 2017-2022, THEMOST LP All rights reserved
/*eslint no-var: "off"*/
// noinspection ES6ConvertVarToLetConst
var {LangUtils, DataError, Args} = require('@themost/common');
var {DataConfigurationStrategy} = require('./data-configuration');
var {QueryField} = require('@themost/query');
var _ = require('lodash');
var { DataAssociationMapping } = require('./types');
var {DataObjectJunction} = require('./data-object-junction');
var {DataQueryable} = require('./data-queryable');
var {isObjectDeep} = require('./is-object');
/**
* @class
* @constructor
* @augments DataQueryable
* @param {DataObject} obj An object which represents the parent data object
* @param {String|*} association A string that represents the name of the field which holds association mapping or the association mapping itself.
* @property {DataModel} baseModel - The model associated with this data object junction
* @property {DataObject} parent - Gets or sets the parent data object associated with this instance of DataObjectTag class.
* @property {DataAssociationMapping} mapping - Gets or sets the mapping definition of this data object association.
*/
function DataObjectTag(obj, association) {
/**
* @property parent
* @memberOf DataObjectTag
* @type {DataObject}
*/
/**
* @type {DataObject}
* @private
*/
var _parent = obj;
var model;
var DataModel = require('./data-model').DataModel;
Object.defineProperty(this, 'parent', { get: function () {
return _parent;
}, set: function (value) {
_parent = value;
}, configurable: false, enumerable: false});
var self = this;
if (typeof association === 'string') {
//infer mapping from field name
//set relation mapping
if (self.parent != null) {
model = self.parent.getModel();
if (model != null)
self.mapping = model.inferMapping(association);
}
} else if (isObjectDeep(association)) {
//get the specified mapping
if (association instanceof DataAssociationMapping) {
self.mapping = association;
} else {
self.mapping = _.assign(new DataAssociationMapping(), association);
}
}
Args.check(self.mapping != null, new DataError('E_MAPPING', 'DataObjectTag.mapping cannot be empty at this context', null))
//validate mapping
var _baseModel;
Object.defineProperty(this, 'baseModel', {
get: function() {
if (_baseModel)
return _baseModel;
//get parent context
var context = self.parent.context;
/**
* @type {DataConfigurationStrategy}
*/
var strategy = context.getConfiguration().getStrategy(DataConfigurationStrategy);
var definition = strategy.getModelDefinition(self.mapping.associationAdapter);
if (_.isNil(definition)) {
var associationObjectField = self.mapping.associationObjectField || DataObjectTag.DEFAULT_OBJECT_FIELD;
var associationValueField = self.mapping.associationValueField || DataObjectTag.DEFAULT_VALUE_FIELD;
var parentModel = self.parent.getModel();
// get value type
var refersTo = context.model(self.mapping.parentModel).getAttribute(self.mapping.refersTo);
var refersToType = (refersTo && refersTo.type) || 'Text';
var objectFieldType = self.mapping.parentModel;
definition = {
'name': self.mapping.associationAdapter,
'hidden': true,
'source': self.mapping.associationAdapter,
'view': self.mapping.associationAdapter,
'version': '1.0',
'fields': [
{
'name': 'id',
'type': 'Counter',
'nullable': false,
'primary': true
},
{
'name': associationObjectField,
'type': objectFieldType,
'nullable': false,
'editable': false,
'many': false,
'indexed': true
},
{
'name': associationValueField,
'type': refersToType,
'nullable': false,
'many': false,
'indexed': false
}
],
'constraints': [
{ 'type':'unique', 'fields': [ associationObjectField, associationValueField ] }
],
'privileges': self.mapping.privileges || [
{
'mask': 15,
'type': 'global'
},
{
'mask': 15,
'type': 'global',
'account': 'Administrators'
}
]
};
if (refersTo.size) {
var attribute = definition.fields.find(function(item) {
return item.name === associationValueField;
});
if (attribute) {
Object.assign(attribute, {
size: refersTo.size
});
}
}
strategy.setModelDefinition(definition);
}
_baseModel = new DataModel(definition);
_baseModel.context = self.parent.context;
return _baseModel;
},configurable:false, enumerable:false
});
/**
* Gets an instance of DataModel class which represents the data adapter of this association
* @returns {DataModel}
*/
this.getBaseModel = function() {
return this.baseModel;
};
// call super class constructor
DataObjectTag.super_.call(this, self.getBaseModel());
// add select
this.select(this.getValueField()).asArray();
// modify query (add join parent model)
var left = {}, right = {};
// get parent adapter
var parentAdapter = self.parent.getModel().viewAdapter;
// set left operand of native join expression
left[ parentAdapter ] = [ this.mapping.parentField ];
// set right operand of native join expression
right[this.mapping.associationAdapter] = [ QueryField.select(this.getObjectField()).from(this.mapping.associationAdapter).$name ];
var field1 = QueryField.select(this.getObjectField()).from(this.mapping.associationAdapter).$name;
// apply join expression
this.query.join(parentAdapter, []).with([left, right]).where(field1).equal(obj[this.mapping.parentField]).prepare(false);
}
LangUtils.inherits(DataObjectTag, DataQueryable);
DataObjectTag.DEFAULT_OBJECT_FIELD = 'object';
DataObjectTag.DEFAULT_VALUE_FIELD = 'value';
/**
* @returns {string}
*/
DataObjectTag.prototype.getObjectField = function() {
return DataObjectJunction.prototype.getObjectField.bind(this)();
};
/**
* @returns {string}
*/
DataObjectTag.prototype.getValueField = function() {
return DataObjectJunction.prototype.getValueField.bind(this)();
};
/**
* Migrates the underlying data association adapter.
* @param callback - A callback function where the first argument will contain the Error object if an error occurred, or null otherwise.
*/
DataObjectTag.prototype.migrate = function(callback) {
this.getBaseModel().migrate(callback);
};
/**
* @return Promise<void>
*/
DataObjectTag.prototype.migrateAsync = function () {
var self = this;
return new Promise(function(resolve, reject) {
self.migrate(function (err) {
if (err) {
return reject(err);
}
return resolve();
});
});
}
/**
* Overrides DataQueryable.count() method
* @param callback - A callback function where the first argument will contain the Error object if an error occurred, or null otherwise.
* @ignore
*/
DataObjectTag.prototype.count = function(callback) {
var self = this;
if (typeof callback === 'undefined') {
return new Promise(function(resolve, reject) {
return self.migrate(function(err) {
if (err) {
return reject(err);
}
// noinspection JSPotentiallyInvalidConstructorUsage
var superCount = DataObjectTag.super_.prototype.count.bind(self);
return superCount().then(function(result) {
return resolve(result);
}).catch(function(err) {
return reject(err);
});
});
});
}
return self.migrate(function(err) {
if (err) {
return callback(err);
}
// noinspection JSPotentiallyInvalidConstructorUsage
var superCount = DataObjectTag.super_.prototype.count.bind(self);
return superCount(callback);
});
};
/**
* Overrides DataQueryable.execute() method
* @param callback - A callback function where the first argument will contain the Error object if an error occurred, or null otherwise.
* @ignore
*/
DataObjectTag.prototype.execute = function(callback) {
var self = this;
self.migrate(function(err) {
if (err) { return callback(err); }
// noinspection JSPotentiallyInvalidConstructorUsage
DataObjectTag.super_.prototype.execute.bind(self)(callback);
});
};
/**
* @this DataObjectTag
* @param obj
* @param callback
* @private
*/
function _insert(obj, callback) {
var self = this;
var values = Array.isArray(obj) ? obj : [ obj ];
self.migrate(function(err) {
if (err) {
return callback(err);
}
// get object field name
var objectField = self.getObjectField();
// get value field name
var valueField = self.getValueField();
// map the given items
var items = _.map(_.filter(values, function(x) {
return !_.isNil(x);
}), function (x) {
var res = {};
res[objectField] = self.parent[self.mapping.parentField];
res[valueField] = x;
return res;
});
var silentMode = self.isSilent();
// and finally save items
return self.getBaseModel().silent(silentMode).save(items).then(function() {
return callback();
}).catch(function(err) {
return callback(err);
});
});
}
/**
* Inserts an array of values
* @param {*} item
* @param {Function=} callback
*/
DataObjectTag.prototype.insert = function(item, callback) {
var self = this;
if (typeof callback === 'undefined') {
return new Promise(function (resolve, reject) {
return _insert.bind(self)(item, function(err) {
if (err) {
return reject(err);
}
return resolve();
});
});
}
return _insert.call(self, item, callback);
};
/**
* @this DataObjectTag
* @param callback
* @private
*/
function _removeAll(callback) {
var self = this;
return self.migrateAsync().then(function() {
var silentMode = self.isSilent();
var objectField = self.getObjectField();
return self.getBaseModel().silent(silentMode)
.where(objectField).equal(self.parent[self.mapping.parentField])
.select('id')
.getAllItems().then(function(result) {
if (result.length === 0) {
return Promise.resolve();
}
return self.getBaseModel().remove(result);
});
}).then(function() {
return callback();
}).catch(function(err) {
return callback(err);
});
}
/**
* Removes all values
* @param {Function=} callback
* @returns Promise<T>|*
*/
DataObjectTag.prototype.removeAll = function(callback) {
var self = this;
if (typeof callback !== 'function') {
return new Promise(function (resolve, reject) {
return _removeAll.bind(self)(function(err) {
if (err) { return reject(err); }
return resolve();
});
});
}
else {
return _removeAll.call(self, callback);
}
};
/**
* @this DataObjectTag
* @param {*} obj
* @param {Function} callback
* @private
*/
function _remove(obj, callback) {
var self = this;
var values = Array.isArray(obj) ? obj : [ obj ];
self.migrate(function(err) {
if (err) {
return callback(err);
}
// get object field name
var objectField = self.getObjectField();
// get value field name
var valueField = self.getValueField();
var items = _.map(_.filter(values, function(x) {
return !_.isNil(x);
}), function (x) {
var res = {};
res[objectField] = self.parent[self.mapping.parentField];
res[valueField] = x;
return res;
});
var silentMode = self.isSilent();
return self.getBaseModel().silent(silentMode).remove(items, callback);
});
}
/**
* Removes a value or an array of values
* @param {Array|*} item
* @param {Function=} callback
* @returns Promise<T>|*
*/
DataObjectTag.prototype.remove = function(item, callback) {
var self = this;
if (typeof callback !== 'function') {
return new Promise(function (resolve, reject) {
return _remove.bind(self)(item, function(err) {
if (err) {
return reject(err);
}
return resolve();
});
});
}
return _remove.call(self, item, callback);
};
module.exports = {
DataObjectTag
};