Members
(constant) BUILDER_PARENT_SETTING :string
The name of the property in modelBuilder settings that will enable the child parent reference functionality
Type:
- string
- Source:
(constant) DEG2RAD
Properties:
Name | Type | Description |
---|---|---|
DEG2RAD |
Number | Factor to convert degrees to radians. |
RAD2DEG |
Number | Factor to convert radians to degrees. |
EARTH_RADIUS |
Object | Radius of the earth. |
- Source:
(constant) PARENT_PROPERTY_NAME :string
The property name that should be defined on each child instance if parent feature flag enabled
Type:
- string
- Source:
defineScope
Module exports
- Source:
Methods
ModelUtils()
A mixin to contain utility methods for DataAccessObject
- Source:
PhoneCtor(label, num)
Phone as a constructor function
Parameters:
Name | Type | Description |
---|---|---|
label |
string | |
num |
number |
- Source:
applyParentProperty(element, parent)
Accept an element, and attach the __parent property to it, unless no object given, while also
making sure to check for already created properties
Parameters:
Name | Type | Description |
---|---|---|
element |
object | |
parent |
Model |
- Source:
applyStrictCheck()
Apply strict check for model's data.
Notice: Please note this method modifies `inst` when `strict` is `validate`.
- Source:
asObjectMap(arr)
Convert an array of strings into an object as the map
Parameters:
Name | Type | Description |
---|---|---|
arr |
Array.<string> | An array of strings |
- Source:
buildOneToOneIdentityMapWithOrigKeys(objs, idName)
Effectively builds associative map on id -> object relation and stores original keys.
Map returned in form of object with ids in keys and object as values.
Parameters:
Name | Type | Description |
---|---|---|
objs |
array of objects to build from | |
idName |
name of property to be used as id. Such property considered to be unique across array. In case of collisions last wins. For non-unique ids use buildOneToManyIdentityMap() |
- Source:
Returns:
object where keys are ids and values are objects itself
collectTargetIds(The, The) → {Object}
Returns an object that queries targetIds.
Parameters:
Name | Type | Description |
---|---|---|
The |
Array | array of targetData |
The |
String | Id property name of target model |
- Source:
Returns:
The object that queries targetIds
- Type
- Object
convertToArray(param) → {Array}
Converts input parameter into array of objects which wraps the value.
"someValue" is converted to [{"someValue":true}]
["someValue"] is converted to [{"someValue":true}]
{"someValue":true} is converted to [{"someValue":true}]
Parameters:
Name | Type | Description |
---|---|---|
param |
String | Array | Object | Input parameter to be converted |
- Source:
Returns:
- Type
- Array
createTestSetupForParentRef()
Helper function that when called should return the current instance of the modelBuilder
Parameters:
Type | Description |
---|---|
- Source:
deepMerge(base, extras) → {Object}
Objects deep merge
Forked from https://github.com/nrf110/deepmerge/blob/master/index.js
The original function tries to merge array items if they are objects, this
was changed to always push new items in arrays, independently of their type.
NOTE: The function operates as a deep clone when called with a single object
argument.
Parameters:
Name | Type | Description |
---|---|---|
base |
Object | The base object |
extras |
Object | The object to merge with base |
- Source:
Returns:
The merged object
- Type
- Object
deepMergeProperty(base, extras) → {Object}
Properties deep merge
Similar as deepMerge but also works on single properties of any type
Parameters:
Name | Type | Description |
---|---|---|
base |
Object | The base property |
extras |
Object | The property to merge with base |
- Source:
Returns:
The merged property
- Type
- Object
defineCachedRelations(obj)
Define an non-enumerable __cachedRelations property
Parameters:
Name | Type | Description |
---|---|---|
obj |
Object | The obj to receive the __cachedRelations |
- Source:
defineReadonlyProp(obj, key, value)
Define readonly property on object
Parameters:
Name | Type | Description |
---|---|---|
obj |
Object | The property owner |
key |
String | The property name |
value |
Mixed | The default value |
- Source:
defineScope(cls, targetClass, name, params, methods)
Define a scope to the class
Parameters:
Name | Type | Description |
---|---|---|
cls |
Model | The class where the scope method is added |
targetClass |
Model | The class that a query to run against |
name |
String | The name of the scope |
params |
Object | function | The parameters object for the query or a function to return the query object |
methods |
An object of methods keyed by the method name to be bound to the class |
- Source:
escapeRegExp(str) → {string}
Accept a RegExp string and make sure that any special characters for RegExp are escaped in case they
create an invalid Regexp
Parameters:
Name | Type | Description |
---|---|---|
str |
string |
- Source:
Returns:
- Type
- string
execTasksWithInterLeave(tasks, callback)
Utility Function to allow interleave before and after high computation tasks
Parameters:
Name | Type | Description |
---|---|---|
tasks |
||
callback |
- Source:
fieldsToArray(fields, properties, excludeUnknown) → {Array.<String>}
Normalize fields to an array of included properties
Parameters:
Name | Type | Description |
---|---|---|
fields |
String | Array.<String> | Object | Fields filter |
properties |
Array.<String> | Property names |
excludeUnknown |
Boolean | To exclude fields that are unknown properties |
- Source:
Returns:
An array of included property names
- Type
- Array.<String>
fromDBName(name, caseFunction)
Renames db column names with different naming conventions:
camelCase for property names as it's LB default naming convention for properties,
or keep the name the same if needed.
Parameters:
Name | Type | Description |
---|---|---|
name |
* | name defined in database |
caseFunction |
* | optional. A function to convert the name into different case. |
- Source:
get()
This defines a property for the scope. For example, user.accounts or
User.vips. Please note the cls can be the model class or prototype of
the model class.
The property value is function. It can be used to query the scope,
such as user.accounts(condOrRefresh, cb) or User.vips(cb). The value
can also have child properties for create/build/delete. For example,
user.accounts.create(act, cb).
- Source:
hiddenProperty(obj, key, value)
Define a hidden property
It is an utility to define a property to the Object with info flags
Parameters:
Name | Type | Description |
---|---|---|
obj |
Object | The property owner |
key |
String | The property name |
value |
Mixed | The default value |
- Source:
idName(m) → {String}
Find the idKey of a Model.
Parameters:
Name | Type | Description |
---|---|---|
m |
ModelConstructor | Model Constructor |
- Source:
Returns:
- Type
- String
idsHaveDuplicates(The) → {boolean}
Check a list of IDs to see if there are any duplicates.
Parameters:
Name | Type | Description |
---|---|---|
The |
Array | array of IDs to check |
- Source:
Returns:
If any duplicates were found
- Type
- boolean
inherits(newClass, baseClass)
Parameters:
Name | Type | Description |
---|---|---|
newClass |
||
baseClass |
- Source:
initialize(dataSource, callbackopt)
Initialize the Memory connector against the given data source
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
dataSource |
DataSource | The loopback-datasource-juggler dataSource | |
callback |
function |
<optional> |
The callback function |
- Source:
initialize(dataSource, callbackopt)
Initialize the Transient connector against the given data source
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
dataSource |
DataSource | The loopback-datasource-juggler dataSource | |
callback |
function |
<optional> |
The callback function |
- Source:
isNestedModel(propType)
A utility function which checks for nested property definitions
Parameters:
Name | Type | Description |
---|---|---|
propType |
* | Property type metadata |
- Source:
isPlainObject(obj) → {boolean}
Check if the argument is plain object
Parameters:
Name | Type | Description |
---|---|---|
obj |
* | The obj value |
- Source:
Returns:
- Type
- boolean
isRegExpOperator(operator) → {boolean}
Accept an operator key and return whether it is used for a regular expression query or not
Parameters:
Name | Type | Description |
---|---|---|
operator |
string |
- Source:
Returns:
- Type
- boolean
join(oneToOneIdMap, oneToManyIdMap, mergeF)
Yeah, it joins. You need three things id -> obj1 map, id -> [obj2] map and merge function.
This functions will take each obj1, locate all data to join in map2 and call merge function.
Parameters:
Name | Type | Description |
---|---|---|
oneToOneIdMap |
||
oneToManyIdMap |
||
mergeF |
function(obj, objectsToMergeIn) |
- Source:
loadSchemasSync(schemaFile)
Load LDL schemas from a json doc
Parameters:
Name | Type | Description |
---|---|---|
schemaFile |
The dataSource json file |
- Source:
Returns:
A map of schemas keyed by name
mergeIncludes(destination, source) → {Object}
Merge include options of default scope with runtime include option.
exhibits the _.extend behaviour. Property value of source overrides
property value of destination if property name collision occurs
Parameters:
Name | Type | Description |
---|---|---|
destination |
String | Array | Object | The default value of `include` option |
source |
String | Array | Object | The runtime value of `include` option |
- Source:
Returns:
- Type
- Object
mixin(newClass, mixinClass, options)
Mix in the a class into the new class
Parameters:
Name | Type | Description |
---|---|---|
newClass |
The target class to receive the mixin | |
mixinClass |
The class to be mixed in | |
options |
- Source:
parseSettings(urlStr) → {Object}
Parse a URL into a settings object
Parameters:
Name | Type | Description |
---|---|---|
urlStr |
String | The URL for connector settings |
- Source:
Returns:
The settings object
- Type
- Object
rankArrayElements(array, rank)
Adds a property __rank to array elements of type object {}
If an inner element already has the __rank property it is not altered
NOTE: the function mutates the provided array
Parameters:
Name | Type | Description |
---|---|---|
array |
The original array | |
rank |
The rank to apply to array elements |
- Source:
Returns:
rankedArray The original array with newly ranked elements
sanitizeQuery(query, options) → {*}
Sanitize the query object
Parameters:
Name | Type | Description |
---|---|---|
query |
object | The query object |
options |
Properties:
Name | Type | Description |
---|---|---|
normalizeUndefinedInQuery |
String | either "nullify", "throw" or "ignore" (default: "ignore") |
prohibitedKeys |
Array.<String> | An array of prohibited keys to be removed |
- Source:
Returns:
- Type
- *
toRegExp(The) → {Object}
Converts a string, regex literal, or a RegExp object to a RegExp object.
Parameters:
Name | Type | Description |
---|---|---|
The |
String | Object | string, regex literal, or RegExp object to convert |
- Source:
Returns:
A RegExp object
- Type
- Object
uniq(an) → {Array}
Dedupe an array
Parameters:
Name | Type | Description |
---|---|---|
an |
Array | array |
- Source:
Returns:
an array with unique items
- Type
- Array
Type Definitions
callback(whereopt, data, err, model)
Update or insert a model instance based on the search criteria.
If there is a single instance retrieved, update the retrieved model.
Creates a new model if no model instances were found.
Returns an error if multiple instances are found.
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
where |
Object |
<optional> |
`where` filter, like
```
{ key: val, key2: {gt: 'val2'}, ...}
```
see [Where filter](https://docs.strongloop.com/display/LB/Where+filter#Wherefilter-Whereclauseforothermethods). |
data |
Object | The model instance data to insert. | |
err |
Error | Error object; see [Error object](http://docs.strongloop.com/display/LB/Error+object). | |
model |
Object | Updated model instance. |
- Source:
callback(err)
Delete all keys (and values) associated to the current model.
Parameters:
Name | Type | Description |
---|---|---|
err |
Error | Error object. |
- Source:
callback(key, err, result)
Delete the key-value pair associated to the given key.
Parameters:
Name | Type | Description |
---|---|---|
key |
String | Key to use when searching the database. |
err |
Error | Error object. |
result |
* | Value associated with the given key. |
- Source:
callback(key, ttl, err)
Set the TTL (time to live) in ms (milliseconds) for a given key. TTL is the
remaining time before a key-value pair is discarded from the database.
Parameters:
Name | Type | Description |
---|---|---|
key |
String | Key to use when searching the database. |
ttl |
Number | TTL in ms to set for the key. |
err |
Error | Error object. |
- Source:
callback(key, err, result)
Return the value associated with a given key.
Parameters:
Name | Type | Description |
---|---|---|
key |
String | Key to use when searching the database. |
err |
Error | Error object. |
result |
* | Value associated with the given key. |
- Source:
callback(filter, options)
Return all keys in the database.
**WARNING**: This method is not suitable for large data sets as all
key-values pairs are loaded into memory at once. For large data sets,
use `iterateKeys()` instead.
Parameters:
Name | Type | Description | ||||||
---|---|---|---|---|---|---|---|---|
filter |
Object | An optional filter object with the following
Properties
|
||||||
options |
Object |
- Source:
callback(key, value, err)
Persist a value and associate it with the given key.
Parameters:
Name | Type | Description |
---|---|---|
key |
String | Key to associate with the given value. |
value |
* | Value to persist. |
err |
Error | Error object. |
Properties:
Name | Type | Description |
---|---|---|
ttl |
Number | TTL for the key-value pair in ms. |
- Source:
callback(key, error, ttl)
Return the TTL (time to live) for a given key. TTL is the remaining time
before a key-value pair is discarded from the database.
Parameters:
Name | Type | Description |
---|---|---|
key |
String | Key to use when searching the database. |
error |
Error | |
ttl |
Number | Expiration time for the key-value pair. `undefined` if TTL was not initially set. |
- Source:
callback(operation, context)
Invoke all async observers for the given operation(s).
Example:
Notify all async observers for the `before save` operation.
```javascript
var context = {
Model: Model,
instance: obj,
isNewInstance: true,
hookState: hookState,
options: options,
};
Model.notifyObserversOf('before save', context, function(err) {
if (err) return cb(err);
// user can specify the logic after the observers have been notified
});
```
Parameters:
Name | Type | Description |
---|---|---|
operation |
String | Array.<String> | The operation name(s). |
context |
Object | Operation-specific context. |
- Source:
callback(operation, context, fn) → {*}
Run the given function with before/after observers.
It's done in three serial asynchronous steps:
- Notify the registered observers under 'before ' + operation
- Execute the function
- Notify the registered observers under 'after ' + operation
If an error happens, it fails first and calls the callback with err.
Example:
```javascript
var context = {
Model: Model,
instance: obj,
isNewInstance: true,
hookState: hookState,
options: options,
};
function work(done) {
process.nextTick(function() {
done(null, 1);
});
}
Model.notifyObserversAround('execute', context, work, function(err) {
if (err) return cb(err);
// user can specify the logic after the observers have been notified
});
```
Parameters:
Name | Type | Description |
---|---|---|
operation |
String | The operation name |
context |
Context | The context object |
fn |
function | The task to be invoked as fn(done) or fn(context, done) |
- Source:
Returns:
- Type
- *
callback(data, options) → {Boolean}
This method performs validation and triggers validation hooks.
Before validation the `obj.errors` collection is cleaned.
Each validation can add errors to `obj.errors` collection.
If collection is not blank, validation failed.
NOTE: This method can be called as synchronous only when no asynchronous validation is
configured. It's strongly recommended to run all validations as asyncronous.
Example: ExpressJS controller - render user if valid, show flash otherwise
```javascript
user.isValid(function (valid) {
if (valid) res.render({user: user});
else res.flash('error', 'User is not valid'), console.log(user.errors), res.redirect('/users');
});
```
Another example:
```javascript
user.isValid(function (valid) {
if (!valid) {
console.log(user.errors);
// => hash of errors
// => {
// => username: [errmessage, errmessage, ...],
// => email: ...
// => }
}
});
```
Parameters:
Name | Type | Description |
---|---|---|
data |
Object | Data to be validated. |
options |
Object | Options to be specified upon validation. |
- Source:
Returns:
True if no asynchronous validation is configured and all properties pass validation.
- Type
- Boolean
cb(modelName, cb) → {Promise}
Discover properties for a given model.
Callback function return value is an object that can have the following properties:
| Key | Type | Description |
|-----|------|-------------|
|owner | String | Database owner or schema|
|tableName | String | Table/view name|
|columnName | String | Column name|
|dataType | String | Data type|
|dataLength | Number | Data length|
|dataPrecision | Number | Numeric data precision|
|dataScale |Number | Numeric data scale|
|nullable |Boolean | If true, then the data can be null|
See [Properties](./Model-definition-JSON-file.html#properties) for more
details on the Property return type.
Parameters:
Name | Type | Description |
---|---|---|
modelName |
String | The table/view name |
cb |
function | Callback function. Optional |
Properties:
Name | Type | Description |
---|---|---|
owner|schema |
String | The database owner or schema |
- Source:
Returns:
A promise that returns an array of Properties (Property[])
- Type
- Promise
cb(targetModelData, err, The)
Create a target model instance
Parameters:
Name | Type | Description |
---|---|---|
targetModelData |
Object | The target model data |
err |
String | Object | Error string or object |
The |
Object | newly created target model instance |
- Source:
cb(targetModelData, err, The)
Create a target model instance
Parameters:
Name | Type | Description |
---|---|---|
targetModelData |
Object | The target model data |
err |
String | Object | Error string or object |
The |
Object | newly created target model instance |
- Source:
cb(options) → {Promise|undefined}
Begin a new transaction.
A transaction can be committed or rolled back. If timeout happens, the
transaction will be rolled back. Please note a transaction is typically
associated with a pooled connection. Committing or rolling back a transaction
will release the connection back to the pool.
Once the transaction is committed or rolled back, the connection property
will be set to null to mark the transaction to be inactive. Trying to commit
or rollback an inactive transaction will receive an error from the callback.
Please also note that the transaction is only honored with the same data
source/connector instance. CRUD methods will not join the current transaction
if its model is not attached the same data source.
Example:
To pass the transaction context to one of the CRUD methods, use the `options`
argument with `transaction` property, for example,
```js
MyModel.beginTransaction('READ COMMITTED', function(err, tx) {
MyModel.create({x: 1, y: 'a'}, {transaction: tx}, function(err, inst) {
MyModel.find({x: 1}, {transaction: tx}, function(err, results) {
// ...
tx.commit(function(err) {...});
});
});
});
```
Parameters:
Name | Type | Description |
---|---|---|
options |
Object | String | Options to be passed upon transaction. Can be one of the forms: - Object: {isolationLevel: '...', timeout: 1000} - String: isolationLevel Valid values of `isolationLevel` are: - Transaction.READ_COMMITTED = 'READ COMMITTED'; // default - Transaction.READ_UNCOMMITTED = 'READ UNCOMMITTED'; - Transaction.SERIALIZABLE = 'SERIALIZABLE'; - Transaction.REPEATABLE_READ = 'REPEATABLE READ'; |
- Source:
Returns:
Returns a callback promise.
- Type
- Promise | undefined
cb() → {Promise|undefined}
Commit a transaction and release it back to the pool.
Example:
```js
MyModel.beginTransaction('READ COMMITTED', function(err, tx) {
// some crud operation of your choice
tx.commit(function(err) {
// release the connection pool upon committing
tx.close(err);
});
});
```
- Source:
Returns:
Returns a callback promise.
- Type
- Promise | undefined
cb() → {Promise|undefined}
Rollback a transaction and release it back to the pool.
Example:
```js
MyModel.beginTransaction('READ COMMITTED', function(err, tx) {
// some crud operation of your choice
tx.rollback(function(err) {
// release the connection pool upon committing
tx.close(err);
});
});
```
- Source:
Returns:
Returns a callback promise.
- Type
- Promise | undefined
listener(operation)
Register an asynchronous observer for the given operation (event).
Example:
Registers a `before save` observer for a given model.
```javascript
MyModel.observe('before save', function filterProperties(ctx, next) {
if (ctx.options && ctx.options.skipPropertyFilter) return next();
if (ctx.instance) {
FILTERED_PROPERTIES.forEach(function(p) {
ctx.instance.unsetAttribute(p);
});
} else {
FILTERED_PROPERTIES.forEach(function(p) {
delete ctx.data[p];
});
}
next();
});
```
Parameters:
Name | Type | Description |
---|---|---|
operation |
String | The operation name. |
- Source:
listener(operation)
Unregister an asynchronous observer for the given operation (event).
Example:
```javascript
MyModel.removeObserver('before save', function removedObserver(ctx, next) {
// some logic user want to apply to the removed observer...
next();
});
```
Parameters:
Name | Type | Description |
---|---|---|
operation |
String | The operation name. |
- Source: