UNPKG

32.8 kBJavaScriptView Raw
1// Copyright IBM Corp. 2013,2019. All Rights Reserved.
2// Node module: loopback-datasource-juggler
3// This file is licensed under the MIT License.
4// License text available at https://opensource.org/licenses/MIT
5
6'use strict';
7
8/*!
9 * Module dependencies
10 */
11
12const g = require('strong-globalize')();
13const inflection = require('inflection');
14const EventEmitter = require('events').EventEmitter;
15const util = require('util');
16const assert = require('assert');
17const deprecated = require('depd')('loopback-datasource-juggler');
18const DefaultModelBaseClass = require('./model.js');
19const List = require('./list.js');
20const ModelDefinition = require('./model-definition.js');
21const MixinProvider = require('./mixins');
22const {
23 deepMerge,
24 deepMergeProperty,
25 rankArrayElements,
26 isClass,
27 applyParentProperty,
28} = require('./utils');
29
30// Set up types
31require('./types')(ModelBuilder);
32
33const introspect = require('./introspection')(ModelBuilder);
34
35/*!
36 * Export public API
37 */
38exports.ModelBuilder = exports.Schema = ModelBuilder;
39
40/*!
41 * Helpers
42 */
43const slice = Array.prototype.slice;
44
45/**
46 * ModelBuilder - A builder to define data models.
47 *
48 * @property {Object} definitions Definitions of the models.
49 * @property {Object} models Model constructors
50 * @class
51 */
52function ModelBuilder() {
53 // create blank models pool
54 this.models = {};
55 this.definitions = {};
56 this.settings = {};
57 this.mixins = new MixinProvider(this);
58 this.defaultModelBaseClass = DefaultModelBaseClass;
59}
60
61// Inherit from EventEmitter
62util.inherits(ModelBuilder, EventEmitter);
63
64// Create a default instance
65ModelBuilder.defaultInstance = new ModelBuilder();
66
67function isModelClass(cls) {
68 if (!cls) {
69 return false;
70 }
71 return cls.prototype instanceof DefaultModelBaseClass;
72}
73
74/**
75 * Get a model by name.
76 *
77 * @param {String} name The model name
78 * @param {Boolean} forceCreate Whether the create a stub for the given name if a model doesn't exist.
79 * @returns {ModelClass} The model class
80 */
81ModelBuilder.prototype.getModel = function(name, forceCreate) {
82 let model = this.models[name];
83 if (!model && forceCreate) {
84 model = this.define(name, {}, {unresolved: true});
85 }
86 return model;
87};
88
89/**
90 * Get the model definition by name
91 * @param {String} name The model name
92 * @returns {ModelDefinition} The model definition
93 */
94ModelBuilder.prototype.getModelDefinition = function(name) {
95 return this.definitions[name];
96};
97
98/**
99 * Define a model class.
100 * Simple example:
101 * ```
102 * var User = modelBuilder.define('User', {
103 * email: String,
104 * password: String,
105 * birthDate: Date,
106 * activated: Boolean
107 * });
108 * ```
109 * More advanced example:
110 * ```
111 * var User = modelBuilder.define('User', {
112 * email: { type: String, limit: 150, index: true },
113 * password: { type: String, limit: 50 },
114 * birthDate: Date,
115 * registrationDate: {type: Date, default: function () { return new Date }},
116 * activated: { type: Boolean, default: false }
117 * });
118 * ```
119 *
120 * @param {String} className Name of class
121 * @param {Object} properties Hash of class properties in format `{property: Type, property2: Type2, ...}` or `{property: {type: Type}, property2: {type: Type2}, ...}`
122 * @param {Object} settings Other configuration of class
123 * @param {Function} parent Parent model
124 * @return {ModelClass} The class constructor.
125 *
126 */
127ModelBuilder.prototype.define = function defineClass(className, properties, settings, parent) {
128 const modelBuilder = this;
129 const args = slice.call(arguments);
130 const pluralName = (settings && settings.plural) ||
131 inflection.pluralize(className);
132
133 const httpOptions = (settings && settings.http) || {};
134 let pathName = httpOptions.path || pluralName;
135
136 if (!className) {
137 throw new Error(g.f('Class name required'));
138 }
139 if (args.length === 1) {
140 properties = {};
141 args.push(properties);
142 }
143 if (args.length === 2) {
144 settings = {};
145 args.push(settings);
146 }
147
148 properties = properties || {};
149 settings = settings || {};
150
151 // Set the strict mode to be false by default
152 if (settings.strict === undefined || settings.strict === null) {
153 settings.strict = false;
154 }
155
156 // Set up the base model class
157 let ModelBaseClass = parent || this.defaultModelBaseClass;
158 const baseClass = settings.base || settings['super'];
159 if (baseClass) {
160 // Normalize base model property
161 settings.base = baseClass;
162 delete settings['super'];
163
164 if (isModelClass(baseClass)) {
165 ModelBaseClass = baseClass;
166 } else {
167 ModelBaseClass = this.models[baseClass];
168 assert(ModelBaseClass, 'Base model is not found: ' + baseClass);
169 }
170 }
171
172 // Assert current model's base class provides method `getMergePolicy()`.
173 assert(ModelBaseClass.getMergePolicy, `Base class ${ModelBaseClass.modelName}
174 does not provide method getMergePolicy(). Most likely it is not inheriting
175 from datasource-juggler's built-in default ModelBaseClass, which is an
176 incorrect usage of the framework.`);
177
178 // Initialize base model inheritance rank if not set already
179 ModelBaseClass.__rank = ModelBaseClass.__rank || 1;
180
181 // Make sure base properties are inherited
182 // See https://github.com/strongloop/loopback-datasource-juggler/issues/293
183 if ((parent && !settings.base) || (!parent && settings.base)) {
184 return ModelBaseClass.extend(className, properties, settings);
185 }
186
187 // Check if there is a unresolved model with the same name
188 let ModelClass = this.models[className];
189
190 // Create the ModelClass if it doesn't exist or it's resolved (override)
191 // TODO: [rfeng] We need to decide what names to use for built-in models such as User.
192 if (!ModelClass || !ModelClass.settings.unresolved) {
193 ModelClass = createModelClassCtor(className, ModelBaseClass);
194
195 // mix in EventEmitter (don't inherit from)
196 const events = new EventEmitter();
197 // The model can have more than 10 listeners for lazy relationship setup
198 // See https://github.com/strongloop/loopback/issues/404
199 events.setMaxListeners(32);
200 for (const f in EventEmitter.prototype) {
201 if (typeof EventEmitter.prototype[f] === 'function') {
202 ModelClass[f] = EventEmitter.prototype[f].bind(events);
203 }
204 }
205 hiddenProperty(ModelClass, 'modelName', className);
206 }
207
208 // Iterate sub model inheritance rank over base model rank
209 ModelClass.__rank = ModelBaseClass.__rank + 1;
210
211 util.inherits(ModelClass, ModelBaseClass);
212
213 // store class in model pool
214 this.models[className] = ModelClass;
215
216 // Return the unresolved model
217 if (settings.unresolved) {
218 ModelClass.settings = {unresolved: true};
219 return ModelClass;
220 }
221
222 // Add metadata to the ModelClass
223 hiddenProperty(ModelClass, 'modelBuilder', modelBuilder);
224 hiddenProperty(ModelClass, 'dataSource', null); // Keep for back-compatibility
225 hiddenProperty(ModelClass, 'pluralModelName', pluralName);
226 hiddenProperty(ModelClass, 'relations', {});
227 if (pathName[0] !== '/') {
228 // Support both flavors path: 'x' and path: '/x'
229 pathName = '/' + pathName;
230 }
231 hiddenProperty(ModelClass, 'http', {path: pathName});
232 hiddenProperty(ModelClass, 'base', ModelBaseClass);
233 hiddenProperty(ModelClass, '_observers', {});
234 hiddenProperty(ModelClass, '_warned', {});
235
236 // inherit ModelBaseClass static methods
237 for (const i in ModelBaseClass) {
238 // We need to skip properties that are already in the subclass, for example, the event emitter methods
239 if (i !== '_mixins' && !(i in ModelClass)) {
240 ModelClass[i] = ModelBaseClass[i];
241 }
242 }
243
244 // Load and inject the model classes
245 if (settings.models) {
246 Object.keys(settings.models).forEach(function(m) {
247 const model = settings.models[m];
248 ModelClass[m] = typeof model === 'string' ? modelBuilder.getModel(model, true) : model;
249 });
250 }
251
252 ModelClass.getter = {};
253 ModelClass.setter = {};
254
255 for (const p in properties) {
256 // e.g excludePropertyList = ['id'] - base properties listed in excludePropertyList will be excluded from the model.
257 // excludeBaseProperties is introduced in SOAP model generation only for now and below logic
258 // handles excludeBaseProperties. Generated SOAP model has base as 'Model' which means 'id' property gets added
259 // automatically and 'id' property shouldn't be there for SOAP models. idInjection = false will not work
260 // for SOAP generator case, since base 'Model' has already id property. 'id: false' at the property level will not
261 // work either for SOAP generator case since generators use ModelDefinition.create to create property in the model
262 // dynamically, that execution path has strict validation where doesn't accept 'id: false' in a property.
263 // See https://github.com/strongloop/loopback-workspace/issues/486 for some more details.
264 const excludePropertyList = settings['excludeBaseProperties'];
265 // Remove properties that reverted by the subclass of the property from excludePropertyList
266 if (properties[p] === null || properties[p] === false ||
267 (excludePropertyList != null && excludePropertyList.indexOf(p) != -1)) {
268 // Hide the base property
269 delete properties[p];
270 }
271
272 // Throw error for properties with unsupported names
273 if (/\./.test(p)) {
274 throw new Error(g.f('Property names containing dot(s) are not supported. ' +
275 'Model: %s, property: %s', className, p));
276 }
277
278 // Warn if property name is 'constructor'
279 if (p === 'constructor') {
280 deprecated(g.f('Property name should not be "{{constructor}}" in Model: %s', className));
281 }
282 }
283
284 const modelDefinition = new ModelDefinition(this, className, properties, settings);
285
286 this.definitions[className] = modelDefinition;
287
288 // expose properties on the ModelClass
289 ModelClass.definition = modelDefinition;
290 // keep a pointer to settings as models can use it for configuration
291 ModelClass.settings = modelDefinition.settings;
292
293 let idInjection = settings.idInjection;
294 if (idInjection !== false) {
295 // Default to true if undefined
296 idInjection = true;
297 }
298
299 let idNames = modelDefinition.idNames();
300 if (idNames.length > 0) {
301 // id already exists
302 idInjection = false;
303 }
304
305 // Add the id property
306 if (idInjection) {
307 // Set up the id property
308 ModelClass.definition.defineProperty('id', {type: Number, id: 1, generated: true});
309 }
310
311 idNames = modelDefinition.idNames(); // Reload it after rebuild
312 // Create a virtual property 'id'
313 if (idNames.length === 1) {
314 const idProp = idNames[0];
315 if (idProp !== 'id') {
316 Object.defineProperty(ModelClass.prototype, 'id', {
317 get: function() {
318 const idProp = ModelClass.definition.idNames()[0];
319 return this.__data[idProp];
320 },
321 configurable: true,
322 enumerable: false,
323 });
324 }
325 } else {
326 // Now the id property is an object that consists of multiple keys
327 Object.defineProperty(ModelClass.prototype, 'id', {
328 get: function() {
329 const compositeId = {};
330 const idNames = ModelClass.definition.idNames();
331 for (let i = 0, p; i < idNames.length; i++) {
332 p = idNames[i];
333 compositeId[p] = this.__data[p];
334 }
335 return compositeId;
336 },
337 configurable: true,
338 enumerable: false,
339 });
340 }
341
342 // updateOnly property is added to indicate that this property will appear in
343 // the model for update/updateorcreate operations but and not for create operation.
344 let forceId = ModelClass.settings.forceId;
345 if (idNames.length > 0) {
346 const idName = modelDefinition.idName();
347 const idProp = ModelClass.definition.rawProperties[idName];
348 if (idProp.generated && forceId !== false) {
349 forceId = 'auto';
350 } else if (!idProp.generated && forceId === 'auto') {
351 // One of our parent models has enabled forceId because
352 // it uses an auto-generated id property. However,
353 // this particular model does not use auto-generated id,
354 // therefore we need to disable `forceId`.
355 forceId = false;
356 }
357
358 if (forceId) {
359 ModelClass.validatesAbsenceOf(idName, {if: 'isNewRecord'});
360 }
361
362 ModelClass.definition.properties[idName].updateOnly = !!forceId;
363 ModelClass.definition.rawProperties[idName].updateOnly = !!forceId;
364
365 ModelClass.settings.forceId = forceId;
366 }
367
368 // A function to loop through the properties
369 ModelClass.forEachProperty = function(cb) {
370 const props = ModelClass.definition.properties;
371 const keys = Object.keys(props);
372 for (let i = 0, n = keys.length; i < n; i++) {
373 cb(keys[i], props[keys[i]]);
374 }
375 };
376
377 // A function to attach the model class to a data source
378 ModelClass.attachTo = function(dataSource) {
379 dataSource.attach(this);
380 };
381
382 /** Extend the model with the specified model, properties, and other settings.
383 * For example, to extend an existing model, for example, a built-in model:
384 *
385 * ```js
386 * var Customer = User.extend('customer', {
387 * accountId: String,
388 * vip: Boolean
389 * });
390 * ```
391 *
392 * To extend the base model, essentially creating a new model:
393 * ```js
394 * var user = loopback.Model.extend('user', properties, options);
395 * ```
396 *
397 * @param {String} className Name of the new model being defined.
398 * @options {Object} subClassProperties child model properties, added to base model
399 * properties.
400 * @options {Object} subClassSettings child model settings such as relations and acls,
401 * merged with base model settings.
402 */
403 ModelClass.extend = function(className, subClassProperties, subClassSettings) {
404 const baseClassProperties = ModelClass.definition.properties;
405 const baseClassSettings = ModelClass.definition.settings;
406
407 subClassProperties = subClassProperties || {};
408 subClassSettings = subClassSettings || {};
409
410 // Check if subclass redefines the ids
411 let idFound = false;
412 for (const k in subClassProperties) {
413 if (subClassProperties[k] && subClassProperties[k].id) {
414 idFound = true;
415 break;
416 }
417 }
418
419 // Merging the properties
420 const keys = Object.keys(baseClassProperties);
421 for (let i = 0, n = keys.length; i < n; i++) {
422 const key = keys[i];
423
424 if (idFound && baseClassProperties[key].id) {
425 // don't inherit id properties
426 continue;
427 }
428 if (subClassProperties[key] === undefined) {
429 const baseProp = baseClassProperties[key];
430 let basePropCopy = baseProp;
431 if (baseProp && typeof baseProp === 'object') {
432 // Deep clone the base properties
433 basePropCopy = deepMerge(baseProp);
434 }
435 subClassProperties[key] = basePropCopy;
436 }
437 }
438
439 // Merging the settings
440 const originalSubclassSettings = subClassSettings;
441 const mergePolicy = ModelClass.getMergePolicy(subClassSettings);
442 subClassSettings = mergeSettings(baseClassSettings, subClassSettings, mergePolicy);
443
444 // Ensure 'base' is not inherited. Note we don't have to delete 'super'
445 // as that is removed from settings by modelBuilder.define and thus
446 // it is never inherited
447 if (!originalSubclassSettings.base) {
448 subClassSettings.base = ModelClass;
449 }
450
451 // Define the subclass
452 const subClass = modelBuilder.define(className, subClassProperties, subClassSettings, ModelClass);
453
454 // Calling the setup function
455 if (typeof subClass.setup === 'function') {
456 subClass.setup.call(subClass);
457 }
458
459 return subClass;
460 };
461
462 /*
463 * Merge parent and child model settings according to the provided merge policy.
464 *
465 * Below is presented the expected merge behaviour for each option of the policy.
466 * NOTE: This applies to top-level settings properties
467 *
468 * - Any
469 * - `{replace: true}` (default): child replaces the value from parent
470 * - assigning `null` on child setting deletes the inherited setting
471 *
472 * - Arrays:
473 * - `{replace: false}`: unique elements of parent and child cumulate
474 * - `{rank: true}` adds the model inheritance rank to array
475 * elements of type Object {} as internal property `__rank`
476 *
477 * - Object {}:
478 * - `{replace: false}`: deep merges parent and child objects
479 * - `{patch: true}`: child replaces inner properties from parent
480 *
481 * Here is an example of merge policy:
482 * ```
483 * {
484 * description: {replace: true}, // string or array
485 * properties: {patch: true}, // object
486 * hidden: {replace: false}, // array
487 * protected: {replace: false}, // array
488 * relations: {acls: true}, // object
489 * acls: {rank: true}, // array
490 * }
491 * ```
492 *
493 * @param {Object} baseClassSettings parent model settings.
494 * @param {Object} subClassSettings child model settings.
495 * @param {Object} mergePolicy merge policy, as defined in `ModelClass.getMergePolicy()`
496 * @return {Object} mergedSettings merged parent and child models settings.
497 */
498 function mergeSettings(baseClassSettings, subClassSettings, mergePolicy) {
499 // deep clone base class settings
500 const mergedSettings = deepMerge(baseClassSettings);
501
502 Object.keys(baseClassSettings).forEach(function(key) {
503 // rank base class settings arrays elements where required
504 if (mergePolicy[key] && mergePolicy[key].rank) {
505 baseClassSettings[key] = rankArrayElements(baseClassSettings[key], ModelBaseClass.__rank);
506 }
507 });
508
509 Object.keys(subClassSettings).forEach(function(key) {
510 // assign default merge policy to unknown settings if specified
511 // if none specified, a deep merge will be applied eventually
512 if (mergePolicy[key] == null) { // undefined or null
513 mergePolicy[key] = mergePolicy.__default || {};
514 }
515
516 // allow null value to remove unwanted settings from base class settings
517 if (subClassSettings[key] === mergePolicy.__delete) {
518 delete mergedSettings[key];
519 return;
520 }
521 // rank sub class settings arrays elements where required
522 if (mergePolicy[key].rank) {
523 subClassSettings[key] = rankArrayElements(subClassSettings[key], ModelBaseClass.__rank + 1);
524 }
525 // replace base class settings where required
526 if (mergePolicy[key].replace) {
527 mergedSettings[key] = subClassSettings[key];
528 return;
529 }
530 // patch inner properties of base class settings where required
531 if (mergePolicy[key].patch) {
532 // mergedSettings[key] might not be initialized
533 mergedSettings[key] = mergedSettings[key] || {};
534 Object.keys(subClassSettings[key]).forEach(function(innerKey) {
535 mergedSettings[key][innerKey] = subClassSettings[key][innerKey];
536 });
537 return;
538 }
539
540 // in case no merge policy matched, apply a deep merge
541 // this for example handles {replace: false} and {rank: true}
542 mergedSettings[key] = deepMergeProperty(baseClassSettings[key], subClassSettings[key]);
543 });
544
545 return mergedSettings;
546 }
547
548 /**
549 * Register a property for the model class
550 * @param {String} propertyName Name of the property.
551 */
552 ModelClass.registerProperty = function(propertyName) {
553 const properties = modelDefinition.build();
554 const prop = properties[propertyName];
555 const DataType = prop.type;
556 if (!DataType) {
557 throw new Error(g.f('Invalid type for property %s', propertyName));
558 }
559
560 if (prop.required) {
561 const requiredOptions = typeof prop.required === 'object' ? prop.required : undefined;
562 ModelClass.validatesPresenceOf(propertyName, requiredOptions);
563 }
564 if (DataType === Date) ModelClass.validatesDateOf(propertyName);
565
566 Object.defineProperty(ModelClass.prototype, propertyName, {
567 get: function() {
568 if (ModelClass.getter[propertyName]) {
569 return ModelClass.getter[propertyName].call(this); // Try getter first
570 } else {
571 return this.__data && this.__data[propertyName]; // Try __data
572 }
573 },
574 set: function(value) {
575 let DataType = ModelClass.definition.properties[propertyName].type;
576 if (Array.isArray(DataType) || DataType === Array) {
577 DataType = List;
578 } else if (DataType === Date) {
579 DataType = DateType;
580 } else if (DataType === Boolean) {
581 DataType = BooleanType;
582 } else if (typeof DataType === 'string') {
583 DataType = modelBuilder.resolveType(DataType);
584 }
585
586 const persistUndefinedAsNull = ModelClass.definition.settings.persistUndefinedAsNull;
587 if (value === undefined && persistUndefinedAsNull) {
588 value = null;
589 }
590
591 if (ModelClass.setter[propertyName]) {
592 ModelClass.setter[propertyName].call(this, value); // Try setter first
593 } else {
594 this.__data = this.__data || {};
595 if (value === null || value === undefined) {
596 this.__data[propertyName] = value;
597 } else {
598 if (DataType === List) {
599 this.__data[propertyName] = isClass(DataType) ?
600 new DataType(value, properties[propertyName].type, this) :
601 DataType(value, properties[propertyName].type, this);
602 } else {
603 // Assume the type constructor handles Constructor() call
604 // If not, we should call new DataType(value).valueOf();
605 this.__data[propertyName] = (value instanceof DataType) ?
606 value :
607 isClass(DataType) ? new DataType(value) : DataType(value);
608 if (value && this.__data[propertyName] instanceof DefaultModelBaseClass) {
609 // we are dealing with an embedded model, apply parent
610 applyParentProperty(this.__data[propertyName], this);
611 }
612 }
613 }
614 }
615 },
616 configurable: true,
617 enumerable: true,
618 });
619
620 // FIXME: [rfeng] Do we need to keep the raw data?
621 // Use $ as the prefix to avoid conflicts with properties such as _id
622 Object.defineProperty(ModelClass.prototype, '$' + propertyName, {
623 get: function() {
624 return this.__data && this.__data[propertyName];
625 },
626 set: function(value) {
627 if (!this.__data) {
628 this.__data = {};
629 }
630 this.__data[propertyName] = value;
631 },
632 configurable: true,
633 enumerable: false,
634 });
635 };
636
637 const props = ModelClass.definition.properties;
638 let keys = Object.keys(props);
639 let size = keys.length;
640 for (let i = 0; i < size; i++) {
641 const propertyName = keys[i];
642 ModelClass.registerProperty(propertyName);
643 }
644
645 const mixinSettings = settings.mixins || {};
646 keys = Object.keys(mixinSettings);
647 size = keys.length;
648 for (let i = 0; i < size; i++) {
649 const name = keys[i];
650 let mixin = mixinSettings[name];
651 if (mixin === true) {
652 mixin = {};
653 }
654 if (Array.isArray(mixin)) {
655 mixin.forEach(function(m) {
656 if (m === true) m = {};
657 if (typeof m === 'object') {
658 modelBuilder.mixins.applyMixin(ModelClass, name, m);
659 }
660 });
661 } else if (typeof mixin === 'object') {
662 modelBuilder.mixins.applyMixin(ModelClass, name, mixin);
663 }
664 }
665
666 ModelClass.emit('defined', ModelClass);
667
668 return ModelClass;
669};
670
671function createModelClassCtor(name, ModelBaseClass) {
672 // A simple sanitization to handle most common characters
673 // that are used in model names but cannot be used as a function/class name.
674 // Note that the rules for valid JS indentifiers are way too complex,
675 // implementing a fully spec-compliant sanitization is not worth the effort.
676 // See https://mathiasbynens.be/notes/javascript-identifiers-es6
677 name = name.replace(/[-.:]/g, '_');
678
679 try {
680 // It is not possible to access closure variables like "ModelBaseClass"
681 // from a dynamically defined function. The solution is to
682 // create a dynamically defined factory function that accepts
683 // closure variables as arguments.
684 const factory = new Function('ModelBaseClass', `
685 // every class can receive hash of data as optional param
686 return function ${name}(data, options) {
687 if (!(this instanceof ${name})) {
688 return new ${name}(data, options);
689 }
690 if (${name}.settings.unresolved) {
691 throw new Error(g.f('Model %s is not defined.', ${JSON.stringify(name)}));
692 }
693 ModelBaseClass.apply(this, arguments);
694 };`);
695
696 return factory(ModelBaseClass);
697 } catch (err) {
698 // modelName is not a valid function/class name, e.g. 'grand-child'
699 // and our simple sanitization was not good enough.
700 // Falling back to legacy 'ModelConstructor' name.
701 if (err.name === 'SyntaxError') {
702 return createModelClassCtor('ModelConstructor', ModelBaseClass);
703 } else {
704 throw err;
705 }
706 }
707}
708
709// DataType for Date
710function DateType(arg) {
711 if (arg === null) return null;
712 const d = new Date(arg);
713 return d;
714}
715
716// Relax the Boolean coercision
717function BooleanType(arg) {
718 if (typeof arg === 'string') {
719 switch (arg) {
720 case 'true':
721 case '1':
722 return true;
723 case 'false':
724 case '0':
725 return false;
726 }
727 }
728 if (arg == null) {
729 return null;
730 }
731 return Boolean(arg);
732}
733
734/**
735 * Define single property named `propertyName` on `model`
736 *
737 * @param {String} model Name of model
738 * @param {String} propertyName Name of property
739 * @param {Object} propertyDefinition Property settings
740 */
741ModelBuilder.prototype.defineProperty = function(model, propertyName, propertyDefinition) {
742 this.definitions[model].defineProperty(propertyName, propertyDefinition);
743 this.models[model].registerProperty(propertyName);
744};
745
746/**
747 * Define a new value type that can be used in model schemas as a property type.
748 * @param {function()} type Type constructor.
749 * @param {string[]=} aliases Optional list of alternative names for this type.
750 */
751ModelBuilder.prototype.defineValueType = function(type, aliases) {
752 ModelBuilder.registerType(type, aliases);
753};
754
755/**
756 * Extend existing model with specified properties
757 *
758 * Example:
759 * Instead of extending a model with attributes like this (for example):
760 *
761 * ```js
762 * db.defineProperty('Content', 'competitionType',
763 * { type: String });
764 * db.defineProperty('Content', 'expiryDate',
765 * { type: Date, index: true });
766 * db.defineProperty('Content', 'isExpired',
767 * { type: Boolean, index: true });
768 *```
769 * This method enables you to extend a model as follows (for example):
770 * ```js
771 * db.extendModel('Content', {
772 * competitionType: String,
773 * expiryDate: { type: Date, index: true },
774 * isExpired: { type: Boolean, index: true }
775 * });
776 *```
777 *
778 * @param {String} model Name of model
779 * @options {Object} properties JSON object specifying properties. Each property is a key whos value is
780 * either the [type](http://docs.strongloop.com/display/LB/LoopBack+types) or `propertyName: {options}`
781 * where the options are described below.
782 * @property {String} type Datatype of property: Must be an [LDL type](http://docs.strongloop.com/display/LB/LoopBack+types).
783 * @property {Boolean} index True if the property is an index; false otherwise.
784 */
785ModelBuilder.prototype.extendModel = function(model, props) {
786 const t = this;
787 const keys = Object.keys(props);
788 for (let i = 0; i < keys.length; i++) {
789 const definition = props[keys[i]];
790 t.defineProperty(model, keys[i], definition);
791 }
792};
793
794ModelBuilder.prototype.copyModel = function copyModel(Master) {
795 const modelBuilder = this;
796 const className = Master.modelName;
797 const md = Master.modelBuilder.definitions[className];
798 const Slave = function SlaveModel() {
799 Master.apply(this, [].slice.call(arguments));
800 };
801
802 util.inherits(Slave, Master);
803
804 Slave.__proto__ = Master;
805
806 hiddenProperty(Slave, 'modelBuilder', modelBuilder);
807 hiddenProperty(Slave, 'modelName', className);
808 hiddenProperty(Slave, 'relations', Master.relations);
809
810 if (!(className in modelBuilder.models)) {
811 // store class in model pool
812 modelBuilder.models[className] = Slave;
813 modelBuilder.definitions[className] = {
814 properties: md.properties,
815 settings: md.settings,
816 };
817 }
818
819 return Slave;
820};
821
822/**
823 * Remove a model from the registry.
824 *
825 * @param {String} modelName
826 */
827ModelBuilder.prototype.deleteModelByName = function(modelName) {
828 delete this.models[modelName];
829 delete this.definitions[modelName];
830};
831
832/*!
833 * Define hidden property
834 */
835function hiddenProperty(where, property, value) {
836 Object.defineProperty(where, property, {
837 writable: true,
838 enumerable: false,
839 configurable: true,
840 value: value,
841 });
842}
843
844/**
845 * Get the schema name. If no parameter is given, then an anonymous model name
846 * is generated and returned.
847 * @param {string=} name The optional name parameter.
848 * @returns {string} The schema name.
849 */
850ModelBuilder.prototype.getSchemaName = function(name) {
851 if (name) {
852 return name;
853 }
854 if (typeof this._nameCount !== 'number') {
855 this._nameCount = 0;
856 } else {
857 this._nameCount++;
858 }
859 return 'AnonymousModel_' + this._nameCount;
860};
861
862/**
863 * Resolve the type string to be a function, for example, 'String' to String.
864 * Returns {Function} if the type is resolved
865 * @param {String | Object | Array} prop The object whose type is to be resolved
866 */
867ModelBuilder.prototype.resolveType = function(prop, isSubProperty) {
868 if (!prop) {
869 return prop;
870 }
871 if (Array.isArray(prop) && prop.length > 0) {
872 // For array types, the first item should be the type string
873 const itemType = this.resolveType(prop[0]);
874 if (typeof itemType === 'function') {
875 return [itemType];
876 } else {
877 return itemType; // Not resolved, return the type string
878 }
879 }
880 if (typeof prop === 'string') {
881 const schemaType = ModelBuilder.schemaTypes[prop.toLowerCase()] || this.models[prop];
882 if (schemaType) {
883 return schemaType;
884 } else {
885 // The type cannot be resolved, let's create a place holder
886 prop = this.define(prop, {}, {unresolved: true});
887 return prop;
888 }
889 } else if (prop.constructor.name === 'Object') {
890 // We also support the syntax {type: 'string', ...}
891 if (!isSubProperty && prop.type) {
892 return this.resolveType(prop.type, true);
893 } else {
894 return this.define(this.getSchemaName(null),
895 prop, {
896 anonymous: true,
897 idInjection: false,
898 strict: this.settings.strictEmbeddedModels || false,
899 });
900 }
901 } else if ('function' === typeof prop) {
902 return prop;
903 }
904 return prop;
905};
906
907/**
908 * Build models from schema definitions
909 *
910 * `schemas` can be one of the following:
911 *
912 * 1. An array of named schema definition JSON objects
913 * 2. A schema definition JSON object
914 * 3. A list of property definitions (anonymous)
915 *
916 * @param {*} schemas The schemas
917 * @returns {Object.<string, ModelClass>} A map of model constructors keyed by
918 * model name.
919 */
920ModelBuilder.prototype.buildModels = function(schemas, createModel) {
921 const models = {};
922
923 // Normalize the schemas to be an array of the schema objects {name: <name>, properties: {}, options: {}}
924 if (!Array.isArray(schemas)) {
925 if (schemas.properties && schemas.name) {
926 // Only one item
927 schemas = [schemas];
928 } else {
929 // Anonymous schema
930 schemas = [
931 {
932 name: this.getSchemaName(),
933 properties: schemas,
934 options: {anonymous: true},
935 },
936 ];
937 }
938 }
939
940 let relations = [];
941 for (let s = 0, n = schemas.length; s < n; s++) {
942 const name = this.getSchemaName(schemas[s].name);
943 schemas[s].name = name;
944 const model = typeof createModel === 'function' ?
945 createModel(schemas[s].name, schemas[s].properties, schemas[s].options) :
946 this.define(schemas[s].name, schemas[s].properties, schemas[s].options);
947 models[name] = model;
948 relations = relations.concat(model.definition.relations);
949 }
950
951 // Connect the models based on the relations
952 for (let i = 0; i < relations.length; i++) {
953 const relation = relations[i];
954 const sourceModel = models[relation.source];
955 const targetModel = models[relation.target];
956 if (sourceModel && targetModel) {
957 if (typeof sourceModel[relation.type] === 'function') {
958 sourceModel[relation.type](targetModel, {as: relation.as});
959 }
960 }
961 }
962 return models;
963};
964
965/**
966 * Introspect the JSON document to build a corresponding model.
967 * @param {String} name The model name
968 * @param {Object} json The JSON object
969 * @param {Object} options The options
970 * @returns {ModelClass} The generated model class constructor.
971 */
972ModelBuilder.prototype.buildModelFromInstance = function(name, json, options) {
973 // Introspect the JSON document to generate a schema
974 const schema = introspect(json);
975
976 // Create a model for the generated schema
977 return this.define(name, schema, options);
978};