code
stringlengths 10
343k
| docstring
stringlengths 36
21.9k
| func_name
stringlengths 1
3.35k
| language
stringclasses 1
value | repo
stringlengths 7
58
| path
stringlengths 4
131
| url
stringlengths 44
195
| license
stringclasses 5
values |
---|---|---|---|---|---|---|---|
module.exports.devices = function(options) {
return new discovery.Devices(options || {});
}; | Get access to all devices on the current network. Will find and connect to
devices automatically. | module.exports.devices ( options ) | javascript | aholstenson/miio | lib/index.js | https://github.com/aholstenson/miio/blob/master/lib/index.js | MIT |
activateCharging() {
return this.call('app_stop', [])
.then(checkResult)
.then(() => this.call('app_charge', [], {
refresh: [ 'state' ],
refreshDelay: 1000
}))
.then(checkResult);
} | Stop the current cleaning session and return to charge. | activateCharging ( ) | javascript | aholstenson/miio | lib/devices/vacuum.js | https://github.com/aholstenson/miio/blob/master/lib/devices/vacuum.js | MIT |
changeFanSpeed(speed) {
return this.call('set_custom_mode', [ speed ], {
refresh: [ 'fanSpeed' ]
})
.then(checkResult);
} | Set the power of the fan. Usually 38, 60 or 77. | changeFanSpeed ( speed ) | javascript | aholstenson/miio | lib/devices/vacuum.js | https://github.com/aholstenson/miio/blob/master/lib/devices/vacuum.js | MIT |
find() {
return this.call('find_me', [''])
.then(() => null);
} | Activate the find function, will make the device give off a sound. | find ( ) | javascript | aholstenson/miio | lib/devices/vacuum.js | https://github.com/aholstenson/miio/blob/master/lib/devices/vacuum.js | MIT |
function generateKey() {
let result = '';
for(let i=0; i<16; i++) {
let idx = Math.floor(Math.random() * CHARS.length);
result += CHARS[idx];
}
return result;
} | Generate a key for use with the local developer API. This does not generate
a secure key, but the Mi Home app does not seem to do that either. | generateKey ( ) | javascript | aholstenson/miio | lib/devices/gateway.js | https://github.com/aholstenson/miio/blob/master/lib/devices/gateway.js | MIT |
changeLEDBrightness(level) {
switch(level) {
case 'bright':
level = 0;
break;
case 'dim':
level = 1;
break;
case 'off':
level = 2;
break;
default:
return Promise.reject(new Error('Invalid LED brigthness: ' + level));
}
return this.call('set_led_b', [ level ], { refresh: [ 'ledBrightness' ] })
.then(() => null);
} | Set the LED brightness to either `bright`, `dim` or `off`. | changeLEDBrightness ( level ) | javascript | aholstenson/miio | lib/devices/humidifier.js | https://github.com/aholstenson/miio/blob/master/lib/devices/humidifier.js | MIT |
changeMode(mode) {
return this.call('set_mode', [ mode ], {
refresh: [ 'power', 'mode' ],
refreshDelay: 200
})
.then(MiioApi.checkOk)
.catch(err => {
throw err.code === -5001 ? new Error('Mode `' + mode + '` not supported') : err;
});
} | Perform a mode change as requested by `mode(string)` or
`setMode(string)`. | changeMode ( mode ) | javascript | aholstenson/miio | lib/devices/air-purifier.js | https://github.com/aholstenson/miio/blob/master/lib/devices/air-purifier.js | MIT |
favoriteLevel(level=undefined) {
if(typeof level === 'undefined') {
return Promise.resolve(this.property('favoriteLevel'));
}
return this.setFavoriteLevel(level);
} | Get the favorite level used when the mode is `favorite`. Between 0 and 16. | favoriteLevel ( level = undefined ) | javascript | aholstenson/miio | lib/devices/air-purifier.js | https://github.com/aholstenson/miio/blob/master/lib/devices/air-purifier.js | MIT |
setFavoriteLevel(level) {
return this.call('set_level_favorite', [ level ])
.then(() => null);
} | Set the favorite level used when the mode is `favorite`, should be
between 0 and 16. | setFavoriteLevel ( level ) | javascript | aholstenson/miio | lib/devices/air-purifier.js | https://github.com/aholstenson/miio/blob/master/lib/devices/air-purifier.js | MIT |
const scan = () => {
let idx = 0;
let tmp = '';
function clearTmp() {
if (tmp) {
parseList.push(tmp);
tmp = '';
}
}
while (idx < jsonStr.length) {
const char = jsonStr[idx];
if (char === '{') {
if (tmp + char === keyword) {
parseList.push(tmp + char);
tmp = '';
} else {
clearTmp();
parseList.push(char);
}
} else if (char === '}') {
clearTmp();
parseList.push(char);
} else {
tmp += char;
}
idx++;
}
}; | '{"$ref":{"foo": "bar"}}' => ['{', '"$ref":{', '"foo": "bar"','}', '}'] | scan | javascript | macacajs/macaca-datahub | app/util/index.js | https://github.com/macacajs/macaca-datahub/blob/master/app/util/index.js | MIT |
constructor (options = {}) {
this.options = Object.assign(defaultOptions, options);
this.fetch = fetch;
this.rootUrl = `${this.options.protocol}://${this.options.hostname}:${this.options.port}/api/`;
} | Create a SDK client.
@param {string} [port=5678] - DataHub port.
@param {string} [hostname='127.0.0.1'] - DataHub hostname.
@param {string} [protocol='http'] - DataHub protocol. | constructor ( options = { } ) | javascript | macacajs/macaca-datahub | sdk/datahub-nodejs-sdk/lib/datahub-nodejs-sdk.js | https://github.com/macacajs/macaca-datahub/blob/master/sdk/datahub-nodejs-sdk/lib/datahub-nodejs-sdk.js | MIT |
async getSceneData (data) {
return await this.get('sdk/scene_data', data);
} | get scene data
@param {Object} options - scene options
@param {string} options.hub - hubname.
@param {string} options.pathname - pathname.
@param {string} options.scene - scene name.
@param {string} [options.method='ALL'] - api method, default is 'ALL'.
@description
```javascript
await client.getSceneData({
hub: 'app',
pathname: 'api',
scene: 'success',
method: 'POST',
})
``` | getSceneData ( data ) | javascript | macacajs/macaca-datahub | sdk/datahub-nodejs-sdk/lib/datahub-nodejs-sdk.js | https://github.com/macacajs/macaca-datahub/blob/master/sdk/datahub-nodejs-sdk/lib/datahub-nodejs-sdk.js | MIT |
async switchScene (options) {
return await this.post('sdk/switch_scene', options);
} | switch one scene
@param {Object} options - switch scene options
@param {string} options.hub - hubname.
@param {string} options.pathname - pathname.
@param {string} options.scene - scene name.
@param {string} [options.method='ALL'] - api method, default is 'ALL'.
@description
```javascript
await client.switchScene({
hub: 'app',
pathname: 'api',
scene: 'success',
method: 'POST',
})
```
```javascript
await client.switchScene({
hub: 'app',
pathname: 'api',
scene: 'success',
method: 'POST',
})
``` | switchScene ( options ) | javascript | macacajs/macaca-datahub | sdk/datahub-nodejs-sdk/lib/datahub-nodejs-sdk.js | https://github.com/macacajs/macaca-datahub/blob/master/sdk/datahub-nodejs-sdk/lib/datahub-nodejs-sdk.js | MIT |
async switchMultiScenes (options) {
return await this.post('sdk/switch_multi_scenes', options);
} | switch multi scenes
@param {Object[]} options - switch scene options
@param {string} options[].hub - hubname.
@param {string} options[].pathname - pathname.
@param {string} options[].scene - scene name.
@param {string} [options[].method='ALL'] - api method, default is 'ALL'.
@description
```javascript
await client.switchMultiScenes([{
hub: 'app',
pathname: 'api',
scene: 'success',
method: 'POST',
}, {
hub: 'app',
pathname: 'api2',
scene: 'success',
method: 'POST',
}])
``` | switchMultiScenes ( options ) | javascript | macacajs/macaca-datahub | sdk/datahub-nodejs-sdk/lib/datahub-nodejs-sdk.js | https://github.com/macacajs/macaca-datahub/blob/master/sdk/datahub-nodejs-sdk/lib/datahub-nodejs-sdk.js | MIT |
async switchAllScenes (options) {
return await this.post('sdk/switch_all_scenes', options);
} | switch all scenes
@param {Object} options - switch scene options
@param {string} options.hub - hubname.
@param {string} options.scene - scene name.
@description
```javascript
await client.switchAllScenes({
hub: 'app',
scene: 'success',
})
``` | switchAllScenes ( options ) | javascript | macacajs/macaca-datahub | sdk/datahub-nodejs-sdk/lib/datahub-nodejs-sdk.js | https://github.com/macacajs/macaca-datahub/blob/master/sdk/datahub-nodejs-sdk/lib/datahub-nodejs-sdk.js | MIT |
async function fileOrDirectoryExist(path) {
try {
if (fs.lstatSync(path).isDirectory()) {
return { isDirectory: true, isFile: false };
}
await fs.promises.access(path);
return { isDirectory: false, isFile: true };
} catch (error) {
return { isDirectory: false, isFile: false };
}
} | Check if 'path' is a directory or a file
@param {string} path
@returns | fileOrDirectoryExist ( path ) | javascript | swagger-autogen/swagger-autogen | src/utils.js | https://github.com/swagger-autogen/swagger-autogen/blob/master/src/utils.js | MIT |
async function getExtension(fileName) {
try {
let extensios = ['.js', '.ts', '.jsx', '.tsx', '.mjs', '.cjs'];
let data = fileName.split('.').slice(-1)[0].toLowerCase();
if (extensios.includes(data)) {
return '';
}
for (let idx = 0; idx < extensios.length; ++idx) {
if (fs.existsSync(fileName + extensios[idx])) {
return extensios[idx];
}
}
return '';
} catch (err) {
return '';
}
} | Get file extension.
@param {string} fileName | getExtension ( fileName ) | javascript | swagger-autogen/swagger-autogen | src/utils.js | https://github.com/swagger-autogen/swagger-autogen/blob/master/src/utils.js | MIT |
function getFileContent(pathFile) {
return new Promise(resolve => {
fs.readFile(pathFile, 'utf8', function (err, data) {
if (err) {
return resolve(null);
}
return resolve(data);
});
});
} | Get file content.
@param {string} pathFile | getFileContent ( pathFile ) | javascript | swagger-autogen/swagger-autogen | src/utils.js | https://github.com/swagger-autogen/swagger-autogen/blob/master/src/utils.js | MIT |
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
} | Check if the input parameter is a number
@param {*} n | isNumeric ( n ) | javascript | swagger-autogen/swagger-autogen | src/utils.js | https://github.com/swagger-autogen/swagger-autogen/blob/master/src/utils.js | MIT |
function stackSymbolRecognizer(data, startSymbol, endSymbol, ignoreString = true) {
return new Promise(resolve => {
if (!data) {
return resolve(data);
}
const origData = data;
try {
let stack = 1;
let ignore = false;
let strSymbol = null;
data = data
.split('')
.filter((c, idx) => {
if (ignoreString && (c == "'" || c == '"' || c == '`') && !strSymbol) {
strSymbol = c;
ignore = true;
} else if (ignoreString && strSymbol == c && data[idx - 1] != '\\') {
strSymbol = null;
ignore = false;
}
if (stack <= 0) return false;
if (c == startSymbol && !ignore) {
stack += 1;
}
if (c == endSymbol && !ignore) {
stack -= 1;
}
return true;
})
.join('');
return resolve(data);
} catch (err) {
return resolve(origData);
}
});
} | Get first substring between two characters (startSymbol and endSymbol).
This method return remove the first character (startSymbol)
@param {string} data file content.
@param {string} startSymbol
@param {string} endSymbol | stackSymbolRecognizer ( data , startSymbol , endSymbol , ignoreString = true ) | javascript | swagger-autogen/swagger-autogen | src/utils.js | https://github.com/swagger-autogen/swagger-autogen/blob/master/src/utils.js | MIT |
function stack0SymbolRecognizer(data, startSymbol, endSymbol, keepSymbol = false) {
return new Promise(resolve => {
try {
let stack = 0;
let rec = 0;
let strVect = [];
if (!endSymbol && startSymbol === '[') {
endSymbol = ']';
} else if (!endSymbol && startSymbol === '{') {
endSymbol = '}';
} else if (!endSymbol && startSymbol === '(') {
endSymbol = ')';
}
for (let idx = 0; idx < data.length; ++idx) {
let c = data[idx];
if (rec == 0 && c == startSymbol) rec = 1;
if (c == startSymbol && rec == 1) stack += 1;
if (c == endSymbol && rec == 1) stack -= 1;
if (stack == 0 && rec == 1) rec = 2;
if (rec == 1) strVect.push(c);
if ((idx === data.length - 1 && rec == 1) || (idx === data.length - 1 && rec == 0)) return resolve(null);
if (idx === data.length - 1 || rec == 2) {
strVect = strVect.join('');
if (keepSymbol) {
return resolve(startSymbol + strVect.slice(1) + endSymbol);
}
return resolve(strVect.slice(1));
}
}
} catch (err) {
if (keepSymbol) {
return resolve(startSymbol + endSymbol);
}
return resolve('');
}
});
} | Get first substring between two characters (startSymbol and endSymbol)
@param {string} data file content.
@param {string} startSymbol
@param {string} endSymbol | stack0SymbolRecognizer ( data , startSymbol , endSymbol , keepSymbol = false ) | javascript | swagger-autogen/swagger-autogen | src/utils.js | https://github.com/swagger-autogen/swagger-autogen/blob/master/src/utils.js | MIT |
function getUntil(data, character, ignoreInString = true) {
if (!data) {
return '';
}
let stringType = null;
let resp = '';
let c = null;
try {
for (let idx = 0; idx < data.length; ++idx) {
c = data[idx];
if (ignoreInString) {
if (c == stringType && data[idx - 1] != '\\') {
stringType = null;
resp += c;
continue;
}
if (c == "'" && !stringType) {
stringType = "'";
} else if (c == '"' && !stringType) {
stringType = '"';
} else if (c == '`' && !stringType) {
stringType = '`';
}
}
if (c == character && !stringType) {
return resp;
}
resp += c;
}
return resp;
} catch (err) {
return resp;
}
} | Getting the string until a character to be found.
@param {string} data content
@param {string} character character that will stop the search
@param {boolean} ignoreInString If 'true', the 'character' won't be searched in the string.
@returns | getUntil ( data , character , ignoreInString = true ) | javascript | swagger-autogen/swagger-autogen | src/code-parser.js | https://github.com/swagger-autogen/swagger-autogen/blob/master/src/code-parser.js | MIT |
function getVariablesNode(node) {
if (node.body) {
let v = [];
if (Array.isArray(node.body)) {
for (let idx = 0; idx < node.body.length; ++idx) {
let e = node.body[idx];
let n = getVariablesNode(e);
if (Array.isArray(n)) {
v = [...v, ...n];
}
v.push(n);
}
} else {
node.body.body.forEach(e => v.push(getVariablesNode(e)));
}
return v.filter(e => e);
} else if (node.type === 'VariableDeclaration') {
if (node.declarations[0].init.type != 'CallExpression') {
return node;
}
} else if (node.type === 'ExpressionStatement') {
return getVariablesNode(node.expression);
} else if (node.type === 'AssignmentExpression') {
return getVariablesNode(node.right);
}
} | Return all nodes that are 'VariableDeclaration'.
@param {*} node
@returns | getVariablesNode ( node ) | javascript | swagger-autogen/swagger-autogen | src/code-parser.js | https://github.com/swagger-autogen/swagger-autogen/blob/master/src/code-parser.js | MIT |
function jsParser(data) {
try {
let jsObj = { variables: [] };
const parse = Parser.parse(data, { ecmaVersion: 2020 });
let variablesNode = getVariablesNode(parse);
// Get variables
for (let idx = 0; idx < variablesNode.length; ++idx) {
let item = variablesNode[idx];
if (item && item.declarations && item.declarations[0].type === 'VariableDeclarator') {
let name = item.declarations[0].id.name;
let end = item.declarations[0].end; // bytePosition of the last byte
let value = resolveVariableValue(item.declarations[0].init, jsObj.variables);
jsObj.variables.push({ name, end, kind: item.kind, typeof: typeof value, value });
}
}
return jsObj;
} catch (err) {
return null;
}
} | Parse a JavaScript content.
It get only the variables. In the future, it will get other patterns.
@param {string} data content
@returns | jsParser ( data ) | javascript | swagger-autogen/swagger-autogen | src/code-parser.js | https://github.com/swagger-autogen/swagger-autogen/blob/master/src/code-parser.js | MIT |
function dataConverter(data) {
return new Promise(resolve => {
const origData = data;
try {
let patterns = new Set();
// CASE: Converting require("./foo")(app) to app.use(require("./foo"))
if (!data) {
return resolve({
data,
patterns: []
});
}
let founds = data.split(new RegExp('(require\\s*\\n*\\t*\\(.*\\)\\s*\\n*\\t*\\(\\s*\\n*\\t*.*\\s*\\n*\\t*\\))'));
for (let idx = 0; idx < founds.length; ++idx) {
let req = founds[idx];
if (req.split(new RegExp('^require')).length == 1) continue;
if (founds[idx - 1] && founds[idx - 1].trim().slice(-1)[0] == '=') {
// avoiding cases, such as: const foo = require(...)()
continue;
}
req = req.split(new RegExp('require\\s*\\n*\\t*\\(|\\)\\s*\\n*\\t*\\('));
if (req && (req.length < 2 || !req[1].includes('./') || !req[2])) {
continue;
}
req[2] = req[2].split(')')[0].trim();
req[2] = req[2].split(',')[0]; // TODO: verify which possition in req[2][0] is a route
patterns.add(req[2]);
let converted = `${req[2]}.use(require(${req[1]}))`;
data = data.replace(founds[idx], converted); // TODO: use replaceAll() ?
}
return resolve({
data,
patterns: [...patterns]
});
} catch (err) {
return resolve({
data: origData,
patterns: []
});
}
});
} | Convert statements such as: "require('./path')(foo)" in "foo.use(require('./path'))"
Useful, because the statement "foo.use(require('./path'))" is already handled successfully.
@param {string} data file content | dataConverter ( data ) | javascript | swagger-autogen/swagger-autogen | src/handle-data.js | https://github.com/swagger-autogen/swagger-autogen/blob/master/src/handle-data.js | MIT |
function removeAwaitsAndAsyncs(data) {
const origData = data;
try {
if (!data || data.length === 0) {
return data;
}
let isStr = 0;
let isComment = false;
const strDelimiters = '\'"`';
let currentDelimiter = null;
for (let idx = 0; idx < data.length; idx += 1) {
if (data.slice(idx, idx + 2) === '*/') {
isComment = false;
}
if (isComment) {
continue;
}
// Check if current character is a string delimiter
if (strDelimiters.includes(data[idx])) {
currentDelimiter = strDelimiters.indexOf(data[idx]) + 1;
if (isStr === 0) {
// If not in a string, set state as "in string using specific delimiter"
isStr = currentDelimiter;
} else if (isStr === currentDelimiter && (data[idx - 1] !== '\\' || data[idx - 2] === '\\')) {
// If in a string, set state as "not in a string"
isStr = 0;
}
}
// If in string, skip current index
if (isStr !== 0) {
continue;
}
// Skip comments
if (data.slice(idx, idx + 2) === '/*') {
isComment = true;
continue;
}
if (data.slice(idx, idx + 6) === 'await ' && idx > 0 && data[idx - 1].split(new RegExp('([a-z]|[A-Z]|[0-9]|_|$)')).length === 1) {
// Remove await keyword
data = data.slice(0, idx) + data.slice(idx + 6);
continue;
} else if (data.slice(idx, idx + 5) === 'async' && idx > 0 && data[idx - 1].split(new RegExp('([a-z]|[A-Z]|[0-9]|_|$)')).length === 1 && data[idx + 5].split(new RegExp('([a-z]|[A-Z]|[0-9]|_|$)')).length === 1) {
// Remove async keyword
data = data.slice(0, idx) + data.slice(idx + 5);
continue;
}
}
return data;
} catch (err) {
return origData;
}
} | Remove the await and async keyword in a string, except in comments and substrings.
@param {string} data file content. | removeAwaitsAndAsyncs ( data ) | javascript | swagger-autogen/swagger-autogen | src/handle-data.js | https://github.com/swagger-autogen/swagger-autogen/blob/master/src/handle-data.js | MIT |
function clearData(data, imports) {
return new Promise(resolve => {
if (!data) {
return resolve(data);
}
const origData = data;
try {
// Change "// ..." comment to "/* ... */"
const origData = data;
data = data.replaceAll(new RegExp('#swagger\\.description\\s*\\=\\s*'), ' #swagger.description = ');
// Backuping descriptions
let swaggerDescriptionsStorage = new Map();
if (data.includes('#swagger.description')) {
let swaggerDescriptions = data.split(new RegExp('#swagger.description = '));
for (let idx = 1; idx < swaggerDescriptions.length; ++idx) {
let key = `__${statics.UNKNOWN}__swagger_description__${idx}`; // TODO: put unknown char here
let description = utils.popString(swaggerDescriptions[idx], true);
swaggerDescriptionsStorage.set(key, description);
data = data.replace('#swagger.description = ' + description, key);
}
}
try {
data = data.split(new RegExp('\\s*\\n*\\t*\\.\\s*\\n*\\t*headers\\s*\\n*\\t*\\[\\s*\\n*\\t*')).join('.headers[');
data = data.split(new RegExp('\\s*\\n*\\t*\\.\\s*\\n*\\t*header\\s*\\n*\\t*\\(\\s*\\n*\\t*'));
if (data.length > 1) {
for (let idxHeader = 1; idxHeader < data.length; ++idxHeader) {
data[idxHeader] = data[idxHeader].replace(')', ']');
}
data = data.join('.headers[');
} else {
data = data[0];
}
data = data.split(new RegExp('\\s*\\n*\\t*\\.\\s*\\n*\\t*header\\s*\\n*\\t*\\(\\s*\\n*\\t*')).join('.headers(');
if (data.split('.headers[').length > 1) {
data = data.split('.headers[');
for (let idxHeaders = 1; idxHeaders < data.length; ++idxHeaders) {
let d = data[idxHeaders];
if (d[0] === "'" || d[0] === '"' || d[0] === '`') {
let str = utils.popString(d);
d = d.replace(new RegExp(`.${str}.`), `${statics.STRING_QUOTE}${str}${statics.STRING_QUOTE}`);
data[idxHeaders] = d;
}
}
data = data.join('.headers[');
}
} catch (err) {
data = origData;
}
data = data.replaceAll('\r', '\n');
data = data.replaceAll('\\r', '\n');
data = data.replaceAll('*//*', '*/\n/*');
data = data.replaceAll('*//*', '*/\n/*');
data = data.replaceAll('*///', '*/\n//');
data = data.replaceAll('///', '//');
data = data.replaceAll('://', ':/' + statics.STRING_BREAKER + '/'); // REFACTOR: improve this. Avoiding cases such as: ... http://... be handled as a comment
data = utils.removeRegexes(data);
data = data.split('//').map((e, idx) => {
if (idx != 0) {
return e.replace('\n', ' */ \n');
}
return e;
});
data = data.join('/*');
data = data.replaceAll(':/' + statics.STRING_BREAKER + '/', '://');
let aData = data.replaceAll('\n', statics.STRING_BREAKER);
aData = aData.replaceAll('\t', ' ');
aData = aData.replaceAll(statics.STRING_BREAKER, '\n');
aData = aData.split(new RegExp('axios\\s*\\n*\\t*\\.\\w*', 'i'));
aData = aData.join('axios.method');
/**
* Removing express-async-handler function
*/
let expressAsyncHandler = null;
if (imports) {
let idx = imports.findIndex(e => e.fileName == 'express-async-handler');
if (idx > -1) {
if (!imports[idx].varFileName && imports[idx].exports.length > 0) {
expressAsyncHandler = imports[idx].exports[0].varName;
} else {
expressAsyncHandler = imports[idx].varFileName;
}
}
if (expressAsyncHandler) {
aData = aData.split(new RegExp(`\\s*\\n*\\t*${expressAsyncHandler}\\s*\\n*\\t*\\(`));
aData = aData.join(' ');
}
}
aData = removeAwaitsAndAsyncs(aData);
// Restoring descriptions
for (let idx = 0; idx < swaggerDescriptionsStorage.size; ++idx) {
let key = `__${statics.UNKNOWN}__swagger_description__${idx + 1}`;
let description = swaggerDescriptionsStorage.get(key);
aData = aData.replace(key, ` #swagger.description = ${description}`);
}
return resolve(aData);
} catch (err) {
return resolve(origData);
}
});
} | Removes unnecessary content.
@param {string} data file content. | clearData ( data , imports ) | javascript | swagger-autogen/swagger-autogen | src/handle-data.js | https://github.com/swagger-autogen/swagger-autogen/blob/master/src/handle-data.js | MIT |
function removeComments(data, keepSwaggerTags = false) {
return new Promise(resolve => {
if (!data || data.length == 0) {
return resolve(data);
}
let storedRegexs = [];
let strToReturn = '';
let stackComment1 = 0; // For type //
let stackComment2 = 0; // For type /* */
let buffer1 = ''; // For type //
let buffer2 = ''; // For type /* */
// Won't remove comments in strings
let isStr1 = 0; // "
let isStr2 = 0; // '
let isStr3 = 0; // `
try {
for (let idx = 0; idx < data.length; ++idx) {
let c = data[idx];
if (stackComment1 == 0 && stackComment2 == 0) {
// Type '
if (c == "'" && (data[idx - 1] != '\\' || (data[idx - 1] == '\\' && data[idx - 2] == '\\')) && isStr1 == 1) {
isStr1 = 2;
} else if (c == "'" && (data[idx - 1] != '\\' || (data[idx - 1] == '\\' && data[idx - 2] == '\\')) && isStr1 == 0 && isStr2 == 0 && isStr3 == 0) {
isStr1 = 1;
}
// Type "
else if (c == '"' && (data[idx - 1] != '\\' || (data[idx - 1] == '\\' && data[idx - 2] == '\\')) && isStr2 == 1) {
isStr2 = 2;
} else if (c == '"' && (data[idx - 1] != '\\' || (data[idx - 1] == '\\' && data[idx - 2] == '\\')) && isStr1 == 0 && isStr2 == 0 && isStr3 == 0) {
isStr2 = 1;
}
// Type `
else if (c == '`' && (data[idx - 1] != '\\' || (data[idx - 1] == '\\' && data[idx - 2] == '\\')) && isStr3 == 1) {
isStr3 = 2;
} else if (c == '`' && (data[idx - 1] != '\\' || (data[idx - 1] == '\\' && data[idx - 2] == '\\')) && isStr1 == 0 && isStr2 == 0 && isStr3 == 0) {
isStr3 = 1;
}
}
// Type //
if (c == '/' && data[idx + 1] == '/' && data[idx - 1] != '\\' && data[idx - 1] != ':' && stackComment1 == 0 && stackComment2 == 0) {
// REFACTOR: improve this. Avoiding cases such as: ... http://... be handled as a comment
stackComment1 = 1;
} else if (c == '\n' && stackComment1 == 1) {
stackComment1 = 2;
}
// Type /* */
else if (c == '/' && data[idx + 1] == '*' && data[idx - 1] != '\\' && stackComment1 == 0 && stackComment2 == 0 && isStr1 == 0 && isStr2 == 0 && isStr3 == 0) {
stackComment2 = 1;
} else if (c == '/' && data[idx - 1] == '*' && stackComment2 == 1 && isStr1 == 0 && isStr2 == 0 && isStr3 == 0 && buffer2 != '/*') {
stackComment2 = 2;
}
/**
* REGEX START
*/
if (c == '/' && data[idx - 1] != '\\' && data[idx + 1] != '/' && isStr1 == 0 && isStr2 == 0 && isStr3 == 0 && stackComment1 == 0 && stackComment2 == 0) {
// Checking if it is valid regex
let lidx = idx + 1;
let lstr = '';
let regexStackParenthesis = 0;
let regexStackSquareBracket = 0;
while (lidx < data.length) {
// prevent loop
let lc = data[lidx];
if (lc == '(') {
regexStackParenthesis += 1;
} else if (lc == ')') {
regexStackParenthesis -= 1;
} else if (lc == '[') {
regexStackSquareBracket += 1;
} else if (lc == ']') {
regexStackSquareBracket -= 1;
}
lstr += lc;
lidx += 1;
if (data[lidx] == '/' && data[idx - 1] != '\\' && regexStackParenthesis < 1 && regexStackSquareBracket < 1) {
if (regexStackParenthesis < 0) {
regexStackParenthesis = 0;
}
if (regexStackSquareBracket < 0) {
regexStackSquareBracket = 0;
}
break;
}
}
try {
// TODO: improve / refactoring
if (''.split(new RegExp(lstr)).length > -1) {
// Valid regex
const ref = `__¬¬¬__${idx}__¬¬¬__`;
data = utils.replaceRange(data, idx, lidx + 1, ref);
c = data[idx];
// Storing regex apart
storedRegexs.push({ ref, regex: `/${lstr}/` });
}
} catch (err) {
// Invalid regex
}
}
/* REGEX END */
if (isStr1 > 0 || isStr2 > 0 || isStr3 > 0 || (stackComment1 == 0 && stackComment2 == 0)) {
strToReturn += c;
} else if (stackComment1 == 1 || stackComment1 == 2) {
// Keeps the comment being ignored. Like: //
buffer1 += c;
} else if (stackComment2 == 1 || stackComment2 == 2) {
// Keeps the comment being ignored. Like: /* */
buffer2 += c;
}
if (stackComment1 == 2) {
stackComment1 = 0;
if (buffer1.includes('#swagger.') && keepSwaggerTags) {
strToReturn += buffer1; // keeping the comment that has a swagger tag
buffer1 = '';
} else buffer1 = '';
}
if (stackComment2 == 2) {
stackComment2 = 0;
if (buffer2.includes('#swagger.') && keepSwaggerTags) {
strToReturn += buffer2; // keeping the comment that has a swagger tag
buffer2 = '';
} else buffer2 = '';
}
if (isStr1 == 2) isStr1 = 0;
if (isStr2 == 2) isStr2 = 0;
if (isStr3 == 2) isStr3 = 0;
if (idx == data.length - 1) {
if (storedRegexs.length > 0) {
storedRegexs
.filter(e => e)
.forEach(r => {
strToReturn = strToReturn.replace(r.ref, r.regex);
});
}
strToReturn = strToReturn.replaceAll(' ', ' ').replaceAll(' ', ' ').replaceAll(' ', ' ').replaceAll(' ', ' ');
return resolve(strToReturn);
}
}
} catch (err) {
if (storedRegexs.length > 0) {
storedRegexs
.filter(e => e)
.forEach(r => {
strToReturn = strToReturn.replace(r.ref, r.regex);
});
}
return resolve(strToReturn);
}
});
} | Remove comments in a string.
@param {string} data file content.
@param {boolean} keepSwaggerTags keep comment with "#swagger.*". | removeComments ( data , keepSwaggerTags = false ) | javascript | swagger-autogen/swagger-autogen | src/handle-data.js | https://github.com/swagger-autogen/swagger-autogen/blob/master/src/handle-data.js | MIT |
function getSwaggerComments(data) {
return new Promise(resolve => {
if (data.length == 0) {
return resolve(data);
}
let strToReturn = '';
let stackComment1 = 0; // For type //
let stackComment2 = 0; // For type /* */
let buffer1 = ''; // For type //
let buffer2 = ''; // For type /* */
// Won't remove comments in strings
let isStr1 = 0; // "
let isStr2 = 0; // '
let isStr3 = 0; // `
try {
for (let idx = 0; idx < data.length; ++idx) {
let c = data[idx];
if (stackComment1 == 0 && stackComment2 == 0) {
// Type '
if (c == "'" && (data[idx - 1] != '\\' || (data[idx - 1] == '\\' && data[idx - 2] == '\\')) && isStr1 == 1) isStr1 = 2;
if (c == "'" && (data[idx - 1] != '\\' || (data[idx - 1] == '\\' && data[idx - 2] == '\\')) && isStr1 == 0 && isStr2 == 0 && isStr3 == 0) isStr1 = 1;
// Type "
if (c == '"' && (data[idx - 1] != '\\' || (data[idx - 1] == '\\' && data[idx - 2] == '\\')) && isStr2 == 1) isStr2 = 2;
if (c == '"' && (data[idx - 1] != '\\' || (data[idx - 1] == '\\' && data[idx - 2] == '\\')) && isStr1 == 0 && isStr2 == 0 && isStr3 == 0) isStr2 = 1;
// Type `
if (c == '`' && (data[idx - 1] != '\\' || (data[idx - 1] == '\\' && data[idx - 2] == '\\')) && isStr3 == 1) isStr3 = 2;
if (c == '`' && (data[idx - 1] != '\\' || (data[idx - 1] == '\\' && data[idx - 2] == '\\')) && isStr1 == 0 && isStr2 == 0 && isStr3 == 0) isStr3 = 1;
}
// Type //
if (c == '/' && data[idx + 1] == '/' && stackComment1 == 0 && stackComment2 == 0) stackComment1 = 1;
if (c == '\n' && stackComment1 == 1) stackComment1 = 2;
// Type /* */
if (c == '/' && data[idx + 1] == '*' && stackComment1 == 0 && stackComment2 == 0) stackComment2 = 1;
if (c == '/' && data[idx - 1] == '*' && stackComment2 == 1) stackComment2 = 2;
if (stackComment1 == 1 || stackComment1 == 2) {
// Keeps the comment being ignored. Like: //
buffer1 += c;
} else if (stackComment2 == 1 || stackComment2 == 2) {
// Keeps the comment being ignored. Like: /* */
buffer2 += c;
}
if (stackComment1 == 2) {
stackComment1 = 0;
if (buffer1.includes('#swagger.')) {
strToReturn += ' ' + buffer1; // keeping the comment that has a swagger tag
buffer1 = '';
} else {
buffer1 = '';
}
}
if (stackComment2 == 2) {
stackComment2 = 0;
if (buffer2.includes('#swagger.')) {
strToReturn += ' ' + buffer2; // keeping the comment that has a swagger tag
buffer2 = '';
} else {
buffer2 = '';
}
}
if (isStr1 == 2) isStr1 = 0;
if (isStr2 == 2) isStr2 = 0;
if (isStr3 == 2) isStr3 = 0;
if (idx == data.length - 1) {
strToReturn = strToReturn.replaceAll(' ', ' ').replaceAll(' ', ' ').replaceAll(' ', ' ').replaceAll(' ', ' ');
return resolve(strToReturn);
}
}
} catch (err) {
return resolve(strToReturn);
}
});
} | Return all "#swagger.*" in a string.
@param {string} data file content. | getSwaggerComments ( data ) | javascript | swagger-autogen/swagger-autogen | src/handle-data.js | https://github.com/swagger-autogen/swagger-autogen/blob/master/src/handle-data.js | MIT |
function removeStrings(data) {
return new Promise(resolve => {
if (!data || data.length == 0) {
return resolve(data);
}
let storedRegexs = [];
let strToReturn = '';
let stackComment1 = 0; // For type //
let stackComment2 = 0; // For type /* */
let buffer = ''; // For type /* */
// Won't remove comments in strings
let isStr1 = 0; // "
let isStr2 = 0; // '
let isStr3 = 0; // `
try {
for (let idx = 0; idx < data.length; ++idx) {
let c = data[idx];
// If in comments or regex, ignore strings
if (stackComment1 == 0 && stackComment2 == 0) {
// Type '
if (c == "'" && (data[idx - 1] != '\\' || (data[idx - 1] == '\\' && data[idx - 2] == '\\')) && isStr1 == 1) {
isStr1 = 2;
} else if (c == "'" && (data[idx - 1] != '\\' || (data[idx - 1] == '\\' && data[idx - 2] == '\\')) && isStr1 == 0 && isStr2 == 0 && isStr3 == 0) {
isStr1 = 1;
}
// Type "
else if (c == '"' && (data[idx - 1] != '\\' || (data[idx - 1] == '\\' && data[idx - 2] == '\\')) && isStr2 == 1) {
isStr2 = 2;
} else if (c == '"' && (data[idx - 1] != '\\' || (data[idx - 1] == '\\' && data[idx - 2] == '\\')) && isStr1 == 0 && isStr2 == 0 && isStr3 == 0) {
isStr2 = 1;
}
// Type `
else if (c == '`' && (data[idx - 1] != '\\' || (data[idx - 1] == '\\' && data[idx - 2] == '\\')) && isStr3 == 1) {
isStr3 = 2;
} else if (c == '`' && (data[idx - 1] != '\\' || (data[idx - 1] == '\\' && data[idx - 2] == '\\')) && isStr1 == 0 && isStr2 == 0 && isStr3 == 0) {
isStr3 = 1;
}
}
// Type //
if (c == '/' && data[idx + 1] == '/' && data[idx - 1] != '\\' && data[idx - 1] != ':' && stackComment1 == 0 && stackComment2 == 0) {
// REFACTOR: improve this. Avoiding cases such as: ... http://... be handled as a comment
stackComment1 = 1;
} else if (c == '\n' && stackComment1 == 1) {
stackComment1 = 2;
}
// Type /* */
else if (c == '/' && data[idx + 1] == '*' && data[idx - 1] != '\\' && stackComment1 == 0 && stackComment2 == 0 && isStr1 == 0 && isStr2 == 0 && isStr3 == 0) {
stackComment2 = 1;
} else if (c == '/' && data[idx - 1] == '*' && stackComment2 == 1 && isStr1 == 0 && isStr2 == 0 && isStr3 == 0 && buffer != '/*') {
stackComment2 = 2;
}
/**
* REGEX START
*/
if (c == '/' && data[idx - 1] != '\\' && data[idx + 1] != '/' && isStr1 == 0 && isStr2 == 0 && isStr3 == 0 && stackComment1 == 0 && stackComment2 == 0) {
// Checking if it is valid regex
let lidx = idx + 1;
let lstr = '';
let regexStackParenthesis = 0;
let regexStackSquareBracket = 0;
while (lidx < data.length) {
let lc = data[lidx];
if (lc == '(') {
regexStackParenthesis += 1;
} else if (lc == ')') {
regexStackParenthesis -= 1;
} else if (lc == '[') {
regexStackSquareBracket += 1;
} else if (lc == ']') {
regexStackSquareBracket -= 1;
}
lstr += lc;
lidx += 1;
if (data[lidx] == '/' && data[idx - 1] != '\\' && regexStackParenthesis < 1 && regexStackSquareBracket < 1) {
if (regexStackParenthesis < 0) {
regexStackParenthesis = 0;
}
if (regexStackSquareBracket < 0) {
regexStackSquareBracket = 0;
}
break;
}
}
try {
if (''.split(new RegExp(lstr)).length > -1) {
// Valid regex
const ref = `__¬¬¬__${idx}__¬¬¬__`;
data = utils.replaceRange(data, idx, lidx + 1, ref);
c = data[idx];
// Storing regex apart
storedRegexs.push({ ref, regex: `/${lstr}/` });
}
} catch (err) {
// Invalid regex
}
}
/* REGEX END */
if (isStr1 == 0 && isStr2 == 0 && isStr3 == 0) {
strToReturn += c;
} else if (stackComment2 == 1 || stackComment2 == 2) {
buffer += c;
}
if (stackComment1 == 2) {
stackComment1 = 0;
}
if (stackComment2 == 2) {
stackComment2 = 0;
}
if (isStr1 == 2) isStr1 = 0;
if (isStr2 == 2) isStr2 = 0;
if (isStr3 == 2) isStr3 = 0;
if (idx == data.length - 1) {
if (storedRegexs.length > 0) {
storedRegexs
.filter(e => e)
.forEach(r => {
strToReturn = strToReturn.replace(r.ref, r.regex);
});
}
strToReturn = strToReturn.replaceAll(' ', ' ').replaceAll(' ', ' ').replaceAll(' ', ' ').replaceAll(' ', ' '); // TODO: Verifiy
return resolve(strToReturn);
}
}
} catch (err) {
if (storedRegexs.length > 0) {
storedRegexs
.filter(e => e)
.forEach(r => {
strToReturn = strToReturn.replace(r.ref, r.regex);
});
}
return resolve(strToReturn);
}
});
} | Remove all strings.
@param {string} data file content. | removeStrings ( data ) | javascript | swagger-autogen/swagger-autogen | src/handle-data.js | https://github.com/swagger-autogen/swagger-autogen/blob/master/src/handle-data.js | MIT |
function removeInsideParentheses(data, keepParentheses = false, level = 0) {
return new Promise(resolve => {
if (data.length == 0) {
return resolve(data);
}
let storedRegexs = [];
let strToReturn = '';
let stack = 0;
let buffer = '';
try {
for (let idx = 0; idx < data.length; ++idx) {
let c = data[idx];
/**
* REGEX START
*/
if (c == '/' && data[idx - 1] != '\\' && data[idx + 1] != '/' && stack < 1) {
// Checking if it is valid regex
let lidx = idx + 1;
let lstr = '';
let regexStackParenthesis = 0;
let regexStackSquareBracket = 0;
while (lidx < data.length) {
// prevent loop
let lc = data[lidx];
if (lc == '(') {
regexStackParenthesis += 1;
} else if (lc == ')') {
regexStackParenthesis -= 1;
} else if (lc == '[') {
regexStackSquareBracket += 1;
} else if (lc == ']') {
regexStackSquareBracket -= 1;
}
lstr += lc;
lidx += 1;
if (data[lidx] == '/' && data[idx - 1] != '\\' && regexStackParenthesis < 1 && regexStackSquareBracket < 1) {
if (regexStackParenthesis < 0) {
regexStackParenthesis = 0;
}
if (regexStackSquareBracket < 0) {
regexStackSquareBracket = 0;
}
break;
}
}
try {
if (''.split(new RegExp(lstr)).length > -1) {
// Valid regex
const ref = `__¬¬¬__${idx}__¬¬¬__`;
data = utils.replaceRange(data, idx, lidx + 1, ref);
c = data[idx];
// Storing regex apart
storedRegexs.push({ ref, regex: `/${lstr}/` });
}
} catch (err) {
// Invalid regex
}
}
/* REGEX END */
if (c == '(' && data[idx - 1] != '\\') {
stack += 1;
if (keepParentheses) {
buffer += '(';
}
}
if (stack == level) {
strToReturn += c;
}
if (stack == 1) {
buffer += c;
}
if (c == ')' && data[idx - 1] != '\\') {
stack -= 1;
if (stack < 0) {
stack = 0;
}
if (keepParentheses) {
buffer += ')';
}
if (stack == level) {
let auxIdx = idx + 1;
let validChar = null;
while (validChar == null && auxIdx <= data.length) {
if (data[auxIdx] != ' ' && data[auxIdx] != '\n' && data[auxIdx] != '\t') {
validChar = data[auxIdx];
}
auxIdx += 1;
}
if (validChar == '(') {
/**
* Recognize middlewares in parentheses
* Issue: #67
*/
strToReturn += buffer;
}
buffer = '';
}
if (stack == level && keepParentheses) {
strToReturn += '()';
}
}
if (idx == data.length - 1) {
if (storedRegexs.length > 0) {
storedRegexs
.filter(e => e)
.forEach(r => {
strToReturn = strToReturn.replace(r.ref, r.regex);
});
}
return resolve(strToReturn);
}
}
} catch (err) {
if (storedRegexs.length > 0) {
storedRegexs
.filter(e => e)
.forEach(r => {
strToReturn = strToReturn.replace(r.ref, r.regex);
});
}
return resolve(strToReturn);
}
});
} | Remove all content in parentheses.
@param {string} data file content.
@param {boolean} keepParentheses if true, keep the parentheses "()" after erasing the contents inside.
@param {number} level remove according to stack level | removeInsideParentheses ( data , keepParentheses = false , level = 0 ) | javascript | swagger-autogen/swagger-autogen | src/handle-data.js | https://github.com/swagger-autogen/swagger-autogen/blob/master/src/handle-data.js | MIT |
function addReferenceToMethods(data, patterns) {
return new Promise(resolve => {
if (!data) {
return resolve(data);
}
let auxData = data;
let routeEndpoints = [];
const origData = data;
try {
// CASE: router.route('/user').get(authorize, (req, res) => {
let aDataRoute = auxData.split(new RegExp(`.*\\s*\\n*\\t*\\.\\s*\\n*\\t*route\\s*\\n*\\t*\\(`));
if (aDataRoute.length > 1) {
for (let idx = 1; idx < aDataRoute.length; ++idx) {
// CASE: app.get([_[get]_])('/automatic1/users/:id', (req, res) => {
for (let mIdx = 0; mIdx < statics.METHODS.length; ++mIdx) {
let method = statics.METHODS[mIdx];
let line = aDataRoute[idx].split(new RegExp(`\\)(\\s*|\\n*|\\t*)\\.\\s*\\n*\\t*${method}\\s*\\n*\\t*\\(`));
if (line.length === 3) {
line[0] = line[0].split(')')[0];
// TODO: refactor this
line[2] = line[2].split(new RegExp(`\\)(\\s*|\\n*|\\t*)\\.\\s*\\n*\\t*get\\s*\\n*\\t*\\(|` + `\\)(\\s*|\\n*|\\t*)\\.\\s*\\n*\\t*head\\s*\\n*\\t*\\(|` + `\\)(\\s*|\\n*|\\t*)\\.\\s*\\n*\\t*post\\s*\\n*\\t*\\(|` + `\\)(\\s*|\\n*|\\t*)\\.\\s*\\n*\\t*put\\s*\\n*\\t*\\(|` + `\\)(\\s*|\\n*|\\t*)\\.\\s*\\n*\\t*delete\\s*\\n*\\t*\\(|` + `\\)(\\s*|\\n*|\\t*)\\.\\s*\\n*\\t*patch\\s*\\n*\\t*\\(|` + `\\)(\\s*|\\n*|\\t*)\\.\\s*\\n*\\t*options\\s*\\n*\\t*\\(`))[0];
routeEndpoints.push((patterns[0] || '_app') + `.${method}(` + line[0] + ',' + line[2]);
}
}
}
auxData = aDataRoute[0] + routeEndpoints.join('\n');
}
/**
* CASE: router.get(...).post(...).put(...)...
*/
let regexChainedEndpoint = '';
for (let idxMethod = 0; idxMethod < statics.METHODS.length; ++idxMethod) {
regexChainedEndpoint += `(\\)\\s*\\n*\\t*\\.\\s*\\n*\\t*${statics.METHODS[idxMethod]}\\s*\\n*\\t*\\()|`;
}
regexChainedEndpoint = regexChainedEndpoint.replace(/\|$/, '');
auxData = auxData.split(new RegExp(regexChainedEndpoint));
auxData = auxData.filter(d => d);
for (let idx = 1; idx < auxData.length; idx += 2) {
if (auxData[idx + 1] && auxData[idx + 1].split('/*')[0].includes('*/'))
// Avoind modification in string of #swagger.description
continue;
auxData[idx] = auxData[idx].replace('.', '____CHAINED____.');
}
auxData = auxData.join('');
// END CASE
let methods = [...statics.METHODS, 'use', 'all'];
for (let idx = 0; idx < methods.length; ++idx) {
for (let idxPtn = 0; idxPtn < patterns.length; ++idxPtn) {
let method = methods[idx];
let pattern = patterns[idxPtn];
let regexMethods = `${pattern}\\s*\\n*\\t*\\.\\s*\\n*\\t*${method}\\s*\\n*\\t*\\((?!\\[)`;
auxData = auxData.split(new RegExp(regexMethods));
/**
* Chained middlewares. For example: route.use(...).use(...).use(...)
*/
if (auxData && auxData.length > 1 && method == 'use') {
for (let idxData = 1; idxData < auxData.length; ++idxData) {
let chainedUse = auxData[idxData].split(new RegExp(`\\)\\s*\\n*\\t*\\.\\s*\\n*\\t*use\\s*\\n*\\t*\\(`));
if (chainedUse.length > 1) {
auxData[idxData] = chainedUse.join(`) ${pattern}` + `.use([_[use]_])([_[${pattern}]_])(`);
}
}
}
auxData = auxData.join((pattern || '_app') + `.${method}([_[${method}]_])([_[${pattern}]_])(`);
}
if (idx == methods.length - 1) {
/* Adding byte position */
auxData = auxData.split(']_])([_[');
let bytePosition = auxData[0].split('([_[')[0].length;
for (let idxPtn = 1; idxPtn < auxData.length; ++idxPtn) {
try {
let auxBytePosition = auxData[idxPtn].split(']_])(')[1].split('([_[')[0].length;
auxData[idxPtn] = auxData[idxPtn].replace(']_])(', `]_])([_[${bytePosition}]_])(`);
bytePosition += auxBytePosition;
} catch (err) {
if (auxData[idxPtn]) {
auxData[idxPtn] = auxData[idxPtn].replace(']_])(', `]_])([_[${999999999999}]_])(`);
}
continue;
}
}
auxData = auxData.join(']_])([_[');
return resolve(auxData);
}
}
} catch (err) {
return resolve(origData);
}
});
} | Add the pattern "([_[method]_])([_[foo]_])([_[index]_])" to all endpoints. This standardize each endpoint.
'method': get, post, put, etc.
'foo': app, route, etc.
'index': id
@param {string} data file content.
@param {array} patterns array containing patterns recognized as: app, route, etc. | addReferenceToMethods ( data , patterns ) | javascript | swagger-autogen/swagger-autogen | src/handle-data.js | https://github.com/swagger-autogen/swagger-autogen/blob/master/src/handle-data.js | MIT |
function getQueryIndirectly(elem, request, objParameters) {
const origObjParameters = objParameters;
try {
for (let idx = 0; idx < request.length; ++idx) {
let req = request[idx];
if (req && req.split(new RegExp('\\;|\\{|\\(|\\[|\\"|\\\'|\\`|\\}|\\)|\\]|\\:|\\,|\\*|\\!|\\|')).length == 1 && elem && elem.split(new RegExp(' .*?\\s*\\t*=\\s*\\t*' + req + '\\.\\s*\\t*query(\\s|\\n|;|\\t)', 'gmi').length > 1)) {
let queryVars = [];
let aQuerys = elem.split(new RegExp('\\s*\\t*=\\s*\\t*' + req + '\\.\\s*\\t*query(\\s|\\n|;|\\t)', 'i'));
aQuerys = aQuerys.slice(0, -1);
if (aQuerys.length > 0) {
// get variables name
for (let idx = 0; idx < aQuerys.length; idx++) {
if (aQuerys[idx] && aQuerys[idx].replaceAll(' ', '') != '') {
queryVars.push(aQuerys[idx].split(new RegExp('\\s*|\\t*')).slice(-1)[0]);
}
}
if (queryVars.length > 0) {
queryVars
.filter(e => e)
.forEach(query => {
if (query.split(new RegExp('\\;|\\{|\\(|\\[|\\"|\\\'|\\`|\\}|\\)|\\]|\\:|\\,|\\*|\\!|\\|')).length == 1) {
let varNames = elem.split(new RegExp(' ' + query + '\\.')).splice(1);
varNames = varNames.filter(e => e).map(v => (v = v.split(new RegExp('\\s|;|\\n|\\t'))[0]));
varNames
.filter(e => e)
.forEach(name => {
objParameters[name] = {
name,
in: 'query'
};
});
}
});
}
}
}
}
return objParameters;
} catch (err) {
return origObjParameters;
}
} | TODO: fill
@param {*} elem
@param {*} request
@param {*} objParameters | getQueryIndirectly ( elem , request , objParameters ) | javascript | swagger-autogen/swagger-autogen | src/handle-data.js | https://github.com/swagger-autogen/swagger-autogen/blob/master/src/handle-data.js | MIT |
function getHeader(elem, path, method, response, objEndpoint) {
const origObjEndpoint = objEndpoint;
try {
for (let idx = 0; idx < response.length; ++idx) {
let res = response[idx];
elem = elem.split(new RegExp('application/xml', 'i'));
elem = elem.join('application/xml');
if (res && elem && elem.split(new RegExp(res + '\\s*\\t*\\n*\\.\\s*\\t*\\n*setHeader\\s*\\t*\\n*\\(')).length > 1) {
elem = elem.split(new RegExp(res + '\\s*\\t*\\n*\\.\\s*\\t*\\n*setHeader\\s*\\('));
if (elem.length > 1 && elem[1].toLocaleLowerCase().includes('content-type')) {
let content = elem[1].split(',')[1];
content = utils.popString(content);
objEndpoint[path][method].produces = [content];
}
}
}
if (swaggerTags.getOpenAPI() || (objEndpoint[path][method].produces && objEndpoint[path][method].produces.length == 0)) {
objEndpoint[path][method].produces = undefined;
}
return objEndpoint;
} catch (err) {
return origObjEndpoint;
}
} | Recognize content of .setHeader(...) method (ExpressJS).
@param {string} elem content.
@param {string} path endpoint's path.
@param {string} method
@param {array} response array containing variables of response.
@param {object} objEndpoint | getHeader ( elem , path , method , response , objEndpoint ) | javascript | swagger-autogen/swagger-autogen | src/handle-data.js | https://github.com/swagger-autogen/swagger-autogen/blob/master/src/handle-data.js | MIT |
function getPath(elem, autoMode) {
if (!elem) {
return null;
}
try {
let path = false;
let line = elem;
line = line.trim();
if (autoMode && !elem.includes(statics.SWAGGER_TAG + '.path')) {
const quotMark = line[0];
if ((quotMark == '"' || quotMark == "'" || quotMark == '`') && line.split(quotMark).length > 2) {
path = utils.popString(line);
path = path.split('/').map(p => {
if (p.includes(':')) p = '{' + p.replace(':', '') + '}';
return p;
});
path = path.join('/');
} else {
path = '/_undefined_path_0x' + elem.length.toString(16);
}
} else if (elem.includes(statics.SWAGGER_TAG + '.path')) {
// Search for #swagger.path
path = elem.split(new RegExp(statics.SWAGGER_TAG + '.path\\s*\\='))[1];
path = utils.popString(path);
} else {
path = '/_undefined_path_0x' + elem.length.toString(16);
}
return path;
} catch (err) {
return '/_undefined_path_0x' + elem.length.toString(16);
}
} | TODO: fill
@param {*} elem
@param {*} autoMode | getPath ( elem , autoMode ) | javascript | swagger-autogen/swagger-autogen | src/swagger-tags.js | https://github.com/swagger-autogen/swagger-autogen/blob/master/src/swagger-tags.js | MIT |
function getMethodTag(data, reference) {
try {
if (data.includes(statics.SWAGGER_TAG + '.method')) {
let method = data.split(new RegExp(statics.SWAGGER_TAG + '.method' + '\\s*\\=\\s*'))[1];
method = utils.popString(method);
if (method && statics.METHODS.includes(method.toLowerCase())) {
return method.toLowerCase();
}
}
return false;
} catch (err) {
if (!getDisableLogs()) {
console.error(`[swagger-autogen]: '${statics.SWAGGER_TAG}.method' out of structure in\n... '${reference.filePath}'`);
}
return false;
}
} | Get #swagger.method
@param {string} data
@returns | getMethodTag ( data , reference ) | javascript | swagger-autogen/swagger-autogen | src/swagger-tags.js | https://github.com/swagger-autogen/swagger-autogen/blob/master/src/swagger-tags.js | MIT |
function getIgnoreTag(elem) {
try {
if (elem && elem.includes(statics.SWAGGER_TAG + '.ignore'))
if (elem.split(new RegExp(statics.SWAGGER_TAG + '.ignore\\s*\\=\\s*'))[1].slice(0, 4) == 'true') {
return true;
}
return false;
} catch (err) {
return false;
}
} | Search for #swagger.ignore
@param {*} elem | getIgnoreTag ( elem ) | javascript | swagger-autogen/swagger-autogen | src/swagger-tags.js | https://github.com/swagger-autogen/swagger-autogen/blob/master/src/swagger-tags.js | MIT |
function getAutoTag(data) {
try {
if (data.includes(statics.SWAGGER_TAG + '.auto')) {
let auto = data.split(new RegExp(statics.SWAGGER_TAG + '.auto' + '\\s*\\=\\s*'))[1];
auto = auto.split(new RegExp('\\s|\\n|\\t|\\;'))[0];
if (auto && auto.toLowerCase() === 'false') {
return false;
}
}
return true;
} catch (err) {
return true;
}
} | Search for #swagger.auto = false (by default is true)
@param {*} data | getAutoTag ( data ) | javascript | swagger-autogen/swagger-autogen | src/swagger-tags.js | https://github.com/swagger-autogen/swagger-autogen/blob/master/src/swagger-tags.js | MIT |
function getDeprecatedTag(data, reference) {
try {
if (data.includes(statics.SWAGGER_TAG + '.deprecated')) {
let deprecated = data.split(new RegExp(statics.SWAGGER_TAG + '.deprecated' + '\\s*\\=\\s*'))[1];
deprecated = deprecated.split(new RegExp('\\s|\\n|\\t|\\;'))[0];
if (deprecated && deprecated.toLowerCase() === 'true') {
return true;
}
}
return false;
} catch (err) {
if (!getDisableLogs()) {
console.error(`[swagger-autogen]: '${statics.SWAGGER_TAG}.deprecated' out of structure in\n'${reference.filePath}' ... ${reference.predefPattern}.${reference.method}('${reference.path}', ...)`);
}
return false;
}
} | Search for #swagger.deprecated = true (by default is false)
@param {*} data | getDeprecatedTag ( data , reference ) | javascript | swagger-autogen/swagger-autogen | src/swagger-tags.js | https://github.com/swagger-autogen/swagger-autogen/blob/master/src/swagger-tags.js | MIT |
function getAutoParameterTag(data, reference, paramName) {
try {
if (data.includes(statics.SWAGGER_TAG + `.${paramName}`)) {
let autoBody = data.split(new RegExp(statics.SWAGGER_TAG + `.${paramName}` + '\\s*\\=\\s*'))[1];
autoBody = autoBody.split(new RegExp('\\s|\\n|\\t|\\;'))[0];
if (autoBody && autoBody.toLowerCase() === 'false') {
return false;
}
}
return true;
} catch (err) {
if (!getDisableLogs()) {
console.error(`[swagger-autogen]: '${statics.SWAGGER_TAG}.${paramName}' out of structure in\n'${reference.filePath}' ... ${reference.predefPattern}.${reference.method}('${reference.path}', ...)`);
}
return true;
}
} | Search for #swagger.someThing = false (by default is true)
@param {*} data | getAutoParameterTag ( data , reference , paramName ) | javascript | swagger-autogen/swagger-autogen | src/swagger-tags.js | https://github.com/swagger-autogen/swagger-autogen/blob/master/src/swagger-tags.js | MIT |
async function getParametersTag(data, objParameters, reference) {
const origObjParameters = objParameters;
try {
data = data.replaceAll('"', "'").replaceAll('`', "'").replaceAll('`', "'").replaceAll('\n', ' ').replaceAll('#definitions', '#/definitions');
data = data.replaceAll("'@enum'", '@enum').replaceAll('"@enum"', '@enum').replaceAll('`@enum`', '@enum').replaceAll('@enum', '"@enum"');
if (getOpenAPI() && data.includes('#/definitions')) {
data = data.replaceAll('#/definitions', '#/components/schemas');
}
let swaggerParameters = data.split(new RegExp(`${statics.SWAGGER_TAG}.parameters`));
swaggerParameters.shift();
for (let idx = 0; idx < swaggerParameters.length; ++idx) {
let name = swaggerParameters[idx].split(new RegExp('\\[|\\]'))[1].replaceAll("'", '');
let parameter = null;
let parameterObj = null;
try {
if (getOpenAPI() && name && name === '$ref') {
swaggerParameters[idx] = swaggerParameters[idx].split('=');
swaggerParameters[idx].shift();
swaggerParameters[idx] = swaggerParameters[idx].join('=');
parameter = await utils.stack0SymbolRecognizer(swaggerParameters[idx], '[', ']');
parameterObj = eval(`(${'[' + parameter + ']'})`);
parameterObj
.filter(e => e)
.forEach((parameter, idx) => {
objParameters[`$ref__¬¬__${idx}`] = {
$ref: parameter
};
});
return objParameters;
} else {
parameter = await utils.stack0SymbolRecognizer(swaggerParameters[idx], '{', '}');
parameterObj = eval(`(${'{' + parameter + '}'})`);
objParameters[name] = {
name,
...objParameters[name],
...parameterObj
};
}
} catch (err) {
console.error('[swagger-autogen]: Syntax error: ' + parameter);
console.error(`[swagger-autogen]: '${statics.SWAGGER_TAG}.parameters' out of structure in\n'${reference.filePath}' ... ${reference.predefPattern}.${reference.method}('${reference.path}', ...)`);
return origObjParameters;
}
/**
* Specification rules
*/
if (objParameters[name].in && objParameters[name].in.toLowerCase() === 'path' && !objParameters[name].required) {
objParameters[name].required = true;
}
if (!objParameters[name].in) {
// by default: 'in' is 'query'
objParameters[name].in = 'query';
}
if (!objParameters[name].type && !objParameters[name].schema && objParameters[name].in != 'body') {
// by default: 'type' is 'string' when 'schema' is missing
if (getOpenAPI()) {
objParameters[name].schema = { type: 'string' };
} else {
objParameters[name].type = 'string';
}
}
if (objParameters[name].type && objParameters[name].in && objParameters[name].in.toLowerCase() === 'body') {
delete objParameters[name].type;
}
if (objParameters[name].required && typeof objParameters[name].required === 'string') {
if (objParameters[name].required.toLowerCase() === 'true') {
objParameters[name].required = true;
} else {
objParameters[name].required = false;
}
}
if (objParameters[name].in && objParameters[name].in.toLowerCase() === 'body' && !objParameters[name].schema) {
objParameters[name].schema = { __AUTO_GENERATE__: true };
}
if (objParameters[name] && objParameters[name]['@schema']) {
objParameters[name].schema = objParameters[name]['@schema'];
delete objParameters[name]['@schema'];
} else if (objParameters[name].schema && objParameters[name] && objParameters[name].schema && !objParameters[name].schema.$ref) {
if (objParameters[name].schema['@enum']) {
/**
* Enum (OpenAPI v3)
*/
let enumType = 'string';
if (objParameters[name].schema['@enum'][0]) {
enumType = typeof objParameters[name].schema['@enum'][0];
}
objParameters[name].schema.type = enumType;
objParameters[name].schema.enum = objParameters[name].schema['@enum'];
delete objParameters[name].schema['@enum'];
} else if (!(Object.keys(objParameters[name].schema).length == 1 && objParameters[name].schema.type) && (!objParameters[name].schema.properties || (!objParameters[name].schema.properties['__AUTO_GENERATE__'] && objParameters[name].schema.properties && Object.keys(objParameters[name].schema.properties).length > 0))) {
objParameters[name].schema = formatDefinitions(objParameters[name].schema);
}
}
/**
* Forcing convertion to OpenAPI 3.x
*/
if (getOpenAPI()) {
if (objParameters[name] && objParameters[name].type && !objParameters[name].schema) {
objParameters[name].schema = { type: objParameters[name].type };
delete objParameters[name].type;
}
if (objParameters[name] && objParameters[name].schema && !objParameters[name].schema.$ref) {
objParameters[name].schema = {
type: objParameters[name].type ? objParameters[name].type : 'string',
...objParameters[name].schema
};
if (objParameters[name].type) {
delete objParameters[name].type;
}
}
}
// prioritizes #swagger.parameters
if (objParameters[`${name}__[__[__${objParameters[name].in}__]__]`]) {
delete objParameters[`${name}__[__[__${objParameters[name].in}__]__]`];
}
}
return objParameters;
} catch (err) {
if (!getDisableLogs()) {
console.error(`[swagger-autogen]: '${statics.SWAGGER_TAG}.parameters' out of structure in\n'${reference.filePath}' ... ${reference.predefPattern}.${reference.method}('${reference.path}', ...)`);
}
return origObjParameters;
}
} | Get the content in '#swagger.parameters'
@param {string} data file content
@param {object} objParameters | getParametersTag ( data , objParameters , reference ) | javascript | swagger-autogen/swagger-autogen | src/swagger-tags.js | https://github.com/swagger-autogen/swagger-autogen/blob/master/src/swagger-tags.js | MIT |
objInBody.name = 'body'; // By default, the name of object recognized automatically in the body will be 'body' if no parameter are found to be concatenate with it. | If #swagger.parameter or #swagger.requestBody is present
the automatic body recognition will be ignored. | (anonymous) | javascript | swagger-autogen/swagger-autogen | src/handle-files.js | https://github.com/swagger-autogen/swagger-autogen/blob/master/src/handle-files.js | MIT |
orm.registerModel = function registerModel(wmd) {
wmds.push(wmd);
}; | .registerModel()
Register a "weird intermediate model definition thing". (see above)
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FUTURE: Deprecate support for this method in favor of simplified `Waterline.start()`
(see bottom of this file). In WL 1.0, remove this method altogether.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
@param {Dictionary} wmd | registerModel ( wmd ) | javascript | balderdashy/waterline | lib/waterline.js | https://github.com/balderdashy/waterline/blob/master/lib/waterline.js | MIT |
module.exports.start = function (options, done){
// Verify usage & apply defaults:
if (!_.isFunction(done)) {
throw new Error('Please provide a valid callback function as the 2nd argument to `Waterline.start()`. (Instead, got: `'+done+'`)');
}
try {
if (!_.isObject(options) || _.isArray(options) || _.isFunction(options)) {
throw new Error('Please provide a valid dictionary (plain JS object) as the 1st argument to `Waterline.start()`. (Instead, got: `'+options+'`)');
}
if (!_.isObject(options.adapters) || _.isArray(options.adapters) || _.isFunction(options.adapters)) {
throw new Error('`adapters` must be provided as a valid dictionary (plain JS object) of adapter definitions, keyed by adapter identity. (Instead, got: `'+options.adapters+'`)');
}
if (!_.isObject(options.datastores) || _.isArray(options.datastores) || _.isFunction(options.datastores)) {
throw new Error('`datastores` must be provided as a valid dictionary (plain JS object) of datastore configurations, keyed by datastore name. (Instead, got: `'+options.datastores+'`)');
}
if (!_.isObject(options.models) || _.isArray(options.models) || _.isFunction(options.models)) {
throw new Error('`models` must be provided as a valid dictionary (plain JS object) of model definitions, keyed by model identity. (Instead, got: `'+options.models+'`)');
}
if (_.isUndefined(options.defaultModelSettings)) {
options.defaultModelSettings = {};
} else if (!_.isObject(options.defaultModelSettings) || _.isArray(options.defaultModelSettings) || _.isFunction(options.defaultModelSettings)) {
throw new Error('If specified, `defaultModelSettings` must be a dictionary (plain JavaScript object). (Instead, got: `'+options.defaultModelSettings+'`)');
}
var VALID_OPTIONS = ['adapters', 'datastores', 'models', 'defaultModelSettings'];
var unrecognizedOptions = _.difference(_.keys(options), VALID_OPTIONS);
if (unrecognizedOptions.length > 0) {
throw new Error('Unrecognized option(s):\n '+unrecognizedOptions+'\n\nValid options are:\n '+VALID_OPTIONS+'\n');
}
// Check adapter identities.
_.each(options.adapters, function (adapter, key){
if (_.isUndefined(adapter.identity)) {
adapter.identity = key;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// Note: We removed the following purely for convenience.
// If this comes up again, we should consider bringing it back instead of the more
// friendly behavior above. But in the mean time, erring on the side of less typing
// in userland by gracefully adjusting the provided adapter def.
// ```
// throw new Error('All adapters should declare an `identity`. But the adapter passed in under `'+key+'` has no identity! (Keep in mind that this adapter could get require()-d from somewhere else.)');
// ```
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
}
else if (adapter.identity !== key) {
throw new Error('The `identity` explicitly defined on an adapter should exactly match the key under which it is passed in to `Waterline.start()`. But the adapter passed in for key `'+key+'` has an identity that does not match: `'+adapter.identity+'`');
}
});//</_.each>
// Now go ahead: start building & initializing the ORM.
var orm = new Waterline();
// Register models (checking model identities along the way).
//
// > In addition: Unfortunately, passing in `defaults` in `initialize()`
// > below doesn't _ACTUALLY_ apply the specified model settings as
// > defaults right now -- it only does so for implicit junction models.
// > So we have to do that ourselves for the rest of the models out here
// > first in this iteratee. Also note that we handle `attributes` as a
// > special case.
_.each(options.models, function (userlandModelDef, key){
if (_.isUndefined(userlandModelDef.identity)) {
userlandModelDef.identity = key;
}
else if (userlandModelDef.identity !== key) {
throw new Error('If `identity` is explicitly defined on a model definition, it should exactly match the key under which it is passed in to `Waterline.start()`. But the model definition passed in for key `'+key+'` has an identity that does not match: `'+userlandModelDef.identity+'`');
}
_.defaults(userlandModelDef, _.omit(options.defaultModelSettings, 'attributes'));
if (options.defaultModelSettings.attributes) {
userlandModelDef.attributes = userlandModelDef.attributes || {};
_.defaults(userlandModelDef.attributes, options.defaultModelSettings.attributes);
}
orm.registerModel(Waterline.Model.extend(userlandModelDef));
});//</_.each>
// Fire 'er up
orm.initialize({
adapters: options.adapters,
datastores: options.datastores,
defaults: options.defaultModelSettings
}, function (err, _classicOntology) {
if (err) { return done(err); }
// Attach two private properties for compatibility's sake.
// (These are necessary for utilities that accept `orm` to work.)
// > But note that we do this as non-enumerable properties
// > to make it less tempting to rely on them in userland code.
// > (Instead, use `getModel()`!)
Object.defineProperty(orm, 'collections', {
value: _classicOntology.collections
});
Object.defineProperty(orm, 'datastores', {
value: _classicOntology.datastores
});
return done(undefined, orm);
});
} catch (err) { return done(err); }
};//</Waterline.start()> | Waterline.start()
Build and initialize a new Waterline ORM instance using the specified
userland ontology, including model definitions, datastore configurations,
and adapters.
--EXPERIMENTAL--
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FUTURE: Have this return a Deferred using parley (so it supports `await`)
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
@param {Dictionary} options
@property {Dictionary} models
@property {Dictionary} datastores
@property {Dictionary} adapters
@property {Dictionary?} defaultModelSettings
@param {Function} done
@param {Error?} err
@param {Ref} orm | module.exports.start ( options , done ) | javascript | balderdashy/waterline | lib/waterline.js | https://github.com/balderdashy/waterline/blob/master/lib/waterline.js | MIT |
module.exports.stop = function (orm, done){
// Verify usage & apply defaults:
if (!_.isFunction(done)) {
throw new Error('Please provide a valid callback function as the 2nd argument to `Waterline.stop()`. (Instead, got: `'+done+'`)');
}
try {
if (!_.isObject(orm)) {
throw new Error('Please provide a Waterline ORM instance (obtained from `Waterline.start()`) as the first argument to `Waterline.stop()`. (Instead, got: `'+orm+'`)');
}
orm.teardown(function (err){
if (err) { return done(err); }
return done();
});//_β_
} catch (err) { return done(err); }
}; | Waterline.stop()
Tear down the specified Waterline ORM instance.
--EXPERIMENTAL--
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FUTURE: Have this return a Deferred using parley (so it supports `await`)
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
@param {Ref} orm
@param {Function} done
@param {Error?} err | module.exports.stop ( orm , done ) | javascript | balderdashy/waterline | lib/waterline.js | https://github.com/balderdashy/waterline/blob/master/lib/waterline.js | MIT |
module.exports.getModel = function (modelIdentity, orm){
return getModel(modelIdentity, orm);
}; | Waterline.getModel()
Look up one of an ORM's models by identity.
(If no matching model is found, this throws an error.)
--EXPERIMENTAL--
------------------------------------------------------------------------------------------
@param {String} modelIdentity
The identity of the model this is referring to (e.g. "pet" or "user")
@param {Ref} orm
The ORM instance to look for the model in.
------------------------------------------------------------------------------------------
@returns {Ref} [the Waterline model]
------------------------------------------------------------------------------------------
@throws {Error} If no such model exists.
E_MODEL_NOT_REGISTERED
@throws {Error} If anything else goes wrong.
------------------------------------------------------------------------------------------ | module.exports.getModel ( modelIdentity , orm ) | javascript | balderdashy/waterline | lib/waterline.js | https://github.com/balderdashy/waterline/blob/master/lib/waterline.js | MIT |
var MetaModel = module.exports = function MetaModel (orm, adapterWrapper) {
// Attach a private reference to the adapter definition indicated by
// this model's configured `datastore`.
this._adapter = adapterWrapper.adapter;
// Attach a private reference to the ORM.
this._orm = orm;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// > Note that we also alias it as `this.waterline`.
this.waterline = orm;
// ^^^
// FUTURE: remove this alias in Waterline v1.0
// (b/c it implies that `this.waterline` might be the stateless export from
// the Waterline package itself, rather than what it actually is: a configured
// ORM instance)
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// Initialize the `attributes` of our new MetaModel instance (e.g. `User.attributes`)
// to an empty dictionary, unless they're already set.
if (_.isUndefined(this.attributes)) {
this.attributes = {};
}
else {
if (!_.isObject(this.attributes)) {
throw new Error('Consistency violation: When instantiating this new instance of MetaModel, it became clear (within the constructor) that `this.attributes` was already set, and not a dictionary: '+util.inspect(this.attributes, {depth: 5})+'');
}
else {
// FUTURE: Consider not allowing this, because it's weird.
}
}
// Build a dictionary of all lifecycle callbacks applicable to this model, and
// attach it as a private property (`_callbacks`).
this._callbacks = LifecycleCallbackBuilder(this);
//^^FUTURE: bust this utility apart to make it stateless like the others
//
//^^FUTURE: Also, document what's going on here as far as timing-- i.e. answering questions
//like "when are model settings from the original model definition applied?" and
//"How are they set?".
// Set the `hasSchema` flag for this model.
// > This is based on a handful of factors, including the original model definition,
// > ORM-wide default model settings, and (if defined) an implicit default from the
// > adapter itself.
this.hasSchema = hasSchemaCheck(this);
// ^^FUTURE: change utility's name to either the imperative mood (e.g. `getSchemafulness()`)
// or interrogative mood (`isSchemaful()`) for consistency w/ the other utilities
// (and to avoid confusion, because the name of the flag makes it kind of crazy in this case.)
// Build a TransformerBuilder instance and attach it as a private property (`_transformer`).
this._transformer = new TransformerBuilder(this.schema);
// ^^FUTURE: bust this utility apart to make it stateless like the others
return this;
// ^^FUTURE: remove this `return` (it shouldn't be necessary)
}; | MetaModel
Construct a new MetaModel instance (e.g. `User` or `WLModel`) with methods for
interacting with a set of structured database records.
> This is really just the same idea as constructing a "Model instance"-- we just
> use the term "MetaModel" for utmost clarity -- since at various points in the
> past, individual records were referred to as "model instances" rather than "records".
>
> In other words, this file contains the entry point for all ORM methods
> (e.g. User.find()). So like, `User` is a MetaModel instance. You might
> call it a "model" or a "model model" -- the important thing is just to
> understand that we're talking about the same thing in either case.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Usage:
```
var WLModel = new MetaModel(orm, { adapter: require('sails-disk') });
// (sorry about the capital "W" in the instance!)
```
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
@param {Dictionary} orm
@param {Dictionary} adapterWrapper
@property {Dictionary} adapter
The adapter definition.
************************************************************
FUTURE: probably just remove this second argument. Instead of
passing it in, it seems like we should just look up the
appropriate adapter at the top of this constructor function
(or even just attach `._adapter` in userland- after instantiating
the new MetaModel instance-- e.g. "WLModel"). The only code that
directly runs `new MetaModel()` or `new SomeCustomizedMetaModel()`
is inside of Waterline core anyway.)
************************************************************
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
@constructs {MetaModel}
The base MetaModel from whence other MetaModels are customized.
Remember: running `new MetaModel()` yields an instance like `User`,
which is itself generically called a WLModel.
> This is kind of confusing, mainly because capitalization. And
> it feels silly to nitpick about something so confusing. But at
> least this way we know what everything's called, and it's consistent.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | MetaModel ( orm , adapterWrapper ) | javascript | balderdashy/waterline | lib/waterline/MetaModel.js | https://github.com/balderdashy/waterline/blob/master/lib/waterline/MetaModel.js | MIT |
MetaModel.extend = function (protoProps, staticProps) {
var thisConstructor = this;
// Sanity checks:
// If a prototypal properties were provided, and one of them is under the `constructor` key,
// then freak out. This is no longer supported, and shouldn't still be in use anywhere.
if (protoProps && _.has(protoProps, 'constructor')) {
throw new Error('Consistency violation: The first argument (`protoProps`) provided to Waterline.Model.extend() should never have a `constructor` property. (This kind of usage is no longer supported.)');
}
// If any additional custom static properties were specified, then freak out.
// This is no longer supported, and shouldn't still be in use anywhere.
if (!_.isUndefined(staticProps)) {
throw new Error('Consistency violation: Unrecognized extra argument provided to Waterline.Model.extend() (`staticProps` is no longer supported.)');
}
//--β’
// Now proceed with the classical, Backbone-flavor extending.
var newConstructor = function() { return thisConstructor.apply(this, arguments); };
// Shallow-copy all of the static properties (top-level props of original constructor)
// over to the new constructor.
_.extend(newConstructor, thisConstructor, staticProps);
// Create an ad hoc "Surrogate" -- a short-lived, bionic kind of a constructor
// that serves as an intermediary... or maybe more of an organ donor? Surrogate
// is probably still best. Anyway it's some dark stuff, that's for sure. Because
// what happens next is that we give it a reference to our original ctor's prototype
// and constructor, then "new up" an instance for us-- but only so that we can cut out
// that newborn instance's `prototype` and put it where the prototype for our new ctor
// is supposed to go.
//
// > Why? Well for one thing, this is important so that our new constructor appears
// > to "inherit" from our original constructor. But likely a more prescient motive
// > is so that our new ctor is a proper clone. That is, it's no longer entangled with
// > the original constructor.
// > (More or less anyway. If there are any deeply nested things, like an `attributes`
// > dictionary -- those could still contain deep, entangled references to stuff from the
// > original ctor's prototype.
var Surrogate = function() { this.constructor = newConstructor; };
Surrogate.prototype = thisConstructor.prototype;
newConstructor.prototype = new Surrogate();
// If extra `protoProps` were provided, merge them onto our new ctor's prototype.
// (now that it's a legitimately separate thing that we can safely modify)
if (protoProps) {
_.extend(newConstructor.prototype, protoProps);
}
// Set a proprietary `__super__` key to keep track of the original ctor's prototype.
// (see http://stackoverflow.com/questions/8596861/super-in-backbone#comment17856929_8614228)
newConstructor.__super__ = thisConstructor.prototype;
// Return our new ctor.
return newConstructor;
}; | MetaModel.extend()
Build & return a new constructor based on the existing constructor in the
current runtime context (`this`) -- which happens to be our base model
constructor (MetaModel). This also attaches the specified properties to
the new constructor's prototype.
> Originally taken from `.extend()` in Backbone source:
> http://backbonejs.org/docs/backbone.html#section-189
>
> Although this is called `extend()`, note that it does not actually modify
> the original MetaModel constructor. Instead, it first builds a shallow
> clone of the original constructor and then extends THAT.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
@param {Dictionary?} protoProps
Optional extra set of properties to attach to the new ctor's prototype.
(& possibly a brand of breakfast cereal)
@param {Dictionary?} staticProps
NO LONGER SUPPORTED: An optional, extra set of properties to attach
directly to the new ctor.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
@returns {Function} [The new constructor -- e.g. `SomeCustomizedMetaModel`]
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
@this {Function} [The original constructor -- BaseMetaModel]
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | MetaModel.extend ( protoProps , staticProps ) | javascript | balderdashy/waterline | lib/waterline/MetaModel.js | https://github.com/balderdashy/waterline/blob/master/lib/waterline/MetaModel.js | MIT |
var Transformation = module.exports = function(attributes) {
// Hold an internal mapping of keys to transform
this._transformations = {};
// Initialize
this.initialize(attributes);
return this;
}; | Transformation
Allows for a Waterline Collection to have different
attributes than what actually exist in an adater's representation.
@param {Object} attributes
@param {Object} tables | module.exports ( attributes ) | javascript | balderdashy/waterline | lib/waterline/utils/system/transformer-builder.js | https://github.com/balderdashy/waterline/blob/master/lib/waterline/utils/system/transformer-builder.js | MIT |
Transformation.prototype.initialize = function(attributes) {
var self = this;
_.each(attributes, function(wlsAttrDef, attrName) {
// Make sure the attribute has a columnName set
if (!_.has(wlsAttrDef, 'columnName')) {
return;
}
// Ensure the columnName is a string
if (!_.isString(wlsAttrDef.columnName)) {
throw new Error('Consistency violation: `columnName` must be a string. But for this attribute (`'+attrName+'`) it is not!');
}
// Set the column name transformation
self._transformations[attrName] = wlsAttrDef.columnName;
});
}; | Initial mapping of transformations.
@param {Object} attributes
@param {Object} tables | Transformation.prototype.initialize ( attributes ) | javascript | balderdashy/waterline | lib/waterline/utils/system/transformer-builder.js | https://github.com/balderdashy/waterline/blob/master/lib/waterline/utils/system/transformer-builder.js | MIT |
Transformation.prototype.serializeValues = function(values) {
// Sanity check
if (!_.isObject(values) || _.isArray(values) || _.isFunction(values)) {
throw new Error('Consistency violation: Must be a dictionary, but instead got: '+util.inspect(values, {depth: 5}));
}
var self = this;
_.each(values, function(propertyValue, propertyName) {
if (_.has(self._transformations, propertyName)) {
values[self._transformations[propertyName]] = propertyValue;
// Only delete if the names are different
if (self._transformations[propertyName] !== propertyName) {
delete values[propertyName];
}
}
});
// We deliberately return undefined here to reiterate that
// this _always_ mutates things in place!
return;
}; | Transform a set of values into a representation used
in an adapter.
> The values are mutated in-place.
@param {Object} values to transform | Transformation.prototype.serializeValues ( values ) | javascript | balderdashy/waterline | lib/waterline/utils/system/transformer-builder.js | https://github.com/balderdashy/waterline/blob/master/lib/waterline/utils/system/transformer-builder.js | MIT |
Transformation.prototype.unserialize = function(pRecord) {
// Get the database columns that we'll be transforming into attribute names.
var colsToTransform = _.values(this._transformations);
// Shallow clone the physical record, so that we don't lose any values in cases
// where one attribute's name conflicts with another attribute's `columnName`.
// (see https://github.com/balderdashy/sails/issues/4079)
var copyOfPhysicalRecord = _.clone(pRecord);
// Remove the values from the pRecord that are set for the columns we're
// going to transform. This ensures that the `columnName` and the
// attribute name don't both appear as properties in the final record
// (unless there's a conflict as described above).
_.each(_.keys(pRecord), function(key) {
if (_.contains(colsToTransform, key)) {
delete pRecord[key];
}
});
// Loop through the keys to transform of this record and reattach them.
_.each(this._transformations, function(columnName, attrName) {
// If there's no value set for this column name, continue.
if (!_.has(copyOfPhysicalRecord, columnName)) {
return;
}
// Otherwise get the value from the cloned record.
pRecord[attrName] = copyOfPhysicalRecord[columnName];
});
// Return the original, mutated record.
return pRecord;
}; | .unserialize()
Destructively transforms a physical-layer record received
from an adapter into a logical representation appropriate
for userland (i.e. swapping out column names for attribute
names)
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
@param {Dictionary} pRecord
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
@returns {Dictionary}
This is an unnecessary return -- this method just
returns the same reference to the original pRecord,
which has been destructively mutated anyway.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | Transformation.prototype.unserialize ( pRecord ) | javascript | balderdashy/waterline | lib/waterline/utils/system/transformer-builder.js | https://github.com/balderdashy/waterline/blob/master/lib/waterline/utils/system/transformer-builder.js | MIT |
module.exports = function validateDatastoreConnectivity(datastore, done) {
var adapterDSEntry = _.get(datastore.adapter.datastores, datastore.config.identity);
// skip validation if `getConnection` and `releaseConnection` methods do not exist.
// aka pretend everything is OK
if (!_.has(adapterDSEntry.driver, 'getConnection') || !_.has(adapterDSEntry.driver, 'releaseConnection')) {
return done();
}
// try to acquire connection.
adapterDSEntry.driver.getConnection({
manager: adapterDSEntry.manager
}, function(err, report) {
if (err) {
return done(err);
}
// release connection.
adapterDSEntry.driver.releaseConnection({
connection: report.connection
}, function(err) {
if (err) {
return done(err);
}
return done();
});//</ releaseConnection() >
});//</ getConnection() >
}; | validateDatastoreConnectivity()
Validates connectivity to a datastore by trying to acquire and release
connection.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
@param {Ref} datastore
@param {Function} done
@param {Error?} err [if an error occured]
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | validateDatastoreConnectivity ( datastore , done ) | javascript | balderdashy/waterline | lib/waterline/utils/system/validate-datastore-connectivity.js | https://github.com/balderdashy/waterline/blob/master/lib/waterline/utils/system/validate-datastore-connectivity.js | MIT |
module.exports = function getModel(modelIdentity, orm) {
// ================================================================================================
// Check that this utility function is being used properly, and that the provided `modelIdentity` and `orm` are valid.
if (!_.isString(modelIdentity) || modelIdentity === '') {
throw new Error('Consistency violation: `modelIdentity` must be a non-empty string. Instead got: '+modelIdentity);
}
var isORMDictionary = _.isObject(orm) && !_.isArray(orm) && !_.isFunction(orm);
if (!isORMDictionary) {
throw new Error('Consistency violation: `orm` must be a valid Waterline ORM instance (must be a dictionary)');
}
var doesORMHaveValidCollectionsDictionary = _.isObject(orm.collections) && !_.isArray(orm.collections) && !_.isFunction(orm.collections);
if (!doesORMHaveValidCollectionsDictionary) {
throw new Error('Consistency violation: `orm` must be a valid Waterline ORM instance (must have a dictionary of "collections")');
}
// ================================================================================================
// Try to look up the Waterline model.
//
// > Note that, in addition to being the model definition, this
// > "WLModel" is actually the hydrated model object (fka a "Waterline collection")
// > which has methods like `find`, `create`, etc.
var WLModel = orm.collections[modelIdentity];
if (_.isUndefined(WLModel)) {
throw flaverr('E_MODEL_NOT_REGISTERED', new Error('The provided `modelIdentity` references a model (`'+modelIdentity+'`) which is not registered in this `orm`.'));
}
// ================================================================================================
// Finally, do a couple of quick sanity checks on the registered
// Waterline model, such as verifying that it declares an extant,
// valid primary key attribute.
var isWLModelDictionary = _.isObject(WLModel) && !_.isArray(WLModel) && !_.isFunction(WLModel);
if (!isWLModelDictionary) {
throw new Error('Consistency violation: All model definitions must be dictionaries, but somehow, the referenced Waterline model (`'+modelIdentity+'`) seems to have become corrupted. Here it is: '+util.inspect(WLModel, {depth: 1}));
}
var doesWLModelHaveValidAttributesDictionary = _.isObject(WLModel.attributes) && !_.isArray(WLModel.attributes) && !_.isFunction(WLModel.attributes);
if (!doesWLModelHaveValidAttributesDictionary) {
throw new Error('Consistency violation: All model definitions must have a dictionary of `attributes`. But somehow, the referenced Waterline model (`'+modelIdentity+'`) seems to have become corrupted and has a missing or invalid `attributes` property. Here is the Waterline model: '+util.inspect(WLModel, {depth: 1}));
}
var doesWLModelHaveValidPrimaryKeySetting = _.isString(WLModel.primaryKey);
if (!doesWLModelHaveValidPrimaryKeySetting) {
throw new Error('Consistency violation: The referenced Waterline model (`'+modelIdentity+'`) defines an invalid `primaryKey` setting. Should be a string (the name of the primary key attribute), but instead, it is: '+util.inspect(WLModel.primaryKey, {depth:5}));
}
// Now a few more checks for the primary key attribute.
var pkAttrDef = WLModel.attributes[WLModel.primaryKey];
if (_.isUndefined(pkAttrDef)) {
throw new Error('Consistency violation: The referenced Waterline model (`'+modelIdentity+'`) declares `primaryKey: \''+WLModel.primaryKey+'\'`, yet there is no `'+WLModel.primaryKey+'` attribute defined in the model!');
}
var isPkAttrDefDictionary = _.isObject(pkAttrDef) && !_.isArray(pkAttrDef) && !_.isFunction(pkAttrDef);
if (!isPkAttrDefDictionary) {
throw new Error('Consistency violation: The `primaryKey` (`'+WLModel.primaryKey+'`) in the referenced Waterline model (`'+modelIdentity+'`) corresponds with a CORRUPTED attribute definition: '+util.inspect(pkAttrDef, {depth:5})+'\n(^^this should have been caught already!)');
}
if (!_.isBoolean(pkAttrDef.required)) {
throw new Error('Consistency violation: The `primaryKey` (`'+WLModel.primaryKey+'`) in the referenced Waterline model (`'+modelIdentity+'`) corresponds with a CORRUPTED attribute definition '+util.inspect(pkAttrDef, {depth:5})+'\n(^^this should have been caught already! `required` must be either true or false!)');
}
if (pkAttrDef.type !== 'number' && pkAttrDef.type !== 'string') {
throw new Error('Consistency violation: The `primaryKey` (`'+WLModel.primaryKey+'`) in the referenced Waterline model (`'+modelIdentity+'`) corresponds with an INCOMPATIBLE attribute definition. In order to be used as the logical primary key, the referenced attribute should declare itself `type: \'string\'` or `type: \'number\'`...but instead its `type` is: '+util.inspect(pkAttrDef.type, {depth:5})+'\n(^^this should have been caught already!)');
}
// ================================================================================================
// Send back a reference to this Waterline model.
return WLModel;
}; | getModel()
Look up a Waterline model by identity.
> Note that we do a few quick assertions in the process, purely as sanity checks
> and to help prevent bugs. If any of these fail, then it means there is some
> unhandled usage error, or a bug going on elsewhere in Waterline.
------------------------------------------------------------------------------------------
@param {String} modelIdentity
The identity of the model this is referring to (e.g. "pet" or "user")
> Useful for looking up the Waterline model and accessing its attribute definitions.
@param {Ref} orm
The Waterline ORM instance.
------------------------------------------------------------------------------------------
@returns {Ref} [the Waterline model]
------------------------------------------------------------------------------------------
@throws {Error} If no such model exists.
E_MODEL_NOT_REGISTERED
@throws {Error} If anything else goes wrong.
------------------------------------------------------------------------------------------ | getModel ( modelIdentity , orm ) | javascript | balderdashy/waterline | lib/waterline/utils/ontology/get-model.js | https://github.com/balderdashy/waterline/blob/master/lib/waterline/utils/ontology/get-model.js | MIT |
module.exports = function isCapableOfOptimizedPopulate(attrName, modelIdentity, orm) {
if (!_.isString(attrName)) {
throw new Error('Consistency violation: Must specify `attrName` as a string. But instead, got: '+util.inspect(attrName, {depth:5})+'');
}
if (!_.isString(modelIdentity)) {
throw new Error('Consistency violation: Must specify `modelIdentity` as a string. But instead, got: '+util.inspect(modelIdentity, {depth:5})+'');
}
if (_.isUndefined(orm)) {
throw new Error('Consistency violation: Must pass in `orm` (a reference to the Waterline ORM instance). But instead, got: '+util.inspect(orm, {depth:5})+'');
}
// β¦ βββββββ¦ββ β¦ β¦βββ ββββββββββββββββ¬βββββ¬ββ¬ββββββ β¬ ββ¬ββββββ¬βββββ¬ βββ
// β β ββ ββ β©β β ββ ββ βββ€βββββββ ββ ββββ€ β ββ ββββ ββΌβ ββββ β ββββ€ β βββ
// β©βββββββββ© β© ββββ© β΄ β΄βββββββββββββ΄β΄ β΄ β΄ β΄ββββββ ββ β΄ β΄βββββ΄βββββ΄βββββ
// Look up the containing model for this association, and the attribute definition itself.
var PrimaryWLModel = getModel(modelIdentity, orm);
var attrDef = getAttribute(attrName, modelIdentity, orm);
assert(attrDef.model || attrDef.collection, 'Attempting to check whether attribute `'+attrName+'` of model `'+modelIdentity+'` is capable of optimized populate, but it\'s not even an association!');
// Look up the other, associated model.
var otherModelIdentity = attrDef.model ? attrDef.model : attrDef.collection;
var OtherWLModel = getModel(otherModelIdentity, orm);
// ββββ¬ β¬βββββββ¬ββ β¬ β¬β¬ β¬βββββ¬ββ¬ β¬ββββ¬ββ ββββ¦ β¦ ββ¬ββββββ¬βββββ¬ βββ
// β βββ€ββ€ β ββ΄β ββββββ€ββ€ β βββ€ββ€ ββ¬β β ββ£β β ββββ β ββββ€ β βββ
// ββββ΄ β΄βββββββ΄ β΄ ββ΄ββ΄ β΄βββ β΄ β΄ β΄ββββ΄ββ β© β©β©βββ©ββ β΄ β΄βββββ΄βββββ΄βββββ
// ββββ¬βββββ β¬ β¬ββββ¬ββββββ ββ¬ββ¬ β¬βββ ββββββββ¦ββββ ββ¦ββββββ¦βββββββββ¦βββββ¦βββββ
// βββ€ββ¬βββ€ β βββββββββ β¬ β βββ€ββ€ ββββ ββ£βββββ£ βββ ββ£ β β ββ£βββ β β ββ β¦βββ£
// β΄ β΄β΄βββββ βββββββ΄ββββββ β΄ β΄ β΄βββ ββββ© β©β© β©βββ ββ©ββ© β© β© β© β©βββ β© ββββ©βββββ
// Determine if the two models are using the same datastore.
var isUsingSameDatastore = (PrimaryWLModel.datastore === OtherWLModel.datastore);
// Sanity check
if (!_.isString(PrimaryWLModel.datastore) || !_.isString(OtherWLModel.datastore)) {
throw new Error('Consistency violation: Outdated semantics (see https://github.com/balderdashy/waterline/commit/ecd3e1c8f05e27a3b0c1ea4f08a73a0b4ad83c07#commitcomment-20271012) The `datastore` property should be a string, not an array or whatever else. But for either the `'+PrimaryWLModel.identity+'` or `'+OtherWLModel.identity+'` model, it is not!');
}
// Now figure out if this association is using a junction (aka "many to many"),
// and if so, which model it is.
// > If it is not using a junction, we'll leave `JunctionWLModel` as undefined.
// ------
var JunctionWLModel;
// To accomplish this, we'll grab the already-mapped relationship info (attached by wl-schema
// to models, as the `schema` property). If our directly-related model (as mapped by WL-schema
// has a `junctionTable` flag or a `throughTable` dictionary, then we can safely say this association
// is using a junction, and that this directly-related model is indeed that junction.
var junctionOrOtherModelIdentity = PrimaryWLModel.schema[attrName].referenceIdentity;
var JunctionOrOtherWLModel = getModel(junctionOrOtherModelIdentity, orm);
var arcaneProto = Object.getPrototypeOf(JunctionOrOtherWLModel);
if (_.isBoolean(arcaneProto.junctionTable) || _.isPlainObject(arcaneProto.throughTable)) {
JunctionWLModel = JunctionOrOtherWLModel;
}//>-
// -----
// If there is a junction, make sure to factor that in too.
// (It has to be using the same datastore as the other two for it to count.)
if (JunctionWLModel) {
isUsingSameDatastore = isUsingSameDatastore && (JunctionWLModel.datastore === PrimaryWLModel.datastore);
// Sanity check
if (!_.isString(JunctionWLModel.datastore)) {
throw new Error('Consistency violation: Outdated semantics (see https://github.com/balderdashy/waterline/commit/ecd3e1c8f05e27a3b0c1ea4f08a73a0b4ad83c07#commitcomment-20271012) The `datastore` property should be a string, not an array or whatever else. But for the `'+JunctionWLModel.identity+'` model, it is not!');
}
}//>-
// Now, if any of the models involved is using a different datastore, then bail.
if (!isUsingSameDatastore) {
return false;
}//-β’
// --β’
// IWMIH, we know that this association is using exactly ONE datastore.
// And we even know that datastore's name.
//
// (remember, we just checked to verify that they're exactly the same above-- so we could have grabbed
// this datastore name from ANY of the involved models)
var relevantDatastoreName = PrimaryWLModel.datastore;
// Sanity check
if (!_.isString(PrimaryWLModel.datastore)) {
throw new Error('Consistency violation: Outdated semantics (see https://github.com/balderdashy/waterline/commit/ecd3e1c8f05e27a3b0c1ea4f08a73a0b4ad83c07#commitcomment-20271012) The `datastore` property should be a string, not an array or whatever else. But for the `'+PrimaryWLModel.identity+'` model, it is not!');
}
// Another sanity check
assert(_.isString(relevantDatastoreName));
// Finally, now that we know which datastore we're dealing with, check to see if that datastore's
// configured adapter supports optimized populates.
var doesDatastoreSupportOptimizedPopulates = PrimaryWLModel._adapter.join;
// If not, then we're done.
if (!doesDatastoreSupportOptimizedPopulates) {
return false;
}//-β’
// IWMIH, then we know that all involved models in this query share a datastore, and that the datastore's
// adapter supports optimized populates. So we return true!
return true;
}; | isCapableOfOptimizedPopulate()
Determine whether this association fully supports optimized populate.
> Note that, if this is a plural association (a `collection` assoc. that is pointed at
> by `via` on the other side, or for which there IS no "other side"), then there will be
> a junction model in play. For this utility to return `true`, that junction model must
> also be on the same datastore!
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
@param {String} attrName [the name of the association in question]
@param {String} modelIdentity [the identity of the model this association belongs to]
@param {Ref} orm [the Waterline ORM instance]
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
@returns {Boolean} | isCapableOfOptimizedPopulate ( attrName , modelIdentity , orm ) | javascript | balderdashy/waterline | lib/waterline/utils/ontology/is-capable-of-optimized-populate.js | https://github.com/balderdashy/waterline/blob/master/lib/waterline/utils/ontology/is-capable-of-optimized-populate.js | MIT |
module.exports = function isExclusive(attrName, modelIdentity, orm) {
if (!_.isString(attrName)) {
throw new Error('Consistency violation: Must specify `attrName` as a string. But instead, got: '+util.inspect(attrName, {depth:5})+'');
}
if (!_.isString(modelIdentity)) {
throw new Error('Consistency violation: Must specify `modelIdentity` as a string. But instead, got: '+util.inspect(modelIdentity, {depth:5})+'');
}
if (_.isUndefined(orm)) {
throw new Error('Consistency violation: Must pass in `orm` (a reference to the Waterline ORM instance). But instead, got: '+util.inspect(orm, {depth:5})+'');
}
// β¦ βββββββ¦ββ β¦ β¦βββ ββββββββββββββββ¬βββββ¬ββ¬ββββββ β¬ ββ¬ββββββ¬βββββ¬ βββ
// β β ββ ββ β©β β ββ ββ βββ€βββββββ ββ ββββ€ β ββ ββββ ββΌβ ββββ β ββββ€ β βββ
// β©βββββββββ© β© ββββ© β΄ β΄βββββββββββββ΄β΄ β΄ β΄ β΄ββββββ ββ β΄ β΄βββββ΄βββββ΄βββββ
// Look up the containing model for this association, and the attribute definition itself.
var attrDef = getAttribute(attrName, modelIdentity, orm);
assert(attrDef.model || attrDef.collection, 'Attempting to check whether attribute `'+attrName+'` of model `'+modelIdentity+'` is an "exclusive" association, but it\'s not even an association in the first place!');
// βββββββ¬ β¬ ββββ¦ β¦βββββββ¦ββ β¦ββ¦β ββββ¦ β¦ββ¦β
// ββββ ββββ β β ββ£ββ£ β β β©β β β β ββ β β
// ββββββββ΄ββ ββββ© β©βββββββ© β© β© β© ββββββ β©
// If this association is singular, then it is not exclusive.
if (!attrDef.collection) {
return false;
}//-β’
// If it has no `via`, then it is not two-way, and also not exclusive.
if (!attrDef.via) {
return false;
}//-β’
// If it has a "through" junction model defined, then it is not exclusive.
if (attrDef.through) {
return false;
}//-β’
// If its `via` points at a plural association, then it is not exclusive.
// > Note that, to do this, we look up the attribute on the OTHER model
// > that is pointed at by THIS association's `via`.
var viaAttrDef = getAttribute(attrDef.via, attrDef.collection, orm);
if (viaAttrDef.collection) {
return false;
}//-β’
// Otherwise, its `via` must be pointing at a singular association, so it's exclusive!
return true;
}; | isExclusive()
Determine whether this association is "exclusive" -- meaning that it is
a two-way, plural ("collection") association, whose `via` points at a
singular ("model") on the other side.
> Note that "through" associations do not count. Although the "via" does
> refer to a singular ("model") association in the intermediate junction
> model, the underlying logical association is still non-exclusive.
> i.e. the same child record can be added to the "through" association
> of multiple different parent records.
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
@param {String} attrName [the name of the association in question]
@param {String} modelIdentity [the identity of the model this association belongs to]
@param {Ref} orm [the Waterline ORM instance]
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
@returns {Boolean} | isExclusive ( attrName , modelIdentity , orm ) | javascript | balderdashy/waterline | lib/waterline/utils/ontology/is-exclusive.js | https://github.com/balderdashy/waterline/blob/master/lib/waterline/utils/ontology/is-exclusive.js | MIT |
module.exports = function getAttribute(attrName, modelIdentity, orm) {
// ================================================================================================
// Check that the provided `attrName` is valid.
// (`modelIdentity` and `orm` will be automatically checked by calling `getModel()`)
//
// > Note that this attr name MIGHT be empty string -- although it should never be.
// > (we prevent against that elsewhere)
if (!_.isString(attrName)) {
throw new Error('Consistency violation: `attrName` must be a string.');
}
// ================================================================================================
// Try to look up the Waterline model.
//
// > Note that, in addition to being the model definition, this
// > "WLModel" is actually the hydrated model object (fka a "Waterline collection")
// > which has methods like `find`, `create`, etc.
var WLModel = getModel(modelIdentity, orm);
// Try to look up the attribute definition.
var attrDef = WLModel.attributes[attrName];
if (_.isUndefined(attrDef)) {
throw flaverr('E_ATTR_NOT_REGISTERED', new Error('No such attribute (`'+attrName+'`) exists in model (`'+modelIdentity+'`).'));
}
// ================================================================================================
// This section consists of more sanity checks for the attribute definition:
if (!_.isObject(attrDef) || _.isArray(attrDef) || _.isFunction(attrDef)) {
throw new Error('Consistency violation: The referenced attribute (`'+attrName+'`, from model `'+modelIdentity+'`) corresponds with a CORRUPTED attribute definition: '+util.inspect(attrDef, {depth:5})+'');
}
// Some basic sanity checks that this is a valid model association.
// (note that we don't get too deep here-- though we could)
if (!_.isUndefined(attrDef.model)) {
if(!_.isString(attrDef.model) || attrDef.model === '') {
throw new Error('Consistency violation: The referenced attribute (`'+attrName+'`, from model `'+modelIdentity+'`) has an invalid `model` property. If specified, `model` should be a non-empty string. But instead, got: '+util.inspect(attrDef.model, {depth:5})+'');
}
if (!_.isUndefined(attrDef.via)){
throw new Error('Consistency violation: The referenced attribute (`'+attrName+'`, from model `'+modelIdentity+'`) is an association, because it declares a `model`. But with a "model" association, the `via` property should always be undefined. But instead, it is: '+util.inspect(attrDef.via, {depth:5})+'');
}
if (!_.isUndefined(attrDef.dominant)){
throw new Error('Consistency violation: The referenced attribute (`'+attrName+'`, from model `'+modelIdentity+'`) is an association, because it declares a `model`. But with a "model" association, the `dominant` property should always be undefined. But instead, it is: '+util.inspect(attrDef.dominant, {depth:5})+'');
}
try {
getModel(attrDef.model, orm);
} catch (e){ throw new Error('Consistency violation: The referenced attribute (`'+attrName+'`, from model `'+modelIdentity+'`) is an association, because it declares a `model`. But the other model it references (`'+attrDef.model+'`) is missing or invalid. Details: '+e.stack); }
}
// Some basic sanity checks that this is a valid collection association.
// (note that we don't get too deep here-- though we could)
else if (!_.isUndefined(attrDef.collection)) {
if (!_.isString(attrDef.collection) || attrDef.collection === '') {
throw new Error('Consistency violation: The referenced attribute (`'+attrName+'`, from model `'+modelIdentity+'`) has an invalid `collection` property. If specified, `collection` should be a non-empty string. But instead, got: '+util.inspect(attrDef.collection, {depth:5})+'');
}
var OtherWLModel;
try {
OtherWLModel = getModel(attrDef.collection, orm);
} catch (e){ throw new Error('Consistency violation: The referenced attribute (`'+attrName+'`, from model `'+modelIdentity+'`) is an association, because it declares a `collection`. But the other model it references (`'+attrDef.collection+'`) is missing or invalid. Details: '+e.stack); }
if (!_.isUndefined(attrDef.via)) {
if (!_.isString(attrDef.via) || attrDef.via === '') {
throw new Error('Consistency violation: The referenced attribute (`'+attrName+'`, from model `'+modelIdentity+'`) has an invalid `via` property. If specified, `via` should be a non-empty string. But instead, got: '+util.inspect(attrDef.via, {depth:5})+'');
}
// Note that we don't call getAttribute recursively. (That would be madness.)
// We also don't check for reciprocity on the other side.
// Instead, we simply do a watered down check.
// > waterline-schema goes much deeper here.
// > Remember, these are just sanity checks for development.
if (!_.isUndefined(attrDef.through)) {
var ThroughWLModel;
try {
ThroughWLModel = getModel(attrDef.through, orm);
} catch (e){ throw new Error('Consistency violation: The referenced attribute (`'+attrName+'`, from model `'+modelIdentity+'`) is a "through" association, because it declares a `through`. But the junction model it references as "through" (`'+attrDef.through+'`) is missing or invalid. Details: '+e.stack); }
if (!ThroughWLModel.attributes[attrDef.via]) {
throw new Error('Consistency violation: The referenced attribute (`'+attrName+'`, from model `'+modelIdentity+'`) is a "through" association, because it declares a `through`. But the association\'s specified `via` ('+attrDef.via+'`) does not correspond with a recognized attribute on the junction model (`'+attrDef.through+'`)');
}
if (!ThroughWLModel.attributes[attrDef.via].model) {
throw new Error('Consistency violation: The referenced attribute (`'+attrName+'`, from model `'+modelIdentity+'`) is a "through" association, but its specified `via` ('+attrDef.via+'`) corresponds with an unexpected attribute on the junction model (`'+attrDef.through+'`). The attribute referenced by `via` should be a singular ("model") association, but instead, got: '+util.inspect(ThroughWLModel.attributes[attrDef.via],{depth: 5})+'');
}
}
else {
if (!OtherWLModel.attributes[attrDef.via]) {
throw new Error('Consistency violation: The referenced attribute (`'+attrName+'`, from model `'+modelIdentity+'`) is an association, because it declares a `collection`. But that association also specifies a `via` ('+attrDef.via+'`) which does not correspond with a recognized attribute on the other model (`'+attrDef.collection+'`)');
}
}
}//</if has `via`>
}//</if has `collection`>
// Otherwise, check that this is a valid, miscellaneous attribute.
else {
if(!_.isString(attrDef.type) || attrDef.type === '') {
throw new Error('Consistency violation: The referenced attribute (`'+attrName+'`, from model `'+modelIdentity+'`) has an invalid `type` property. If specified, `type` should be a non-empty string. But instead, got: '+util.inspect(attrDef.type, {depth:5})+'');
}
if(!_.contains(KNOWN_ATTR_TYPES, attrDef.type)) {
throw new Error('Consistency violation: The referenced attribute (`'+attrName+'`, from model `'+modelIdentity+'`) has an unrecognized `type`: `'+attrDef.type+'`.');
}
if (!_.isBoolean(attrDef.required)) {
throw new Error('Consistency violation: The referenced attribute (`'+attrName+'`, from model `'+modelIdentity+'`) has an unrecognized `required` property in its definition. By this time, it should always be true or false. But instead, got: '+util.inspect(attrDef.required, {depth:5})+'');
}
if (attrDef.required && !_.isUndefined(attrDef.defaultsTo)) {
throw new Error('Consistency violation: The referenced attribute (`'+attrName+'`, from model `'+modelIdentity+'`) has `required: true`, but it also specifies a `defaultsTo`. This should never have been allowed-- defaultsTo should be undefined! But instead, got: '+util.inspect(attrDef.defaultsTo, {depth:5})+'');
}
}
// ================================================================================================
//-β’
// Send back a reference to this attribute definition.
return attrDef;
}; | getAttribute()
Look up an attribute definition (by name) from the specified model.
Usable with normal attributes AND with associations.
> Note that we do a few quick assertions in the process, purely as sanity checks
> and to help prevent bugs. If any of these fail, then it means there is some
> unhandled usage error, or a bug going on elsewhere in Waterline.
------------------------------------------------------------------------------------------
@param {String} attrName
The name of the attribute (e.g. "id" or "favoriteBrands")
> Useful for looking up the Waterline model and accessing its attribute definitions.
@param {String} modelIdentity
The identity of the model this is referring to (e.g. "pet" or "user")
> Useful for looking up the Waterline model and accessing its attribute definitions.
@param {Ref} orm
The Waterline ORM instance.
------------------------------------------------------------------------------------------
@returns {Ref} [the attribute definition (a direct reference to it, so be careful!!)]
------------------------------------------------------------------------------------------
@throws {Error} If no such model exists.
E_MODEL_NOT_REGISTERED
@throws {Error} If no such attribute exists.
E_ATTR_NOT_REGISTERED
@throws {Error} If anything else goes wrong.
------------------------------------------------------------------------------------------ | getAttribute ( attrName , modelIdentity , orm ) | javascript | balderdashy/waterline | lib/waterline/utils/ontology/get-attribute.js | https://github.com/balderdashy/waterline/blob/master/lib/waterline/utils/ontology/get-attribute.js | MIT |
module.exports = function verifyModelMethodContext(context) {
if (!context.waterline) {
throw flaverr({ name: 'UsageError' }, new Error(
'Model method called from an unexpected context. Expected `this` to refer to a Sails/Waterline '+
'model, but it doesn\'t seem to. (This sometimes occurs when passing a model method directly '+
'through as the argument for something like `async.eachSeries()` or `.stream().eachRecord()`. '+
'If that\'s what happened here, then just use a wrapper function.) For further help, see '+
'http://sailsjs.com/support.'
));
}
}; | verifyModelMethodContext()
Take a look at the provided reference (presumably the `this` context of a
model method when it runs) and give it a sniff to make sure it's _probably_
a Sails/Waterline model.
If it's definitely NOT a Sails/Waterline model, then throw a usage error
that explains that the model method seems to have been run from an invalid
context, and throw out some ideas about what you might do about that.
> This utility is designed exclusively for use by the model methods defined
> within Waterline core.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
@param {Ref} context
The context (`this`) that this Waterline model method was invoked with.
@throws {Error} If the context is not a model.
@property {String} name :: 'UsageError'
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | verifyModelMethodContext ( context ) | javascript | balderdashy/waterline | lib/waterline/utils/query/verify-model-method-context.js | https://github.com/balderdashy/waterline/blob/master/lib/waterline/utils/query/verify-model-method-context.js | MIT |
meta: function(metadata) {
// If meta already exists, merge on top of it.
// (this is important for when this method is combined with other things
// like .usingConnection() that mutate meta keys)
if (this._wlQueryInfo.meta) {
_.extend(this._wlQueryInfo.meta, metadata);
}
else {
this._wlQueryInfo.meta = metadata;
}
return this;
}, | Pass special metadata (a dictionary of "meta keys") down to Waterline core,
and all the way to the adapter that won't be processed or touched by Waterline.
> Note that we use `_wlQueryInfo.meta` internally because we're already using
> `.meta()` as a method! In an actual S2Q, this key continues to be called `meta`. | meta ( metadata ) | javascript | balderdashy/waterline | lib/waterline/utils/query/get-query-modifier-methods.js | https://github.com/balderdashy/waterline/blob/master/lib/waterline/utils/query/get-query-modifier-methods.js | MIT |
usingConnection: function(db) {
this._wlQueryInfo.meta = this._wlQueryInfo.meta || {};
this._wlQueryInfo.meta.leasedConnection = db;
return this;
} | Pass an active database connection down to the query. | usingConnection ( db ) | javascript | balderdashy/waterline | lib/waterline/utils/query/get-query-modifier-methods.js | https://github.com/balderdashy/waterline/blob/master/lib/waterline/utils/query/get-query-modifier-methods.js | MIT |
eachRecord: function(iteratee) {
assert(this._wlQueryInfo.method === 'stream', 'Cannot chain `.eachRecord()` onto the `.'+this._wlQueryInfo.method+'()` method. The `.eachRecord()` method is only chainable to `.stream()`. (In fact, this shouldn\'t even be possible! So the fact that you are seeing this message at all is, itself, likely due to a bug in Waterline.)');
this._wlQueryInfo.eachRecordFn = iteratee;
return this;
}, | Add an iteratee to the query
@param {Function} iteratee
@returns {Query} | eachRecord ( iteratee ) | javascript | balderdashy/waterline | lib/waterline/utils/query/get-query-modifier-methods.js | https://github.com/balderdashy/waterline/blob/master/lib/waterline/utils/query/get-query-modifier-methods.js | MIT |
eachBatch: function(batchSizeOrIteratee, iteratee) {
assert(this._wlQueryInfo.method === 'stream', 'Cannot chain `.eachBatch()` onto the `.'+this._wlQueryInfo.method+'()` method. The `.eachBatch()` method is only chainable to `.stream()`. (In fact, this shouldn\'t even be possible! So the fact that you are seeing this message at all is, itself, likely due to a bug in Waterline.)');
if (arguments.length > 2) {
throw new Error('Invalid usage for `.eachBatch()` -- no more than 2 arguments should be passed in.');
}//β’
if (iteratee === undefined) {
this._wlQueryInfo.eachBatchFn = batchSizeOrIteratee;
} else {
this._wlQueryInfo.eachBatchFn = iteratee;
// Apply custom batch size:
// > If meta already exists, merge on top of it.
// > (this is important for when this method is combined with .meta()/.usingConnection()/etc)
if (this._wlQueryInfo.meta) {
_.extend(this._wlQueryInfo.meta, { batchSize: batchSizeOrIteratee });
}
else {
this._wlQueryInfo.meta = { batchSize: batchSizeOrIteratee };
}
}
return this;
}, | Add an iteratee to the query
@param {Number|Function} batchSizeOrIteratee
@param {Function} iteratee
@returns {Query} | eachBatch ( batchSizeOrIteratee , iteratee ) | javascript | balderdashy/waterline | lib/waterline/utils/query/get-query-modifier-methods.js | https://github.com/balderdashy/waterline/blob/master/lib/waterline/utils/query/get-query-modifier-methods.js | MIT |
set: function(values) {
if (this._wlQueryInfo.method === 'create') {
console.warn(
'Deprecation warning: In future versions of Waterline, the use of .set() with .create()\n'+
'will no longer be supported. In the past, you could use .set() to provide the initial\n'+
'skeleton of a new record to create (like `.create().set({})`)-- but really .set() should\n'+
'only be used with .update(). So instead, please change this code so that it just passes in\n'+
'the initial new record as the first argument to `.create().`'
);
this._wlQueryInfo.newRecord = values;
}
else if (this._wlQueryInfo.method === 'createEach') {
console.warn(
'Deprecation warning: In future versions of Waterline, the use of .set() with .createEach()\n'+
'will no longer be supported. In the past, you could use .set() to provide an array of\n'+
'new records to create (like `.createEach().set([{}, {}])`)-- but really .set() was designed\n'+
'to be used with .update() only. So instead, please change this code so that it just\n'+
'passes in the initial new record as the first argument to `.createEach().`'
);
this._wlQueryInfo.newRecords = values;
}
else {
this._wlQueryInfo.valuesToSet = values;
}
return this;
}, | Add values to be used in update or create query
@param {Dictionary} values
@returns {Query} | set ( values ) | javascript | balderdashy/waterline | lib/waterline/utils/query/get-query-modifier-methods.js | https://github.com/balderdashy/waterline/blob/master/lib/waterline/utils/query/get-query-modifier-methods.js | MIT |
members: function(associatedIds) {
this._wlQueryInfo.associatedIds = associatedIds;
return this;
}, | Add associated IDs to the query
@param {Array} associatedIds
@returns {Query} | members ( associatedIds ) | javascript | balderdashy/waterline | lib/waterline/utils/query/get-query-modifier-methods.js | https://github.com/balderdashy/waterline/blob/master/lib/waterline/utils/query/get-query-modifier-methods.js | MIT |
populateAll: function() {
var pleaseDoNotUseThisArgument = arguments[0];
if (!_.isUndefined(pleaseDoNotUseThisArgument)) {
console.warn(
'Deprecation warning: Passing in an argument to `.populateAll()` is no longer supported.\n'+
'(But interpreting this usage the original way for you this time...)\n'+
'Note: If you really want to use the _exact same_ criteria for simultaneously populating multiple\n'+
'different plural ("collection") associations, please use separate calls to `.populate()` instead.\n'+
'Or, alternatively, instead of using `.populate()`, you can choose to call `.find()`, `.findOne()`,\n'+
'or `.stream()` with a dictionary (plain JS object) as the second argument, where each key is the\n'+
'name of an association, and each value is either:\n'+
' β’ true (for singular aka "model" associations), or\n'+
' β’ a criteria dictionary (for plural aka "collection" associations)\n'
);
}//>-
var self = this;
this._WLModel.associations.forEach(function (associationInfo) {
self.populate(associationInfo.alias, pleaseDoNotUseThisArgument);
});
return this;
}, | Modify this query so that it populates all associations (singular and plural).
@returns {Query} | populateAll ( ) | javascript | balderdashy/waterline | lib/waterline/utils/query/get-query-modifier-methods.js | https://github.com/balderdashy/waterline/blob/master/lib/waterline/utils/query/get-query-modifier-methods.js | MIT |
populate: function(keyName, subcriteria) {
assert(this._wlQueryInfo.method === 'find' || this._wlQueryInfo.method === 'findOne' || this._wlQueryInfo.method === 'stream', 'Cannot chain `.populate()` onto the `.'+this._wlQueryInfo.method+'()` method. (In fact, this shouldn\'t even be possible! So the fact that you are seeing this message at all is, itself, likely due to a bug in Waterline.)');
// Backwards compatibility for arrays passed in as `keyName`.
if (_.isArray(keyName)) {
console.warn(
'Deprecation warning: `.populate()` no longer accepts an array as its first argument.\n'+
'Please use separate calls to `.populate()` instead. Or, alternatively, instead of\n'+
'using `.populate()`, you can choose to call `.find()`, `.findOne()` or `.stream()`\n'+
'with a dictionary (plain JS object) as the second argument, where each key is the\n'+
'name of an association, and each value is either:\n'+
' β’ true (for singular aka "model" associations), or\n'+
' β’ a criteria dictionary (for plural aka "collection" associations)\n'+
'(Interpreting this usage the original way for you this time...)\n'
);
var self = this;
_.each(keyName, function(populate) {
self.populate(populate, subcriteria);
});
return this;
}//-β’
// Verify that we're dealing with a semi-reasonable string.
// (This is futher validated)
if (!keyName || !_.isString(keyName)) {
throw new Error('Invalid usage for `.populate()` -- first argument should be the name of an assocation.');
}
// If this is the first time, make the `populates` query key an empty dictionary.
if (_.isUndefined(this._wlQueryInfo.populates)) {
this._wlQueryInfo.populates = {};
}
// Then, if subcriteria was specified, use it.
if (!_.isUndefined(subcriteria)){
this._wlQueryInfo.populates[keyName] = subcriteria;
}
else {
// (Note: even though we set {} regardless, even when it should really be `true`
// if it's a singular association, that's ok because it gets silently normalized
// in FS2Q.)
this._wlQueryInfo.populates[keyName] = {};
}
return this;
}, | .populate()
Set the `populates` key for this query.
> Used for populating associations.
@param {String|Array} key, the key to populate or array of string keys
@returns {Query} | populate ( keyName , subcriteria ) | javascript | balderdashy/waterline | lib/waterline/utils/query/get-query-modifier-methods.js | https://github.com/balderdashy/waterline/blob/master/lib/waterline/utils/query/get-query-modifier-methods.js | MIT |
limit: function(limit) {
if (!this._alreadyInitiallyExpandedCriteria) {
this._wlQueryInfo.criteria = expandWhereShorthand(this._wlQueryInfo.criteria);
this._alreadyInitiallyExpandedCriteria = true;
}//>-
this._wlQueryInfo.criteria.limit = limit;
return this;
}, | Add a `limit` clause to the query's criteria.
@param {Number} number to limit
@returns {Query} | limit ( limit ) | javascript | balderdashy/waterline | lib/waterline/utils/query/get-query-modifier-methods.js | https://github.com/balderdashy/waterline/blob/master/lib/waterline/utils/query/get-query-modifier-methods.js | MIT |
skip: function(skip) {
if (!this._alreadyInitiallyExpandedCriteria) {
this._wlQueryInfo.criteria = expandWhereShorthand(this._wlQueryInfo.criteria);
this._alreadyInitiallyExpandedCriteria = true;
}//>-
this._wlQueryInfo.criteria.skip = skip;
return this;
}, | Add a `skip` clause to the query's criteria.
@param {Number} number to skip
@returns {Query} | skip ( skip ) | javascript | balderdashy/waterline | lib/waterline/utils/query/get-query-modifier-methods.js | https://github.com/balderdashy/waterline/blob/master/lib/waterline/utils/query/get-query-modifier-methods.js | MIT |
paginate: function(pageNumOrOpts, pageSize) {
if (!this._alreadyInitiallyExpandedCriteria) {
this._wlQueryInfo.criteria = expandWhereShorthand(this._wlQueryInfo.criteria);
this._alreadyInitiallyExpandedCriteria = true;
}//>-
// Interpret page number.
var pageNum;
// If not specified...
if (_.isUndefined(pageNumOrOpts)) {
console.warn(
'Please always specify a `page` when calling .paginate() -- for example:\n'+
'```\n'+
'var first30Boats = await Boat.find()\n'+
'.sort(\'wetness DESC\')\n'+
'.paginate(0, 30)\n'+
'```\n'+
'(In the mean time, assuming the first page (#0)...)'
);
pageNum = 0;
}
// If dictionary... (temporary backwards-compat.)
else if (_.isObject(pageNumOrOpts)) {
pageNum = pageNumOrOpts.page || 0;
console.warn(
'Deprecation warning: Passing in a dictionary (plain JS object) to .paginate()\n'+
'is no longer supported -- instead, please use:\n'+
'```\n'+
'.paginate(pageNum, pageSize)\n'+
'```\n'+
'(In the mean time, interpreting this as page #'+pageNum+'...)'
);
}
// Otherwise, assume it's the proper usage.
else {
pageNum = pageNumOrOpts;
}
// Interpret the page size (number of records per page).
if (!_.isUndefined(pageSize)) {
if (!_.isNumber(pageSize)) {
console.warn(
'Unrecognized usage for .paginate() -- if specified, 2nd argument (page size)\n'+
'should be a number like 10 (otherwise, it defaults to 30).\n'+
'(Ignoring this and switching to a page size of 30 automatically...)'
);
pageSize = 30;
}
}
else if (_.isObject(pageNumOrOpts) && !_.isUndefined(pageNumOrOpts.limit)) {
// Note: IWMIH, then we must have already logged a deprecation warning above--
// so no need to do it again.
pageSize = pageNumOrOpts.limit || 30;
}
else {
// Note that this default is the same as the default batch size used by `.stream()`.
pageSize = 30;
}
// If page size is Infinity, then bail out now without doing anything.
// (Unless of course, this is a page other than the first-- that would be an error,
// because ordinals beyond infinity don't exist in real life)
if (pageSize === Infinity) {
if (pageNum !== 0) {
console.warn(
'Unrecognized usage for .paginate() -- if 2nd argument (page size) is Infinity,\n'+
'then the 1st argument (page num) must be zero, indicating the first page.\n'+
'(Ignoring this and using page zero w/ an infinite page size automatically...)'
);
}
return this;
}//-β’
// Now, apply the page size as the limit, and compute & apply the appropriate `skip`.
// (REMEMBER: pages are now zero-indexed!)
this
.skip(pageNum * pageSize)
.limit(pageSize);
return this;
}, | .paginate()
Add a `skip`+`limit` clause to the query's criteria
based on the specified page number (and optionally,
the page size, which defaults to 30 otherwise.)
> This method is really just a little dollop of syntactic sugar.
```
Show.find({ category: 'home-and-garden' })
.paginate(0)
.exec(...)
```
-OR- (for backwards compat.)
```
Show.find({ category: 'home-and-garden' })
.paginate({ page: 0, limit: 30 })
.exec(...)
```
- - - - - - - - - - - - - - - - - - - - - - - - - - - -
@param {Number} pageNumOrOpts
@param {Number?} pageSize
-OR-
@param {Number|Dictionary} pageNumOrOpts
@property {Number} page [the page num. (backwards compat.)]
@property {Number?} limit [the page size (backwards compat.)]
- - - - - - - - - - - - - - - - - - - - - - - - - - - -
@returns {Query}
- - - - - - - - - - - - - - - - - - - - - - - - - - - - | paginate ( pageNumOrOpts , pageSize ) | javascript | balderdashy/waterline | lib/waterline/utils/query/get-query-modifier-methods.js | https://github.com/balderdashy/waterline/blob/master/lib/waterline/utils/query/get-query-modifier-methods.js | MIT |
sort: function(sortClause) {
if (!this._alreadyInitiallyExpandedCriteria) {
this._wlQueryInfo.criteria = expandWhereShorthand(this._wlQueryInfo.criteria);
this._alreadyInitiallyExpandedCriteria = true;
}//>-
this._wlQueryInfo.criteria.sort = sortClause;
return this;
}, | Add a `sort` clause to the criteria object
@param {Ref} sortClause
@returns {Query} | sort ( sortClause ) | javascript | balderdashy/waterline | lib/waterline/utils/query/get-query-modifier-methods.js | https://github.com/balderdashy/waterline/blob/master/lib/waterline/utils/query/get-query-modifier-methods.js | MIT |
select: function(selectAttributes) {
if (!this._alreadyInitiallyExpandedCriteria) {
this._wlQueryInfo.criteria = expandWhereShorthand(this._wlQueryInfo.criteria);
this._alreadyInitiallyExpandedCriteria = true;
}//>-
this._wlQueryInfo.criteria.select = selectAttributes;
return this;
}, | Add projections to the query.
@param {Array} attributes to select
@returns {Query} | select ( selectAttributes ) | javascript | balderdashy/waterline | lib/waterline/utils/query/get-query-modifier-methods.js | https://github.com/balderdashy/waterline/blob/master/lib/waterline/utils/query/get-query-modifier-methods.js | MIT |
omit: function(omitAttributes) {
if (!this._alreadyInitiallyExpandedCriteria) {
this._wlQueryInfo.criteria = expandWhereShorthand(this._wlQueryInfo.criteria);
this._alreadyInitiallyExpandedCriteria = true;
}//>-
this._wlQueryInfo.criteria.omit = omitAttributes;
return this;
}, | Add an omit clause to the query's criteria.
@param {Array} attributes to select
@returns {Query} | omit ( omitAttributes ) | javascript | balderdashy/waterline | lib/waterline/utils/query/get-query-modifier-methods.js | https://github.com/balderdashy/waterline/blob/master/lib/waterline/utils/query/get-query-modifier-methods.js | MIT |
where: function(whereCriteria) {
if (!this._alreadyInitiallyExpandedCriteria) {
this._wlQueryInfo.criteria = expandWhereShorthand(this._wlQueryInfo.criteria);
this._alreadyInitiallyExpandedCriteria = true;
}//>-
this._wlQueryInfo.criteria.where = whereCriteria;
return this;
}, | Add a `where` clause to the query's criteria.
@param {Dictionary} criteria to append
@returns {Query} | where ( whereCriteria ) | javascript | balderdashy/waterline | lib/waterline/utils/query/get-query-modifier-methods.js | https://github.com/balderdashy/waterline/blob/master/lib/waterline/utils/query/get-query-modifier-methods.js | MIT |
fetch: function() {
if (arguments.length > 0) {
throw new Error('Invalid usage for `.fetch()` -- no arguments should be passed in.');
}
// If meta already exists, merge on top of it.
// (this is important for when this method is combined with .meta()/.usingConnection()/etc)
if (this._wlQueryInfo.meta) {
_.extend(this._wlQueryInfo.meta, { fetch: true });
}
else {
this._wlQueryInfo.meta = { fetch: true };
}
return this;
}, | Add `fetch: true` to the query's `meta`.
@returns {Query} | fetch ( ) | javascript | balderdashy/waterline | lib/waterline/utils/query/get-query-modifier-methods.js | https://github.com/balderdashy/waterline/blob/master/lib/waterline/utils/query/get-query-modifier-methods.js | MIT |
decrypt: function() {
if (arguments.length > 0) {
throw new Error('Invalid usage for `.decrypt()` -- no arguments should be passed in.');
}
// If meta already exists, merge on top of it.
// (this is important for when this method is combined with .meta()/.usingConnection()/etc)
if (this._wlQueryInfo.meta) {
_.extend(this._wlQueryInfo.meta, { decrypt: true });
}
else {
this._wlQueryInfo.meta = { decrypt: true };
}
return this;
}, | Add `decrypt: true` to the query's `meta`.
@returns {Query} | decrypt ( ) | javascript | balderdashy/waterline | lib/waterline/utils/query/get-query-modifier-methods.js | https://github.com/balderdashy/waterline/blob/master/lib/waterline/utils/query/get-query-modifier-methods.js | MIT |
sum: function() {
if (!this._alreadyInitiallyExpandedCriteria) {
this._wlQueryInfo.criteria = expandWhereShorthand(this._wlQueryInfo.criteria);
this._alreadyInitiallyExpandedCriteria = true;
}//>-
this._wlQueryInfo.criteria.sum = arguments[0];
return this;
}, | Add the (NO LONGER SUPPORTED) `sum` clause to the criteria.
> This is allowed through purposely, in order to trigger
> the proper query error in FS2Q.
@returns {Query} | sum ( ) | javascript | balderdashy/waterline | lib/waterline/utils/query/get-query-modifier-methods.js | https://github.com/balderdashy/waterline/blob/master/lib/waterline/utils/query/get-query-modifier-methods.js | MIT |
avg: function() {
if (!this._alreadyInitiallyExpandedCriteria) {
this._wlQueryInfo.criteria = expandWhereShorthand(this._wlQueryInfo.criteria);
this._alreadyInitiallyExpandedCriteria = true;
}//>-
this._wlQueryInfo.criteria.avg = arguments[0];
return this;
}, | Add the (NO LONGER SUPPORTED) `avg` clause to the criteria.
> This is allowed through purposely, in order to trigger
> the proper query error in FS2Q.
@returns {Query} | avg ( ) | javascript | balderdashy/waterline | lib/waterline/utils/query/get-query-modifier-methods.js | https://github.com/balderdashy/waterline/blob/master/lib/waterline/utils/query/get-query-modifier-methods.js | MIT |
min: function() {
if (!this._alreadyInitiallyExpandedCriteria) {
this._wlQueryInfo.criteria = expandWhereShorthand(this._wlQueryInfo.criteria);
this._alreadyInitiallyExpandedCriteria = true;
}//>-
this._wlQueryInfo.criteria.min = arguments[0];
return this;
}, | Add the (NO LONGER SUPPORTED) `min` clause to the criteria.
> This is allowed through purposely, in order to trigger
> the proper query error in FS2Q.
@returns {Query} | min ( ) | javascript | balderdashy/waterline | lib/waterline/utils/query/get-query-modifier-methods.js | https://github.com/balderdashy/waterline/blob/master/lib/waterline/utils/query/get-query-modifier-methods.js | MIT |
max: function() {
if (!this._alreadyInitiallyExpandedCriteria) {
this._wlQueryInfo.criteria = expandWhereShorthand(this._wlQueryInfo.criteria);
this._alreadyInitiallyExpandedCriteria = true;
}//>-
this._wlQueryInfo.criteria.max = arguments[0];
return this;
}, | Add the (NO LONGER SUPPORTED) `max` clause to the criteria.
> This is allowed through purposely, in order to trigger
> the proper query error in FS2Q.
@returns {Query} | max ( ) | javascript | balderdashy/waterline | lib/waterline/utils/query/get-query-modifier-methods.js | https://github.com/balderdashy/waterline/blob/master/lib/waterline/utils/query/get-query-modifier-methods.js | MIT |
groupBy: function() {
if (!this._alreadyInitiallyExpandedCriteria) {
this._wlQueryInfo.criteria = expandWhereShorthand(this._wlQueryInfo.criteria);
this._alreadyInitiallyExpandedCriteria = true;
}//>-
this._wlQueryInfo.criteria.groupBy = arguments[0];
return this;
}, | Add the (NO LONGER SUPPORTED) `groupBy` clause to the criteria.
> This is allowed through purposely, in order to trigger
> the proper query error in FS2Q. | groupBy ( ) | javascript | balderdashy/waterline | lib/waterline/utils/query/get-query-modifier-methods.js | https://github.com/balderdashy/waterline/blob/master/lib/waterline/utils/query/get-query-modifier-methods.js | MIT |
module.exports = function getQueryModifierMethods(category){
assert(category && _.isString(category), 'A category must be provided as a valid string.');
// Set up the initial state of the dictionary that we'll be returning.
var queryMethods = {};
// No matter what category this is, we always begin with certain baseline methods.
_.extend(queryMethods, BASELINE_Q_METHODS);
// But from there, the methods become category specific:
switch (category) {
case 'find': _.extend(queryMethods, FILTER_Q_METHODS, PAGINATION_Q_METHODS, OLD_AGGREGATION_Q_METHODS, PROJECTION_Q_METHODS, POPULATE_Q_METHODS, DECRYPT_Q_METHODS); break;
case 'findOne': _.extend(queryMethods, FILTER_Q_METHODS, PROJECTION_Q_METHODS, POPULATE_Q_METHODS, DECRYPT_Q_METHODS); break;
case 'stream': _.extend(queryMethods, FILTER_Q_METHODS, PAGINATION_Q_METHODS, PROJECTION_Q_METHODS, POPULATE_Q_METHODS, STREAM_Q_METHODS, DECRYPT_Q_METHODS); break;
case 'count': _.extend(queryMethods, FILTER_Q_METHODS); break;
case 'sum': _.extend(queryMethods, FILTER_Q_METHODS); break;
case 'avg': _.extend(queryMethods, FILTER_Q_METHODS); break;
case 'create': _.extend(queryMethods, SET_Q_METHODS, FETCH_Q_METHODS, DECRYPT_Q_METHODS); break;
case 'createEach': _.extend(queryMethods, SET_Q_METHODS, FETCH_Q_METHODS, DECRYPT_Q_METHODS); break;
case 'findOrCreate': _.extend(queryMethods, FILTER_Q_METHODS, SET_Q_METHODS, FETCH_Q_METHODS, DECRYPT_Q_METHODS); break;
case 'update': _.extend(queryMethods, FILTER_Q_METHODS, SET_Q_METHODS, FETCH_Q_METHODS, DECRYPT_Q_METHODS); break;
case 'updateOne': _.extend(queryMethods, FILTER_Q_METHODS, SET_Q_METHODS, FETCH_Q_METHODS, DECRYPT_Q_METHODS); break;
case 'destroy': _.extend(queryMethods, FILTER_Q_METHODS, FETCH_Q_METHODS, DECRYPT_Q_METHODS); break;
case 'destroyOne': _.extend(queryMethods, FILTER_Q_METHODS, FETCH_Q_METHODS, DECRYPT_Q_METHODS); break;
case 'archive': _.extend(queryMethods, FILTER_Q_METHODS, FETCH_Q_METHODS, DECRYPT_Q_METHODS); break;
case 'archiveOne': _.extend(queryMethods, FILTER_Q_METHODS, FETCH_Q_METHODS, DECRYPT_Q_METHODS); break;
case 'addToCollection': _.extend(queryMethods, COLLECTION_Q_METHODS); break;
case 'removeFromCollection': _.extend(queryMethods, COLLECTION_Q_METHODS); break;
case 'replaceCollection': _.extend(queryMethods, COLLECTION_Q_METHODS); break;
default: throw new Error('Consistency violation: Unrecognized category (model method name): `'+category+'`');
}
// Now that we're done, return the new dictionary of methods.
return queryMethods;
}; | getQueryModifierMethods()
Return a dictionary containing the appropriate query (Deferred) methods
for the specified category (i.e. model method name).
> For example, calling `getQueryModifierMethods('find')` returns a dictionary
> of methods like `where` and `select`, as well as the usual suspects
> like `meta` and `usingConnection`.
>
> This never returns generic, universal Deferred methods; i.e. `exec`,
> `then`, `catch`, and `toPromise`. Those are expected to be supplied
> by parley.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
@param {String} category
The name of the model method this query is for.
@returns {Dictionary}
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | getQueryModifierMethods ( category ) | javascript | balderdashy/waterline | lib/waterline/utils/query/get-query-modifier-methods.js | https://github.com/balderdashy/waterline/blob/master/lib/waterline/utils/query/get-query-modifier-methods.js | MIT |
module.exports = function buildOmen(caller){
var omen = flaverr({}, new Error('omen'), caller);
return omen;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// FUTURE: do something fancier here, or where this is called, to keep track of the omen so that it
// can support both sorts of usages (Deferred and explicit callback.)
//
// This way, it could do an even better job of reporting exactly where the error came from in
// userland code as the very first entry in the stack trace. e.g.
// ```
// var omen = flaverr({}, new Error('omen'), Deferred.prototype.exec);
// // ^^ but would need to pass through the original omen or something
// ```
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
}; | buildOmen()
Build an omen, an Error instance defined ahead of time in order to grab a stack trace.
(used for providing a better experience when viewing the stack trace of errors
that come from one or more asynchronous ticks down the line; e.g. uniqueness errors)
> Note that the Error returned by this utility can only be used once.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
@param {Function} caller
The function to use for context.
The stack trace of the omen will be snipped based on the instruction where
this "caller" function was invoked.
@returns {Error}
The new omen (an Error instance.) | buildOmen ( caller ) | javascript | balderdashy/waterline | lib/waterline/utils/query/build-omen.js | https://github.com/balderdashy/waterline/blob/master/lib/waterline/utils/query/build-omen.js | MIT |
module.exports = function forgeStageTwoQuery(query, orm) {
// if (process.env.NODE_ENV !== 'production') {
// console.time('forgeStageTwoQuery');
// }
// Create a JS timestamp to represent the current (timezone-agnostic) date+time.
var theMomentBeforeFS2Q = Date.now();
// ^^ -- -- -- -- -- -- -- -- -- -- -- -- --
// Since Date.now() has trivial performance impact, we generate our
// JS timestamp up here no matter what, just in case we end up needing
// it later for `autoCreatedAt` or `autoUpdatedAt`, in situations where
// we might need to automatically add it in multiple spots (such as
// in `newRecords`, when processing a `.createEach()`.)
//
// > Benchmark:
// > β’ Absolute: ~0.021ms
// > β’ Relative: http://jsben.ch/#/TOF9y (vs. `(new Date()).getTime()`)
// -- -- -- -- -- -- -- -- -- -- -- -- -- --
// ββββββββββ βββββββββββ ββββββββββ βββ ββββββββββββ βββββββββββ
// βββββββββββ ββββββββββββββββββββββ ββββ ββββββββββββ βββββββββββ
// βββ ββββββββββββββ βββ βββββββ βββ ββββββββββββββ
// βββ ββββββββββββββ βββ βββββββ βββ ββββββββββββββ
// βββββββββββ ββββββββββββββββββββββ βββ βββ βββ βββββββββββ
// ββββββββββ βββββββββββ ββββββββββ βββ βββ βββ βββββββββββ
//
// ββββββββββββββββββββββββββββββββββββ βββββββββββββββ ββββββ βββ ββββββββ
// βββββββββββββββββββββββββββββββββββββ ββββββββββββββββββββββββββ ββββββββ
// ββββββ ββββββββββββββββββββββ ββββββ βββ βββ ββββββββββββββ ββββββββ
// ββββββ ββββββββββββββββββββββ ββββββββββ βββ ββββββββββββββ ββββββββ
// βββββββββββββββββββββββββββββββββββ ββββββ βββ ββββββ βββββββββββββββββββ
// βββββββββββββββββββββββββββββββββββ βββββ βββ ββββββ βββββββββββββββββββ
// ββββ¬ β¬βββββββ¬ββ β¦ β¦ββββ¦ββββββ
// β βββ€ββ€ β ββ΄β β βββββββββ β¦
// ββββ΄ β΄βββββββ΄ β΄ βββββββ©ββββββ
// Always check `using`.
if (!_.isString(query.using) || query.using === '') {
throw new Error(
'Consistency violation: Every stage 1 query should include a property called `using` as a non-empty string.'+
' But instead, got: ' + util.inspect(query.using, {depth:5})
);
}//-β’
// Look up the Waterline model for this query.
// > This is so that we can reference the original model definition.
var WLModel;
try {
WLModel = getModel(query.using, orm);
} catch (e) {
switch (e.code) {
case 'E_MODEL_NOT_REGISTERED': throw new Error('Consistency violation: The specified `using` ("'+query.using+'") does not match the identity of any registered model.');
default: throw e;
}
}//</catch>
// ββββ¬ β¬βββββββ¬ββ ββ¦ββββββ¦ββ¦ β¦βββββ¦β
// β βββ€ββ€ β ββ΄β βββββ£ β β ββ£β β ββ
// ββββ΄ β΄βββββββ΄ β΄ β© β©βββ β© β© β©βββββ©β
// β¬ ββββ¬ β¬βββββββ¬ββ βββββββ¬ββ βββββ β¬ββ¬ββ¬βββββββββββββββ¬ β¬βββ β¬ββββββ¬ β¬βββ
// ββΌβ β βββ€ββ€ β ββ΄β ββ€ β βββ¬β ββ€ ββ΄β¬β β ββ¬ββββ€βββββ€ β ββ ββββ ββ΄βββ€ ββ¬ββββ
// ββ ββββ΄ β΄βββββββ΄ β΄ β ββββ΄ββ ββββ΄ ββ β΄ β΄βββ΄ β΄βββββββββββββββ β΄ β΄βββ β΄ ββββ
// β¬ ββ¬ββββββ¬βββββ¬ββββ¬ββ¬ββββββ βββ β¬ β¬ββββ¬βββ¬ β¬ β¬ββββββ¬ β¬βββ
// ββΌβ ββββ€ β ββ€ ββ¬ββββββββββ€ βββΌββ βββ€ ββ¬βββ¬β ββ΄βββ€ ββ¬ββββ
// ββ ββ΄ββββ β΄ ββββ΄βββ΄ β΄β΄ββββββ βββββββββββ΄ββ β΄ β΄ β΄βββ β΄ βββ
// Always check `method`.
if (!_.isString(query.method) || query.method === '') {
throw new Error(
'Consistency violation: Every stage 1 query should include a property called `method` as a non-empty string.'+
' But instead, got: ' + util.inspect(query.method, {depth:5})
);
}//-β’
// Determine the set of acceptable query keys for the specified `method`.
// (and, in the process, verify that we recognize this method in the first place)
var queryKeys = (function _getQueryKeys (){
switch(query.method) {
case 'find': return [ 'criteria', 'populates' ];
case 'findOne': return [ 'criteria', 'populates' ];
case 'stream': return [ 'criteria', 'populates', 'eachRecordFn', 'eachBatchFn' ];
case 'count': return [ 'criteria' ];
case 'sum': return [ 'numericAttrName', 'criteria' ];
case 'avg': return [ 'numericAttrName', 'criteria' ];
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// FUTURE: consider renaming "numericAttrName" to something like "targetField"
// so that it's more descriptive even after being forged as part of a s3q.
// But note that this would be a pretty big change throughout waterline core,
// possibly other utilities, as well as being a breaking change to the spec
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
case 'create': return [ 'newRecord' ];
case 'createEach': return [ 'newRecords' ];
case 'findOrCreate': return [ 'criteria', 'newRecord' ];
case 'update': return [ 'criteria', 'valuesToSet' ];
case 'updateOne': return [ 'criteria', 'valuesToSet' ];
case 'destroy': return [ 'criteria' ];
case 'destroyOne': return [ 'criteria' ];
case 'archive': return [ 'criteria' ];
case 'archiveOne': return [ 'criteria' ];
case 'addToCollection': return [ 'targetRecordIds', 'collectionAttrName', 'associatedIds' ];
case 'removeFromCollection': return [ 'targetRecordIds', 'collectionAttrName', 'associatedIds' ];
case 'replaceCollection': return [ 'targetRecordIds', 'collectionAttrName', 'associatedIds' ];
default:
throw new Error('Consistency violation: Unrecognized `method` ("'+query.method+'")');
}
})();//</self-calling function :: _getQueryKeys()>
// > Note:
// >
// > It's OK if keys are missing at this point. We'll do our best to
// > infer a reasonable default, when possible. In some cases, it'll
// > still fail validation later, but in other cases, it'll pass.
// >
// > Anyway, that's all handled below.
// Now check that we see ONLY the expected keys for that method.
// (i.e. there should never be any miscellaneous stuff hanging out on the stage1 query dictionary)
// We start off by building up an array of legal keys, starting with the universally-legal ones.
var allowedKeys = [
'meta',
'using',
'method'
].concat(queryKeys);
// Then finally, we check that no extraneous keys are present.
var extraneousKeys = _.difference(_.keys(query), allowedKeys);
if (extraneousKeys.length > 0) {
throw new Error('Consistency violation: Provided "stage 1 query" contains extraneous top-level keys: '+extraneousKeys);
}
// ββββ βββββββββββββββββββββ ββββββ
// βββββ ββββββββββββββββββββββββββββββ
// βββββββββββββββββ βββ ββββββββ
// βββββββββββββββββ βββ ββββββββ
// βββ βββ βββββββββββ βββ βββ βββ
// βββ βββββββββββ βββ βββ βββ
//
// ββββ¬ β¬βββββββ¬ββ ββ¦ββββββ¦ββββ ββ β¬βββ ββββ¬ββββββ¬ β¬β¬ββ¬ββββββ¬β ββ
// β βββ€ββ€ β ββ΄β βββββ£ β β ββ£ β βββ€ βββββ¬ββ ββββββ ββββ€ ββ β
// ββββ΄ β΄βββββββ΄ β΄ β© β©βββ β© β© β© ββ β΄β β΄ β΄βββββ ββ β΄ββ΄ββββββ΄β ββ
// If specified, check that `meta` is a dictionary.
if (!_.isUndefined(query.meta)) {
if (!_.isObject(query.meta) || _.isArray(query.meta) || _.isFunction(query.meta)) {
throw buildUsageError(
'E_INVALID_META',
'If `meta` is provided, it should be a dictionary (i.e. a plain JavaScript object). '+
'But instead, got: ' + util.inspect(query.meta, {depth:5})+'',
query.using
);
}//-β’
}//>-β’
// Now check a few different model settings that correspond with `meta` keys,
// and set the relevant `meta` keys accordingly.
//
// > Remember, we rely on waterline-schema to have already validated
// > these model settings when the ORM was first initialized.
// βββββββββββββββββ¬ββββ ββββββ ββ¬βββββββββ¬ββ¬ββββββ¬ β¬βββ
// β βββ€ββββ βββ€ ββββ€ β ββββ ββββ€ βββ β ββ¬ββ βββ¬β ββ
// ββββ΄ β΄βββββββ΄ β΄ββ΄ββββ ββββββ ββ΄βββββββ β΄ β΄βββββ β΄ o
if (query.method === 'destroy' && !_.isUndefined(WLModel.cascadeOnDestroy)) {
if (!_.isBoolean(WLModel.cascadeOnDestroy)) {
throw new Error('Consistency violation: If specified, expecting `cascadeOnDestroy` model setting to be `true` or `false`. But instead, got: '+util.inspect(WLModel.cascadeOnDestroy, {depth:5})+'');
}
if (!query.meta || query.meta.cascade === undefined) {
// Only bother setting the `cascade` meta key if the model setting is `true`.
// (because otherwise it's `false`, which is the default anyway)
if (WLModel.cascadeOnDestroy) {
query.meta = query.meta || {};
query.meta.cascade = WLModel.cascadeOnDestroy;
}
}//ο¬
}//>-
// ββββββββ¬βββββ¬ β¬ β¬ββββββββββββ¬ββββ¬ββββ ββββββ β¬ β¬βββββ¬ββββββ¬βββββββ
// ββ€ ββ€ β β βββ€ ββ¬βββ€ β β βββ¬β βββββ β ββββ β ββββ βββββ€ β ββ€ ββ
// β βββ β΄ ββββ΄ β΄ β΄ββββββββββββ΄ββββ΄ββββ ββββββ ββββ΄ ββ΄ββ΄ β΄ β΄ βββ o
if (query.method === 'update' && !_.isUndefined(WLModel.fetchRecordsOnUpdate)) {
if (!_.isBoolean(WLModel.fetchRecordsOnUpdate)) {
throw new Error('Consistency violation: If specified, expecting `fetchRecordsOnUpdate` model setting to be `true` or `false`. But instead, got: '+util.inspect(WLModel.fetchRecordsOnUpdate, {depth:5})+'');
}
if (!query.meta || query.meta.fetch === undefined) {
// Only bother setting the `fetch` meta key if the model setting is `true`.
// (because otherwise it's `false`, which is the default anyway)
if (WLModel.fetchRecordsOnUpdate) {
query.meta = query.meta || {};
query.meta.fetch = WLModel.fetchRecordsOnUpdate;
}
}//ο¬
}//>-
// ββββββββ¬βββββ¬ β¬ β¬ββββββββββββ¬ββββ¬ββββ ββββββ ββ¬βββββββββ¬ββ¬ββββββ¬ β¬βββ
// ββ€ ββ€ β β βββ€ ββ¬βββ€ β β βββ¬β βββββ β ββββ ββββ€ βββ β ββ¬ββ βββ¬β ββ
// β βββ β΄ ββββ΄ β΄ β΄ββββββββββββ΄ββββ΄ββββ ββββββ ββ΄βββββββ β΄ β΄βββββ β΄ o
if (query.method === 'destroy' && !_.isUndefined(WLModel.fetchRecordsOnDestroy)) {
if (!_.isBoolean(WLModel.fetchRecordsOnDestroy)) {
throw new Error('Consistency violation: If specified, expecting `fetchRecordsOnDestroy` model setting to be `true` or `false`. But instead, got: '+util.inspect(WLModel.fetchRecordsOnDestroy, {depth:5})+'');
}
if (!query.meta || query.meta.fetch === undefined) {
// Only bother setting the `fetch` meta key if the model setting is `true`.
// (because otherwise it's `false`, which is the default anyway)
if (WLModel.fetchRecordsOnDestroy) {
query.meta = query.meta || {};
query.meta.fetch = WLModel.fetchRecordsOnDestroy;
}
}//ο¬
}//>-
// ββββββββ¬βββββ¬ β¬ β¬ββββββββββββ¬ββββ¬ββββ ββββββ ββββ¬ββββββββββ¬βββββββ
// ββ€ ββ€ β β βββ€ ββ¬βββ€ β β βββ¬β βββββ β ββββ β ββ¬βββ€ βββ€ β ββ€ ββ
// β βββ β΄ ββββ΄ β΄ β΄ββββββββββββ΄ββββ΄ββββ ββββββ ββββ΄ββββββ΄ β΄ β΄ βββ o
if (query.method === 'create' && !_.isUndefined(WLModel.fetchRecordsOnCreate)) {
if (!_.isBoolean(WLModel.fetchRecordsOnCreate)) {
throw new Error('Consistency violation: If specified, expecting `fetchRecordsOnCreate` model setting to be `true` or `false`. But instead, got: '+util.inspect(WLModel.fetchRecordsOnCreate, {depth:5})+'');
}
if (!query.meta || query.meta.fetch === undefined) {
// Only bother setting the `fetch` meta key if the model setting is `true`.
// (because otherwise it's `false`, which is the default anyway)
if (WLModel.fetchRecordsOnCreate) {
query.meta = query.meta || {};
query.meta.fetch = WLModel.fetchRecordsOnCreate;
}
}//ο¬
}//>-
// ββββββββ¬βββββ¬ β¬ β¬ββββββββββββ¬ββββ¬ββββ ββββββ ββββ¬ββββββββββ¬ββββ ββββββββββ¬ β¬βββ
// ββ€ ββ€ β β βββ€ ββ¬βββ€ β β βββ¬β βββββ β ββββ β ββ¬βββ€ βββ€ β ββ€ ββ€ βββ€β βββ€ ββ
// β βββ β΄ ββββ΄ β΄ β΄ββββββββββββ΄ββββ΄ββββ ββββββ ββββ΄ββββββ΄ β΄ β΄ βββ ββββ΄ β΄ββββ΄ β΄ o
if (query.method === 'createEach' && !_.isUndefined(WLModel.fetchRecordsOnCreateEach)) {
if (!_.isBoolean(WLModel.fetchRecordsOnCreateEach)) {
throw new Error('Consistency violation: If specified, expecting `fetchRecordsOnCreateEach` model setting to be `true` or `false`. But instead, got: '+util.inspect(WLModel.fetchRecordsOnCreateEach, {depth:5})+'');
}
if (!query.meta || query.meta.fetch === undefined) {
// Only bother setting the `fetch` meta key if the model setting is `true`.
// (because otherwise it's `false`, which is the default anyway)
if (WLModel.fetchRecordsOnCreateEach) {
query.meta = query.meta || {};
query.meta.fetch = WLModel.fetchRecordsOnCreateEach;
}
}
}//>-
// ββββ¬βββββββββββββββββββ¬ββββ βββββββββ βββββ β¬ββββββββ¬β β¬ββ¬β ββ¬βββββ¬ ββββ¬ββββββββββββββ
// βββββ¬ββ βββββββ€β β¬βββ€ β ββ€ ββββ ββββββββ βββ΄β βββ€ β βββββ ββ β β ββ ββ€ ββ¬ββββ€ββββ ββ€
// β΄ β΄ββββββ΄ β΄ β΄ββββ΄ β΄ β΄ βββ βββββββββ ββββββββββββββ β΄ β΄ββ΄β β΄ ββββ΄ββββββ΄βββ΄ β΄βββββββββ
// ββ¬ββββββ¬βββββ¬ ββββββββ¬βββ¬ββ¬ββββββ ββ¬ββββ ββ¬ββ¬ β¬βββ ββββββββββ¬βββββββββ¬βββ¬βββββ¬ββββ
// ββββ β ββββ€ β βββββ€ β β βββββ β¬ β β β β βββ€ββ€ βββ€ββββββββ¬ββ ββββββ¬βββββ€ β ββ€
// β΄ β΄βββββ΄βββββ΄ββ ββββββ β΄ β΄ β΄ββββββ β΄ βββ β΄ β΄ β΄βββ β΄ β΄β΄ β΄ β΄ββββββ΄ β΄βββ΄β΄ β΄ β΄ βββ
// ββ¬ββββββ¬ββββ β¬ββββββ¬ β¬ ββ βββββββ¬ββ ββ¬βββββββββββββ ββ
// βββββ€ β βββ€ ββ΄βββ€ ββ¬β β ββ€ β βββ¬β ββββ βββββ β¬β β β
// β΄ β΄βββ β΄ β΄ β΄ β΄ β΄βββ β΄ ββ β ββββ΄ββ β΄ β΄ββββββββββββ ββ
// Set the `modelsNotUsingObjectIds` meta key of the query based on
// the `dontUseObjectIds` model setting of relevant models.
//
// Note that if no models have this flag set, the meta key won't be set at all.
// This avoids the weirdness of seeing this key pop up in a query for a non-mongo adapter.
//
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// FUTURE: Remove the need for this mongo-specific code by respecting this model setting
// in the adapter itself. (To do that, Waterline needs to be sending down actual WL models
// though. See the waterline.js file in this repo for notes about that.)
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
(function() {
var modelsNotUsingObjectIds = _.reduce(orm.collections, function(memo, WLModel) {
if (WLModel.dontUseObjectIds === true) { memo.push(WLModel.identity); }
return memo;
}, []);
if (modelsNotUsingObjectIds.length > 0) {
query.meta = query.meta || {};
query.meta.modelsNotUsingObjectIds = modelsNotUsingObjectIds;
}
})();
// Next, check specific, common `meta` keys, to make sure they're valid.
// > (Not all `meta` keys can be checked, obviously, because there could be **anything**
// > in there, such as meta keys proprietary to particular adapters. But certain core
// > `meta` keys can be properly verified. Currently, we only validate _some_ of the
// > ones that are more commonly used.)
if (query.meta !== undefined) {
// ββββββββ¬βββββ¬ β¬
// ββ€ ββ€ β β βββ€
// β βββ β΄ ββββ΄ β΄
if (query.meta.fetch !== undefined) {
if (!_.isBoolean(query.meta.fetch)) {
throw buildUsageError(
'E_INVALID_META',
'If provided, `fetch` should be either `true` or `false`.',
query.using
);
}//β’
// If this is a findOrCreate/updateOne/destroyOne/archiveOne query,
// make sure that the `fetch` meta key hasn't been explicitly set
// (because that wouldn't make any sense).
if (_.contains(['findOrCreate', 'updateOne', 'destroyOne', 'archiveOne'], query.method)) {
console.warn(
'warn: `fetch` is unnecessary when calling .'+query.method+'(). '+
'If successful, .'+query.method+'() *always* returns the affected record.'
);
}//ο¬
}//ο¬
// ββ¬ββ¬ β¬ββ¬ββββββ¬ββββ ββββ¬ββββββββ
// ββββ β β βββ€ β ββ€ βββ€ββ¬ββ β¬βββ
// β΄ β΄βββ β΄ β΄ β΄ β΄ βββ β΄ β΄β΄ββββββββ
//
// EXPERIMENTAL: The `mutateArgs` meta key enabled optimizations by preventing
// unnecessary cloning of arguments.
//
// > Note that this is ONLY respected at the stage 2 level!
// > That is, it doesn't matter if this meta key is set or not when you call adapters.
//
// > PLEASE DO NOT RELY ON `mutateArgs` IN YOUR OWN CODE- IT COULD CHANGE
// > AT ANY TIME AND BREAK YOUR APP OR PLUGIN!
if (query.meta.mutateArgs !== undefined) {
if (!_.isBoolean(query.meta.mutateArgs)) {
throw buildUsageError(
'E_INVALID_META',
'If provided, `mutateArgs` should be either `true` or `false`.',
query.using
);
}//β’
}//ο¬
// ββ¬ββββββββ¬βββ¬ β¬βββββ¬β
// ββββ€ β ββ¬βββ¬ββββ β
// ββ΄ββββββββ΄ββ β΄ β΄ β΄
if (query.meta.decrypt !== undefined) {
if (!_.isBoolean(query.meta.decrypt)) {
throw buildUsageError(
'E_INVALID_META',
'If provided, `decrypt` should be either `true` or `false`.',
query.using
);
}//β’
}//ο¬
// ββββββββββ¬βββ¬ β¬βββββ¬ββ¬ β¬β¬ββ¬ββ¬ β¬
// ββ€ ββββ ββ¬βββ¬ββββ β ββββ β βββ€
// ββββββββββ΄ββ β΄ β΄ β΄ ββ΄ββ΄ β΄ β΄ β΄
if (query.meta.encryptWith !== undefined) {
if (!query.meta.encryptWith || !_.isString(query.meta.encryptWith)) {
throw buildUsageError(
'E_INVALID_META',
'If provided, `encryptWith` should be a non-empty string (the name of '+
'one of the configured data encryption keys).',
query.using
);
}//β’
}//ο¬
// ββββ¬βββ¬βββββββββββββ¬βββ¬ β¬βββββ¬ββ¬ββββββ
// βββββ΄βββββββ€ ββββ ββ¬βββ¬ββββ β ββ ββββ
// ββββ΄ β΄β΄β΄ ββββββββββ΄ββ β΄ β΄ β΄ β΄ββββββ
//
// EXPERIMENTAL: The `skipEncryption` meta key prevents encryption.
// (see the implementation of findOrCreate() for more information)
//
// > PLEASE DO NOT RELY ON `skipEncryption` IN YOUR OWN CODE- IT COULD
// > CHANGE AT ANY TIME AND BREAK YOUR APP OR PLUGIN!
if (query.meta.skipEncryption !== undefined) {
if (!_.isBoolean(query.meta.skipEncryption)) {
throw buildUsageError(
'E_INVALID_META',
'If provided, `skipEncryption` should be true or false.',
query.using
);
}//β’
}//ο¬
// ββ βββββ¬βββββ¬ β¬ββββ¬ββββββ
// ββ΄ββββ€ β β βββ€βββββββββ€
// ββββ΄ β΄ β΄ ββββ΄ β΄ββββ΄ββββββ
if (query.meta.batchSize !== undefined) {
if (!_.isNumber(query.meta.batchSize) || !isSafeNaturalNumber(query.meta.batchSize)) {
throw buildUsageError(
'E_INVALID_META',
'If provided, `batchSize` should be a whole, positive, safe, and natural integer. '+
'Instead, got '+util.inspect(query.meta.batchSize, {depth: null})+'.',
query.using
);
}//β’
if (query.method !== 'stream') {
// FUTURE: consider changing this usage error to a warning instead.
throw buildUsageError(
'E_INVALID_META',
'`batchSize` cannot be used with .'+query.method+'() -- it is only compatible '+
'with the .stream() model method.',
query.using
);
}//β’
}//ο¬
// β¦
}//ο¬
//-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
// -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
//- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
//-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
// -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
//- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
//-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
// ββββββββββββββ βββββββββββββββββββββββββββ βββ ββββββ
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// βββ βββββββββββ βββ ββββββ βββββββββββββββββββ
// βββ βββββββββββ βββ ββββββ βββββββββββββββββββ
// βββββββββββ ββββββ βββ βββββββββββ βββββββββ βββ
// ββββββββββ ββββββ βββ βββββββββββ βββββββββ βββ
//
if (_.contains(queryKeys, 'criteria')) {
// βββββββββββββ¦ββββ¦ βββββββββββββββ
// ββββ ββββ£ β ββ ββ£β β β ββ£βββββ£ βββ
// ββββ© βββββββ©β© β©β©ββ ββββ© β©βββββββββ
// ββ β¬ βββ β¬ β¬βββββββ¬ β¬ββββββββββ¬ββββ¬ββββββ¬β ββββββββ¬βββ β¬ββββββββ¬ββ¬βββββββββ ββββββ
// ββββ β ββ€ β ββββββββ ββββββββ βββ¬β β ββ€ ββ β β ββββββ΄ββββββββ€ β ββ βββββββ β βββ€
// ββ β΄oβββo βββββββββββββ΄ β΄ ββββ΄ββ β΄ βββββ΄β βββββββ΄ β΄ββββ΄ββββ΄ β΄ β΄ β΄βββββββββ ββββ
// βββββββ¬ββββ¬βββββ¬βββ ββββ¬βββ¬ββ¬βββββ¬βββ¬βββ ββββ¬ ββββ¬ β¬βββββββββ βββββββ¬ββ
// β ββ€ ββ¬β β βββ€ββββ β ββ¬ββ β ββ€ ββ¬βββββ€ β β βββ€β ββββββ€ βββ ββ€ β βββ¬β
// βββββββ΄ββ β΄ β΄ β΄β΄βββ ββββ΄βββ΄ β΄ ββββ΄βββ΄β΄ β΄ ββββ΄βββ΄ β΄ββββββββββββ β ββββ΄ββ
// βββββββββββββ¬ββββ¬βββ ββ¬ββββββ¬βββββ¬ ββ¬ββββββ¬ββ¬ β¬βββββ¬ββββ ββ
// ββββββββ€ β βββ€ ββ ββββ β ββββ€ β βββββ€ β βββ€β β βββββ ββββ
// ββββ΄ βββββββ΄β β΄βββ β΄ β΄βββββ΄βββββ΄ββ β΄ β΄βββ β΄ β΄ β΄βββββ΄ββββ ββ
//
// Next, handle a few special cases that we are careful to fail loudly about.
//
// > Because if we don't, it can cause major confusion. Think about it: in some cases,
// > certain usage can seem intuitive, and like a reasonable enough thing to try out...
// > ...but it might actually be unsupported.
// >
// > When you do try it out, unless it fails LOUDLY, then you could easily end
// > up believing that it is actually doing something. And then, as is true when
// > working w/ any library or framework, you end up with all sorts of weird superstitions
// > and false assumptions that take a long time to wring out of your code base.
// > So let's do our best to prevent that.
//
// > WARNING:
// > It is really important that we do this BEFORE we normalize the criteria!
// > (Because by then, it'll be too late to tell what was and wasn't included
// > in the original, unnormalized criteria dictionary.)
//
// If the criteria explicitly specifies `select` or `omit`, then make sure the query method
// is actually compatible with those clauses.
if (_.isObject(query.criteria) && !_.isArray(query.criteria) && (!_.isUndefined(query.criteria.select) || !_.isUndefined(query.criteria.omit))) {
var PROJECTION_COMPATIBLE_METHODS = ['find', 'findOne', 'stream'];
var isCompatibleWithProjections = _.contains(PROJECTION_COMPATIBLE_METHODS, query.method);
if (!isCompatibleWithProjections) {
throw buildUsageError('E_INVALID_CRITERIA', 'Cannot use `select`/`omit` with this method (`'+query.method+'`).', query.using);
}
}//>-β’
// If the criteria explicitly specifies `limit`, `skip`, or `sort`, then make sure
// the query method is actually compatible with those clauses.
if (_.isObject(query.criteria) && !_.isArray(query.criteria) && (!_.isUndefined(query.criteria.limit) || !_.isUndefined(query.criteria.skip) || !_.isUndefined(query.criteria.sort))) {
var PAGINATION_COMPATIBLE_METHODS = ['find', 'stream'];
var isCompatibleWithLimit = _.contains(PAGINATION_COMPATIBLE_METHODS, query.method);
if (!isCompatibleWithLimit) {
throw buildUsageError('E_INVALID_CRITERIA', 'Cannot use `limit`, `skip`, or `sort` with this method (`'+query.method+'`).', query.using);
}
}//>-β’
// If the criteria is not defined, then in most cases, we treat it like `{}`.
// BUT if this query will be running as a result of an `update()`, or a `destroy()`,
// or an `.archive()`, then we'll be a bit more picky in order to prevent accidents.
if (_.isUndefined(query.criteria) && (query.method === 'update' || query.method === 'destroy' || query.method === 'archive')) {
throw buildUsageError('E_INVALID_CRITERIA', 'Cannot use this method (`'+query.method+'`) with a criteria of `undefined`. (This is just a simple failsafe to help protect your data: if you really want to '+query.method+' ALL records, no problem-- please just be explicit and provide a criteria of `{}`.)', query.using);
}//>-β’
// ββ¦βββββββββββ¦ β¦β¦ ββ¦β
// ββββ£ β β£ β ββ£β ββ β
// ββ©βββββ β© β©ββββ©βββ©
// Tolerate this being left undefined by inferring a reasonable default.
// (This will be further processed below.)
if (_.isUndefined(query.criteria)) {
query.criteria = {};
}//>-
// βββββββ¦ββββ¦βββββ¦ β¦ββββββ β¬ β¦ β¦ββββ¦ β¦ββ¦ββββββ¦ββββ
// ββββ ββ β¦βββββ ββ£β ββββββ£ ββΌβ βββββ ββ£β β βββ ββ£ β ββ£
// βββββββ©βββ© β©β© β©β©βββ©ββββββ ββ ββ β© β©β©βββ©ββ©ββ© β© β© βββ
// Validate and normalize the provided `criteria`.
try {
query.criteria = normalizeCriteria(query.criteria, query.using, orm, query.meta);
} catch (e) {
switch (e.code) {
case 'E_HIGHLY_IRREGULAR':
throw buildUsageError('E_INVALID_CRITERIA', e.message, query.using);
case 'E_WOULD_RESULT_IN_NOTHING':
throw buildUsageError('E_NOOP', 'The provided criteria would not match any records. '+e.message, query.using);
// If no error code (or an unrecognized error code) was specified,
// then we assume that this was a spectacular failure do to some
// kind of unexpected, internal error on our part.
default:
throw new Error('Consistency violation: Encountered unexpected internal error when attempting to normalize/validate the provided criteria:\n```\n'+util.inspect(query.criteria, {depth:5})+'\n```\nAnd here is the actual error itself:\n```\n'+e.stack+'\n```');
}
}//>-β’
// ββββ¬ β¬ β¬ββββ¬ β¬βββ βββββββ¬ββββββββ β¦ β¦ββ¦ββ¦ββ¦β ββ¬ββββ ββ¦ββ¦ β¦βββ
// βββ€β ββββββ€ββ¬ββββ ββ€ β βββ¬ββ ββ€ β βββββ β β β β β ββββ β
// β΄ β΄β΄ββββ΄ββ΄ β΄ β΄ βββ β ββββ΄ββββββββ β©βββ©β© β©β© β© β΄ βββ β© ββ©ββββ
// ββ β¬βββ ββ¬ββ¬ β¬β¬βββ β¬βββ βββ ββββ¦βββββ¦β βββββββββ βββ β¬ β¬ββββ¬βββ¬ β¬ ββ
// ββββ βββ€ β βββ€ββββ ββββ βββ€ β β£ ββββ ββ β ββββββ£ βββΌββ βββ€ ββ¬βββ¬β ββββ
// ββ β΄β β΄ β΄ β΄β΄βββ β΄βββ β΄ β΄ β β©βββββ©β βββββββββ βββββββββββ΄ββ β΄ ββ
// Last but not least, if the current method is `findOne`, then set `limit: 2`.
//
// > This is a performance/stability check that prevents accidentally fetching the entire database
// > with queries like `.findOne({})`. If > 1 record is found, the findOne will fail w/ an error
// > anyway, so it only makes sense to fetch _just enough_.
if (query.method === 'findOne') {
query.criteria.limit = 2;
}//>-
// ββββββββββ¬ β¬β¬βββββ β¦ β¦β¦ β¦ββββ¦βββββ ββββ¬ ββββ¬ β¬ββββββ β¬βββ βββββββββββββ¬ββββ¬βββ
// ββ€ βββββββ βββ¬βββ€ ββββ ββ£ββ£ β β¦βββ£ β β βββ€β ββββββ€ ββββ ββββββββ€ β βββ€ ββ
// βββββββββββββ΄βββββ ββ©ββ© β©ββββ©βββββ ββββ΄βββ΄ β΄βββββββββ β΄βββ ββββ΄ βββββββ΄β β΄βββ
// ββ β¬βββ ββ¬ββ¬ β¬β¬βββ β¬βββ βββ \β/βββββββββ βββ β¬ β¬ββββ¬βββ¬ β¬ ββ
// ββββ βββ€ β βββ€ββββ ββββ βββ€ β ββ ββββββ£ βββΌββ βββ€ ββ¬βββ¬β ββββ
// ββ β΄β β΄ β΄ β΄β΄βββ β΄βββ β΄ β΄ o/β\βββββββββ βββββββββββ΄ββ β΄ ββ
// If this is a `findOne`/`updateOne`/`destroyOne`/`archiveOne` query,
// and the `where` clause is not defined, or if it is `{}`, then fail
// with a usage error (for clarity's sake).
if (_.contains(['findOne','updateOne','destroyOne','archiveOne'], query.method) && _.isEqual(query.criteria.where, {})) {
throw buildUsageError(
'E_INVALID_CRITERIA',
'Cannot `'+query.method+'()` without specifying a more specific `where` clause (the provided `where` clause, `{}`, is too broad).'+
(query.method === 'findOne' ? ' (If you want to work around this, use `.find().limit(1)`.)' : ''),
query.using
);
}//>-β’
}// >-β’
// βββββββ βββββββ βββββββ βββ ββββββ ββββββ βββββββββββββββββββββββββ
// ββββββββββββββββββββββββββββ ββββββ βββββββββββββββββββββββββββββββββ
// βββββββββββ ββββββββββββββ ββββββ ββββββββ βββ ββββββ ββββββββ
// βββββββ βββ ββββββββββ βββ ββββββ ββββββββ βββ ββββββ ββββββββ
// βββ ββββββββββββ ββββββββββββββββββββ βββ βββ ββββββββββββββββ
// βββ βββββββ βββ βββββββ βββββββββββ βββ βββ ββββββββββββββββ
//
// Validate/normalize the `populates` query key.
//
// > NOTE: At this point, we know that the `criteria` query key has already been checked/normalized.
if (_.contains(queryKeys, 'populates')) {
// Tolerate this being left undefined by inferring a reasonable default.
if (_.isUndefined(query.populates)) {
query.populates = {};
}//>-
// Verify that `populates` is a dictionary.
if (!_.isObject(query.populates) || _.isArray(query.populates) || _.isFunction(query.populates)) {
throw buildUsageError(
'E_INVALID_POPULATES',
'`populates` must be a dictionary. But instead, got: '+util.inspect(query.populates, {depth: 1}),
query.using
);
}//-β’
// For each key in our `populates` dictionary...
_.each(_.keys(query.populates), function (populateAttrName) {
// For convenience/consistency, if the RHS of this "populate" directive was set
// to `false`/`undefined`, understand it to mean the same thing as if this particular
// populate directive wasn't included in the first place. In other words, strip
// this key from the `populates` dictionary and just return early.
if (query.populates[populateAttrName] === false || _.isUndefined(query.populates[populateAttrName])) {
delete query.populates[populateAttrName];
return;
}//-β’
// β¬ βββββββ¬ββ β¬ β¬βββ βββββ¦βββ¦ββ¦ββ ββ¦βββββββ βββββββ¬ββ ββββββββββββββββ¬βββββ¬ββ¬ββββββ
// β β ββ βββ΄β β ββββ β ββ£ β β β β¦β ββββ£ β β£ ββ€ β βββ¬β βββ€βββββββ ββ ββββ€ β ββ ββββ
// β΄βββββββββ΄ β΄ ββββ΄ β© β© β© β© β©ββ ββ©βββββ β ββββ΄ββ β΄ β΄βββββββββββββ΄β΄ β΄ β΄ β΄ββββββ
// Look up the attribute definition for the association being populated.
// (at the same time, validating that an association by this name actually exists in this model definition.)
var populateAttrDef;
try {
populateAttrDef = getAttribute(populateAttrName, query.using, orm);
} catch (e) {
switch (e.code) {
case 'E_ATTR_NOT_REGISTERED':
throw buildUsageError(
'E_INVALID_POPULATES',
'Could not populate `'+populateAttrName+'`. '+
'There is no attribute named `'+populateAttrName+'` defined in this model.',
query.using
);
default: throw new Error('Consistency violation: When attempting to populate `'+populateAttrName+'` for this model (`'+query.using+'`), an unexpected error occurred looking up the association\'s definition. This SHOULD never happen. Here is the original error:\n```\n'+e.stack+'\n```');
}
}//</catch>
// β¬ βββββββ¬ββ β¬ β¬βββ β¬βββββββββ ββββββ ββ¬ββ¬ β¬βββ βββββ¦ββ¦ β¦ββββ¦ββ ββ¦ββββββ¦βββββ¦
// β β ββ βββ΄β β ββββ ββββββ€ β β β ββββ β βββ€ββ€ β β β β ββ£ββ£ β β¦β ββββ β ββββ£ β
// β΄βββββββββ΄ β΄ ββββ΄ β΄ββββ βββ ββββββ β΄ β΄ β΄βββ βββ β© β© β©ββββ©ββ β© β©βββββ©βββββ©ββ
// Determine the identity of the other (associated) model, then use that to make
// sure that the other model's definition is actually registered in our `orm`.
var otherModelIdentity;
if (populateAttrDef.model) {
otherModelIdentity = populateAttrDef.model;
}//β‘
else if (populateAttrDef.collection) {
otherModelIdentity = populateAttrDef.collection;
}//β‘
// Otherwise, this query is invalid, since the attribute with this name is
// neither a "collection" nor a "model" association.
else {
throw buildUsageError(
'E_INVALID_POPULATES',
'Could not populate `'+populateAttrName+'`. '+
'The attribute named `'+populateAttrName+'` defined in this model (`'+query.using+'`) '+
'is not defined as a "collection" or "model" association, and thus cannot '+
'be populated. Instead, its definition looks like this:\n'+
util.inspect(populateAttrDef, {depth: 1}),
query.using
);
}//>-β’
// β¬ β¬βββ ββββ¦βββ¦ββ¦βββββ¦βββ¦ β¦ ββββ¦βββ¦ββ¦βββββ¦βββ¦βββ
// βββββββ β βββ β¦ββββββ ββ£β β¦βββ¦β β β β¦ββ β ββ£ β β¦βββ ββ£
// ββ βββo β© β©βββ©β© β©β© β©β©ββ β© ββββ©βββ© β© ββββ©βββ©β© β©
// If trying to populate an association that is ALSO being omitted (in the primary criteria),
// then we say this is invalid.
//
// > We know that the primary criteria has been normalized already at this point.
// > Note: You can NEVER `select` or `omit` plural associations anyway, but that's
// > already been dealt with above from when we normalized the criteria.
if (_.contains(query.criteria.omit, populateAttrName)) {
throw buildUsageError(
'E_INVALID_POPULATES',
'Could not populate `'+populateAttrName+'`. '+
'This query also indicates that this attribute should be omitted. '+
'Cannot populate AND omit an association at the same time!',
query.using
);
}//-β’
// If trying to populate an association that was included in an explicit `select` clause
// in the primary criteria, then gracefully modify that select clause so that it is NOT included.
// (An explicit `select` clause is only used for singular associations that AREN'T populated.)
//
// > We know that the primary criteria has been normalized already at this point.
if (query.criteria.select[0] !== '*' && _.contains(query.criteria.select, populateAttrName)) {
_.remove(query.criteria.select, populateAttrName);
}//>-
// If trying to populate an association that was ALSO included in an explicit
// `sort` clause in the primary criteria, then don't allow this to be populated.
//
// > We know that the primary criteria has been normalized already at this point.
var isMentionedInPrimarySort = _.any(query.criteria.sort, function (comparatorDirective){
var sortBy = _.keys(comparatorDirective)[0];
return (sortBy === populateAttrName);
});
if (isMentionedInPrimarySort) {
throw buildUsageError(
'E_INVALID_POPULATES',
'Could not populate `'+populateAttrName+'`. '+
'Cannot populate AND sort by an association at the same time!',
query.using
);
}//>-
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// Similar to the above...
//
// FUTURE: Verify that trying to populate a association that was ALSO referenced somewhere
// from within the `where` clause in the primary criteria (i.e. as an fk) works properly.
// (This is an uncommon use case, and is not currently officially supported.)
//
// > Note that we already throw out any attempts to filter based on a plural ("collection")
// > association, whether it's populated or not-- but that's taken care of separately in
// > normalizeCriteria().
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// ββββ¬ β¬βββββββ¬ββ ββ¬ββ¬ β¬βββ β¦βββ¦ β¦βββ
// β βββ€ββ€ β ββ΄β β βββ€ββ€ β β¦ββ ββ£βββ
// ββββ΄ β΄βββββββ΄ β΄ β΄ β΄ β΄βββ β©βββ© β©βββ
// If this is a singular ("model") association, then it should always have
// an empty dictionary on the RHS. (For this type of association, there is
// always either exactly one associated record, or none of them.)
if (populateAttrDef.model) {
// Tolerate a subcriteria of `{}`, interpreting it to mean that there is
// really no criteria at all, and that we should just use `true` (the
// default "enabled" value for singular "model" associations.)
if (_.isEqual(query.populates[populateAttrName], {})) {
query.populates[populateAttrName] = true;
}
// Otherwise, this simply must be `true`. Otherwise it's invalid.
else {
if (query.populates[populateAttrName] !== true) {
throw buildUsageError(
'E_INVALID_POPULATES',
'Could not populate `'+populateAttrName+'`. '+
'This is a singular ("model") association, which means it never refers to '+
'more than _one_ associated record. So passing in subcriteria (i.e. as '+
'the second argument to `.populate()`) is not supported for this association, '+
'since it generally wouldn\'t make any sense. But that\'s the trouble-- it '+
'looks like some sort of a subcriteria (or something) _was_ provided!\n'+
'(Note that subcriterias consisting ONLY of `omit` or `select` are a special '+
'case that _does_ make sense. This usage will be supported in a future version '+
'of Waterline.)\n'+
'\n'+
'Here\'s what was passed in:\n'+
util.inspect(query.populates[populateAttrName], {depth: 5}),
query.using
);
}//-β’
}//>-β’
}
// Otherwise, this is a plural ("collection") association, so we'll need to
// validate and fully-normalize the provided subcriteria.
else {
// For compatibility, interpet a subcriteria of `true` to mean that there
// is really no subcriteria at all, and that we should just use the default (`{}`).
// > This will be further expanded into a fully-formed criteria dictionary shortly.
if (query.populates[populateAttrName] === true) {
query.populates[populateAttrName] = {};
}//>-
// Track whether `sort` was effectively omitted from the subcriteria.
// (this is used just a little ways down below.)
//
// > Be sure to see "FUTURE (1)" for details about how we might improve this in
// > the future-- it's not a 100% accurate or clean check right now!!
var isUsingDefaultSort = (
!_.isObject(query.populates[populateAttrName]) ||
_.isUndefined(query.populates[populateAttrName].sort) ||
_.isEqual(query.populates[populateAttrName].sort, [])
);
// Validate and normalize the provided subcriteria.
try {
query.populates[populateAttrName] = normalizeCriteria(query.populates[populateAttrName], otherModelIdentity, orm, query.meta);
} catch (e) {
switch (e.code) {
case 'E_HIGHLY_IRREGULAR':
throw buildUsageError(
'E_INVALID_POPULATES',
'Could not use the specified subcriteria for populating `'+populateAttrName+'`: '+e.message,
// (Tip: Instead of that ^^^, when debugging Waterline itself, replace `e.message` with `e.stack`)
query.using
);
case 'E_WOULD_RESULT_IN_NOTHING':
// If the criteria indicates this populate would result in nothing, then set it to
// `false` - a special value indicating that it is a no-op.
// > β’ In Waterline's operation builder, whenever we see a subcriteria of `false`,
// > we simply skip the populate (i.e. don't factor it in to our stage 3 queries)
// > β’ And in the transformer, whenever we're putting back together a result set,
// > and we see a subcriteria of `false` from the original stage 2 query, then
// > we ensure that the virtual attributes comes back set to `[]` in the resulting
// > record.
query.populates[populateAttrName] = false;
// And then return early from this iteration of our loop to skip further checks
// for this populate (since they won't be relevant anyway)
return;
// If no error code (or an unrecognized error code) was specified,
// then we assume that this was a spectacular failure do to some
// kind of unexpected, internal error on our part.
default:
throw new Error('Consistency violation: Encountered unexpected internal error when attempting to normalize/validate the provided criteria for populating `'+populateAttrName+'`:\n```\n'+util.inspect(query.populates[populateAttrName], {depth:5})+'\n```\nThe following error occurred:\n```\n'+e.stack+'\n```');
}
}//>-β’
// ββββ¬βββββββ¬ββ¬ β¬βββββ¬ββ¬ββββββ ββββ¬ β¬βββββββ¬ββ
// βββββ¬ββ β βββ ββ β ββ ββββ β βββ€ββ€ β ββ΄β
// β΄ β΄βββββββ΄βββββββ β΄ β΄ββββββ ββββ΄ β΄βββββββ΄ β΄
// βββββββ¬ββ βββββββββ ββββββββ¦ββ¦ββ¦ββ¦ββββββββ¦β ββββββββββ¬ β¬β¬ βββββ¬βββββββ
// ββ€ β βββ¬β ββββ ββββββββ ββ ββ β ββββββββββ£ ββ ββββ βββββ ββ βββ€ β ββ€ βββ
// β ββββ΄ββ βββββββββ ββββ© β© β©β© β©β©ββββββββ©β β΄ ββββ΄ ββββ΄βββ΄ β΄ β΄ ββββββ
// ββ¬ββ¬ β¬βββββ¬β ββββ¦ ββββββ β¦ β¦ββββββ ββββ¦ β¦ββ ββββ¦βββ¦ββ¦βββββ¦βββ¦βββ
// β βββ€βββ€ β β ββ£β ββββ β β ββββββ£ ββββ ββ β©ββ β β¦ββ β ββ£ β β¦βββ ββ£
// β΄ β΄ β΄β΄ β΄ β΄ β© β©β©ββββββββ βββββββββ βββββββββββββ©βββ© β© ββββ©βββ©β© β©
// In production, if this check fails, a warning will be logged.
// Determine if we are populating an association that does not support a fully-optimized populate.
var isAssociationFullyCapable = isCapableOfOptimizedPopulate(populateAttrName, query.using, orm);
// If so, then make sure we are not attempting to perform a "dangerous" populate--
// that is, one that is not currently safe using our built-in joining shim.
// (This is related to memory usage, and is a result of the shim's implementation.)
if (!isAssociationFullyCapable) {
var subcriteria = query.populates[populateAttrName];
var isPotentiallyDangerous = (
subcriteria.skip !== 0 ||
subcriteria.limit !== (Number.MAX_SAFE_INTEGER||9007199254740991) ||
!isUsingDefaultSort
);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// > FUTURE (1): make this check more restrictive-- not EVERYTHING it prevents is actually
// > dangerous given the current implementation of the shim. But in the mean time,
// > better to err on the safe side.
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// > FUTURE (2): overcome this by implementing a more complicated batching strategy-- however,
// > this is not a priority right now, since this is only an issue for xD/A associations,
// > which will likely never come up for the majority of applications. Our focus is on the
// > much more common real-world scenario of populating across associations in the same database.
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
if (isPotentiallyDangerous) {
if (process.env.NODE_ENV === 'production') {
console.warn('\n'+
'Warning: Attempting to populate `'+populateAttrName+'` with the specified subcriteria,\n'+
'but this MAY NOT BE SAFE, depending on the number of records stored in your models.\n'+
'Since this association does not support optimized populates (i.e. it spans multiple '+'\n'+
'datastores, or uses an adapter that does not support native joins), it is not a good '+'\n'+
'idea to populate it along with a subcriteria that uses `limit`, `skip`, and/or `sort`-- '+'\n'+
'at least not in a production environment.\n'+
'\n'+
'This is because, to satisfy the specified `limit`/`skip`/`sort`, many additional records\n'+
'may need to be fetched along the way -- perhaps enough of them to overflow RAM on your server.\n'+
'\n'+
'If you are just using sails-disk during development, or are certain this is not a problem\n'+
'based on your application\'s requirements, then you can safely ignore this message.\n'+
'But otherwise, to overcome this, either (A) remove or change this subcriteria and approach\n'+
'this query a different way (such as multiple separate queries or a native query), or\n'+
'(B) configure all involved models to use the same datastore, and/or switch to an adapter\n'+
'like sails-mysql or sails-postgresql that supports native joins.\n'+
' [?] See https://sailsjs.com/support for help.\n'
);
}//ο¬ </ if production >
}//ο¬ </ if populating would be potentially- dangerous as far as process memory consumption >
}//ο¬ </ if association is NOT fully capable of being populated in a fully-optimized way >
}//</else :: this is a plural ("collection") association>
});//</_.each() key in the `populates` dictionary>
}//>-β’
// ββββ ββββββ βββββββ βββββββββββββββββββ βββ βββββββ
// βββββ ββββββ ββββββββ ββββββββββββββββββββββββββββββββ
// ββββββ ββββββ ββββββββββββββββββββ ββββββββββββββ
// βββββββββββββ ββββββββββββββββββββ ββββββββββββββ
// βββ ββββββββββββββββββ βββ ββββββββββββββ ββββββββββββββ
// βββ βββββ βββββββ βββ ββββββββββββββ ββββββ βββββββ
//
// ββββββ βββββββββββββββββββββββββ ββββ βββ ββββββ ββββ ββββββββββββ
// ββββββββββββββββββββββββββββββββββ βββββ ββββββββββββββββ βββββββββββββ
// ββββββββ βββ βββ ββββββββ ββββββ ββββββββββββββββββββββββββββ
// ββββββββ βββ βββ ββββββββ βββββββββββββββββββββββββββββββββββ
// βββ βββ βββ βββ βββ βββ βββ βββββββββ ββββββ βββ βββββββββββ
// βββ βββ βββ βββ βββ βββ βββ ββββββββ ββββββ βββββββββββ
//
if (_.contains(queryKeys, 'numericAttrName')) {
if (_.isUndefined(query.numericAttrName)) {
throw buildUsageError(
'E_INVALID_NUMERIC_ATTR_NAME',
'Please specify `numericAttrName` (required for this variety of query).',
query.using
);
}
if (!_.isString(query.numericAttrName)) {
throw buildUsageError(
'E_INVALID_NUMERIC_ATTR_NAME',
'Instead of a string, got: '+util.inspect(query.numericAttrName,{depth:5}),
query.using
);
}
// Validate that an attribute by this name actually exists in this model definition.
var numericAttrDef;
try {
numericAttrDef = getAttribute(query.numericAttrName, query.using, orm);
} catch (e) {
switch (e.code) {
case 'E_ATTR_NOT_REGISTERED':
throw buildUsageError(
'E_INVALID_NUMERIC_ATTR_NAME',
'There is no attribute named `'+query.numericAttrName+'` defined in this model.',
query.using
);
default: throw e;
}
}//</catch>
// If this attempts to use a singular (`model`) association that happens to also
// correspond with an associated model that has a `type: 'number'` primary key, then
// STILL THROW -- but just use a more explicit error message explaining the reason this
// is not allowed (i.e. because it doesn't make any sense to get the sum or average of
// a bunch of ids... and more often than not, this scenario happens due to mistakes in
// userland code. We have yet to see a use case where this is necessary.)
var isSingularAssociationToModelWithNumericPk = numericAttrDef.model && (getAttribute(getModel(numericAttrDef.model, orm).primaryKey, numericAttrDef.model, orm).type === 'number');
if (isSingularAssociationToModelWithNumericPk) {
throw buildUsageError(
'E_INVALID_NUMERIC_ATTR_NAME',
'While the attribute named `'+query.numericAttrName+'` defined in this model IS guaranteed '+
'to be a number (because it is a singular association to a model w/ a numeric primary key), '+
'it almost certainly shouldn\'t be used for this purpose. If you are seeing this error message, '+
'it is likely due to a mistake in userland code, so please check your query.',
query.using
);
}//-β’
// Validate that the attribute with this name is a number.
if (numericAttrDef.type !== 'number') {
throw buildUsageError(
'E_INVALID_NUMERIC_ATTR_NAME',
'The attribute named `'+query.numericAttrName+'` defined in this model is not guaranteed to be a number '+
'(it should declare `type: \'number\'`).',
query.using
);
}
}//>-β’
//-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
// -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
//- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
//-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
// -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
//- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
//-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
// ββββββββ ββββββ ββββββββββ βββ βββββββ ββββββββ βββββββ βββββββ βββββββ βββββββ
// βββββββββββββββββββββββββββ βββ βββββββββββββββββββββββββββββββββββββββββββββββββ
// ββββββ βββββββββββ ββββββββ ββββββββββββββ βββ βββ ββββββββββββββ βββ
// ββββββ βββββββββββ ββββββββ ββββββββββββββ βββ βββ ββββββββββββββ βββ
// βββββββββββ ββββββββββββββ βββ βββ βββββββββββββββββββββββββββββββ βββββββββββ
// βββββββββββ βββ ββββββββββ βββ βββ βββββββββββ βββββββ βββββββ βββ ββββββββββ
//
// βββ ββββββββ ββββββ ββββββββββ βββ βββββββ ββββββ βββββββββ ββββββββββ βββ
// ββββ βββββββββββββββββββββββββββ βββ ββββββββββββββββββββββββββββββββββββ βββ
// ββββ ββββββ βββββββββββ ββββββββ ββββββββββββββββ βββ βββ ββββββββ
// ββββ ββββββ βββββββββββ ββββββββ ββββββββββββββββ βββ βββ ββββββββ
// ββββ βββββββββββ ββββββββββββββ βββ βββββββββββ βββ βββ βββββββββββ βββ
// βββ βββββββββββ βββ ββββββββββ βββ βββββββ βββ βββ βββ ββββββββββ βββ
//
// ββββββββββββββ βββββββ βββ βββββββββββββββββββ βββββββ ββββ ββββββββββββββ
// βββββββββββββββ ββββββββ βββββββββββββββββββββββββββββββββββββ βββββββββββββββ
// βββ ββββββ βββ βββββββββ ββββββ βββ ββββββ βββββββββ βββββββββββ βββ
// βββ ββββββ βββ ββββββββββββββββ βββ ββββββ βββββββββββββββββββββ βββ
// βββββββ ββββββββββββ ββββββββββββββ βββ βββββββββββββββ ββββββββββββββββββ
// ββββββ βββββββ βββ βββββ βββββββ βββ βββ βββββββ βββ ββββββββββββββββ
//
// If we are expecting either eachBatchFn or eachRecordFn, then make sure
// one or the other is set... but not both! And make sure that, whichever
// one is specified, it is a function.
//
// > This is only a problem if BOTH `eachRecordFn` and `eachBatchFn` are
// > left undefined, or if they are BOTH set. (i.e. xor)
// > See https://gist.github.com/mikermcneil/d1e612cd1a8564a79f61e1f556fc49a6#edge-cases--details
if (_.contains(queryKeys, 'eachRecordFn') || _.contains(queryKeys, 'eachBatchFn')) {
// -> Both functions were defined
if (!_.isUndefined(query.eachRecordFn) && !_.isUndefined(query.eachBatchFn)) {
throw buildUsageError(
'E_INVALID_STREAM_ITERATEE',
'An iteratee function should be passed in to `.stream()` via either ' +
'`.eachRecord()` or `.eachBatch()` -- but never both. Please set one or the other.',
query.using
);
}
// -> Only `eachRecordFn` was defined
else if (!_.isUndefined(query.eachRecordFn)) {
if (!_.isFunction(query.eachRecordFn)) {
throw buildUsageError(
'E_INVALID_STREAM_ITERATEE',
'For `eachRecordFn`, instead of a function, got: '+util.inspect(query.eachRecordFn,{depth:5}),
query.using
);
}
}
// -> Only `eachBatchFn` was defined
else if (!_.isUndefined(query.eachBatchFn)) {
if (!_.isFunction(query.eachBatchFn)) {
throw buildUsageError(
'E_INVALID_STREAM_ITERATEE',
'For `eachBatchFn`, instead of a function, got: '+util.inspect(query.eachBatchFn,{depth:5}),
query.using
);
}
}
// -> Both were left undefined
else {
throw buildUsageError(
'E_INVALID_STREAM_ITERATEE',
'Either `eachRecordFn` or `eachBatchFn` should be defined, but neither of them are.',
query.using
);
}
}//>-β’
//-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
// -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
//- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
//-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
// -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
//- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
//-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
// ββββ ββββββββββββββ βββ βββββββ ββββββββ βββββββ βββββββ βββββββ βββββββ
// βββββ ββββββββββββββ βββ βββββββββββββββββββββββββββββββββββββββββββββββββ
// ββββββ βββββββββ βββ ββ βββ ββββββββββββββ βββ βββ ββββββββββββββ βββ
// ββββββββββββββββ ββββββββββ ββββββββββββββ βββ βββ ββββββββββββββ βββ
// βββ ββββββββββββββββββββββββ βββ βββββββββββββββββββββββββββββββ βββββββββββ
// βββ βββββββββββββ ββββββββ βββ βββββββββββ βββββββ βββββββ βββ ββββββββββ
if (_.contains(queryKeys, 'newRecord')) {
// If this was provided as an array, apprehend it before calling our `normalizeNewRecord()` ,
// in order to log a slightly more specific error message.
if (_.isArray(query.newRecord)) {
throw buildUsageError(
'E_INVALID_NEW_RECORD',
'Got an array, but expected new record to be provided as a dictionary (plain JavaScript object). '+
'Array usage is no longer supported as of Sails v1.0 / Waterline 0.13. Instead, please explicitly '+
'call `.createEach()`.',
query.using
);
}//-β’
try {
query.newRecord = normalizeNewRecord(query.newRecord, query.using, orm, theMomentBeforeFS2Q, query.meta);
} catch (e) {
switch (e.code){
case 'E_TYPE':
case 'E_REQUIRED':
case 'E_VIOLATES_RULES':
throw buildUsageError('E_INVALID_NEW_RECORD', e.message, query.using);
case 'E_HIGHLY_IRREGULAR':
throw buildUsageError('E_INVALID_NEW_RECORD', e.message, query.using);
default: throw e;
}
}//</catch>
}//>-β’
// ββββ ββββββββββββββ βββ βββββββ ββββββββ βββββββ βββββββ βββββββ βββββββ ββββββββ
// βββββ ββββββββββββββ βββ βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// ββββββ βββββββββ βββ ββ βββ ββββββββββββββ βββ βββ ββββββββββββββ βββββββββββ
// ββββββββββββββββ ββββββββββ ββββββββββββββ βββ βββ ββββββββββββββ βββββββββββ
// βββ ββββββββββββββββββββββββ βββ βββββββββββββββββββββββββββββββ βββββββββββββββββββ
// βββ βββββββββββββ ββββββββ βββ βββββββββββ βββββββ βββββββ βββ ββββββββββ ββββββββ
if (_.contains(queryKeys, 'newRecords')) {
if (_.isUndefined(query.newRecords)) {
throw buildUsageError('E_INVALID_NEW_RECORDS', 'Please specify `newRecords`.', query.using);
}//-β’
if (!_.isArray(query.newRecords)) {
throw buildUsageError(
'E_INVALID_NEW_RECORDS',
'Expecting an array but instead, got: '+util.inspect(query.newRecords,{depth:5}),
query.using
);
}//-β’
// If the array of new records contains any `undefined` items, strip them out.
//
// > Note that this does not work:
// > ```
// > _.remove(query.newRecords, undefined);
// > ```
_.remove(query.newRecords, function (newRecord){
return _.isUndefined(newRecord);
});
// If the array is empty, bail out now with an E_NOOP error.
// (This will actually not be interpreted as an error. We will just
// pretend it worked.)
//
// > Note that we do this AFTER stripping undefineds.
if (query.newRecords.length === 0) {
throw buildUsageError('E_NOOP', 'No things to create were provided.', query.using);
}//-β’
// Ensure no two items in the `newRecords` array point to the same object reference.
// Why? Multiple references to the same object can get tangly and cause problems downstream
// in Waterline, such as this confusing error message: https://github.com/balderdashy/sails/issues/7266
//
// On the other hand, simply using `.uniq()` to deduplicate can be somewhat unexpected behavior.
// (Imagine using `let x = {}; await Widget.createEach([x,x,x,x]);` to create four widgets.
// It would be a surprise if it only created one widget.)
if (query.newRecords.length !== _.uniq(query.newRecords).length) {
throw buildUsageError(
'E_INVALID_NEW_RECORDS',
'Two or more of the items in the provided array of new records are actually references '+
'to the same JavaScript object (`.createEach(x,y,x)`). This is too ambiguous, since it '+
'could mean creating much more or much less data than intended. Instead, pass in distinct '+
'dictionaries for each new record you would like to create (`.createEach({},{},x,y,z)`).',
query.using
);
}//-β’
// Validate and normalize each new record in the provided array.
query.newRecords = _.map(query.newRecords, function (newRecord){
try {
return normalizeNewRecord(newRecord, query.using, orm, theMomentBeforeFS2Q, query.meta);
} catch (e) {
switch (e.code){
case 'E_TYPE':
case 'E_REQUIRED':
case 'E_VIOLATES_RULES':
throw buildUsageError(
'E_INVALID_NEW_RECORDS',
'Could not use one of the provided new records: '+e.message,
query.using
);
case 'E_HIGHLY_IRREGULAR':
throw buildUsageError(
'E_INVALID_NEW_RECORDS',
'Could not use one of the provided new records: '+e.message,
query.using
);
default: throw e;
}
}//</catch>
});//</_.each()>
}//>-β’
//-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
// -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
//- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
//-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
// -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
//- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
//-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
// βββ βββ ββββββ βββ βββ βββββββββββββββββββ
// βββ ββββββββββββββ βββ βββββββββββββββββββ
// βββ ββββββββββββββ βββ βββββββββ ββββββββ
// ββββ βββββββββββββββ βββ βββββββββ ββββββββ
// βββββββ βββ ββββββββββββββββββββββββββββββββββββ
// βββββ βββ βββββββββββ βββββββ ββββββββββββββββ
//
// βββββββββ βββββββ βββββββββββββββββββββββββ
// ββββββββββββββββββ βββββββββββββββββββββββββ
// βββ βββ βββ ββββββββββββββ βββ
// βββ βββ βββ ββββββββββββββ βββ
// βββ βββββββββ ββββββββββββββββ βββ
// βββ βββββββ ββββββββββββββββ βββ
if (_.contains(queryKeys, 'valuesToSet')) {
if (!_.isObject(query.valuesToSet) || _.isFunction(query.valuesToSet) || _.isArray(query.valuesToSet)) {
throw buildUsageError(
'E_INVALID_VALUES_TO_SET',
'Expecting a dictionary (plain JavaScript object) but instead, got: '+util.inspect(query.valuesToSet,{depth:5}),
query.using
);
}//-β’
// Now loop over and check every key specified in `valuesToSet`.
_.each(_.keys(query.valuesToSet), function (attrNameToSet){
// Validate & normalize this value.
// > Note that we could explicitly NOT allow literal arrays of pks to be provided
// > for collection attributes (plural associations) -- by passing in `false`.
// > That said, we currently still allow this.
try {
query.valuesToSet[attrNameToSet] = normalizeValueToSet(query.valuesToSet[attrNameToSet], attrNameToSet, query.using, orm, query.meta);
} catch (e) {
switch (e.code) {
// If its RHS should be ignored (e.g. because it is `undefined`), then delete this key and bail early.
case 'E_SHOULD_BE_IGNORED':
delete query.valuesToSet[attrNameToSet];
return;
case 'E_TYPE':
case 'E_REQUIRED':
case 'E_VIOLATES_RULES':
throw buildUsageError(
'E_INVALID_VALUES_TO_SET',
'Could not use specified `'+attrNameToSet+'`. '+e.message,
query.using
);
// For future reference, here are the additional properties we might expose:
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// β’ For E_TYPE:
// ```
// throw flaverr({
// code: 'E_TYPE',
// attrName: attrNameToSet,
// expectedType: e.expectedType
// }, new Error(
// 'The wrong type of data was specified for `'+attrNameToSet+'`. '+e.message
// ));
// ```
//
// β’ For E_VIOLATES_RULES:
// ```
// assert(_.isArray(e.ruleViolations) && e.ruleViolations.length > 0, 'This error should ALWAYS have a non-empty array as its `ruleViolations` property. But instead, its `ruleViolations` property is: '+e.ruleViolations+'\nAlso, for completeness/context, here is the error\'s complete stack: '+e.stack);
// throw flaverr({
// code: 'E_VIOLATES_RULES',
// attrName: attrNameToSet,
// ruleViolations: ruleViolations
// }, new Error(
// 'Could not use specified `'+attrNameToSet+'`. '+e.message
// ));
// ```
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
case 'E_HIGHLY_IRREGULAR':
throw buildUsageError(
'E_INVALID_VALUES_TO_SET',
'Could not use specified `'+attrNameToSet+'`. '+e.message,
query.using
);
default:
throw e;
}
}//</catch>
});//</_.each() key in the new record>
// Now, for each `autoUpdatedAt` attribute, check if there was a corresponding value provided.
// If not, then set the current timestamp as the value being set on the RHS.
_.each(WLModel.attributes, function (attrDef, attrName) {
if (!attrDef.autoUpdatedAt) { return; }
if (!_.isUndefined(query.valuesToSet[attrName])) { return; }
// -β’ IWMIH, this is an attribute that has `autoUpdatedAt: true`,
// and no value was explicitly provided for it.
assert(attrDef.type === 'number' || attrDef.type === 'string' || attrDef.type === 'ref', 'If an attribute has `autoUpdatedAt: true`, then it should always have either `type: \'string\'`, `type: \'number\'` or `type: \'ref\'`. But the definition for attribute (`'+attrName+'`) has somehow gotten into this state! This should be impossible, but it has both `autoUpdatedAt: true` AND `type: \''+attrDef.type+'\'`');
// Set the value equal to the current timestamp, using the appropriate format.
if (attrDef.type === 'string') {
query.valuesToSet[attrName] = (new Date(theMomentBeforeFS2Q)).toJSON();
}
else if (attrDef.type === 'ref') {
query.valuesToSet[attrName] = new Date(theMomentBeforeFS2Q);
}
else {
query.valuesToSet[attrName] = theMomentBeforeFS2Q;
}
});//</_.each() : looping over autoUpdatedAt attributes >
}//>-β’
//-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
// -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
//- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
//-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
// -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
//- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
//-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
// βββββββ βββββββ βββ βββ ββββββββ βββββββββββββββββββ βββββββ ββββ βββ
// ββββββββββββββββββββ βββ ββββββββββββββββββββββββββββββββββββββββββ βββ
// βββ βββ ββββββ βββ ββββββ βββ βββ ββββββ βββββββββ βββ
// βββ βββ ββββββ βββ ββββββ βββ βββ ββββββ βββββββββββββ
// βββββββββββββββββββββββββββββββββββββββββββββββββ βββ βββββββββββββββ ββββββ
// βββββββ βββββββ ββββββββββββββββββββββββ βββββββ βββ βββ βββββββ βββ βββββ
//
// ββββββ βββββββββββββββββββββββββ ββββ βββ ββββββ ββββ ββββββββββββ
// ββββββββββββββββββββββββββββββββββ βββββ ββββββββββββββββ βββββββββββββ
// ββββββββ βββ βββ ββββββββ ββββββ ββββββββββββββββββββββββββββ
// ββββββββ βββ βββ ββββββββ βββββββββββββββββββββββββββββββββββ
// βββ βββ βββ βββ βββ βββ βββ βββββββββ ββββββ βββ βββββββββββ
// βββ βββ βββ βββ βββ βββ βββ ββββββββ ββββββ βββββββββββ
// Look up the association by this name in this model definition.
if (_.contains(queryKeys, 'collectionAttrName')) {
if (!_.isString(query.collectionAttrName)) {
throw buildUsageError(
'E_INVALID_COLLECTION_ATTR_NAME',
'Instead of a string, got: '+util.inspect(query.collectionAttrName,{depth:5}),
query.using
);
}
// Validate that an association by this name actually exists in this model definition.
var associationDef;
try {
associationDef = getAttribute(query.collectionAttrName, query.using, orm);
} catch (e) {
switch (e.code) {
case 'E_ATTR_NOT_REGISTERED':
throw buildUsageError(
'E_INVALID_COLLECTION_ATTR_NAME',
'There is no attribute named `'+query.collectionAttrName+'` defined in this model.',
query.using
);
default: throw e;
}
}//</catch>
// Validate that the association with this name is a plural ("collection") association.
if (!associationDef.collection) {
throw buildUsageError(
'E_INVALID_COLLECTION_ATTR_NAME',
'The attribute named `'+query.collectionAttrName+'` defined in this model is not a plural ("collection") association.',
query.using
);
}
}//>-β’
// βββββββββ ββββββ βββββββ βββββββ βββββββββββββββββ
// βββββββββββββββββββββββββββββββββ βββββββββββββββββ
// βββ βββββββββββββββββββ ββββββββββ βββ
// βββ βββββββββββββββββββ βββββββββ βββ
// βββ βββ ββββββ ββββββββββββββββββββ βββ
// βββ βββ ββββββ βββ βββββββ ββββββββ βββ
//
// βββββββ ββββββββ βββββββ βββββββ βββββββ βββββββ ββββββββββ ββββββββ
// βββββββββββββββββββββββββββββββββββββββββββββββββ βββββββββββββββββββ
// ββββββββββββββ βββ βββ ββββββββββββββ βββ ββββββ βββββββββββ
// ββββββββββββββ βββ βββ ββββββββββββββ βββ ββββββ βββββββββββ
// βββ βββββββββββββββββββββββββββββββ βββββββββββ βββββββββββββββββββ
// βββ βββββββββββ βββββββ βββββββ βββ ββββββββββ ββββββββββ ββββββββ
if (_.contains(queryKeys, 'targetRecordIds')) {
// βββββββ¦ββββ¦βββββ¦ β¦ββββββ β¬ β¦ β¦ββββ¦ β¦ββ¦ββββββ¦ββββ ββββββ ββββ¬ββ β¬ β¬ββββ¬ βββ
// ββββ ββ β¦βββββ ββ£β ββββββ£ ββΌβ βββββ ββ£β β βββ ββ£ β ββ£ βββ€βββ βββββ΄β βββββββ€β βββ
// βββββββ©βββ© β©β© β©β©βββ©ββββββ ββ ββ β© β©β©βββ©ββ©ββ© β© β© βββ β΄ β΄βββ β΄ β΄ β΄ ββ β΄ β΄β΄βββββ
// Normalize (and validate) the specified target record pk values.
// (if a singular string or number was provided, this converts it into an array.)
//
// > Note that this ensures that they match the expected type indicated by this
// > model's primary key attribute.
try {
var pkAttrDef = getAttribute(WLModel.primaryKey, query.using, orm);
query.targetRecordIds = normalizePkValueOrValues(query.targetRecordIds, pkAttrDef.type);
} catch(e) {
switch (e.code) {
case 'E_INVALID_PK_VALUE':
throw buildUsageError(
'E_INVALID_TARGET_RECORD_IDS',
e.message,
query.using
);
default:
throw e;
}
}//< / catch : normalizePkValueOrValues >
// β¬ β¬ββββββββ¬ββ¬ βββ ββββββ ββββββ
// βββ€βββ€βββ βββ ββ€ ββββ βββββ ββ ββ
// β΄ β΄β΄ β΄βββββ΄ββ΄βββββ ββββββ ββββ©
// No query that takes target record ids is meaningful without any of said ids.
if (query.targetRecordIds.length === 0) {
throw buildUsageError('E_NOOP', 'No target record ids were provided.', query.using);
}//-β’
// β¬ β¬ββββββββ¬ββ¬ βββ βββββββββββββ¦ββββ¦ ββββββββββββ
// βββ€βββ€βββ βββ ββ€ ββββ ββββ£ β ββ ββ£β β β ββ£βββββ£
// β΄ β΄β΄ β΄βββββ΄ββ΄βββββ ββββ© βββββββ©β© β©β©ββ ββββ© β©ββββββ
// βββββββ¬ββ βββββ β¦ββββ¦ β¦ β¦ββββ¦β¦ β¦βββ ββ¬ββ¬ β¬βββ β¬ β¬ββββ¬ β¬ ββββββββββββββββ¬βββββ¬ββ¬βββββββββ
// ββ€ β βββ¬β ββ£ ββ©β¦ββ β β βββββββββββ£ β ββββ ββββββββββ€ββ¬β βββ€βββββββ ββ ββββ€ β ββ βββββββ
// β ββββ΄ββ ββββ© ββββββ©βββββββββ© ββ ββββ β΄ ββ΄ββββ ββ΄ββ΄ β΄ β΄ β΄ β΄βββββββββββββ΄β΄ β΄ β΄ β΄βββββββββ
// Next, handle one other special case that we are careful to fail loudly about.
// If this query's method is `addToCollection` or `replaceCollection`, and if there is MORE THAN ONE target record,
// AND if there is AT LEAST ONE associated id...
var isRelevantMethod = (query.method === 'addToCollection' || query.method === 'replaceCollection');
var isTryingToSetOneOrMoreAssociatedIds = _.isArray(query.associatedIds) && query.associatedIds.length > 0;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// ^^Note: If there are zero associated ids, this query may still fail a bit later because of
// physical-layer constraints or Waterline's cascade polyfill (e.g. if the foreign key
// attribute happens to have required: true). Where possible, checks to protect against this
// live in the implementation of the `.replaceCollection()` method.
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
if (query.targetRecordIds.length > 1 && isRelevantMethod && isTryingToSetOneOrMoreAssociatedIds) {
// Now check to see if this is a two-way, exclusive association.
// If so, then this query is impossible.
//
// > Note that, IWMIH, we already know this association is plural
// > (we checked that above when validating `collectionAttrName`)
var isAssociationExclusive = isExclusive(query.collectionAttrName, query.using, orm);
if (isAssociationExclusive) {
throw buildUsageError(
'E_INVALID_TARGET_RECORD_IDS',
'The `'+query.collectionAttrName+'` association of the `'+query.using+'` model is exclusive, meaning that associated child '+
'records cannot belong to the `'+query.collectionAttrName+'` collection of more than one `'+query.using+'` record. '+
'You are seeing this error because this query would have tried to share the same child record(s) across the `'+query.collectionAttrName+'` '+
'collections of 2 or more different `'+query.using+'` records. To resolve this error, change the query, or change your models '+
'to make this association non-exclusive (i.e. use `collection` & `via` on the other side of the association, instead of `model`.) '+
'In other words, imagine trying to run a query like `Car.replaceCollection([1,2], \'wheels\', [99, 98])`. If a wheel always belongs '+
'to one particular car via `wheels`, then this query would be impossible. To make it possible, you\'d have to change your models so '+
'that each wheel is capable of being associated with more than one car.',
query.using
);
}//-β’
}//>-β’
}//>-β’
// ββββββ ββββββββββββββββ βββββββ ββββββββββ ββββββ ββββββββββββββββββββββββ
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// βββββββββββββββββββββββββββ ββββββ βββββββββββ βββ ββββββ βββ βββ
// βββββββββββββββββββββββββββ ββββββ βββββββββββ βββ ββββββ βββ βββ
// βββ ββββββββββββββββββββββββββββββββββββββββββ βββ βββ ββββββββββββββββ
// βββ βββββββββββββββββββ βββββββ βββββββββββββ βββ βββ βββββββββββββββ
//
// ββββββββββ ββββββββ
// βββββββββββββββββββ
// ββββββ βββββββββββ
// ββββββ βββββββββββ
// βββββββββββββββββββ
// ββββββββββ ββββββββ
if (_.contains(queryKeys, 'associatedIds')) {
// Look up the ASSOCIATED Waterline model for this query, based on the `collectionAttrName`.
// Then use that to look up the declared type of its primary key.
//
// > Note that, if there are any problems that would prevent us from doing this, they
// > should have already been caught above, and we should never have made it to this point
// > in the code. So i.e. we can proceed with certainty that the model will exist.
// > And since its definition will have already been verified for correctness when
// > initializing Waterline, we can safely assume that it has a primary key, etc.
var associatedPkType = (function(){
var _associationDef = getAttribute(query.collectionAttrName, query.using, orm);
var _otherModelIdentity = _associationDef.collection;
var AssociatedModel = getModel(_otherModelIdentity, orm);
var _associatedPkDef = getAttribute(AssociatedModel.primaryKey, _otherModelIdentity, orm);
return _associatedPkDef.type;
})();
// βββββββ¦ββββ¦βββββ¦ β¦ββββββ β¬ β¦ β¦ββββ¦ β¦ββ¦ββββββ¦ββββ ββββββ ββββ¬ββ β¬ β¬ββββ¬ βββ
// ββββ ββ β¦βββββ ββ£β ββββββ£ ββΌβ βββββ ββ£β β βββ ββ£ β ββ£ βββ€βββ βββββ΄β βββββββ€β βββ
// βββββββ©βββ© β©β© β©β©βββ©ββββββ ββ ββ β© β©β©βββ©ββ©ββ© β© β© βββ β΄ β΄βββ β΄ β΄ β΄ ββ β΄ β΄β΄βββββ
// Validate the provided set of associated record ids.
// (if a singular string or number was provided, this converts it into an array.)
//
// > Note that this ensures that they match the expected type indicated by this
// > model's primary key attribute.
try {
query.associatedIds = normalizePkValueOrValues(query.associatedIds, associatedPkType);
} catch(e) {
switch (e.code) {
case 'E_INVALID_PK_VALUE':
throw buildUsageError('E_INVALID_ASSOCIATED_IDS', e.message, query.using);
default:
throw e;
}
}//< / catch :: normalizePkValueOrValues >
// βββββββββββββ¦ββββ¦ βββββββββββββββ
// ββββ ββββ£ β ββ ββ£β β β ββ£βββββ£ βββ
// ββββ© βββββββ©β© β©β©ββ ββββ© β©βββββββββ
// ββ β¬ βββ β¬ β¬βββββββ¬ β¬ββββββββββ¬ββββ¬ββββββ¬β ββββββββ¬βββ β¬ββββββββ¬ββ¬βββββββββ
// ββββ β ββ€ β ββββββββ ββββββββ βββ¬β β ββ€ ββ β β ββββββ΄ββββββββ€ β ββ βββββββ
// ββ β΄oβββo βββββββββββββ΄ β΄ ββββ΄ββ β΄ βββββ΄β βββββββ΄ β΄ββββ΄ββββ΄ β΄ β΄ β΄βββββββββ
// βββββββ¬ββ βββββββ¬ββββ¬βββββ¬βββ ββ¬ββββββ¬βββββ¬ ββ¬ββββββ¬ββ¬ β¬βββββ¬ββββ ββ
// ββ€ β βββ¬β β ββ€ ββ¬β β βββ€ββββ ββββ β ββββ€ β βββββ€ β βββ€β β βββββ ββββ
// β ββββ΄ββ βββββββ΄ββ β΄ β΄ β΄β΄βββ β΄ β΄βββββ΄βββββ΄ββ β΄ β΄βββ β΄ β΄ β΄βββββ΄ββββ ββ
//
// Handle the case where this is a no-op.
// An empty array is only a no-op if this query's method is `removeFromCollection` or `addToCollection`.
var isQueryMeaningfulWithNoAssociatedIds = (query.method === 'removeFromCollection' || query.method === 'addToCollection');
if (query.associatedIds.length === 0 && isQueryMeaningfulWithNoAssociatedIds) {
throw buildUsageError('E_NOOP', 'No associated ids were provided.', query.using);
}//-β’
}//>-β’
//-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
// -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
//- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
//-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
// -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
//- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
//-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
// if (process.env.NODE_ENV !== 'production') {
// console.timeEnd('forgeStageTwoQuery');
// }
// console.log('\n\n****************************\n\n\n********\nStage 2 query: ',util.inspect(query,{depth:5}),'\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^');
// --
// The provided "stage 1 query guts" dictionary is now a logical protostatement ("stage 2 query").
//
// Do not return anything.
return;
}; | forgeStageTwoQuery()
Normalize and validate userland query keys (called a "stage 1 query" -- see `ARCHITECTURE.md`)
i.e. these are things like `criteria` or `populates` that are passed in, either explicitly or
implicitly, to a static model method (fka "collection method") such as `.find()`.
> This DOES NOT RETURN ANYTHING! Instead, it modifies the provided "stage 1 query" in-place.
> And when this is finished, the provided "stage 1 query" will be a normalized, validated
> "stage 2 query" - aka logical protostatement.
>
> ALSO NOTE THAT THIS IS NOT ALWAYS IDEMPOTENT!! (Consider encryption.)
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
@param {Dictionary} query [A stage 1 query to destructively mutate into a stage 2 query.]
| @property {String} method
| @property {Dictionary} meta
| @property {String} using
|
|...PLUS a number of other potential properties, depending on the "method". (see below)
@param {Ref} orm
The Waterline ORM instance.
> Useful for accessing the model definitions, datastore configurations, etc.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
@throws {Error} If it encounters irrecoverable problems or unsupported usage in the provided query keys.
@property {String} name (Always "UsageError")
@property {String} code
One of:
- E_INVALID_META (universal)
- E_INVALID_CRITERIA
- E_INVALID_POPULATES
- E_INVALID_NUMERIC_ATTR_NAME
- E_INVALID_STREAM_ITERATEE (for `eachBatchFn` & `eachRecordFn`)
- E_INVALID_NEW_RECORD
- E_INVALID_NEW_RECORDS
- E_INVALID_VALUES_TO_SET
- E_INVALID_TARGET_RECORD_IDS
- E_INVALID_COLLECTION_ATTR_NAME
- E_INVALID_ASSOCIATED_IDS
- E_NOOP (relevant for various different methods, like find/count/addToCollection/etc.)
@property {String} details
The lower-level, original error message, without any sort of "Invalid yada yada. Details: ..." wrapping.
Use this property to create custom messages -- for example:
```
new Error(e.details);
```
@property {String} message
The standard `message` property of any Error-- just note that this Error's `message` is composed
from an original, lower-level error plus a template (see buildUsageError() for details.)
@property {String} stack
The standard `stack` property, like any Error. Combines name + message + stack trace.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
@throws {Error} If anything else unexpected occurs
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | forgeStageTwoQuery ( query , orm ) | javascript | balderdashy/waterline | lib/waterline/utils/query/forge-stage-two-query.js | https://github.com/balderdashy/waterline/blob/master/lib/waterline/utils/query/forge-stage-two-query.js | MIT |
module.exports = function normalizePkValueOrValues (pkValueOrPkValues, expectedPkType){
// Check usage
if (expectedPkType !== 'string' && expectedPkType !== 'number') {
throw new Error('Consistency violation: The internal normalizePkValueOrValues() utility must always be called with a valid second argument ("string" or "number"). But instead, got: '+util.inspect(expectedPkType, {depth:5})+'');
}
// Our normalized result.
var pkValues;
// If a singular string or number was provided, convert it into an array.
if (_.isString(pkValueOrPkValues) || _.isNumber(pkValueOrPkValues)) {
pkValues = [ pkValueOrPkValues ];
}
// Otherwise, we'll assume it must already be an array.
// (Don't worry, we'll validate it momentarily.)
else {
pkValues = pkValueOrPkValues;
}
//>-
// Now, handle the case where something completely invalid was provided.
if (!_.isArray(pkValues)) {
throw flaverr('E_INVALID_PK_VALUE', new Error('Expecting either an individual primary key value (a '+expectedPkType+') or a homogeneous array of primary key values ('+expectedPkType+'s). But instead got a '+(typeof pkValues)+': '+util.inspect(pkValues,{depth:5})+''));
}//-β’
// Now that we most definitely have an array, ensure that it doesn't contain anything
// strange, curious, or malevolent by looping through and calling `normalizePkValue()`
// on each item.
pkValues = _.map(pkValues, function (thisPkValue){
// Return this primary key value, which might have been coerced.
try {
return normalizePkValue(thisPkValue, expectedPkType);
} catch (e) {
switch (e.code) {
case 'E_INVALID_PK_VALUE':
throw flaverr('E_INVALID_PK_VALUE', new Error(
(
_.isArray(pkValueOrPkValues) ?
'One of the values in the provided array' :
'The provided value'
)+' is not valid primary key value. '+e.message
));
default: throw e;
}
}
});//</_.map()>
// Ensure uniqueness.
// (Strip out any duplicate pk values.)
pkValues = _.uniq(pkValues);
// Return the normalized array of pk values.
return pkValues;
}; | normalizePkValueOrValues()
Validate and normalize an array of pk values, OR a single pk value, into a consistent format.
> Internally, this uses the `normalizePkValue()` utility to check/normalize each
> primary key value before returning them. If an array is provided, and if it contains
> _more than one pk value that is exactly the same_, then the duplicates will be stripped
> out.
------------------------------------------------------------------------------------------
@param {Array|String|Number} pkValueOrPkValues
@param {String} expectedPkType [either "number" or "string"]
------------------------------------------------------------------------------------------
@returns {Array}
A valid, homogeneous array of primary key values that are guaranteed
to match the specified `expectedPkType`.
> WE should NEVER rely on this array coming back in a particular order.
> (Could change at any time.)
------------------------------------------------------------------------------------------
@throws {Error} if invalid
@property {String} code (=== "E_INVALID_PK_VALUE") | normalizePkValueOrValues ( pkValueOrPkValues , expectedPkType ) | javascript | balderdashy/waterline | lib/waterline/utils/query/private/normalize-pk-value-or-values.js | https://github.com/balderdashy/waterline/blob/master/lib/waterline/utils/query/private/normalize-pk-value-or-values.js | MIT |
module.exports = function normalizeWhereClause(whereClause, modelIdentity, orm, meta) {
// Look up the Waterline model for this query.
// > This is so that we can reference the original model definition.
var WLModel = getModel(modelIdentity, orm);
// ββββ¬ β¬ββββββββββ¬ββββ¬β ββ¦ββ¦ β¦ββ¦ββββββ¦ββββ ββββ¦ββββββββ ββ¬ββββββ¬ββββ β¬ββββββ¬ β¬
// ββββ ββββββββ βββ¬β β ββββ β β β ββ£ β ββ£ β ββ£β β¦ββ β¦βββ βββββ€ β βββ€ ββ΄βββ€ ββ¬β
// βββββββ΄ β΄ ββββ΄ββ β΄ β© β©βββ β© β© β© β© βββ β© β©β©ββββββββ β΄ β΄βββ β΄ β΄ β΄ β΄ β΄βββ β΄
// Unless the `mutateArgs` meta key is enabled, deep-clone the entire `where` clause.
if (!meta || !meta.mutateArgs) {
whereClause = _.cloneDeep(whereClause);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// FUTURE: Replace this naive implementation with something better.
// (This isn't great because it can mess up things like Buffers... which you
// shouldn't really be using in a `where` clause anyway, but still-- it makes
// it way harder to figure out what's wrong when folks find themselves in that
// situation. It could also affect any weird custom constraints for `type:'ref'`
// attrs. And if the current approach were also used in valuesToSet, newRecord,
// newRecords etc, it would matter even more.)
//
// The full list of query keys that need to be carefully checked:
// β’ criteria
// β’ populates
// β’ newRecord
// β’ newRecords
// β’ valuesToSet
// β’ targetRecordIds
// β’ associatedIds
//
// The solution will probably mean distributing this deep clone behavior out
// to the various places it's liable to come up. In reality, this will be
// more performant anyway, since we won't be unnecessarily cloning things like
// big JSON values, etc.
//
// The important thing is that this should do shallow clones of deeply-nested
// control structures like top level query key dictionaries, criteria clauses,
// predicates/constraints/modifiers in `where` clauses, etc.
//
// > And remember: Don't deep-clone functions.
// > Note that, weirdly, it's fine to deep-clone dictionaries/arrays
// > that contain nested functions (they just don't get cloned-- they're
// > the same reference). But if you try to deep-clone a function at the
// > top level, it gets messed up.
// >
// > More background on this: https://trello.com/c/VLXPvyN5
// > (Note that this behavior maintains backwards compatibility with Waterline <=0.12.)
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
}//ο¬
// ββ¦βββββββββββ¦ β¦β¦ ββ¦β
// ββββ£ β β£ β ββ£β ββ β
// ββ©βββββ β© β©ββββ©βββ©
// If no `where` clause was provided, give it a default value.
if (_.isUndefined(whereClause)) {
whereClause = {};
}//>-
// ββββββββ¦βββββββββ¦ββ¦ββ β¦β¦ β¦ββ¦ββ¦ β¦ (COMPATIBILITY)
// β β βββββ βββ ββ£ β ββ β©βββ β β ββ¦β
// βββββββ© β©β© β© β© β© β©ββββ©β©βββ© β© β©
// COMPATIBILITY
// If where is `null`, turn it into an empty dictionary.
if (_.isNull(whereClause)) {
console.warn();
console.warn(
'Deprecated: In previous versions of Waterline, the specified `where` '+'\n'+
'clause (`null`) would match ALL records in this model (`'+modelIdentity+'`). '+'\n'+
'So for compatibility, that\'s what just happened. If that is what you intended '+'\n'+
'then, in the future, please pass in `{}` instead, or simply omit the `where` '+'\n'+
'clause altogether-- both of which are more explicit and future-proof ways of '+'\n'+
'doing the same thing.\n'+
'\n'+
'> Warning: This backwards compatibility will be removed\n'+
'> in a future release of Sails/Waterline. If this usage\n'+
'> is left unchanged, then queries like this one will eventually \n'+
'> fail with an error.'
);
console.warn();
whereClause = {};
}//>-
// βββββββ¬ββββ¬βββββ¬ β¬ββββββ ββββ¦βββ¦ β¦ ββββ¬ββ β¦βββ ββββ¬ β¬ββββ¬ββββ¬ββ¬ β¬ββββββββ¬β
// ββββ βββ¬βββββββ€β ββββββ€ β βββ β©βββββ β βββ¬β ββββ ββββββ€β βββ¬β β βββ€βββ€βββ ββ
// βββββββ΄βββ΄ β΄β΄ β΄β΄βββ΄ββββββ β© β© β© ββ ββββ΄ββ β©βββ ββββ΄ β΄ββββ΄ββ β΄ β΄ β΄β΄ β΄βββββ΄β
// ββ βββββ¬β ββ¬ββ¬ β¬βββ ββ¬βββββββ β¬ ββββ¬ β¬ββββ¬ ββββββ β¦ β¦β¦ β¦ββββ¦βββββ ββ
// ββββ βββ€ β β βββ€ββ€ β β ββββ β ββ€ ββββββ€ β β βββ€ ββββ ββ£ββ£ β β¦βββ£ ββββ
// ββ β΄ β΄ β΄ β΄ β΄ β΄βββ β΄ ββββ΄ β΄βββββ ββ ββββ΄ββ ββββ ββ©ββ© β©ββββ©βββββ ββ
//
// If the `where` clause itself is an array, string, or number, then we'll
// be able to understand it as a primary key, or as an array of primary key values.
//
// ```
// where: [...]
// ```
//
// ```
// where: 'bar'
// ```
//
// ```
// where: 29
// ```
if (_.isArray(whereClause) || _.isNumber(whereClause) || _.isString(whereClause)) {
var topLvlPkValuesOrPkValueInWhere = whereClause;
// So expand that into the beginnings of a proper `where` dictionary.
// (This will be further normalized throughout the rest of this file--
// this is just enough to get us to where we're working with a dictionary.)
whereClause = {};
whereClause[WLModel.primaryKey] = topLvlPkValuesOrPkValueInWhere;
}//>-
// β¬ β¬ββββ¬βββ¬ββββ¬ β¬ ββ¬ββ¬ β¬βββββ¬β ββ¬ββ¬ β¬βββ β¦ β¦β¦ β¦ββββ¦βββββ ββββ¬ ββββ¬ β¬ββββββ
// ββββββ€ ββ¬ββββ€ ββ¬β β βββ€βββ€ β β βββ€ββ€ ββββ ββ£ββ£ β β¦βββ£ β β βββ€β ββββββ€
// ββ ββββ΄βββ΄β β΄ β΄ β΄ β΄β΄ β΄ β΄ β΄ β΄ β΄βββ ββ©ββ© β©ββββ©βββββ ββββ΄βββ΄ β΄βββββββββ
// β¬βββ βββββββ¬ β¬ βββ ββ¦ββ¦βββββ¦ββ¦ββββββββββ¦βββ¦ β¦
// ββββ ββββ ββββ βββ€ ββββ β ββ βββββ ββ£β β¦βββ¦β
// β΄βββ ββββββββ΄β β΄ β΄ ββ©ββ©βββ β© β©βββββββ© β©β©ββ β©
// At this point, the `where` clause should be a dictionary.
if (!_.isObject(whereClause) || _.isArray(whereClause) || _.isFunction(whereClause)) {
throw flaverr('E_WHERE_CLAUSE_UNUSABLE', new Error(
'If provided, `where` clause should be a dictionary. But instead, got: '+
util.inspect(whereClause, {depth:5})+''
));
}//-β’
// βββ βββββββ ββββββββ ββββββββββ ββββββββββ βββββββββββ βββββββ ββββ βββ βββ
// ββββ βββββββββββββββββββββββββββ ββββββββββββββββββββββββββββββββββββ βββ ββββ
// ββββ ββββββββββββββ βββ βββ βββββββββββββββββββββββββ βββββββββ βββ ββββ
// ββββ ββββββββββββββ βββ βββ βββββββββββββββββββββββββ βββββββββββββ ββββ
// ββββ βββ βββββββββββββββββββββββββββββββ ββββββββββββββββββββββββββ ββββββ ββββ
// βββ βββ βββββββββββ βββββββ βββββββ βββ ββββββββββββββ βββββββ βββ βββββ βββ
// ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// ββ¬ββββ ββ¬ββ¬ β¬βββ β¦βββββββββ¦ β¦β¦ββββββ¦β¦ β¦βββ ββββ¦ββββββ¦ β¦β¦
// βββ β β βββ€ββ€ β β¦βββ£ β β ββ β¦βββββββββββ£ β β β¦ββ ββ£ββββ
// ββ΄ββββ β΄ β΄ β΄βββ β©ββββββββββββ©ββββββ© ββ βββ ββββ©βββ© β©ββ©ββ©ββ
// Recursively iterate through the provided `where` clause, starting with the top level.
//
// > Note that we mutate the `where` clause IN PLACE here-- there is no return value
// > from this self-calling recursive function.
//
//
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// EDGE CASES INVOLVING "VOID" AND "UNIVERSAL"
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// In order to provide the simplest possible interface for adapter implementors
// (i.e. fully-normalized stage 2&3 queries, w/ the fewest possible numbers of
// extraneous symbols) we need to handle certain edge cases in a special way.
//
// For example, an empty array of conjuncts/disjuncts is not EXACTLY invalid, per se.
// Instead, what exactly it means depends on the circumstances:
//
// |-------------------------|-------------------|-------------------|-------------------|
// | || Parent branch => | Parent is `and` | Parent is `or` | No parent |
// | \/ This branch | (conjunct, `β©`) | (disjunct, `βͺ`) | (at top level) |
// |-------------------------|===================|===================|===================|
// | | | | |
// | `{ and: [] }` | Rip out this | Throw to indicate | Replace entire |
// | `{ ??: { nin: [] } }` | conjunct. | parent will match | `where` clause |
// | `{}` | | EVERYTHING. | with `{}`. |
// | | | | |
// | Ξ : universal | x β© Ξ = x | x βͺ Ξ = Ξ | Ξ |
// | ("matches everything") | <<identity>> | <<annihilator>> | (universal) |
// |-------------------------|-------------------|-------------------|-------------------|
// | | | | |
// | `{ or: [] }` | Throw to indicate | Rip out this | Throw E_WOULD_... |
// | `{ ??: { in: [] } }` | parent will NEVER | disjunct. | RESULT_IN_NOTHING |
// | | match anything. | | error to indicate |
// | | | | that this query |
// | | | | is a no-op. |
// | | | | |
// | Γ : void | x β© Γ = Γ | x βͺ Γ = x | Γ |
// | ("matches nothing") | <<annihilator>> | <<identity>> | (void) |
// |-------------------------|-------------------|-------------------|-------------------|
//
// > For deeper reference, here are the boolean monotone laws:
// > https://en.wikipedia.org/wiki/Boolean_algebra#Monotone_laws
// >
// > See also the "identity" and "domination" laws from fundamental set algebra:
// > (the latter of which is roughly equivalent to the "annihilator" law from boolean algebra)
// > https://en.wikipedia.org/wiki/Algebra_of_sets#Fundamentals
//
// Anyways, as it turns out, this is exactly how it should work for ANY universal/void
// branch in the `where` clause. So as you can see below, we use this strategy to handle
// various edge cases involving `and`, `or`, `nin`, `in`, and `{}`.
//
// **There are some particular bits to notice in the implementation below:**
// β’ If removing this conjunct/disjunct would cause the parent predicate operator to have
// NO items, then we recursively apply the normalization all the way back up the tree,
// until we hit the root. That's taken care of above (in the place in the code where we
// make the recursive call).
// β’ If there is no containing conjunct/disjunct (i.e. because we're at the top-level),
// then we'll either throw a E_WOULD_RESULT_IN_NOTHING error (if this is an `or`),
// or revert the criteria to `{}` so it matches everything (if this is an `and`).
// That gets taken care of below.
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
//
// With that, let's begin.
try {
// Initially invoke our self-calling, recursive function.
(function _recursiveStep(branch, recursionDepth, parent, indexInParent){
var MAX_RECURSION_DEPTH = 25;
if (recursionDepth > MAX_RECURSION_DEPTH) {
throw flaverr('E_WHERE_CLAUSE_UNUSABLE', new Error('This `where` clause seems to have a circular reference. Aborted automatically after reaching maximum recursion depth ('+MAX_RECURSION_DEPTH+').'));
}//-β’
//-β’ IWMIH, we know that `branch` is a dictionary.
// But that's about all we can trust.
//
// > In an already-fully-normalized `where` clause, we'd know that this dictionary
// > would ALWAYS be a valid conjunct/disjunct. But since we're doing the normalizing
// > here, we have to be more forgiving-- both for usability and backwards-compatibility.
// βββββ¦ββ¦βββ¦βββ β¦ββββββ¦ β¦βββ β¬ β¬β¬ββ¬ββ¬ β¬ β¦ β¦βββββ¦ββββββββ¦ββββββββ¦β β¬βββ¬ β¬βββ
// βββ β β β¦βββ ββ β β©βββ£ ββ¦ββββ ββββ β βββ€ β ββββ ββββ£ β β£ ββββββ£ ββ ββ¬ββββ€βββ
// βββ β© β©βββ©β© β© β©βββ β© βββ ββ΄ββ΄ β΄ β΄ β΄ ββββββββ©βββββ β©ββββββββ©β β΄βββ΄ β΄βββ
// Strip out any keys with undefined values.
_.each(_.keys(branch), function (key){
if (_.isUndefined(branch[key])) {
delete branch[key];
}
});
// Now count the keys.
var origBranchKeys = _.keys(branch);
// β¬ β¬ββββββββ¬ββ¬ βββ βββββ¦ββββββ¦ββ¦ β¦ β¬ β¬β¬ β¬ββββ¬βββββ ββββ¬ ββββ¬ β¬ββββββ
// βββ€βββ€βββ βββ ββ€ ββ£ ββββ ββ β ββ¦β ββββββ€ββ€ ββ¬βββ€ β β βββ€β ββββββ€
// β΄ β΄β΄ β΄βββββ΄ββ΄βββββ ββββ© β©β© β© β© ββ΄ββ΄ β΄ββββ΄βββββ ββββ΄βββ΄ β΄βββββββββ
// If there are 0 keys...
if (origBranchKeys.length === 0) {
// An empty dictionary means that this branch is universal (Ξ).
// That is, that it would match _everything_.
//
// So we'll throw a special signal indicating that to the previous recursive step.
// (or to our `catch` statement below, if we're at the top level-- i.e. an empty `where` clause.)
//
// > Note that we could just `return` instead of throwing if we're at the top level.
// > That's because it's a no-op and throwing would achieve exactly the same thing.
// > Since this is a hot code path, we might consider doing that as a future optimization.
throw flaverr('E_UNIVERSAL', new Error('`{}` would match everything'));
}//-β’
// ββββ¦ββββββββββ¦ββ¦ β¦β¦βββββ ββ β¬ββββββββββββ¬ β¬
// β β£ β β¦ββ ββ£β β β ββ β¦βββ£ ββ΄βββ¬ββββ€ββββ βββ€
// β β©βββ© β©βββ β© ββββ©βββββ ββββ΄βββ΄ β΄βββββββ΄ β΄
// Now we may need to denormalize (or "fracture") this branch.
// This is to normalize it such that it has only one key, with a
// predicate operator on the RHS.
//
// For example:
// ```
// {
// name: 'foo',
// age: 2323,
// createdAt: 23238828382,
// hobby: { contains: 'ball' }
// }
// ```
// ==>
// ```
// {
// and: [
// { name: 'foo' },
// { age: 2323 }
// { createdAt: 23238828382 },
// { hobby: { contains: 'ball' } }
// ]
// }
// ```
if (origBranchKeys.length > 1) {
// Loop over each key in the original branch and build an array of conjuncts.
var fracturedConjuncts = [];
_.each(origBranchKeys, function (origKey){
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// For now, we don't log this warning.
// It is still convenient to write criteria this way, and it's still
// a bit too soon to determine whether we should be recommending a change.
//
// > NOTE: There are two sides to this, for sure.
// > If you like this usage the way it is, please let @mikermcneil or
// > @particlebanana know.
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// // Check if this is a key for a predicate operator.
// // e.g. the `or` in this example:
// // ```
// // {
// // age: { '>': 28 },
// // or: [
// // { name: { 'startsWith': 'Jon' } },
// // { name: { 'endsWith': 'Snow' } }
// // ]
// // }
// // ```
// //
// // If so, we'll still automatically map it.
// // But also log a deprecation warning here, since it's more explicit to avoid
// // using predicates within multi-facet shorthand (i.e. could have used an additional
// // `and` predicate instead.)
// //
// if (_.contains(PREDICATE_OPERATOR_KINDS, origKey)) {
//
// // console.warn();
// // console.warn(
// // 'Deprecated: Within a `where` clause, it tends to be better (and certainly '+'\n'+
// // 'more explicit) to use an `and` predicate when you need to group together '+'\n'+
// // 'constraints side by side with additional predicates (like `or`). This was '+'\n'+
// // 'automatically normalized on your behalf for compatibility\'s sake, but please '+'\n'+
// // 'consider changing your usage in the future:'+'\n'+
// // '```'+'\n'+
// // util.inspect(branch, {depth:5})+'\n'+
// // '```'+'\n'+
// // '> Warning: This backwards compatibility may be removed\n'+
// // '> in a future release of Sails/Waterline. If this usage\n'+
// // '> is left unchanged, then queries like this one may eventually \n'+
// // '> fail with an error.'
// // );
// // console.warn();
//
// }//>-
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
var conjunct = {};
conjunct[origKey] = branch[origKey];
fracturedConjuncts.push(conjunct);
});//</ _.each() >
// Change this branch so that it now contains a predicate consisting of
// the conjuncts we built above.
//
// > Note that we change the branch in-place (on its parent) AND update
// > our `branch` variable. If the branch has no parent (i.e. top lvl),
// > then we change the actual variable we're using instead. This will
// > change the return value from this utility.
branch = {
and: fracturedConjuncts
};
if (parent) {
parent[indexInParent] = branch;
}
else {
whereClause = branch;
}
}//>- </if this branch was a multi-key dictionary>
// --β’ IWMIH, then we know there is EXACTLY one key.
var soleBranchKey = _.keys(branch)[0];
// β¬ β¬ββββββββ¬ββ¬ βββ ββββββββββββββ¦ββ¦ββββββ¦βββββ¦β
// βββ€βββ€βββ βββ ββ€ β β βββββββ β β β¦ββ ββ£ββββ β
// β΄ β΄β΄ β΄βββββ΄ββ΄βββββ ββββββββββββ β© β©βββ© β©β©βββ β©
// If this key is NOT a predicate (`and`/`or`)...
if (!_.contains(PREDICATE_OPERATOR_KINDS, soleBranchKey)) {
// ...then we know we're dealing with a constraint.
// ββββ¦ββββββββββ¦ββ¦ β¦β¦βββββ ββββββββ¬βββββ¬ βββββ β¬ ββββββββββββββ¬ββ¬ββββββ¬βββββ¬β
// β β£ β β¦ββ ββ£β β β ββ β¦βββ£ β β ββββββββ ββ€ ββ΄β¬β β β βββββββ β ββ¬ββββ€ββββ β
// β β©βββ© β©βββ β© ββββ©βββββ βββββββ΄ β΄β΄ β΄ββββββ΄ ββ ββββββββββββ β΄ β΄βββ΄ β΄β΄βββ β΄
// ββ β¬βββ β¬ββ¬β β¬βββ ββ¬ββ¬ β¬β¬ ββ¬ββ¬ β¬ββββββ¬ β¬ ββ
// β βββ€ β β ββββ ββββ ββ β ββββββ΄βββ€ ββ¬β β
// ββ β΄β β΄ β΄ β΄βββ β΄ β΄ββββ΄βββ΄ β΄ β΄ β΄βββ β΄ ββ
// Before proceeding, we may need to fracture the RHS of this key.
// (if it is a complex constraint w/ multiple keys-- like a "range" constraint)
//
// > This is to normalize it such that every complex constraint ONLY EVER has one key.
// > In order to do this, we may need to reach up to our highest ancestral predicate.
var isComplexConstraint = _.isObject(branch[soleBranchKey]) && !_.isArray(branch[soleBranchKey]) && !_.isFunction(branch[soleBranchKey]);
// If this complex constraint has multiple keys...
if (isComplexConstraint && _.keys(branch[soleBranchKey]).length > 1){
// Then fracture it before proceeding.
var complexConstraint = branch[soleBranchKey];
// Loop over each modifier in the complex constraint and build an array of conjuncts.
var fracturedModifierConjuncts = [];
_.each(complexConstraint, function (modifier, modifierKind){
var conjunct = {};
conjunct[soleBranchKey] = {};
conjunct[soleBranchKey][modifierKind] = modifier;
fracturedModifierConjuncts.push(conjunct);
});//</ _.each() key in the complex constraint>
// Change this branch so that it now contains a predicate consisting of
// the new conjuncts we just built for these modifiers.
//
// > Note that we change the branch in-place (on its parent) AND update
// > our `branch` variable. If the branch has no parent (i.e. top lvl),
// > then we change the actual variable we're using instead. This will
// > change the return value from this utility.
//
branch = {
and: fracturedModifierConjuncts
};
if (parent) {
parent[indexInParent] = branch;
}
else {
whereClause = branch;
}
// > Also note that we update the sole branch key variable.
soleBranchKey = _.keys(branch)[0];
// Now, since we know our branch is a predicate, we'll continue on.
// (see predicate handling code below)
}
// Otherwise, we can go ahead and normalize the constraint, then bail.
else {
// βββββββ¦ββββ¦βββββ¦ β¦ββββββ ββββββββββββββ¦ββ¦ββββββ¦βββββ¦β
// ββββ ββ β¦βββββ ββ£β ββββββ£ β β βββββββ β β β¦ββ ββ£ββββ β
// βββββββ©βββ© β©β© β©β©βββ©ββββββ ββββββββββββ β© β©βββ© β©β©βββ β©
// Normalize the constraint itself.
// (note that this checks the RHS, but it also checks the key aka constraint target -- i.e. the attr name)
try {
branch[soleBranchKey] = normalizeConstraint(branch[soleBranchKey], soleBranchKey, modelIdentity, orm, meta);
} catch (e) {
switch (e.code) {
case 'E_CONSTRAINT_NOT_USABLE':
throw flaverr('E_WHERE_CLAUSE_UNUSABLE', new Error(
'Could not filter by `'+soleBranchKey+'`: '+ e.message
));
case 'E_CONSTRAINT_WOULD_MATCH_EVERYTHING':
throw flaverr('E_UNIVERSAL', e);
case 'E_CONSTRAINT_WOULD_MATCH_NOTHING':
throw flaverr('E_VOID', e);
default:
throw e;
}
}//</catch>
// Then bail early.
return;
}//</ else (i.e. case where the constraint was good to go w/o needing any fracturing)>
}//</ if the sole branch key is NOT a predicate >
// >-β’ IWMIH, then we know that this branch's sole key is a predicate (`and`/`or`).
// (If it isn't, then our code above has a bug.)
assert(soleBranchKey === 'and' || soleBranchKey === 'or', 'Should never have made it here if the sole branch key is not `and` or `or`!');
// βββ βββ ββββββ ββββ ββββββββββ βββ ββββββββ
// βββ ββββββββββββββββ ββββββββββββββ ββββββββ
// ββββββββββββββββββββββ ββββββ ββββββ ββββββ
// βββββββββββββββββββββββββββββ ββββββ ββββββ
// βββ ββββββ ββββββ ββββββββββββββββββββββββββββββ
// βββ ββββββ ββββββ ββββββββββββ ββββββββββββββββ
//
// βββββββ βββββββ βββββββββββββββ βββ βββββββ ββββββ βββββββββββββββββ
// ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// ββββββββββββββββββββββ βββ βββββββββ ββββββββ βββ ββββββ
// βββββββ ββββββββββββββ βββ βββββββββ ββββββββ βββ ββββββ
// βββ βββ βββββββββββββββββββββββββββββββββ βββ βββ ββββββββ
// βββ βββ ββββββββββββββββββ βββ ββββββββββ βββ βββ ββββββββ
//
//
// ``` ```
// { {
// or: [...] and: [...]
// } }
// ``` ```
var conjunctsOrDisjuncts = branch[soleBranchKey];
// RHS of a predicate must always be an array.
if (!_.isArray(conjunctsOrDisjuncts)) {
throw flaverr('E_WHERE_CLAUSE_UNUSABLE', new Error('Expected an array at `'+soleBranchKey+'`, but instead got: '+util.inspect(conjunctsOrDisjuncts,{depth: 5})+'\n(`and`/`or` should always be provided with an array on the right-hand side.)'));
}//-β’
// Now loop over each conjunct or disjunct within this AND/OR predicate.
// Along the way, track any that will need to be trimmed out.
var indexesToRemove = [];
_.each(conjunctsOrDisjuncts, function (conjunctOrDisjunct, i){
// If conjunct/disjunct is `undefined`, trim it out and bail to the next one.
if (conjunctsOrDisjuncts[i] === undefined) {
indexesToRemove.push(i);
return;
}//β’
// Check that each conjunct/disjunct is a plain dictionary, no funny business.
if (!_.isObject(conjunctOrDisjunct) || _.isArray(conjunctOrDisjunct) || _.isFunction(conjunctOrDisjunct)) {
throw flaverr('E_WHERE_CLAUSE_UNUSABLE', new Error('Expected each item within an `and`/`or` predicate\'s array to be a dictionary (plain JavaScript object). But instead, got: `'+util.inspect(conjunctOrDisjunct,{depth: 5})+'`'));
}
// Recursive call
try {
_recursiveStep(conjunctOrDisjunct, recursionDepth+1, conjunctsOrDisjuncts, i);
} catch (e) {
switch (e.code) {
// If this conjunct or disjunct is universal (Ξ)...
case 'E_UNIVERSAL':
// If this item is a disjunct, then annihilate our branch by throwing this error
// on up for the previous recursive step to take care of.
// ```
// x βͺ Ξ = Ξ
// ```
if (soleBranchKey === 'or') {
throw e;
}//-β’
// Otherwise, rip it out of the array.
// ```
// x β© Ξ = x
// ```
indexesToRemove.push(i);
break;
// If this conjunct or disjunct is void (Γ)...
case 'E_VOID':
// If this item is a conjunct, then annihilate our branch by throwing this error
// on up for the previous recursive step to take care of.
// ```
// x β© Γ = Γ
// ```
if (soleBranchKey === 'and') {
throw e;
}//-β’
// Otherwise, rip it out of the array.
// ```
// x βͺ Γ = x
// ```
indexesToRemove.push(i);
break;
default:
throw e;
}
}//</catch>
});//</each conjunct or disjunct inside of predicate operator>
// If any conjuncts/disjuncts were scheduled for removal above,
// go ahead and take care of that now.
if (indexesToRemove.length > 0) {
for (var i = 0; i < indexesToRemove.length; i++) {
var indexToRemove = indexesToRemove[i] - i;
conjunctsOrDisjuncts.splice(indexToRemove, 1);
}//</for>
}//>-
// If the array is NOT EMPTY, then this is the normal case, and we can go ahead and bail.
if (conjunctsOrDisjuncts.length > 0) {
return;
}//-β’
// Otherwise, the predicate array is empty (e.g. `{ or: [] }` / `{ and: [] }`)
//
// For our purposes here, we just need to worry about signaling either "universal" or "void".
// (see table above for more information).
// If this branch is universal (i.e. matches everything / `{and: []}`)
// ```
// Ξ
// ```
if (soleBranchKey === 'and') {
throw flaverr('E_UNIVERSAL', new Error('`{and: []}` with an empty array would match everything.'));
}
// Otherwise, this branch is void (i.e. matches nothing / `{or: []}`)
// ```
// Γ
// ```
else {
throw flaverr('E_VOID', new Error('`{or: []}` with an empty array would match nothing.'));
}
})(whereClause, 0, undefined, undefined);
//</self-invoking recursive function that kicked off our recursion with the `where` clause>
} catch (e) {
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// Note:
// This `catch` block exists to handle top-level E_UNIVERSAL and E_VOID exceptions.
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
switch (e.code) {
// If an E_UNIVERSAL exception made it all the way up here, then we know that
// this `where` clause should match EVERYTHING. So we set it to `{}`.
case 'E_UNIVERSAL':
whereClause = {};
break;
// If an E_VOID exception made it all the way up here, then we know that
// this `where` clause would match NOTHING. So we throw `E_WOULD_RESULT_IN_NOTHING`
// to pass that message along.
case 'E_VOID':
throw flaverr('E_WOULD_RESULT_IN_NOTHING', new Error('Would match nothing'));
default:
throw e;
}
}//</catch>
// ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
//
// βββ βββ βββββββ ββββββββ ββββββββββ ββββββββββ βββββββββββ βββββββ ββββ βββ βββ
// ββββ ββββ βββββββββββββββββββββββββββ ββββββββββββββββββββββββββββββββββββ βββ ββββ
// ββββ ββββ ββββββββββββββ βββ βββ βββββββββββββββββββββββββ βββββββββ βββ ββββ
// ββββ ββββ ββββββββββββββ βββ βββ βββββββββββββββββββββββββ βββββββββββββ ββββ
// ββββββββ βββ βββββββββββββββββββββββββββββββ ββββββββββββββββββββββββββ ββββββ ββββ
// ββββββ βββ βββββββββββ βββββββ βββββββ βββ ββββββββββββββ βββββββ βββ βββββ βββ
//
// Return the modified `where` clause.
return whereClause;
}; | normalizeWhereClause()
Validate and normalize the `where` clause, rejecting any obviously-unsupported
usage, and tolerating certain backwards-compatible things.
------------------------------------------------------------------------------------------
@param {Ref} whereClause
A hypothetically well-formed `where` clause from a Waterline criteria.
(i.e. in a "stage 1 query")
> WARNING:
> IN SOME CASES (BUT NOT ALL!), THE PROVIDED VALUE WILL
> UNDERGO DESTRUCTIVE, IN-PLACE CHANGES JUST BY PASSING IT
> IN TO THIS UTILITY.
@param {String} modelIdentity
The identity of the model this `where` clause is referring to (e.g. "pet" or "user")
> Useful for looking up the Waterline model and accessing its attribute definitions.
@param {Ref} orm
The Waterline ORM instance.
> Useful for accessing the model definitions.
@param {Dictionary?} meta
The contents of the `meta` query key, if one was provided.
> Useful for propagating query options to low-level utilities like this one.
------------------------------------------------------------------------------------------
@returns {Dictionary}
The successfully-normalized `where` clause, ready for use in a stage 2 query.
> Note that the originally provided `where` clause MAY ALSO HAVE BEEN
> MUTATED IN PLACE!
------------------------------------------------------------------------------------------
@throws {Error} If it encounters irrecoverable problems or unsupported usage in
the provided `where` clause.
@property {String} code
- E_WHERE_CLAUSE_UNUSABLE
@throws {Error} If the `where` clause indicates that it should never match anything.
@property {String} code
- E_WOULD_RESULT_IN_NOTHING
@throws {Error} If anything else unexpected occurs. | normalizeWhereClause ( whereClause , modelIdentity , orm , meta ) | javascript | balderdashy/waterline | lib/waterline/utils/query/private/normalize-where-clause.js | https://github.com/balderdashy/waterline/blob/master/lib/waterline/utils/query/private/normalize-where-clause.js | MIT |
module.exports = function normalizeComparisonValue (value, attrName, modelIdentity, orm){
if (!_.isString(attrName)) { throw new Error('Consistency violation: This internal utility must always be called with a valid second argument (the attribute name). But instead, got: '+util.inspect(attrName, {depth:5})+''); }
if (!_.isString(modelIdentity)) { throw new Error('Consistency violation: This internal utility must always be called with a valid third argument (the model identity). But instead, got: '+util.inspect(modelIdentity, {depth:5})+''); }
if (!_.isObject(orm)) { throw new Error('Consistency violation: This internal utility must always be called with a valid fourth argument (the orm instance). But instead, got: '+util.inspect(orm, {depth:5})+''); }
if (_.isUndefined(value)) {
throw flaverr('E_VALUE_NOT_USABLE', new Error(
'Cannot compare vs. `undefined`!\n'+
'--\n'+
'Usually, this just means there is some kind of logic error in the code that builds this `where` clause. '+
'On the other hand, if you purposely built this query with `undefined`, bear in mind that you\'ll '+
'need to be more explicit: When comparing "emptiness" in a `where` clause, specify null, empty string (\'\'), '+
'0, or false.\n'+
'--'
));
}//-β’
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// FUTURE: Maybe make the RTTC validation in this file strict (instead of also performing light coercion).
// On one hand, it's better to show an error than have experience of fetching stuff from the database
// be inconsistent with what you can search for. But on the other hand, it's nice to have Waterline
// automatically coerce the string "4" into the number 4 (and vice versa) within an eq constraint.
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// Look up the primary Waterline model and attribute.
var WLModel = getModel(modelIdentity, orm);
// Try to look up the attribute definition.
// (`attrDef` will either be a valid attribute or `undefined`)
var attrDef = WLModel.attributes[attrName];
// If this attribute exists, ensure that it is not a plural association.
if (attrDef) {
assert(!attrDef.collection, 'Should not call this internal utility on a plural association (i.e. `collection` attribute).');
}
// ββββ¦ β¦β¦ β¦
// ββββ ββ β
// βββββββ©βββ©ββ
if (_.isNull(value)) {
// `null` is always allowed as a constraint.
}//β‘
// βββββββ¬ββ β¦ β¦ββββ¦ββββββββββββββββββ¦ββββββββ¦β βββββ¦βββ¦ββ¦βββ¦ββ β¦ β¦ββ¦ββββ
// ββ€ β βββ¬β β βββββ β¦βββ£ β β ββ β¦βββββββββ£ ββ β ββ£ β β β β¦βββ β©ββ β β ββ£
// β ββββ΄ββ βββββββ©ββββββββββββββββββ©ββββββββ©β β© β© β© β© β©βββ©ββββββ β© βββ
// If unrecognized, normalize the value as if there was a matching attribute w/ `type: 'json'`.
// > This is because we don't want to leave potentially-circular/crazy constraints
// > in the criteria unless they correspond w/ `type: 'ref'` attributes.
else if (!attrDef) {
try {
value = rttc.validate('json', value);
} catch (e) {
switch (e.code) {
case 'E_INVALID':
throw flaverr('E_VALUE_NOT_USABLE', new Error(
'There is no such attribute declared by this model... which is fine, '+
'because the model supports unrecognized attributes (`schema: false`). '+
'However, all comparison values in constraints for unrecognized attributes '+
'must be JSON-compatible, and this one is not. '+e.message
));
default:
throw e;
}
}//>-β’
}//β‘
// βββββββ¬ββ ββββ¦βββββββ¦ β¦β¦ ββββ¦ββ ββββββββββββββββ¦βββββ¦ββ¦ββββββ
// ββ€ β βββ¬β ββββββββ β¦β ββ β ββ£β β¦β β ββ£βββββββ ββ ββ ββ£ β ββ ββββ
// β ββββ΄ββ ββββ©ββββββββββ©βββ© β©β©ββ β© β©βββββββββββββ©β© β© β© β©ββββββ
else if (attrDef.model) {
// Ensure that this is a valid primary key value for the associated model.
var associatedPkType = getAttribute(getModel(attrDef.model, orm).primaryKey, attrDef.model, orm).type;
try {
// Note: While searching for an fk of 3.3 would be weird, we don't
// use the `normalizePKValue()` utility here. Instead we simply
// use rttc.validate().
//
// > (This is just to allow for edge cases where the schema changed
// > and some records in the db were not migrated properly.)
value = rttc.validate(associatedPkType, value);
} catch (e) {
switch (e.code) {
case 'E_INVALID':
throw flaverr('E_VALUE_NOT_USABLE', new Error(
'The corresponding attribute (`'+attrName+'`) is a singular ("model") association, '+
'but the provided value does not match the declared type of the primary key attribute '+
'for the associated model (`'+attrDef.model+'`). '+
e.message
));
default:
throw e;
}
}//</catch>
}//β‘
// βββββββ¬ββ ββββ¦βββ¦ββ¦βββββ¦βββ¦ β¦ β¦ββββββ¦ β¦ βββββ¦βββ¦ββ¦βββ¦ββ β¦ β¦ββ¦ββββ
// ββ€ β βββ¬β β βββ β¦ββββββ ββ£β β¦βββ¦β β β©βββ£ ββ¦β β ββ£ β β β β¦βββ β©ββ β β ββ£
// β ββββ΄ββ β© β©βββ©β© β©β© β©β©ββ β© β© β©βββ β© β© β© β© β© β©βββ©ββββββ β© βββ
// ββββ¬ββ ββ¦ββ¦ββββββββββ¦ β¦ βββββββββββββ¦ β¦βββ βββββ¦βββ¦ββ¦βββ¦ββ β¦ β¦ββ¦ββββ
// β βββ¬β ββββββββ ββ£ β β β ββ£βββββ£ β ββ ββββ β ββ£ β β β β¦βββ β©ββ β β ββ£
// ββββ΄ββ β© β©β©ββββββββββ©βββ©βββ© β©βββββββββββββββ β© β© β© β© β©βββ©ββββββ β© βββ
//
// Note that even though primary key values have additional rules on top of basic
// RTTC type validation, we still treat them the same for our purposes here.
// > (That's because we want you to be able to search for things in the database
// > that you might not necessarily be possible to create/update in Waterline.)
else {
if (!_.isString(attrDef.type) || attrDef.type === '') {
throw new Error('Consistency violation: There is no way this attribute (`'+attrName+'`) should have been allowed to be registered with neither a `type`, `model`, nor `collection`! Here is the attr def: '+util.inspect(attrDef, {depth:5})+'');
}
try {
value = rttc.validate(attrDef.type, value);
} catch (e) {
switch (e.code) {
case 'E_INVALID':
throw flaverr('E_VALUE_NOT_USABLE', new Error(
'Does not match the declared data type of the corresponding attribute. '+e.message
));
default:
throw e;
}
}//</catch>
}//>-
// Return the normalized value.
return value;
}; | normalizeComparisonValue()
Validate and normalize the provided value vs. a particular attribute,
taking `type` into account, as well as whether the referenced attribute is
a singular association or a primary key. And if no such attribute exists,
then this at least ensure the value is JSON-compatible.
------------------------------------------------------------------------------------------
This utility is for the purposes of `normalizeConstraint()` (e.g. within `where` clause)
so does not care about required/defaultsTo/etc. It is used for eq constraints, `in` and
`nin` modifiers, as well as comparison modifiers like `!=`, `<`, `>`, `<=`, and `>=`.
> β’ It always tolerates `null` (& does not care about required/defaultsTo/etc.)
> β’ Collection attrs are never allowed.
> (Attempting to use one will cause this to throw a consistency violation error
> so i.e. it should be checked beforehand.)
------------------------------------------------------------------------------------------
@param {Ref} value
The eq constraint or modifier to normalize.
@param {String} attrName
The name of the attribute to check against.
@param {String} modelIdentity
The identity of the model the attribute belongs to (e.g. "pet" or "user")
@param {Ref} orm
The Waterline ORM instance.
------------------------------------------------------------------------------------------
@returns {Ref}
The provided value, now normalized and guaranteed to match the specified attribute.
This might be the same original reference, or it might not.
------------------------------------------------------------------------------------------
@throws {Error} if invalid and cannot be coerced
@property {String} code (=== "E_VALUE_NOT_USABLE")
------------------------------------------------------------------------------------------
@throws {Error} If anything unexpected happens, e.g. bad usage, or a failed assertion.
------------------------------------------------------------------------------------------ | normalizeComparisonValue ( value , attrName , modelIdentity , orm ) | javascript | balderdashy/waterline | lib/waterline/utils/query/private/normalize-comparison-value.js | https://github.com/balderdashy/waterline/blob/master/lib/waterline/utils/query/private/normalize-comparison-value.js | MIT |
module.exports = function normalizeConstraint (constraintRhs, constraintTarget, modelIdentity, orm, meta){
if (_.isUndefined(constraintRhs)) {
throw new Error('Consistency violation: The internal normalizeConstraint() utility must always be called with a first argument (the RHS of the constraint to normalize). But instead, got: '+util.inspect(constraintRhs, {depth:5})+'');
}
if (!_.isString(constraintTarget)) {
throw new Error('Consistency violation: The internal normalizeConstraint() utility must always be called with a valid second argument (a string). But instead, got: '+util.inspect(constraintTarget, {depth:5})+'');
}
if (!_.isString(modelIdentity)) {
throw new Error('Consistency violation: The internal normalizeConstraint() utility must always be called with a valid third argument (a string). But instead, got: '+util.inspect(modelIdentity, {depth:5})+'');
}
// Look up the Waterline model for this query.
var WLModel = getModel(modelIdentity, orm);
// Before we look at the constraint's RHS, we'll check the key (the constraint target)
// to be sure it is valid for this model.
// (in the process, we look up the expected type for the corresponding attribute,
// so that we have something to validate against)
var attrName;
var isDeepTarget;
var deepTargetHops;
if (_.isString(constraintTarget)){
deepTargetHops = constraintTarget.split(/\./);
isDeepTarget = (deepTargetHops.length > 1);
}
if (isDeepTarget) {
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// FUTURE: Replace this opt-in experimental support with official support for
// deep targets for constraints: i.e. dot notation for lookups within JSON embeds.
// This will require additional tests + docs, as well as a clear way of indicating
// whether a particular adapter supports this feature so that proper error messages
// can be displayed otherwise.
// (See https://github.com/balderdashy/waterline/pull/1519)
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
if (!meta || !meta.enableExperimentalDeepTargets) {
throw flaverr('E_CONSTRAINT_NOT_USABLE', new Error(
'Cannot use dot notation in a constraint target without enabling experimental support '+
'for "deep targets". Please try again with `.meta({enableExperimentalDeepTargets:true})`.'
));
}//β’
attrName = deepTargetHops[0];
}
else {
attrName = constraintTarget;
}
// Try to look up the definition of the attribute that this constraint is referring to.
var attrDef;
try {
attrDef = getAttribute(attrName, modelIdentity, orm);
} catch (e){
switch (e.code) {
case 'E_ATTR_NOT_REGISTERED':
// If no matching attr def exists, then just leave `attrDef` undefined
// and continue... for now anyway.
break;
default: throw e;
}
}//</catch>
// If model is `schema: true`...
if (WLModel.hasSchema === true) {
// Make sure this matched a recognized attribute name.
if (!attrDef) {
throw flaverr('E_CONSTRAINT_NOT_USABLE', new Error(
'`'+attrName+'` is not a recognized attribute for this '+
'model (`'+modelIdentity+'`). And since the model declares `schema: true`, '+
'this is not allowed.'
));
}//-β’
}
// Else if model is `schema: false`...
else if (WLModel.hasSchema === false) {
// Make sure this is at least a valid name for a Waterline attribute.
if (!isValidAttributeName(attrName)) {
throw flaverr('E_CONSTRAINT_NOT_USABLE', new Error(
'`'+attrName+'` is not a valid name for an attribute in Waterline. '+
'Even though this model (`'+modelIdentity+'`) declares `schema: false`, '+
'this is not allowed.'
));
}//-β’
} else { throw new Error('Consistency violation: Every instantiated Waterline model should always have a `hasSchema` property as either `true` or `false` (should have been derived from the `schema` model setting when Waterline was being initialized). But somehow, this model (`'+modelIdentity+'`) ended up with `hasSchema: '+util.inspect(WLModel.hasSchema, {depth:5})+'`'); }
// If this attribute is a plural (`collection`) association, then reject it out of hand.
// (filtering by plural associations is not supported, regardless of what constraint you're using.)
if (attrDef && attrDef.collection) {
throw flaverr('E_CONSTRAINT_NOT_USABLE', new Error(
'Cannot filter by `'+attrName+'` because it is a plural association (which wouldn\'t make sense).'
));
}//-β’
if (isDeepTarget) {
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// FUTURE: See the other note above. This is still experimental.
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
if (isDeepTarget && attrDef && attrDef.type !== 'json' && attrDef.type !== 'ref') {
throw flaverr('E_CONSTRAINT_NOT_USABLE', new Error(
'Cannot use dot notation in a constraint for the `'+attrName+'` attribute. '+
(attrDef.model||attrDef.collection?
'Dot notation is not currently supported for "whose" lookups across associations '+
'(see https://github.com/balderdashy/waterline/pull/1519 for details).'
:
'Dot notation is only supported for fields which might potentially contain embedded JSON.'
)
));
}//β’
}//ο¬
// If this attribute is a singular (`model`) association, then look up
// the reciprocal model def, as well as its primary attribute def.
var Reciprocal;
var reciprocalPKA;
if (attrDef && attrDef.model) {
Reciprocal = getModel(attrDef.model, orm);
reciprocalPKA = getAttribute(Reciprocal.primaryKey, attrDef.model, orm);
}//>-
// βββββββββββ βββ βββββββ βββββββ ββββββββββββ βββ ββββββ ββββ ββββββββββ
// βββββββββββ ββββββββββββββββββββββββββββββββ ββββββββββββββββ βββββββββββ
// βββββββββββββββββββ βββββββββββ βββ ββββββββββββββββββββββ ββββββ βββ
// βββββββββββββββββββ βββββββββββ βββ βββββββββββββββββββββββββββββ βββ
// βββββββββββ βββββββββββββββ βββ βββ βββ ββββββ ββββββ ββββββββββββββ
// βββββββββββ βββ βββββββ βββ βββ βββ βββ ββββββ ββββββ ββββββββββββ
//
// ββββββββ βββββββ βββββββ βββββββ βββ
// βββββββββββββββββββββββββ ββββββββ βββ
// ββββββ βββ βββββββββββ βββββββββββββββ βββββββββ
// ββββββ βββ βββββββββββ βββββββββββββββββββββββββ
// βββ ββββββββββββ βββ ββββββ ββββββ
// βββ βββββββ βββ βββ ββββββ βββββ
//
// βββββββ βββββββ ββββ βββββββββββββββββββββββββββ ββββββ βββββββ ββββββββββββ
// ββββββββββββββββββββββ ββββββββββββββββββββββββββββββββββββββββββββ ββββββββββββ
// βββ βββ βββββββββ βββββββββββ βββ βββββββββββββββββββββββββ βββ βββ
// βββ βββ βββββββββββββββββββββ βββ βββββββββββββββββββββββββββββ βββ
// ββββββββββββββββββββ ββββββββββββββ βββ βββ ββββββ βββββββββ ββββββ βββ
// βββββββ βββββββ βββ βββββββββββββ βββ βββ ββββββ βββββββββ βββββ βββ
//
// If this is "IN" shorthand (an array)...
if (_.isArray(constraintRhs)) {
// Normalize this into a complex constraint with an `in` modifier.
var inConstraintShorthandArray = constraintRhs;
constraintRhs = { in: inConstraintShorthandArray };
}//>-
// βββββββ βββββββ ββββ βββββββββββ βββ βββββββββββ βββ
// ββββββββββββββββββββββ ββββββββββββββββ ββββββββββββββββ
// βββ βββ βββββββββββββββββββββββββ ββββββ ββββββ
// βββ βββ βββββββββββββββββββββ βββ ββββββ ββββββ
// ββββββββββββββββββββ βββ ββββββ ββββββββββββββββββββ βββ
// βββββββ βββββββ βββ ββββββ βββββββββββββββββββ βββ
//
// βββββββ βββββββ ββββ βββββββββββββββββββββββββββ ββββββ βββββββ ββββββββββββ
// ββββββββββββββββββββββ ββββββββββββββββββββββββββββββββββββββββββββ ββββββββββββ
// βββ βββ βββββββββ βββββββββββ βββ βββββββββββββββββββββββββ βββ βββ
// βββ βββ βββββββββββββββββββββ βββ βββββββββββββββββββββββββββββ βββ
// ββββββββββββββββββββ ββββββββββββββ βββ βββ ββββββ βββββββββ ββββββ βββ
// βββββββ βββββββ βββ βββββββββββββ βββ βββ ββββββ βββββββββ βββββ βββ
//
// If this is a complex constraint (a dictionary)...
if (_.isObject(constraintRhs) && !_.isFunction(constraintRhs) && !_.isArray(constraintRhs)) {
// β¬ β¬ββββββββ¬ββ¬ βββ βββββ¬ββββββ¬ββ¬ β¬ ββ¬ββ¬βββββ¬ββ¬ββββββββββ¬βββ¬ β¬
// βββ€βββ€βββ βββ ββ€ ββ€ ββββββ β ββ¬β ββββ β ββ βββββββ€ββ¬βββ¬β
// β΄ β΄β΄ β΄βββββ΄ββ΄βββββ ββββ΄ β΄β΄ β΄ β΄ ββ΄ββ΄βββ β΄ β΄βββββββ΄ β΄β΄ββ β΄
// An empty dictionary (or a dictionary w/ an unrecognized modifier key)
// is never allowed as a complex constraint.
var numKeys = _.keys(constraintRhs).length;
if (numKeys === 0) {
throw flaverr('E_CONSTRAINT_NOT_USABLE', new Error(
'If specifying a complex constraint, there should always be at least one modifier. But the constraint provided as `'+constraintTarget+'` has no keys-- it is just `{}`, an empty dictionary (aka plain JavaScript object).'
));
}//-β’
if (numKeys !== 1) {
throw new Error('Consistency violation: If provided as a dictionary, the constraint RHS passed in to the internal normalizeConstraint() utility must always have exactly one key. (Should have been normalized already.) But instead, got: '+util.inspect(constraintRhs, {depth:5})+'');
}
// Determine what kind of modifier this constraint has, and get a reference to the modifier's RHS.
// > Note that we HAVE to set `constraint[modifierKind]` any time we make a by-value change.
// > We take care of this at the bottom of this section.
var modifierKind = _.keys(constraintRhs)[0];
var modifier = constraintRhs[modifierKind];
// β¬ β¬ββββββββ¬ββ¬ βββ ββββ¬ β¬ββββββββββββ
// βββ€βββ€βββ βββ ββ€ βββ€β ββββ€βββββ€ βββ
// β΄ β΄β΄ β΄βββββ΄ββ΄βββββ β΄ β΄β΄βββ΄β΄ β΄βββββββββ
// Handle simple modifier aliases, for compatibility.
if (!MODIFIER_KINDS[modifierKind] && MODIFIER_ALIASES[modifierKind]) {
var originalModifierKind = modifierKind;
delete constraintRhs[originalModifierKind];
modifierKind = MODIFIER_ALIASES[originalModifierKind];
constraintRhs[modifierKind] = modifier;
console.warn();
console.warn(
'Deprecated: The `where` clause of this query contains '+'\n'+
'a `'+originalModifierKind+'` modifier (for `'+constraintTarget+'`). But as of Sails v1.0,'+'\n'+
'this modifier is deprecated. (Please use `'+modifierKind+'` instead.)\n'+
'This was automatically normalized on your behalf for the'+'\n'+
'sake of compatibility, but please change this ASAP.'+'\n'+
'> Warning: This backwards compatibility may be removed\n'+
'> in a future release of Sails/Waterline. If this usage\n'+
'> is left unchanged, then queries like this one may eventually \n'+
'> fail with an error.'
);
console.warn();
}//>-
// Understand the "!=" modifier as "nin" if it was provided as an array.
if (modifierKind === '!=' && _.isArray(modifier)) {
delete constraintRhs[modifierKind];
modifierKind = 'nin';
constraintRhs[modifierKind] = modifier;
}//>-
//
// --β’ At this point, we're doing doing uninformed transformations of the constraint.
// i.e. while, in some cases, the code below changes the `modifierKind`, the
// following if/else statements are effectively a switch statement. So in other
// words, any transformations going on are specific to a particular `modifierKind`.
//
// ββββββββ¦β ββββββ β¦ β¦ββββ¦
// ββββ β β ββ£ βββ¬ββ ββ ββ£β
// ββββββ β© βββββββββββ© β©β©ββ
if (modifierKind === '!=') {
// Ensure this modifier is valid, normalizing it if possible.
try {
modifier = normalizeComparisonValue(modifier, constraintTarget, modelIdentity, orm);
} catch (e) {
switch (e.code) {
case 'E_VALUE_NOT_USABLE': throw flaverr('E_CONSTRAINT_NOT_USABLE', new Error('Invalid `!=` ("not equal") modifier. '+e.message));
default: throw e;
}
}//>-β’
}//β‘
// β¦βββ
// ββββ
// β©βββ
else if (modifierKind === 'in') {
if (!_.isArray(modifier)) {
throw flaverr('E_CONSTRAINT_NOT_USABLE', new Error(
'An `in` modifier should always be provided as an array. '+
'But instead, for the `in` modifier at `'+constraintTarget+'`, got: '+
util.inspect(modifier, {depth:5})+''
));
}//-β’
// Strip undefined items.
_.remove(modifier, function (item) { return item === undefined; });
// If this modifier is now an empty array, then bail with a special exception.
if (modifier.length === 0) {
throw flaverr('E_CONSTRAINT_WOULD_MATCH_NOTHING', new Error(
'Since this `in` modifier is an empty array, it would match nothing.'
));
}//-β’
// Ensure that each item in the array matches the expected data type for the attribute.
modifier = _.map(modifier, function (item){
// First, ensure this is not `null`.
// (We never allow items in the array to be `null`.)
if (_.isNull(item)){
throw flaverr('E_CONSTRAINT_NOT_USABLE', new Error(
'Got unsupported value (`null`) in an `in` modifier array. Please use `or: [{ '+constraintTarget+': null }, ...]` instead.'
));
}//-β’
// Ensure this item is valid, normalizing it if possible.
try {
item = normalizeComparisonValue(item, constraintTarget, modelIdentity, orm);
} catch (e) {
switch (e.code) {
case 'E_VALUE_NOT_USABLE': throw flaverr('E_CONSTRAINT_NOT_USABLE', new Error('Invalid item within `in` modifier array. '+e.message));
default: throw e;
}
}//>-β’
return item;
});//</_.map>
}//β‘
// ββββ¦βββ
// βββββββ
// ββββ©βββ
else if (modifierKind === 'nin') {
if (!_.isArray(modifier)) {
throw flaverr('E_CONSTRAINT_NOT_USABLE', new Error(
'A `nin` ("not in") modifier should always be provided as an array. '+
'But instead, for the `nin` modifier at `'+constraintTarget+'`, got: '+
util.inspect(modifier, {depth:5})+''
));
}//-β’
// Strip undefined items.
_.remove(modifier, function (item) { return item === undefined; });
// If this modifier is now an empty array, then bail with a special exception.
if (modifier.length === 0) {
throw flaverr('E_CONSTRAINT_WOULD_MATCH_EVERYTHING', new Error(
'Since this `nin` ("not in") modifier is an empty array, it would match ANYTHING.'
));
}//-β’
// Ensure that each item in the array matches the expected data type for the attribute.
modifier = _.map(modifier, function (item){
// First, ensure this is not `null`.
// (We never allow items in the array to be `null`.)
if (_.isNull(item)){
throw flaverr('E_CONSTRAINT_NOT_USABLE', new Error(
'Got unsupported value (`null`) in a `nin` ("not in") modifier array. Please use `or: [{ '+constraintTarget+': { \'!=\': null }, ...]` instead.'
));
}//-β’
// Ensure this item is valid, normalizing it if possible.
try {
item = normalizeComparisonValue(item, constraintTarget, modelIdentity, orm);
} catch (e) {
switch (e.code) {
case 'E_VALUE_NOT_USABLE': throw flaverr('E_CONSTRAINT_NOT_USABLE', new Error('Invalid item within `nin` ("not in") modifier array. '+e.message));
default: throw e;
}
}//>-β’
return item;
});//</_.map>
}//β‘
// ββββ¦ββββββββββ¦βββββ¦ββ ββ¦ββ¦ β¦ββββββ
// β β¦β β¦βββ£ β ββ£ β ββ£ β β¦β β β ββ£β ββ£βββ
// ββββ©ββββββ© β© β© ββββ©ββ β© β© β©β© β©βββ
// `>` ("greater than")
else if (modifierKind === '>') {
// If it matches a known attribute, verify that the attribute does not declare
// itself `type: 'boolean'` (it wouldn't make any sense to attempt that)
if (attrDef && attrDef.type === 'boolean'){
throw flaverr('E_CONSTRAINT_NOT_USABLE', new Error(
'A `>` ("greater than") modifier cannot be used with a boolean attribute. (Please use `or` instead.)'
));
}//-β’
// Ensure this modifier is valid, normalizing it if possible.
// > Note that, in addition to using the standard utility, we also verify that this
// > was not provided as `null`. (It wouldn't make any sense.)
try {
if (_.isNull(modifier)){
throw flaverr('E_VALUE_NOT_USABLE', new Error(
'`null` is not supported with comparison modifiers. '+
'Please use `or: [{ '+constraintTarget+': { \'!=\': null }, ...]` instead.'
));
}//-β’
modifier = normalizeComparisonValue(modifier, constraintTarget, modelIdentity, orm);
} catch (e) {
switch (e.code) {
case 'E_VALUE_NOT_USABLE': throw flaverr('E_CONSTRAINT_NOT_USABLE', new Error('Invalid `>` ("greater than") modifier. '+e.message));
default: throw e;
}
}//>-β’
}//β‘
// ββββ¦ββββββββββ¦βββββ¦ββ ββ¦ββ¦ β¦ββββββ ββββ¦ββ ββββββ β¦ β¦ββββ¦
// β β¦β β¦βββ£ β ββ£ β ββ£ β β¦β β β ββ£β ββ£βββ β ββ β¦β ββ£ βββ¬ββ ββ ββ£β
// ββββ©ββββββ© β© β© ββββ©ββ β© β© β©β© β©βββ ββββ©ββ βββββββββββ© β©β©ββ
// `>=` ("greater than or equal")
else if (modifierKind === '>=') {
// If it matches a known attribute, verify that the attribute does not declare
// itself `type: 'boolean'` (it wouldn't make any sense to attempt that)
if (attrDef && attrDef.type === 'boolean'){
throw flaverr('E_CONSTRAINT_NOT_USABLE', new Error(
'A `>=` ("greater than or equal") modifier cannot be used with a boolean attribute. (Please use `or` instead.)'
));
}//-β’
// Ensure this modifier is valid, normalizing it if possible.
// > Note that, in addition to using the standard utility, we also verify that this
// > was not provided as `null`. (It wouldn't make any sense.)
try {
if (_.isNull(modifier)){
throw flaverr('E_VALUE_NOT_USABLE', new Error(
'`null` is not supported with comparison modifiers. '+
'Please use `or: [{ '+constraintTarget+': { \'!=\': null }, ...]` instead.'
));
}//-β’
modifier = normalizeComparisonValue(modifier, constraintTarget, modelIdentity, orm);
} catch (e) {
switch (e.code) {
case 'E_VALUE_NOT_USABLE': throw flaverr('E_CONSTRAINT_NOT_USABLE', new Error('Invalid `>=` ("greater than or equal") modifier. '+e.message));
default: throw e;
}
}//>-β’
}//β‘
// β¦ βββββββββ ββ¦ββ¦ β¦ββββββ
// β ββ£ ββββββ β β ββ£β ββ£βββ
// β©βββββββββββ β© β© β©β© β©βββ
// `<` ("less than")
else if (modifierKind === '<') {
// If it matches a known attribute, verify that the attribute does not declare
// itself `type: 'boolean'` (it wouldn't make any sense to attempt that)
if (attrDef && attrDef.type === 'boolean'){
throw flaverr('E_CONSTRAINT_NOT_USABLE', new Error(
'A `<` ("less than") modifier cannot be used with a boolean attribute. (Please use `or` instead.)'
));
}//-β’
// Ensure this modifier is valid, normalizing it if possible.
// > Note that, in addition to using the standard utility, we also verify that this
// > was not provided as `null`. (It wouldn't make any sense.)
try {
if (_.isNull(modifier)){
throw flaverr('E_VALUE_NOT_USABLE', new Error(
'`null` is not supported with comparison modifiers. '+
'Please use `or: [{ '+constraintTarget+': { \'!=\': null }, ...]` instead.'
));
}//-β’
modifier = normalizeComparisonValue(modifier, constraintTarget, modelIdentity, orm);
} catch (e) {
switch (e.code) {
case 'E_VALUE_NOT_USABLE': throw flaverr('E_CONSTRAINT_NOT_USABLE', new Error('Invalid `<` ("less than") modifier. '+e.message));
default: throw e;
}
}//>-β’
}//β‘
// β¦ βββββββββ ββ¦ββ¦ β¦ββββββ ββββ¦ββ ββββββ β¦ β¦ββββ¦
// β ββ£ ββββββ β β ββ£β ββ£βββ β ββ β¦β ββ£ βββ¬ββ ββ ββ£β
// β©βββββββββββ β© β© β©β© β©βββ ββββ©ββ βββββββββββ© β©β©ββ
// `<=` ("less than or equal")
else if (modifierKind === '<=') {
// If it matches a known attribute, verify that the attribute does not declare
// itself `type: 'boolean'` (it wouldn't make any sense to attempt that)
if (attrDef && attrDef.type === 'boolean'){
throw flaverr('E_CONSTRAINT_NOT_USABLE', new Error(
'A `<=` ("less than or equal") modifier cannot be used with a boolean attribute. (Please use `or` instead.)'
));
}//-β’
// Ensure this modifier is valid, normalizing it if possible.
// > Note that, in addition to using the standard utility, we also verify that this
// > was not provided as `null`. (It wouldn't make any sense.)
try {
if (_.isNull(modifier)){
throw flaverr('E_VALUE_NOT_USABLE', new Error(
'`null` is not supported with comparison modifiers. '+
'Please use `or: [{ '+constraintTarget+': { \'!=\': null }, ...]` instead.'
));
}//-β’
modifier = normalizeComparisonValue(modifier, constraintTarget, modelIdentity, orm);
} catch (e) {
switch (e.code) {
case 'E_VALUE_NOT_USABLE': throw flaverr('E_CONSTRAINT_NOT_USABLE', new Error('Invalid `<=` ("less than or equal") modifier. '+e.message));
default: throw e;
}
}//>-β’
}//β‘
// βββββββββββ¦βββββ¦ββββββ
// β β ββββ β β ββ£βββββββ
// βββββββββ β© β© β©β©ββββββ
else if (modifierKind === 'contains') {
// If it matches a known attribute, verify that the attribute
// does not declare itself `type: 'boolean'` or `type: 'number'`;
// and also, if it is a singular association, that the associated
// model's primary key value is not a number either.
if (attrDef && (
attrDef.type === 'number' ||
attrDef.type === 'boolean' ||
(attrDef.model && reciprocalPKA.type === 'number')
)){
throw flaverr('E_CONSTRAINT_NOT_USABLE', new Error(
'A `contains` (i.e. string search) modifier cannot be used with a '+
'boolean or numeric attribute (it wouldn\'t make any sense).'
));
}//>-β’
// Ensure that this modifier is a string, normalizing it if possible.
// (note that this explicitly forbids the use of `null`)
try {
modifier = rttc.validate('string', modifier);
} catch (e) {
switch (e.code) {
case 'E_INVALID':
throw flaverr('E_CONSTRAINT_NOT_USABLE', new Error(
'Invalid `contains` (string search) modifier. '+e.message
));
default:
throw e;
}
}//</catch>
// If this modifier is the empty string (''), then it means that
// this constraint would match EVERYTHING.
if (modifier === '') {
throw flaverr('E_CONSTRAINT_WOULD_MATCH_EVERYTHING', new Error(
'Since this `contains` (string search) modifier was provided as '+
'`\'\'` (empty string), it would match ANYTHING!'
));
}//-β’
// Convert this modifier into a `like`, making the necessary adjustments.
//
// > This involves escaping any existing occurences of '%',
// > converting them to '\\%' instead.
// > (It's actually just one backslash, but...you know...strings )
delete constraintRhs[modifierKind];
modifierKind = 'like';
modifier = modifier.replace(/%/g,'\\%');
modifier = '%'+modifier+'%';
constraintRhs[modifierKind] = modifier;
}//β‘
// βββββ¦βββββ¦ββββ¦ββββ β¦ β¦β¦ββ¦ββ¦ β¦
// βββ β β ββ£β β¦β β βββ ββββ β β ββ£
// βββ β© β© β©β©ββ β© βββ ββ©ββ© β© β© β©
else if (modifierKind === 'startsWith') {
// If it matches a known attribute, verify that the attribute
// does not declare itself `type: 'boolean'` or `type: 'number'`;
// and also, if it is a singular association, that the associated
// model's primary key value is not a number either.
if (attrDef && (
attrDef.type === 'number' ||
attrDef.type === 'boolean' ||
(attrDef.model && reciprocalPKA.type === 'number')
)){
throw flaverr('E_CONSTRAINT_NOT_USABLE', new Error(
'A `startsWith` (i.e. string search) modifier cannot be used with a '+
'boolean or numeric attribute (it wouldn\'t make any sense).'
));
}//>-β’
// Ensure that this modifier is a string, normalizing it if possible.
// (note that this explicitly forbids the use of `null`)
try {
modifier = rttc.validate('string', modifier);
} catch (e) {
switch (e.code) {
case 'E_INVALID':
throw flaverr('E_CONSTRAINT_NOT_USABLE', new Error(
'Invalid `startsWith` (string search) modifier. '+e.message
));
default:
throw e;
}
}//</catch>
// If this modifier is the empty string (''), then it means that
// this constraint would match EVERYTHING.
if (modifier === '') {
throw flaverr('E_CONSTRAINT_WOULD_MATCH_EVERYTHING', new Error(
'Since this `startsWith` (string search) modifier was provided as '+
'`\'\'` (empty string), it would match ANYTHING!'
));
}//-β’
// Convert this modifier into a `like`, making the necessary adjustments.
//
// > This involves escaping any existing occurences of '%',
// > converting them to '\\%' instead.
// > (It's actually just one backslash, but...you know...strings )
delete constraintRhs[modifierKind];
modifierKind = 'like';
modifier = modifier.replace(/%/g,'\\%');
modifier = modifier+'%';
constraintRhs[modifierKind] = modifier;
}//β‘
// ββββββββ¦ββββ β¦ β¦β¦ββ¦ββ¦ β¦
// ββ£ βββ βββββ ββββ β β ββ£
// ββββββββ©ββββ ββ©ββ© β© β© β©
else if (modifierKind === 'endsWith') {
// If it matches a known attribute, verify that the attribute
// does not declare itself `type: 'boolean'` or `type: 'number'`;
// and also, if it is a singular association, that the associated
// model's primary key value is not a number either.
if (attrDef && (
attrDef.type === 'number' ||
attrDef.type === 'boolean' ||
(attrDef.model && reciprocalPKA.type === 'number')
)){
throw flaverr('E_CONSTRAINT_NOT_USABLE', new Error(
'An `endsWith` (i.e. string search) modifier cannot be used with a '+
'boolean or numeric attribute (it wouldn\'t make any sense).'
));
}//>-β’
// Ensure that this modifier is a string, normalizing it if possible.
// (note that this explicitly forbids the use of `null`)
try {
modifier = rttc.validate('string', modifier);
} catch (e) {
switch (e.code) {
case 'E_INVALID':
throw flaverr('E_CONSTRAINT_NOT_USABLE', new Error(
'Invalid `endsWith` (string search) modifier. '+e.message
));
default:
throw e;
}
}//</catch>
// If this modifier is the empty string (''), then it means that
// this constraint would match EVERYTHING.
if (modifier === '') {
throw flaverr('E_CONSTRAINT_WOULD_MATCH_EVERYTHING', new Error(
'Since this `endsWith` (string search) modifier was provided as '+
'`\'\'` (empty string), it would match ANYTHING!'
));
}//-β’
// Convert this modifier into a `like`, making the necessary adjustments.
//
// > This involves escaping any existing occurences of '%',
// > converting them to '\\%' instead.
// > (It's actually just one backslash, but...you know...strings )
delete constraintRhs[modifierKind];
modifierKind = 'like';
modifier = modifier.replace(/%/g,'\\%');
modifier = '%'+modifier;
constraintRhs[modifierKind] = modifier;
}//β‘
// β¦ β¦β¦βββββ
// β ββ β©βββ£
// β©βββ©β© β©βββ
else if (modifierKind === 'like') {
// If it matches a known attribute, verify that the attribute
// does not declare itself `type: 'boolean'` or `type: 'number'`;
// and also, if it is a singular association, that the associated
// model's primary key value is not a number either.
if (attrDef && (
attrDef.type === 'number' ||
attrDef.type === 'boolean' ||
(attrDef.model && reciprocalPKA.type === 'number')
)){
throw flaverr('E_CONSTRAINT_NOT_USABLE', new Error(
'A `like` (i.e. SQL-style "LIKE") modifier cannot be used with a '+
'boolean or numeric attribute (it wouldn\'t make any sense).'
));
}//>-β’
// Strictly verify that this modifier is a string.
// > You should really NEVER use anything other than a non-empty string for
// > `like`, because of the special % syntax. So we won't try to normalize
// > for you.
if (!_.isString(modifier) || modifier === '') {
throw flaverr('E_CONSTRAINT_NOT_USABLE', new Error(
'Invalid `like` (i.e. SQL-style "LIKE") modifier. Should be provided as '+
'a non-empty string, using `%` symbols as wildcards, but instead, got: '+
util.inspect(modifier,{depth: 5})+''
));
}//-β’
// If this modifier is '%%', then it means that this `like` constraint
// would match EVERYTHING.
if (modifier === '%%') {
throw flaverr('E_CONSTRAINT_WOULD_MATCH_EVERYTHING', new Error(
'Since this `like` (string search) modifier was provided as '+
'`%%`, it would match ANYTHING!'
));
}//-β’
}//β‘
// β¬ β¬ββββ¬ββββββββββββββββββ¬ββββββββ¬β ββ¬ββββββ¬ββ¬ββββ¬ββββ¬ββ
// β ββββββ¬βββ€ β β ββ β¬βββββββββ€ ββ ββββ β βββββ€ βββ€ ββ¬β
// βββββββ΄ββββββββββββββββββ΄ββββββββ΄β β΄ β΄βββββ΄ββ΄β β΄ββββ΄ββ
// A complex constraint must always contain a recognized modifier.
else {
throw flaverr('E_CONSTRAINT_NOT_USABLE', new Error(
'Unrecognized modifier (`'+modifierKind+'`) within provided constraint for `'+constraintTarget+'`.'
));
}//>-β’
// Just in case we made a by-value change above, set our potentially-modified modifier
// on the constraint.
constraintRhs[modifierKind] = modifier;
}
// ββββββββ βββββββ βββββββ βββββββ ββββ βββββββββββββββββββββββββββ ββββββ βββββββ ββββββββββββ
// βββββββββββββββββ ββββββββββββββββββββββ ββββββββββββββββββββββββββββββββββββββββββββ ββββββββββββ
// ββββββ βββ βββ βββ βββ βββββββββ βββββββββββ βββ βββββββββββββββββββββββββ βββ βββ
// ββββββ βββββ βββ βββ βββ βββββββββββββββββββββ βββ βββββββββββββββββββββββββββββ βββ
// βββββββββββββββββ ββββββββββββββββββββ ββββββββββββββ βββ βββ ββββββ βββββββββ ββββββ βββ
// ββββββββ βββββββ βββββββ βββββββ βββ βββββββββββββ βββ βββ ββββββ βββββββββ βββββ βββ
//
// Otherwise, ensure that this constraint is a valid eq constraint, including schema-aware
// normalization vs. the attribute def.
//
// > If there is no attr def, then check that it's a string, number, boolean, or `null`.
else {
// Ensure the provided eq constraint is valid, normalizing it if possible.
try {
constraintRhs = normalizeComparisonValue(constraintRhs, constraintTarget, modelIdentity, orm);
} catch (e) {
switch (e.code) {
case 'E_VALUE_NOT_USABLE': throw flaverr('E_CONSTRAINT_NOT_USABLE', e);
default: throw e;
}
}//>-β’
}//>- </ else >
// Return the normalized constraint.
return constraintRhs;
}; | normalizeConstraint()
Validate and normalize the provided constraint target (LHS), as well as the RHS.
------------------------------------------------------------------------------------------
@param {Ref} constraintRhs [may be MUTATED IN PLACE!]
@param {String} constraintTarget
The LHS of this constraint; usually, the attribute name it is referring to (unless
the model is `schema: false` or the constraint is invalid).
@param {String} modelIdentity
The identity of the model this contraint is referring to (e.g. "pet" or "user")
> Useful for looking up the Waterline model and accessing its attribute definitions.
@param {Ref} orm
The Waterline ORM instance.
> Useful for accessing the model definitions.
@param {Dictionary?} meta
The contents of the `meta` query key, if one was provided.
> Useful for propagating query options to low-level utilities like this one.
------------------------------------------------------------------------------------------
@returns {Dictionary|String|Number|Boolean|JSON}
The constraint (potentially the same ref), guaranteed to be valid for a stage 2 query.
This will always be either a complex constraint (dictionary), or an eq constraint (a
primitive-- string/number/boolean/null)
------------------------------------------------------------------------------------------
@throws {Error} if the provided constraint cannot be normalized
@property {String} code (=== "E_CONSTRAINT_NOT_USABLE")
------------------------------------------------------------------------------------------
@throws {Error} If the provided constraint would match everything
@property {String} code (=== "E_CONSTRAINT_WOULD_MATCH_EVERYTHING")
------------------------------------------------------------------------------------------
@throws {Error} If the provided constraint would NEVER EVER match anything
@property {String} code (=== "E_CONSTRAINT_WOULD_MATCH_NOTHING")
------------------------------------------------------------------------------------------
@throws {Error} If anything unexpected happens, e.g. bad usage, or a failed assertion.
------------------------------------------------------------------------------------------ | normalizeConstraint ( constraintRhs , constraintTarget , modelIdentity , orm , meta ) | javascript | balderdashy/waterline | lib/waterline/utils/query/private/normalize-constraint.js | https://github.com/balderdashy/waterline/blob/master/lib/waterline/utils/query/private/normalize-constraint.js | MIT |
module.exports = function buildUsageError(code, details, modelIdentity) {
// Sanity checks
if (!_.isString(code)) {
throw new Error('Consistency violation: `code` must be provided as a string, but instead, got: '+util.inspect(code, {depth:5})+'');
}
if (!_.isString(details)) {
throw new Error('Consistency violation: `details` must be provided as a string, but instead got: '+util.inspect(details, {depth:5})+'');
}
if (!_.isString(modelIdentity)) {
throw new Error('Consistency violation: `modelIdentity` must be provided as a string, but instead, got: '+util.inspect(code, {depth:5})+'');
}
// Look up standard template for this particular error code.
if (!USAGE_ERR_MSG_TEMPLATES[code]) {
throw new Error('Consistency violation: Unrecognized error code: '+code);
}
// Build error message.
var errorMessage = USAGE_ERR_MSG_TEMPLATES[code]({
details: details
});
// Instantiate Error.
// (This builds the stack trace.)
var err = new Error(errorMessage);
// Flavor the error with the appropriate `code`, direct access to the provided `details`,
// and a consistent "name" (i.e. so it reads nicely when logged.)
err = flaverr({
name: 'UsageError',
code: code,
details: details,
modelIdentity: modelIdentity
}, err);
// That's it!
// Send it on back.
return err;
}; | buildUsageError()
Build a new Error instance from the provided metadata.
> Currently, this is designed for use with the `forgeStageTwoQuery()` utility, and its recognized
> error codes are all related to that use case. But the idea is that, over time, this can also
> be used with any other sorts of new, end-developer-facing usage errors.
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
@param {String} code [e.g. 'E_INVALID_CRITERIA']
@param {String} details [e.g. 'The provided criteria contains an unrecognized property (`foo`):\n\'bar\'']
@param {String} modelIdentity [e.g. 'user']
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
@returns {Error}
@property {String} name (==> 'UsageError')
@property {String} message [composed from `details` and a built-in template]
@property {String} stack [built automatically by `new Error()`]
@property {String} code [the specified `code`]
@property {String} details [the specified `details`]
> The returned Error will have normalized properties and a standard,
> nicely-formatted error message built from stitching together the
> provided pieces of information.
>
> Note that, until we do automatic munging of stack traces, using
> this utility adds another internal item to the top of the trace. | buildUsageError ( code , details , modelIdentity ) | javascript | balderdashy/waterline | lib/waterline/utils/query/private/build-usage-error.js | https://github.com/balderdashy/waterline/blob/master/lib/waterline/utils/query/private/build-usage-error.js | MIT |
module.exports = function normalizeValueToSet(value, supposedAttrName, modelIdentity, orm, meta) {
// ================================================================================================
assert(_.isString(supposedAttrName), '`supposedAttrName` must be a string.');
// (`modelIdentity` and `orm` will be automatically checked by calling `getModel()` below)
// > Note that this attr name MIGHT be empty string -- although it should never be.
// > (we check that below)
// ================================================================================================
// ββββββββββ βββββββββββ ββββββββββ βββ ββββ ββββ βββββββ βββββββ βββββββββββ
// βββββββββββ ββββββββββββββββββββββ ββββ βββββ βββββββββββββββββββββββββββββββββ
// βββ ββββββββββββββ βββ βββββββ ββββββββββββββ ββββββ βββββββββ βββ
// βββ ββββββββββββββ βββ βββββββ ββββββββββββββ ββββββ βββββββββ βββ
// βββββββββββ ββββββββββββββββββββββ βββ βββ βββ ββββββββββββββββββββββββββββββββββββ
// ββββββββββ βββββββββββ ββββββββββ βββ βββ βββ βββββββ βββββββ ββββββββββββββββ
//
// ββββββ ββββ ββββββββββ ββββββ βββββββββββββββββββββββββ
// βββββββββββββ βββββββββββ ββββββββββββββββββββββββββββββββββ
// ββββββββββββββ ββββββ βββ ββββββββ βββ βββ ββββββββ
// βββββββββββββββββββββ βββ ββββββββ βββ βββ ββββββββ
// βββ ββββββ ββββββββββββββ βββ βββ βββ βββ βββ βββ
// βββ ββββββ ββββββββββββ βββ βββ βββ βββ βββ βββ
//
// Look up the Waterline model.
// > This is so that we can reference the original model definition.
var WLModel;
try {
WLModel = getModel(modelIdentity, orm);
} catch (e) {
switch (e.code) {
case 'E_MODEL_NOT_REGISTERED': throw new Error('Consistency violation: '+e.message);
default: throw e;
}
}//</catch>
// This local variable is used to hold a reference to the attribute def
// that corresponds with this value (if there is one).
var correspondingAttrDef;
try {
correspondingAttrDef = getAttribute(supposedAttrName, modelIdentity, orm);
} catch (e) {
switch (e.code) {
case 'E_ATTR_NOT_REGISTERED':
// If no matching attr def exists, then just leave `correspondingAttrDef`
// undefined and continue... for now anyway.
break;
default:
throw e;
}
}//</catch>
// ββββ¬ β¬βββββββ¬ββ βββββ¬βββ¬ββ¬βββ¬ββ β¬ β¬ββ¬ββββ ββββββββ¬ββββ
// β βββ€ββ€ β ββ΄β βββ€ β β ββ¬ββββ΄ββ β β ββ€ ββββββ€βββββ€
// ββββ΄ β΄βββββββ΄ β΄ β΄ β΄ β΄ β΄ β΄βββ΄ββββββ β΄ βββ ββββ΄ β΄β΄ β΄βββ
// If this model declares `schema: true`...
if (WLModel.hasSchema === true) {
// Check that this key corresponded with a recognized attribute definition.
//
// > If no such attribute exists, then fail gracefully by bailing early, indicating
// > that this value should be ignored (For example, this might cause this value to
// > be stripped out of the `newRecord` or `valuesToSet` query keys.)
if (!correspondingAttrDef) {
throw flaverr('E_SHOULD_BE_IGNORED', new Error(
'This model declares itself `schema: true`, but this value does not match '+
'any recognized attribute (thus it will be ignored).'
));
}//-β’
}//</else if `hasSchema === true` >
// β‘
// Else if this model declares `schema: false`...
else if (WLModel.hasSchema === false) {
// Check that this key is a valid Waterline attribute name, at least.
if (!isValidAttributeName(supposedAttrName)) {
if (supposedAttrName === '') {
throw flaverr('E_HIGHLY_IRREGULAR', new Error('Empty string (\'\') is not a valid name for an attribute.'));
}
else {
throw flaverr('E_HIGHLY_IRREGULAR', new Error('This is not a valid name for an attribute.'));
}
}//-β’
}
// β‘
else {
throw new Error(
'Consistency violation: Every live Waterline model should always have the `hasSchema` flag '+
'as either `true` or `false` (should have been automatically derived from the `schema` model setting '+
'shortly after construction. And `schema` should have been verified as existing by waterline-schema). '+
'But somehow, this model\'s (`'+modelIdentity+'`) `hasSchema` property is as follows: '+
util.inspect(WLModel.hasSchema, {depth:5})+''
);
}//</ else >
// ββββββββββ βββββββββββ ββββββββββ βββ βββ βββ ββββββ βββ βββ βββββββββββ
// βββββββββββ ββββββββββββββββββββββ ββββ βββ ββββββββββββββ βββ βββββββββββ
// βββ ββββββββββββββ βββ βββββββ βββ ββββββββββββββ βββ βββββββββ
// βββ ββββββββββββββ βββ βββββββ ββββ βββββββββββββββ βββ βββββββββ
// βββββββββββ ββββββββββββββββββββββ βββ βββββββ βββ ββββββββββββββββββββββββββββ
// ββββββββββ βββββββββββ ββββββββββ βββ βββββ βββ βββββββββββ βββββββ ββββββββ
//
// Validate+lightly coerce this value, both as schema-agnostic data,
// and vs. the corresponding attribute definition's declared `type`,
// `model`, or `collection`.
// Declare var to flag whether or not an attribute should have validation rules applied.
// This will typically be the case for primary keys and generic attributes under certain conditions.
var doCheckForRuleViolations = false;
// If this value is `undefined`, then bail early, indicating that it should be ignored.
if (_.isUndefined(value)) {
throw flaverr('E_SHOULD_BE_IGNORED', new Error(
'This value is `undefined`. Remember: in Sails/Waterline, we always treat keys with '+
'`undefined` values as if they were never there in the first place.'
));
}//-β’
// βββββββββββββ¬ββββ¬βββββ¬β β¬ β¬ββββ¬ β¬ β¬βββ β¬βββ βββββββ¬ββ ββββββ
// ββββββββ€ β βββ€ βββ€ ββ βββββββ€β β βββ€ ββββ ββ€ β βββ¬β βββ€βββ
// ββββ΄ βββββββ΄β β΄βββββ΄β ββ β΄ β΄β΄ββββββββ β΄βββ β ββββ΄ββ β΄ β΄βββ
// β¦ β¦ββββ¦ββββββββββββββββββ¦ββββββββ¦β βββββ¬βββ¬ββ¬βββ¬ββ β¬ β¬ββ¬ββββ
// β βββββ β¦βββ£ β β ββ β¦βββββββββ£ ββ βββ€ β β ββ¬ββββ΄ββ β β ββ€
// βββββββ©ββββββββββββββββββ©ββββββββ©β β΄ β΄ β΄ β΄ β΄βββ΄ββββββ β΄ βββ
//
// If this value doesn't actually match an attribute definition...
if (!correspondingAttrDef) {
// IWMIH then we already know this model has `schema: false`.
// So if this value doesn't match a recognized attribute def,
// then we'll validate it as `type: json`.
//
// > This is because we don't want to send a potentially-circular/crazy
// > value down to the adapter unless it corresponds w/ a `type: 'ref'` attribute.
try {
value = rttc.validate('json', value);
} catch (e) {
switch (e.code) {
case 'E_INVALID': throw flaverr({ code: 'E_TYPE', expectedType: 'json' }, new Error(
'Invalid value for unrecognized attribute (must be JSON-compatible). To explicitly allow '+
'non-JSON-compatible values like this, define a `'+supposedAttrName+'` attribute, and specify '+
'`type: ref`. More info on this error: '+e.message
));
default: throw e;
}
}
}//β‘
// βββββββ¬ββ ββββ¦βββ¦ββ¦βββββ¦βββ¦ β¦ β¦ββββββ¦ β¦ βββββ¦βββ¦ββ¦βββ¦ββ β¦ β¦ββ¦ββββ
// ββ€ β βββ¬β β βββ β¦ββββββ ββ£β β¦βββ¦β β β©βββ£ ββ¦β β ββ£ β β β β¦βββ β©ββ β β ββ£
// β ββββ΄ββ β© β©βββ©β© β©β© β©β©ββ β© β© β©βββ β© β© β© β© β© β©βββ©ββββββ β© βββ
else if (WLModel.primaryKey === supposedAttrName) {
// Primary key attributes should have validation rules applied if they have any.
if (!_.isUndefined(correspondingAttrDef.validations)) {
doCheckForRuleViolations = true;
}
try {
value = normalizePkValue(value, correspondingAttrDef.type);
} catch (e) {
switch (e.code) {
case 'E_INVALID_PK_VALUE':
throw flaverr('E_HIGHLY_IRREGULAR', new Error(
'Invalid primary key value. '+e.message
));
default:
throw e;
}
}
}//β‘
// βββββββ¬ββ ββββ¦ β¦ β¦β¦ββββββ¦ ββββββββββββββββ¦βββββ¦ββ¦ββββββ
// ββ€ β βββ¬β β βββ β ββ β¦ββ ββ£β β ββ£βββββββ ββ ββ ββ£ β ββ ββββ
// β ββββ΄ββ β© β©ββββββ©βββ© β©β©ββ β© β©βββββββββββββ©β© β© β© β©ββββββ
else if (correspondingAttrDef.collection) {
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// NOTE: For a brief period of time in the past, it was not permitted to call .update() or .validate()
// using an array of ids for a collection. But prior to the stable release of Waterline v0.13, this
// decision was reversed. The following commented-out code is left in Waterline to track what this
// was about, for posterity:
// ```
// // If properties are not allowed for plural ("collection") associations,
// // then throw an error.
// if (!allowCollectionAttrs) {
// throw flaverr('E_HIGHLY_IRREGULAR', new Error(
// 'As a precaution, prevented replacing entire plural ("collection") association (`'+supposedAttrName+'`). '+
// 'To do this, use `replaceCollection(...,\''+supposedAttrName+'\').members('+util.inspect(value, {depth:5})+')` '+
// 'instead.'
// ));
// }//-β’
// ```
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// Ensure that this is an array, and that each item in the array matches
// the expected data type for a pk value of the associated model.
try {
value = normalizePkValueOrValues(value, getAttribute(getModel(correspondingAttrDef.collection, orm).primaryKey, correspondingAttrDef.collection, orm).type);
} catch (e) {
switch (e.code) {
case 'E_INVALID_PK_VALUE':
throw flaverr('E_HIGHLY_IRREGULAR', new Error(
'If specified, expected `'+supposedAttrName+'` to be an array of ids '+
'(representing the records to associate). But instead, got: '+
util.inspect(value, {depth:5})+''
// 'If specifying the value for a plural (`collection`) association, you must do so by '+
// 'providing an array of associated ids representing the associated records. But instead, '+
// 'for `'+supposedAttrName+'`, got: '+util.inspect(value, {depth:5})+''
));
default: throw e;
}
}
}//β‘
// βββββββ¬ββ ββββ¦βββββββ¦ β¦β¦ ββββ¦ββ ββββββββββββββββ¦βββββ¦ββ¦ββββββ
// ββ€ β βββ¬β ββββββββ β¦β ββ β ββ£β β¦β β ββ£βββββββ ββ ββ ββ£ β ββ ββββ
// β ββββ΄ββ ββββ©ββββββββββ©βββ© β©β©ββ β© β©βββββββββββββ©β© β© β© β©ββββββ
else if (correspondingAttrDef.model) {
// If `null` was specified, then it _might_ be OK.
if (_.isNull(value)) {
// We allow `null` for singular associations UNLESS they are required.
if (correspondingAttrDef.required) {
throw flaverr('E_REQUIRED', new Error(
'Cannot set `null` for required association (`'+supposedAttrName+'`).'
));
}//-β’
}//β‘
// Otherwise, this value is NOT null.
// So ensure that it matches the expected data type for a pk value
// of the associated model (normalizing it, if appropriate/possible.)
else {
try {
value = normalizePkValue(value, getAttribute(getModel(correspondingAttrDef.model, orm).primaryKey, correspondingAttrDef.model, orm).type);
} catch (e) {
switch (e.code) {
case 'E_INVALID_PK_VALUE':
throw flaverr('E_HIGHLY_IRREGULAR', new Error(
'Expecting an id representing the associated record, or `null` to indicate '+
'there will be no associated record. But the specified value is not a valid '+
'`'+supposedAttrName+'`. '+e.message
));
default:
throw e;
}
}//</catch>
}//</else (not null)>
}//β‘
// βββββββ¬ββ ββ¦ββ¦ββββββββββ¦ β¦ βββββββββββββ¦ β¦βββ βββββ¦βββ¦ββ¦βββ¦ββ β¦ β¦ββ¦ββββ
// ββ€ β βββ¬β ββββββββ ββ£ β β β ββ£βββββ£ β ββ ββββ β ββ£ β β β β¦βββ β©ββ β β ββ£
// β ββββ΄ββ β© β©β©ββββββββββ©βββ©βββ© β©βββββββββββββββ β© β© β© β© β©βββ©ββββββ β© βββ
// Otherwise, the corresponding attr def is just a normal attr--not an association or primary key.
// > We'll use loose validation (& thus also light coercion) on the value and see what happens.
else {
if (!_.isString(correspondingAttrDef.type) || correspondingAttrDef.type === '') {
throw new Error('Consistency violation: There is no way this attribute (`'+supposedAttrName+'`) should have been allowed to be registered with neither a `type`, `model`, nor `collection`! Here is the attr def: '+util.inspect(correspondingAttrDef, {depth:5})+'');
}
// First, check if this is an auto-*-at timestamp, and if it is...
if (correspondingAttrDef.autoCreatedAt || correspondingAttrDef.autoUpdatedAt) {
// Ensure we are not trying to set it to empty string
// (this would never make sense.)
if (value === '') {
throw flaverr('E_HIGHLY_IRREGULAR', new Error(
'If specified, should be a valid '+
(
correspondingAttrDef.type === 'number' ?
'JS timestamp (unix epoch ms)' :
'JSON timestamp (ISO 8601)'
)+'. '+
'But instead, it was empty string ("").'
));
}//-β’
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// FUTURE: If there is significant confusion being caused by allowing `autoUpdatedAt`
// attrs to be set explicitly on .create() and .update() , then we should reevaluate
// adding in the following code:
// ```
// // And log a warning about how this auto-* timestamp is being set explicitly,
// // whereas the generally expected behavior is to let it be set automatically.
// var autoTSDisplayName;
// if (correspondingAttrDef.autoCreatedAt) {
// autoTSDisplayName = 'autoCreatedAt';
// }
// else {
// autoTSDisplayName = 'autoUpdatedAt';
// }
//
// console.warn('\n'+
// 'Warning: Explicitly overriding `'+supposedAttrName+'`...\n'+
// '(This attribute of the `'+modelIdentity+'` model is defined as '+
// '`'+autoTSDisplayName+': true`, meaning it is intended to be set '+
// 'automatically, except in special cases when debugging or migrating data.)\n'
// );
// ```
//
// But for now, leaving it (^^) out.
//
// > See https://github.com/balderdashy/waterline/pull/1440#issuecomment-275943205
// > for more information. Note that we'd need an extra meta key because of
// > auto-migrations and other higher level tooling built on Waterline.
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
}//>-β’
// Handle a special case where we want a more specific error:
//
// > Note: This is just like normal RTTC validation ("loose" mode), with one major exception:
// > We handle `null` as a special case, regardless of the type being validated against;
// > whether or not this attribute is `required: true`. That's because it's so easy to
// > get confused about how `required` works in a given database vs. Waterline vs. JavaScript.
// > (Especially when it comes to null vs. undefined vs. empty string, etc)
// >
// > In RTTC, `null` is only valid vs. `json` and `ref` types, for singular associations,
// > and for completely unrecognized attributes -- and that's still true here.
// > But most schemaful databases also support a configuration where `null` is ALSO allowed
// > as an implicit base value for any type of data. This sorta serves the same purpose as
// > `undefined`, or omission, in JavaScript or MongoDB. BUT that doesn't mean we necessarily
// > allow `null` -- consistency of type safety rules is too important -- it just means that
// > we give it its own special error message.
// >
// > BUT NOTE: if `allowNull` is enabled, we DO allow null.
// >
// > Review the "required"-ness checks in the `normalize-new-record.js` utility for examples
// > of related behavior, and see the more detailed spec for more information:
// > https://docs.google.com/spreadsheets/d/1whV739iW6O9SxRZLCIe2lpvuAUqm-ie7j7tn_Pjir3s/edit#gid=1814738146
var isProvidingNullForIncompatibleOptionalAttr = (
_.isNull(value) &&
correspondingAttrDef.type !== 'json' &&
correspondingAttrDef.type !== 'ref' &&
!correspondingAttrDef.allowNull &&
!correspondingAttrDef.required
);
if (isProvidingNullForIncompatibleOptionalAttr) {
throw flaverr({ code: 'E_TYPE', expectedType: correspondingAttrDef.type }, new Error(
'Specified value (`null`) is not a valid `'+supposedAttrName+'`. '+
'Even though this attribute is optional, it still does not allow `null` to '+
'be explicitly set, because `null` is not valid vs. the expected '+
'type: \''+correspondingAttrDef.type+'\'. Instead, to indicate "voidness", '+
'please set the value for this attribute to the base value for its type, '+
(function _getBaseValuePhrase(){
switch(correspondingAttrDef.type) {
case 'string': return '`\'\'` (empty string)';
case 'number': return '`0` (zero)';
default: return '`'+rttc.coerce(correspondingAttrDef.type)+'`';
}
})()+'. Or, if you specifically need to save `null`, then change this '+
'attribute to either `type: \'json\'` or `type: \'ref\'`. '+
(function _getExtraPhrase(){
if (_.isUndefined(correspondingAttrDef.defaultsTo)) {
return 'Also note: Since this attribute does not define a `defaultsTo`, '+
'the base value will be used as an implicit default if `'+supposedAttrName+'` '+
'is omitted when creating a record.';
}
else { return ''; }
})()
));
}//-β’
// ββββ¬ β¬ββββ¬ββββββββββ¬βββββββ ββ¦ββ¦ β¦ββββββ ββββββββββββββ¦ββ¦ β¦
// β β¬β ββββ€ββ¬ββββ€βββ β ββ€ ββ€ β ββ¦ββ ββββ£ ββββ ββ£β β£ ββ£ β ββ¦β
// βββββββ΄ β΄β΄βββ΄ β΄βββ β΄ ββββββ β© β© β© βββ ββββ© β©β βββ β© β©
// If the value is `null` and the attribute has allowNull set to true it's ok.
if (correspondingAttrDef.allowNull && _.isNull(value)) {
// Nothing else to validate here.
}
//β‘
// Otherwise, verify that this value matches the expected type, and potentially
// perform loose coercion on it at the same time. This throws an E_INVALID error
// if validation fails.
else {
try {
value = rttc.validate(correspondingAttrDef.type, value);
} catch (e) {
switch (e.code) {
case 'E_INVALID': throw flaverr({ code: 'E_TYPE', expectedType: correspondingAttrDef.type }, new Error(
'Specified value is not a valid `'+supposedAttrName+'`. '+e.message
));
default: throw e;
}
}
}
// β¬ β¬ββββββββ¬ββ¬ βββ βββββββββββββ¬ββββ¬ βββββββββββββββ
// βββ€βββ€βββ βββ ββ€ ββββββββ€ β ββββ€β β βββ€βββββ€ βββ
// β΄ β΄β΄ β΄βββββ΄ββ΄βββββ ββββ΄ βββββββ΄β΄ β΄β΄ββ ββββ΄ β΄βββββββββ
// ββ βββββββ¬ββ β¦ββββββββ β¦ β¦β¦β¦βββββββ¦β ββ
// ββββ ββ€ β βββ¬β β β¦βββ£ βββ¬ββ βββ β¦βββ£ ββ ββββ
// ββ β ββββ΄ββ β©βββββββββββββ©β©βββββββ©β ββ
if (correspondingAttrDef.required) {
// "" (empty string) is never allowed as a value for a required attribute.
if (value === '') {
throw flaverr('E_REQUIRED', new Error(
'Cannot set "" (empty string) for a required attribute.'
));
}//>-β’
// `null` is never allowed as a value for a required attribute.
if (_.isNull(value)) {
throw flaverr('E_REQUIRED', new Error(
'Cannot set `null` for a required attribute.'
));
}//-β’
}//>- </ if required >
// Decide whether validation rules should be checked for this attribute.
//
// > β’ High-level validation rules are ALWAYS skipped for `null`.
// > β’ If there is no `validations` attribute key, then there's nothing for us to check.
doCheckForRuleViolations = !_.isNull(value) && !_.isUndefined(correspondingAttrDef.validations);
}//</else (i.e. corresponding attr def is just a normal attr--not an association or primary key)>
// ββββ¬ β¬βββββββ¬ββ βββββββ¬ββ β¦βββ¦ β¦β¦ βββ β¦ β¦β¦ββββ¦ βββββ¦ββ¦βββββββββ
// β βββ€ββ€ β ββ΄β ββ€ β βββ¬β β β¦ββ ββ ββ£ ββββββ ββ β ββ£ β ββ βββββββ
// ββββ΄ β΄βββββββ΄ β΄ β ββββ΄ββ β©ββββββ©βββββ ββ β©ββββ©βββ© β© β© β©βββββββββ
// If appropriate, strictly enforce our (potentially-mildly-coerced) value
// vs. the validation ruleset defined on the corresponding attribute.
// Then, if there are any rule violations, stick them in an Error and throw it.
if (doCheckForRuleViolations) {
var ruleset = correspondingAttrDef.validations;
var isRulesetDictionary = _.isObject(ruleset) && !_.isArray(ruleset) && !_.isFunction(ruleset);
if (!isRulesetDictionary) {
throw new Error('Consistency violation: If set, an attribute\'s validations ruleset (`validations`) should always be a dictionary (plain JavaScript object). But for the `'+modelIdentity+'` model\'s `'+supposedAttrName+'` attribute, it somehow ended up as this instead: '+util.inspect(correspondingAttrDef.validations,{depth:5})+'');
}
var ruleViolations;
try {
ruleViolations = anchor(value, ruleset);
// e.g.
// [ { rule: 'isEmail', message: 'Value was not a valid email address.' }, ... ]
} catch (e) {
throw new Error(
'Consistency violation: Unexpected error occurred when attempting to apply '+
'high-level validation rules from `'+modelIdentity+'` model\'s `'+supposedAttrName+'` '+
'attribute. '+e.stack
);
}//</ catch >
if (ruleViolations.length > 0) {
// Format rolled-up summary for use in our error message.
// e.g.
// ```
// β’ Value was not in the configured whitelist (delinquent, new, paid)
// β’ Value was an empty string.
// ```
var summary = _.reduce(ruleViolations, function (memo, violation){
memo += ' β’ '+violation.message+'\n';
return memo;
}, '');
throw flaverr({
code: 'E_VIOLATES_RULES',
ruleViolations: ruleViolations
}, new Error(
'Violated one or more validation rules:\n'+
summary
));
}//-β’
}//>-β’ </if (doCheckForRuleViolations) >
// ββββββββββββ βββ ββββββββββββββ βββ ββββββββββ βββββββββ βββββββ ββββββ βββββββββ ββββββ
// βββββββββββββ βββββββββββββββββββββββ βββββββββββββββββββββ βββββββββββββββββββββββββββββββββ
// ββββββ ββββββ ββββββ ββββββββ βββββββ ββββββββ βββ βββ βββββββββββ βββ ββββββββ
// ββββββ βββββββββββββ ββββββββ βββββ βββββββ βββ βββ βββββββββββ βββ ββββββββ
// βββββββββββ βββββββββββββββββ βββ βββ βββ βββ βββββββββββ βββ βββ βββ βββ
// βββββββββββ βββββ ββββββββββ βββ βββ βββ βββ βββββββ βββ βββ βββ βββ βββ
// β¦βββ β¬ββββββ¬ ββββ¬ β¬ββββββββ¬β
// ββ β£ ββ¬βββ€ β ββ€ βββββββ€βββ β
// β©β β΄ββββββ΄βββββ ββ β΄ β΄βββ β΄ooo
if (correspondingAttrDef && correspondingAttrDef.encrypt) {
if (correspondingAttrDef.encrypt !== true) {
throw new Error(
'Consistency violation: `'+modelIdentity+'` model\'s `'+supposedAttrName+'` attribute '+
'has a corrupted definition. Should not have been allowed to set `encrypt` to anything '+
'other than `true` or `false`.'
);
}//β’
if (correspondingAttrDef.type === 'ref') {
throw new Error(
'Consistency violation: `'+modelIdentity+'` model\'s `'+supposedAttrName+'` attribute '+
'has a corrupted definition. Should not have been allowed to be both `type: \'ref\' '+
'AND `encrypt: true`.'
);
}//β’
if (!_.isObject(WLModel.dataEncryptionKeys) || !WLModel.dataEncryptionKeys.default || !_.isString(WLModel.dataEncryptionKeys.default)) {
throw new Error(
'Consistency violation: `'+modelIdentity+'` model has a corrupted definition. Should not '+
'have been allowed to declare an attribute with `encrypt: true` without also specifying '+
'the `dataEncryptionKeys` model setting as a valid dictionary (including a valid "default" '+
'key).'
);
}//β’
// Figure out what DEK to encrypt with.
var idOfDekToEncryptWith;
if (meta && meta.encryptWith) {
idOfDekToEncryptWith = meta.encryptWith;
}
else {
idOfDekToEncryptWith = 'default';
}
if (!WLModel.dataEncryptionKeys[idOfDekToEncryptWith]) {
throw new Error(
'There is no known data encryption key by that name (`'+idOfDekToEncryptWith+'`). '+
'Please make sure a valid DEK (data encryption key) is configured under `dataEncryptionKeys`.'
);
}//β’
try {
// Never encrypt `''`(empty string), `0` (zero), `false`, or `null`, since these are possible
// base values. (Note that the current code path only runs when a value is explicitly provided
// for the attribute-- not when it is omitted. Thus these base values can get into the database
// without being encrypted _anyway_.)
if (value === '' || value === 0 || value === false || _.isNull(value)) {
// Don't encrypt.
}
// Never encrypt if the (private/experimental) `skipEncryption` meta key is
// set truthy. PLEASE DO NOT RELY ON THIS IN YOUR OWN CODE- IT COULD CHANGE
// AT ANY TIME AND BREAK YOUR APP OR PLUGIN!
// > (Useful for internal method calls-- e.g. the internal "create()" that
// > Waterline uses to implement `findOrCreate()`. For more info on that,
// > see https://github.com/balderdashy/sails/issues/4302#issuecomment-363883885)
else if (meta && meta.skipEncryption) {
// Don't encrypt.
}
else {
// First, JSON-encode value, to allow for differentiating between strings/numbers/booleans/null.
var jsonEncoded;
try {
jsonEncoded = JSON.stringify(value);
} catch (err) {
// Note: Stringification SHOULD always work, because we just checked all that out above.
// But just in case it doesn't, or if this code gets moved elsewhere in the future, here
// we include a reasonable error here as a backup.
throw flaverr({
message: 'Before encrypting, Waterline attempted to JSON-stringify this value to ensure it '+
'could be accurately decoded into the correct data type later (for example, `2` vs `\'2\'`). '+
'But this time, JSON.stringify() failed with the following error: '+err.message
}, err);
}
// Encrypt using the appropriate key from the configured DEKs.
// console.log('β’β’β’β’β’encrypting JSON-encoded value: `'+util.inspect(jsonEncoded, {depth:null})+'`');
// Require this down here for Node version compat.
var EA = require('encrypted-attr');
value = EA([supposedAttrName], {
keys: WLModel.dataEncryptionKeys,
keyId: idOfDekToEncryptWith
})
.encryptAttribute(undefined, jsonEncoded);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// Alternative: (hack for testing)
// ```
// if (value.match(/^ENCRYPTED:/)){ throw new Error('Unexpected behavior: Can\'t encrypt something already encrypted!!!'); }
// value = 'ENCRYPTED:'+jsonEncoded;
// ```
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
}//ο¬
} catch (err) {
// console.log('β’β’β’β’β’was attempting to encrypt this value: `'+util.inspect(value, {depth:null})+'`');
throw flaverr({
message: 'Encryption failed for `'+supposedAttrName+'`\n'+
'Details:\n'+
' '+err.message
}, _.isError(err) ? err : new Error());
}
}//ο¬
// Return the normalized (and potentially encrypted) value.
return value;
}; | normalizeValueToSet()
Validate and normalize the provided `value`, hammering it destructively into a format
that is compatible with the specified attribute. (Also take care of encrypting the `value`,
if configured to do so by the corresponding attribute definition.)
This function has a return value. But realize that this is only because the provided value
_might_ be a string, number, or some other primitive that is NOT passed by reference, and thus
must be replaced, rather than modified.
--
@param {Ref} value
The value to set (i.e. from the `valuesToSet` or `newRecord` query keys of a "stage 1 query").
(If provided as `undefined`, it will be ignored)
> WARNING:
> IN SOME CASES (BUT NOT ALL!), THE PROVIDED VALUE WILL
> UNDERGO DESTRUCTIVE, IN-PLACE CHANGES JUST BY PASSING IT
> IN TO THIS UTILITY.
@param {String} supposedAttrName
The "supposed attribute name"; i.e. the LHS the provided value came from (e.g. "id" or "favoriteBrands")
> Useful for looking up the appropriate attribute definition.
@param {String} modelIdentity
The identity of the model this value is for (e.g. "pet" or "user")
> Useful for looking up the Waterline model and accessing its attribute definitions.
@param {Ref} orm
The Waterline ORM instance.
> Useful for accessing the model definitions.
@param {Dictionary?} meta
The contents of the `meta` query key, if one was provided.
> Useful for propagating query options to low-level utilities like this one.
--
@returns {Ref}
The successfully-normalized value, ready for use within the `valuesToSet` or `newRecord`
query key of a stage 2 query. (May or may not be the original reference.)
--
@throws {Error} If the value should be ignored/stripped (e.g. because it is `undefined`, or because it
does not correspond with a recognized attribute, and the model def has `schema: true`)
@property {String} code
- E_SHOULD_BE_IGNORED
@throws {Error} If it encounters incompatible usage in the provided `value`,
including e.g. the case where an invalid value is specified for
an association.
@property {String} code
- E_HIGHLY_IRREGULAR
@throws {Error} If the provided `value` has an incompatible data type.
| @property {String} code
| - E_TYPE
| @property {String} expectedType
| - string
| - number
| - boolean
| - json
|
| This is only versus the attribute's declared "type", or other similar type safety issues --
| certain failed checks for associations result in a different error code (see above).
|
| Remember:
| This is the case where a _completely incorrect type of data_ was passed in.
| This is NOT a high-level "anchor" validation failure! (see below for that)
| > Unlike anchor validation errors, this exception should never be negotiated/parsed/used
| > for delivering error messages to end users of an application-- it is carved out
| > separately purely to make things easier to follow for the developer.
@throws {Error} If the provided `value` fails the requiredness guarantee of the corresponding attribute.
| @property {String} code
| - E_REQUIRED
@throws {Error} If the provided `value` violates one or more of the high-level validation rules
| configured for the corresponding attribute.
| @property {String} code
| - E_VIOLATES_RULES
| @property {Array} ruleViolations
| e.g.
| ```
| [
| {
| rule: 'minLength', //(isEmail/isNotEmptyString/max/isNumber/etc)
| message: 'Too few characters (max 30)'
| }
| ]
| ```
@throws {Error} If anything else unexpected occurs. | normalizeValueToSet ( value , supposedAttrName , modelIdentity , orm , meta ) | javascript | balderdashy/waterline | lib/waterline/utils/query/private/normalize-value-to-set.js | https://github.com/balderdashy/waterline/blob/master/lib/waterline/utils/query/private/normalize-value-to-set.js | MIT |
module.exports = function normalizePkValue (pkValue, expectedPkType){
// Check usage
if (expectedPkType !== 'string' && expectedPkType !== 'number') {
throw new Error('Consistency violation: The internal normalizePkValue() utility must always be called with a valid second argument ("string" or "number"). But instead, got: '+util.inspect(expectedPkType, {depth:5})+'');
}
// If explicitly expecting strings...
if (expectedPkType === 'string') {
if (!_.isString(pkValue)) {
// > Note that we DO NOT tolerate non-strings being passed in, even though it
// > would be possible to cast them into strings automatically. While this would
// > be useful for key/value adapters like Redis, or in SQL databases when using
// > a string primary key, it can lead to bugs when querying against a database
// > like MongoDB that uses special hex or uuid strings.
throw flaverr('E_INVALID_PK_VALUE', new Error('Instead of a string (the expected pk type), the provided value is: '+util.inspect(pkValue,{depth:5})+''));
}//-β’
// Empty string ("") is never a valid primary key value.
if (pkValue === '') {
throw flaverr('E_INVALID_PK_VALUE', new Error('Cannot use empty string ('+util.inspect(pkValue,{depth:5})+') as a primary key value.'));
}//-β’
}//β‘
// Else if explicitly expecting numbers...
else if (expectedPkType === 'number') {
if (!_.isNumber(pkValue)) {
// If this is not even a _string_ either, then reject it.
// (Note that we handle this case separately in order to support a more helpful error message.)
if (!_.isString(pkValue)) {
throw flaverr('E_INVALID_PK_VALUE', new Error(
'Instead of a number (the expected pk type), got: '+util.inspect(pkValue,{depth:5})+''
));
}//-β’
// Tolerate strings that _look_ like base-10, non-zero, positive integers;
// and that wouldn't be too big to be a safe JavaScript number.
// (Cast them into numbers automatically.)
var GOT_STRING_FOR_NUMERIC_PK_SUFFIX =
'To resolve this error, pass in a valid base-10, non-zero, positive integer instead. '+
'(Or if you must use strings, then change the relevant model\'s pk attribute from '+
'`type: \'number\'` to `type: \'string\'`.)';
var canPrblyCoerceIntoValidNumber = _.isString(pkValue) && pkValue.match(/^[0-9]+$/);
if (!canPrblyCoerceIntoValidNumber) {
throw flaverr('E_INVALID_PK_VALUE', new Error(
'Instead of a number, the provided value (`'+util.inspect(pkValue,{depth:5})+'`) is a string, '+
'and it cannot be coerced into a valid primary key value automatically (contains characters other '+
'than numerals 0-9). '+
GOT_STRING_FOR_NUMERIC_PK_SUFFIX
));
}//-β’
var coercedNumber = +pkValue;
if (coercedNumber > (Number.MAX_SAFE_INTEGER||9007199254740991)) {
throw flaverr('E_INVALID_PK_VALUE', new Error(
'Instead of a valid number, the provided value (`'+util.inspect(pkValue,{depth:5})+'`) is '+
'a string that looks like a number. But it cannot be coerced automatically because, despite '+
'its "numbery" appearance, it\'s just too big! '+
GOT_STRING_FOR_NUMERIC_PK_SUFFIX
));
}//-β’
pkValue = coercedNumber;
}//>-β’ </ if !_.isNumber(pkValue) >
//-β’
// IWMIH, then we know that `pkValue` is now a number.
// (But it might be something like `NaN` or `Infinity`!)
//
// `pkValue` should be provided as a safe, positive, non-zero, finite integer.
//
// > We do a few explicit checks below for better error messages, and then finally
// > do one last check as a catchall, at the very end.
// NaN is never valid as a primary key value.
if (_.isNaN(pkValue)) {
throw flaverr('E_INVALID_PK_VALUE', new Error('Cannot use `NaN` as a primary key value.'));
}//-β’
// Zero is never a valid primary key value.
if (pkValue === 0) {
throw flaverr('E_INVALID_PK_VALUE', new Error('Cannot use zero ('+util.inspect(pkValue,{depth:5})+') as a primary key value.'));
}//-β’
// A negative number is never a valid primary key value.
if (pkValue < 0) {
throw flaverr('E_INVALID_PK_VALUE', new Error('Cannot use a negative number ('+util.inspect(pkValue,{depth:5})+') as a primary key value.'));
}//-β’
// A floating point number is never a valid primary key value.
if (Math.floor(pkValue) !== pkValue) {
throw flaverr('E_INVALID_PK_VALUE', new Error('Cannot use a floating point number ('+util.inspect(pkValue,{depth:5})+') as a primary key value.'));
}//-β’
// Neither Infinity nor -Infinity are ever valid as primary key values.
if (Infinity === pkValue || -Infinity === pkValue) {
throw flaverr('E_INVALID_PK_VALUE', new Error('Cannot use `Infinity` or `-Infinity` (`'+util.inspect(pkValue,{depth:5})+'`) as a primary key value.'));
}//-β’
// Numbers greater than the maximum safe JavaScript integer are never valid as a primary key value.
// > Note that we check for `Infinity` above FIRST, before we do this comparison. That's just so that
// > we can display a tastier error message.
if (pkValue > (Number.MAX_SAFE_INTEGER||9007199254740991)) {
throw flaverr('E_INVALID_PK_VALUE', new Error('Cannot use the provided value (`'+util.inspect(pkValue,{depth:5})+'`), because it is too large to safely fit into a JavaScript integer (i.e. `> Number.MAX_SAFE_INTEGER`)'));
}//-β’
// Now do one last check as a catch-all, w/ a generic error msg.
if (!isSafeNaturalNumber(pkValue)) {
throw flaverr('E_INVALID_PK_VALUE', new Error('Cannot use the provided value (`'+util.inspect(pkValue,{depth:5})+'`) as a primary key value -- it is not a "safe", natural number (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isSafeInteger).'));
}
} else { throw new Error('Consistency violation: Should not be possible to make it here in the code! If you are seeing this error, there\'s a bug in Waterline!'); }
//>-β’
// Return the normalized pk value.
return pkValue;
}; | normalizePkValue()
Validate and normalize the provided pk value.
> This ensures the provided pk value is a string or a number.
> β’ If a string, it also validates that it is not the empty string ("").
> β’ If a number, it also validates that it is a base-10, non-zero, positive integer
> that is not larger than the maximum safe integer representable by JavaScript.
> Also, if we are expecting numbers, numeric strings are tolerated, so long as they
> can be parsed as valid numeric pk values.
------------------------------------------------------------------------------------------
@param {String|Number} pkValue
@param {String} expectedPkType [either "number" or "string"]
------------------------------------------------------------------------------------------
@returns {String|Number}
A valid primary key value, guaranteed to match the specified `expectedPkType`.
------------------------------------------------------------------------------------------
@throws {Error} if invalid
@property {String} code (=== "E_INVALID_PK_VALUE")
------------------------------------------------------------------------------------------
@throws {Error} If anything unexpected happens, e.g. bad usage, or a failed assertion.
------------------------------------------------------------------------------------------ | normalizePkValue ( pkValue , expectedPkType ) | javascript | balderdashy/waterline | lib/waterline/utils/query/private/normalize-pk-value.js | https://github.com/balderdashy/waterline/blob/master/lib/waterline/utils/query/private/normalize-pk-value.js | MIT |
module.exports = function expandWhereShorthand(criteria){
if (_.isUndefined(criteria)) {
criteria = {};
}
else if (!_.isObject(criteria)) {
criteria = {
where: criteria
};
}
else {
var recognizedClauses = _.intersection(_.keys(criteria), RECOGNIZED_S2Q_CRITERIA_CLAUSE_NAMES);
if (recognizedClauses.length === 0) {
criteria = {
where: criteria
};
}
}
return criteria;
}; | expandWhereShorthand()
Return a new dictionary wrapping the provided `where` clause, or if the
provided dictionary already contains a criteria clause (`where`, `limit`, etc),
then just return it as-is.
> This handles implicit `where` clauses provided instead of criteria.
>
> If the provided criteria dictionary DOES NOT contain the names of ANY known
> criteria clauses (like `where`, `limit`, etc.) as properties, then we can
> safely assume that it is relying on shorthand: i.e. simply specifying what
> would normally be the `where` clause, but at the top level.
> Note that, _in addition_ to calling this utility from FS2Q, it is sometimes
> necessary to call this directly from relevant methods. That's because FS2Q
> normalization does not occur until we _actually_ execute the query, and in
> the mean time, we provide deferred methods for building criteria piece by piece.
> In other words, we need to allow for hybrid usage like:
> ```
> User.find({ name: 'Santa' }).limit(30)
> ```
>
> And:
> ```
> User.find().limit(30)
> ```
>
> ...in addition to normal usage like this:
> ```
> User.find({ limit: 30 }).where({ name: 'Santa', age: { '>': 1000 } })
> ```
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
@param {Ref?} criteria
@returns {Dictionary}
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | expandWhereShorthand ( criteria ) | javascript | balderdashy/waterline | lib/waterline/utils/query/private/expand-where-shorthand.js | https://github.com/balderdashy/waterline/blob/master/lib/waterline/utils/query/private/expand-where-shorthand.js | MIT |
module.exports = function isSafeNaturalNumber(value) {
// Return false for:
// β’Β NaN
// β’ Infinity / -Infinity
// β’ 0 / -0
// β’ fractions
// β’ negative integers
// β’ and integers greater than `Number.MAX_SAFE_INTEGER`
//
// Otherwise, return true!
//
// > For more on `Number.isSafeInteger()`, check out MDN:
// > https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isSafeInteger
// Note that, eventually, we can just do:
// ```
// return Number.isSafeInteger(value) && value > 0;
// ```
// But for compatibility with legacy versions of Node.js, we do:
// (implementation borrowed from https://github.com/lodash/lodash/blob/4.17.2/lodash.js#L12094)
return lodash4IsSafeInteger(value) && value > 0;
}; | isSafeNaturalNumber()
Determine whether this value is a safe, natural number:
β’ `safe` | `<= Number.MAX_SAFE_INTEGER` (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER)
β’ `natural` | `> 0 && !== Infinity && !== NaN && Math.floor(x) === x` (positive, non-zero, finite, round number. In other words, no funny business -- aka "positive, non-zero integer")
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
@param {Ref} value
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
@returns {Boolean} | isSafeNaturalNumber ( value ) | javascript | balderdashy/waterline | lib/waterline/utils/query/private/is-safe-natural-number.js | https://github.com/balderdashy/waterline/blob/master/lib/waterline/utils/query/private/is-safe-natural-number.js | MIT |
module.exports = function normalizeCriteria(criteria, modelIdentity, orm, meta) {
// Sanity checks.
// > These are just some basic, initial usage assertions to help catch
// > bugs during development of Waterline core.
//
// At this point, `criteria` MUST NOT be undefined.
// (Any defaulting related to that should be taken care of before calling this function.)
if (_.isUndefined(criteria)) {
throw new Error('Consistency violation: `criteria` should never be `undefined` when it is passed in to the normalizeCriteria() utility.');
}
// Look up the Waterline model for this query.
// > This is so that we can reference the original model definition.
var WLModel;
try {
WLModel = getModel(modelIdentity, orm);
} catch (e) {
switch (e.code) {
case 'E_MODEL_NOT_REGISTERED': throw new Error('Consistency violation: '+e.message);
default: throw e;
}
}//</catch>
// βββββββββ βββββββ βββββββ βββ βββββββββββ ββββββββββββββ
// ββββββββββββββββββββββββββ βββ βββββββββββ ββββββββββββββ
// βββ βββ ββββββββββββββββββββ ββββββ βββ βββββββββ βββ
// βββ βββ ββββββββββ βββββββββ ββββββ ββββ ββββββββββ βββ
// βββ ββββββββββββ ββββββββββββββββ βββββββ ββββββββββββββββ
// βββ βββββββ βββ ββββββββββββββββ βββββ ββββββββββββββββ
//
// ββββββββ ββββββ ββββ ββββββββββββββββββββββββββ ββββββ ββββββββββββ βββββββ ββββ βββ
// βββββββββββββββββββββ ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ βββ
// ββββββββββββββββββββββ ββββββ βββ βββ βββββ ββββββββ βββ ββββββ βββββββββ βββ
// βββββββββββββββββββββββββββββ βββ βββ βββββ ββββββββ βββ ββββββ βββββββββββββ
// βββββββββββ ββββββ βββββββββ βββ ββββββββββββββ βββ βββ βββββββββββββββ ββββββ
// βββββββββββ ββββββ ββββββββ βββ ββββββββββββββ βββ βββ βββ βββββββ βββ βββββ
//
// ββββββββ¦βββββββββ¦ββ¦ββ β¦β¦ β¦ββ¦ββ¦ β¦ (COMPATIBILITY)
// β β βββββ βββ ββ£ β ββ β©βββ β β ββ¦β
// βββββββ© β©β© β© β© β© β©ββββ©β©βββ© β© β©
// ββ ββ¬ββββββββ¬ β¬ β¬β¬ βββββββ¬ ββββββ β¬ β¬βββ ββ¬ββ¬ββββββ βββββββ¬ βββββββ¬ β¬ ββ
// ββββ β β βββββ βββββ ββ€ βββ€β βββββ€ βββββββ ββββββββ ββ€ βββ€β βββββ€ ββ¬β ββββ
// ββ β΄ ββββ΄ β΄ββββ β΄ββ β β΄ β΄β΄ββββββββ ββ βββo β΄ β΄β΄ββββββ β β΄ β΄β΄ββββββββ β΄ ββ
// If criteria is `false`, then we take that to mean that this is a special reserved
// criteria (Γ) that will never match any records.
if (criteria === false) {
throw flaverr('E_WOULD_RESULT_IN_NOTHING', new Error(
'In previous versions of Waterline, a criteria of `false` indicated that '+
'the specified query should simulate no matches. Now, it is up to the method. '+
'Be aware that support for using `false` in userland criterias may be completely '+
'removed in a future release of Sails/Waterline.'
));
}//-β’
// If criteria is otherwise falsey (false, null, empty string, NaN, zero, negative zero)
// then understand it to mean the empty criteria (`{}`), which simulates ALL matches.
// Note that backwards-compatible support for this could be removed at any time!
if (!criteria) {
console.warn(
'Deprecated: In previous versions of Waterline, the specified criteria '+
'(`'+util.inspect(criteria,{depth:5})+'`) would match ALL records in '+
'this model. If that is what you are intending to happen, then please pass '+
'in `{}` instead, or simply omit the `criteria` dictionary altogether-- both of '+
'which are more explicit and future-proof ways of doing the same thing.\n'+
'> Warning: This backwards compatibility will be removed\n'+
'> in a future release of Sails/Waterline. If this usage\n'+
'> is left unchanged, then queries like this one will eventually \n'+
'> fail with an error.'
);
criteria = {};
}//>-
// βββββββ¬ββββ¬βββββ¬ β¬ββββββ ββββ¦βββ¦ β¦ ββββ¬ββ β¦βββ ββββ¬ β¬ββββ¬ββββ¬ββ¬ β¬ββββββββ¬β
// ββββ βββ¬βββββββ€β ββββββ€ β βββ β©βββββ β βββ¬β ββββ ββββββ€β βββ¬β β βββ€βββ€βββ ββ
// βββββββ΄βββ΄ β΄β΄ β΄β΄βββ΄ββββββ β© β© β© ββ ββββ΄ββ β©βββ ββββ΄ β΄ββββ΄ββ β΄ β΄ β΄β΄ β΄βββββ΄β
// ββ ββ¬ββββββββ¬ β¬ β¬β¬ βββββ¬ββ¬ββ ββββ¬ β¬ββ¬β ββββ¬ββ ββββ¬βββ¬ββββββ¬ β¬ ββ
// ββββ β β βββββ βββββ βββ β ββ¬β ββββ ββββ β βββ¬β βββ€ββ¬βββ¬ββββ€ββ¬β ββββ
// ββ β΄ ββββ΄ β΄ββββ β΄ββ βββ β΄ β΄βββ βββββββ΄ β΄β ββββ΄ββ β΄ β΄β΄βββ΄βββ΄ β΄ β΄ ββ
//
// If the provided criteria is an array, string, or number, then we'll be able
// to understand it as a primary key, or as an array of primary key values.
if (_.isArray(criteria) || _.isNumber(criteria) || _.isString(criteria)) {
var topLvlPkValuesOrPkValue = criteria;
// So expand that into the beginnings of a proper criteria dictionary.
// (This will be further normalized throughout the rest of this file--
// this is just enough to get us to where we're working with a dictionary.)
criteria = {};
criteria.where = {};
criteria.where[WLModel.primaryKey] = topLvlPkValuesOrPkValue;
}//>-
// β¬ β¬ββββ¬βββ¬ββββ¬ β¬ ββββ¦βββββββ¦ ββ¬βββββββ β¬ β¬ β¬β¬ ββ¬ββββββ¬ββββ ββ¬ββ¬ β¬ββββββ
// ββββββ€ ββ¬ββββ€ ββ¬β β β£ βββββ ββ£β β β ββββββββ βββββ βββββ€ β βββ€ β ββ¬ββββββ€
// ββ ββββ΄βββ΄β β΄ β β©ββββ© β©β©ββ β΄ ββββ΄ β΄ββββ β΄ββ ββ΄ββ΄ β΄ β΄ β΄ β΄ β΄ β΄ β΄ βββ
//
// IWMIH and the provided criteria is anything OTHER than a proper dictionary,
// (e.g. if it's a function or regexp or something) then that means it is invalid.
if (!_.isObject(criteria) || _.isArray(criteria) || _.isFunction(criteria)){
throw flaverr('E_HIGHLY_IRREGULAR', new Error('The provided criteria is invalid. Should be a dictionary (plain JavaScript object), but instead got: '+util.inspect(criteria, {depth:5})+''));
}//-β’
// ββββββββ¦βββββββββ¦ββ¦ββ β¦β¦ β¦ββ¦ββ¦ β¦ (COMPATIBILITY)
// β β βββββ βββ ββ£ β ββ β©βββ β β ββ¦β
// βββββββ© β©β© β© β© β© β©ββββ©β©βββ© β© β©
// ββββββββββ¬βββββββββββββ¬ββ¬βββββββββ β¬ β¬ββββ¬βββ¬ββ ββ¬ββ¬ββββββββββ¬ββββββββββ¬ββ¬ β¬ β¬ βββββββ¬ β¬
// βββ€β β¬β β¬ββ¬βββ€ β β¬βββ€ β ββ βββββββ ββββ βββ¬βββ΄β βββββ€ ββ€ ββ€ ββ¬βββ€ βββ β β ββ¬β ββββ ββββ
// β΄ β΄βββββββ΄βββββββββ΄ β΄ β΄ β΄βββββββββ ββ΄βββββ΄βββ΄ β΄ ββ΄ββ΄β β ββββ΄ββββββββ β΄ β΄βββ΄ ββββββββ΄β
//
// If we see `sum`, `average`, `min`, `max`, or `groupBy`, throw a
// fatal error to explain what's up, and also to suggest a suitable
// alternative.
//
// > Support for basic aggregations via criteria clauses was removed
// > in favor of new model methods in Waterline v0.13. Specifically
// > for `min`, `max`, and `groupBy`, for which there are no new model
// > methods, we recommend using native queries (aka "stage 5 queries").
// > (Note that, in the future, you will also be able to do the same thing
// > using Waterline statements, aka "stage 4 queries". But as of Nov 2016,
// > they only support the basic aggregations: count, sum, and avg.)
if (!_.isUndefined(criteria.groupBy)) {
// ^^
// Note that `groupBy` comes first, since it might have been used in conjunction
// with the others (and if it was, you won't be able to do whatever it is you're
// trying to do using the approach suggested by the other compatibility errors
// below.)
throw new Error(
'The `groupBy` clause is no longer supported in Sails/Waterline.\n'+
'In previous versions, `groupBy` could be provided in a criteria '+
'to perform an aggregation query. But as of Sails v1.0/Waterline v0.13, the '+
'usage has changed. Now, to run aggregate queries using the `groupBy` operator, '+
'use a native query instead.\n'+
'\n'+
'Alternatively, if you are using `groupBy` as a column/attribute name then '+
'please be advised that some things won\'t work as expected.\n'+
'\n'+
'For more info, visit:\n'+
'http://sailsjs.com/docs/upgrading/to-v1.0'
);
}//-β’
if (!_.isUndefined(criteria.sum)) {
throw new Error(
'The `sum` clause is no longer supported in Sails/Waterline.\n'+
'In previous versions, `sum` could be provided in a criteria '+
'to perform an aggregation query. But as of Sails v1.0/Waterline v0.13, the '+
'usage has changed. Now, to sum the value of an attribute across multiple '+
'records, use the `.sum()` model method.\n'+
'\n'+
'For example:\n'+
'```\n'+
'// Get the cumulative account balance of all bank accounts that '+'\n'+
'// have less than $32,000, or that are flagged as "suspended".'+'\n'+
'BankAccount.sum(\'balance\').where({'+'\n'+
' or: ['+'\n'+
' { balance: { \'<\': 32000 } },'+'\n'+
' { suspended: true }'+'\n'+
' ]'+'\n'+
'}).exec(function (err, total){'+'\n'+
' // ...'+'\n'+
'});'+'\n'+
'```\n'+
'Alternatively, if you are using `sum` as a column/attribute name then '+
'please be advised that some things won\'t work as expected.\n'+
'\n'+
'For more info, see:\n'+
'http://sailsjs.com/docs/reference/waterline-orm/models/sum'
);
}//-β’
if (!_.isUndefined(criteria.average)) {
throw new Error(
'The `average` clause is no longer supported in Sails/Waterline.\n'+
'In previous versions, `average` could be provided in a criteria '+
'to perform an aggregation query. But as of Sails v1.0/Waterline v0.13, the '+
'usage has changed. Now, to calculate the mean value of an attribute across '+
'multiple records, use the `.avg()` model method.\n'+
'\n'+
'For example:\n'+
'```\n'+
'// Get the average balance of bank accounts owned by people between '+'\n'+
'// the ages of 35 and 45.'+'\n'+
'BankAccount.avg(\'balance\').where({'+'\n'+
' ownerAge: { \'>=\': 35, \'<=\': 45 }'+'\n'+
'}).exec(function (err, averageBalance){'+'\n'+
' // ...'+'\n'+
'});'+'\n'+
'```\n'+
'Alternatively, if you are using `average` as a column/attribute name then '+
'please be advised that some things won\'t work as expected.\n'+
'\n'+
'For more info, see:\n'+
'http://sailsjs.com/docs/reference/waterline-orm/models/avg'
);
}//-β’
if (!_.isUndefined(criteria.min)) {
throw new Error(
'The `min` clause is no longer supported in Sails/Waterline.\n'+
'In previous versions, `min` could be provided in a criteria '+
'to perform an aggregation query. But as of Sails v1.0/Waterline v0.13, the '+
'usage has changed. Now, to calculate the minimum value of an attribute '+
'across multiple records, use the `.find()` model method.\n'+
'\n'+
'For example:\n'+
'```\n'+
'// Get the smallest account balance from amongst all account holders '+'\n'+
'// between the ages of 35 and 45.'+'\n'+
'BankAccount.find(\'balance\').where({'+'\n'+
' ownerAge: { \'>=\': 35, \'<=\': 45 }'+'\n'+
'})'+'\n'+
'.limit(1)'+'\n'+
'.select([\'balance\'])'+'\n'+
'.sort(\'balance ASC\')'+'\n'+
'}).exec(function (err, relevantAccounts){'+'\n'+
' // ...'+'\n'+
' var minBalance;'+'\n'+
' if (relevantAccounts[0]) {'+'\n'+
' minBalance = relevantAccounts[0].balance;'+'\n'+
' }'+'\n'+
' else {'+'\n'+
' minBalance = null;'+'\n'+
' }'+'\n'+
'});'+'\n'+
'```\n'+
'Alternatively, if you are using `min` as a column/attribute name then '+
'please be advised that some things won\'t work as expected.\n'+
'\n'+
'For more info, see:\n'+
'http://sailsjs.com/docs/reference/waterline-orm/models/find'
);
}//-β’
if (!_.isUndefined(criteria.max)) {
throw new Error(
'The `max` clause is no longer supported in Sails/Waterline.\n'+
'In previous versions, `max` could be provided in a criteria '+
'to perform an aggregation query. But as of Sails v1.0/Waterline v0.13, the '+
'usage has changed. Now, to calculate the maximum value of an attribute '+
'across multiple records, use the `.find()` model method.\n'+
'\n'+
'For example:\n'+
'```\n'+
'// Get the largest account balance from amongst all account holders '+'\n'+
'// between the ages of 35 and 45.'+'\n'+
'BankAccount.find(\'balance\').where({'+'\n'+
' ownerAge: { \'>=\': 35, \'<=\': 45 }'+'\n'+
'})'+'\n'+
'.limit(1)'+'\n'+
'.select([\'balance\'])'+'\n'+
'.sort(\'balance DESC\')'+'\n'+
'}).exec(function (err, relevantAccounts){'+'\n'+
' // ...'+'\n'+
' var maxBalance;'+'\n'+
' if (relevantAccounts[0]) {'+'\n'+
' maxBalance = relevantAccounts[0].balance;'+'\n'+
' }'+'\n'+
' else {'+'\n'+
' maxBalance = null;'+'\n'+
' }'+'\n'+
'});'+'\n'+
'```\n'+
'Alternatively, if you are using `max` as a column/attribute name then '+
'please be advised that some things won\'t work as expected.\n'+
'\n'+
'For more info, see:\n'+
'http://sailsjs.com/docs/reference/waterline-orm/models/find'
);
}//-β’
// β¬ β¬ββββββββ¬ββ¬ βββ β¦ββ¦βββββ¦ β¦ββββ¦ββ¦β β¦ β¦β¦ β¦ββββ¦βββββ ββββ¦ ββββ¦ β¦ββββββ
// βββ€βββ€βββ βββ ββ€ βββββ βββ ββ β β ββββ ββ£ββ£ β β¦βββ£ β β β ββ£β ββββββ£
// β΄ β΄β΄ β΄βββββ΄ββ΄βββββ β©β© β©β© β©βββ©ββββ© β© ββ©ββ© β©ββββ©βββββ ββββ©βββ© β©βββββββββ
//
// Now, if the provided criteria dictionary DOES NOT contain the names of ANY
// known criteria clauses (like `where`, `limit`, etc.) as properties, then we
// can safely assume that it is relying on shorthand: i.e. simply specifying what
// would normally be the `where` clause, but at the top level.
var recognizedClauses = _.intersection(_.keys(criteria), NAMES_OF_RECOGNIZED_CLAUSES);
if (recognizedClauses.length === 0) {
criteria = {
where: criteria
};
}
// Otherwise, it DOES contain a recognized clause keyword.
else {
// In which case... well, there's nothing else to do just yet.
//
// > Note: a little ways down, we do a check for any extraneous properties.
// > That check is important, because mixed criterias like `{foo: 'bar', limit: 3}`
// > _were_ supported in previous versions of Waterline, but they are not anymore.
}//>-
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// ββββββββ¦βββββββββ¦ββ¦ββ β¦β¦ β¦ββ¦ββ¦ β¦ (COMPATIBILITY)
// β β βββββ βββ ββ£ β ββ β©βββ β β ββ¦β
// βββββββ© β©β© β© β© β© β©ββββ©β©βββ© β© β©
// ββ βββββββ¬βββ¬ β¬ββ ββββββββββ¦ β¦β¦ βββββ¦ββββ β¬ ββββββββββ¦ β¦β¦ βββββ¦βββββββ ββ
// ββββ ββββ ββ¬ββ βββ΄β β βββ ββ βββ ββ β ββ£ β ββ£ ββΌβ β βββ ββ βββ ββ β ββ£ β ββ£ βββ ββββ
// ββ βββββββ΄ββββββββ β© ββββ© ββββ©βββ© β© β© βββ ββ β© ββββ© ββββ©βββ© β© β© ββββββ ββ
//
// - - - - - - - - - - - - -
// NOTE:
// Leaving this stuff commented out, because we should really just break
// backwards-compatibility here. If either of these properties are used,
// they are caught below by the unrecognized property check.
//
// This was not documented, and so hopefully was not widely used. If you've
// got feedback on that, hit up @particlebanana or @mikermcneil on Twitter.
// - - - - - - - - - - - - -
// ```
// // For compatibility, tolerate the presence of `.populate` or `.populates` on the
// // criteria dictionary (but scrub those suckers off right away).
// delete criteria.populate;
// delete criteria.populates;
// ```
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// ββββ¬ββββββ¬ β¬ββββββββ¬β βββββ β¦ββ¦ββ¦βββββββββββββββ¦ β¦βββ ββββ¦ββββββββββββ¦ββββ¦ββ¦ββββββ
// βββββ¬βββ€ ββββββ€ βββ β ββ£ ββ©β¦β β β β¦ββ ββ£βββββ£ β ββ ββββ β βββ β¦ββ ββ ββββ£ β β¦β β βββ£ βββ
// β΄ β΄βββββ ββ ββββββ β΄ ββββ© ββ β© β©βββ© β©βββββββββββββββ β© β©ββββββ© ββββ©ββ β© β©ββββββ
//
// Now that we've handled the "implicit `where`" case, make sure all remaining
// top-level keys on the criteria dictionary match up with recognized criteria
// clauses.
_.each(_.keys(criteria), function(clauseName) {
var clauseDef = criteria[clauseName];
// If this is NOT a recognized criteria clause...
var isRecognized = _.contains(NAMES_OF_RECOGNIZED_CLAUSES, clauseName);
if (!isRecognized) {
// Then, check to see if the RHS is `undefined`.
// If so, just strip it out and move on.
if (_.isUndefined(clauseDef)) {
delete criteria[clauseName];
return;
}//-β’
// Otherwise, this smells like a mistake.
// It's at least highly irregular, that's for sure.
throw flaverr('E_HIGHLY_IRREGULAR', new Error(
'The provided criteria contains an unrecognized property: '+
util.inspect(clauseName, {depth:5})+'\n'+
'* * *\n'+
'In previous versions of Sails/Waterline, this criteria _may_ have worked, since '+
'keywords like `limit` were allowed to sit alongside attribute names that are '+
'really supposed to be wrapped inside of the `where` clause. But starting in '+
'Sails v1.0/Waterline 0.13, if a `limit`, `skip`, `sort`, etc is defined, then '+
'any <attribute name> vs. <constraint> pairs should be explicitly contained '+
'inside the `where` clause.\n'+
'* * *'
));
}//-β’
// Otherwise, we know this must be a recognized criteria clause, so we're good.
// (We'll check it out more carefully in just a sec below.)
return;
});//</ _.each() :: each top-level property on the criteria >
// βββ ββββββ ββββββββββββββββββ ββββββββ
// βββ ββββββ βββββββββββββββββββββββββββ
// βββ ββ βββββββββββββββββ ββββββββββββββ
// ββββββββββββββββββββββββ ββββββββββββββ
// βββββββββββββ ββββββββββββββ βββββββββββ
// ββββββββ βββ ββββββββββββββ βββββββββββ
//
try {
criteria.where = normalizeWhereClause(criteria.where, modelIdentity, orm, meta);
} catch (e) {
switch (e.code) {
case 'E_WHERE_CLAUSE_UNUSABLE':
throw flaverr('E_HIGHLY_IRREGULAR', new Error(
'Could not use the provided `where` clause. '+ e.message
));
case 'E_WOULD_RESULT_IN_NOTHING':
throw e;
// If no error code (or an unrecognized error code) was specified,
// then we assume that this was a spectacular failure do to some
// kind of unexpected, internal error on our part.
default:
throw new Error('Consistency violation: Unexpected error normalizing/validating the `where` clause: '+e.stack);
}
}//>-β’
// βββ βββββββ ββββββββββββββββ
// βββ ββββββββ βββββββββββββββββ
// βββ βββββββββββββββββ βββ
// βββ βββββββββββββββββ βββ
// ββββββββββββββ βββ ββββββ βββ
// ββββββββββββββ ββββββ βββ
// Validate/normalize `limit` clause.
// ββ¦βββββββββββ¦ β¦β¦ ββ¦β β¬ β¬ββ¬ββ¬ββ¬β
// ββββ£ β β£ β ββ£β ββ β β βββββ β
// ββ©βββββ β© β©ββββ©βββ© β΄βββ΄β΄ β΄β΄ β΄
// If no `limit` clause was provided, give it a default value.
if (_.isUndefined(criteria.limit)) {
criteria.limit = (Number.MAX_SAFE_INTEGER||9007199254740991);
}//>-
// βββββββ¦ββββββββ ββββ¬βββββββ¬β βββββ¦ββ¦βββ¦ββββββ
// β βββ ββ£β β¦ββββββ£ ββ€ ββ¬ββ ββββ βββ β β β¦ββββββ β¦
// β© β© β©β©ββββββββ β β΄ββββββ΄ β΄ βββ β© β©βββ©ββββββ
// If the provided `limit` is a string, attempt to parse it into a number.
if (_.isString(criteria.limit)) {
criteria.limit = +criteria.limit;
}//>-β’
// ββββββββ¦βββββββββ¦ββ¦ββ β¦β¦ β¦ββ¦ββ¦ β¦ (COMPATIBILITY)
// β β βββββ βββ ββ£ β ββ β©βββ β β ββ¦β
// βββββββ© β©β© β© β© β© β©ββββ©β©βββ© β© β©
// ββ ββββ¬ β¬β¬ β¬ β¬βββββββ¬ββββ¬ββ¬ββ¬ β¬ βββββββ¬βββββ
// ββββ ββββ ββ β ββββββ€ βββββ β ββ¬β βββββ€ ββ¬ββ β
// ββ βββββββ΄βββ΄βββ β΄ββββ β΄ββββ΄ β΄ β΄β βββββββ΄ββββββ
// β¬ ββββββββββββββ¬ββ¬β¬ β¬βββ ββββ¬ β¬ββ¬βββ ββββ¬βββββ ββ
// ββΌβ βββββ€ β β¬βββ€ β βββββββ€ ββββ ββββββ΄βββ€ ββ¬ββββ ββββ
// ββ ββββββββββ΄ β΄ β΄ β΄ ββ βββ βββββββ΄ β΄βββββββ΄βββββ ββ
// For convenience/compatibility, we also tolerate `null` and `Infinity`,
// and understand them to mean the same thing.
if (_.isNull(criteria.limit) || criteria.limit === Infinity) {
criteria.limit = (Number.MAX_SAFE_INTEGER||9007199254740991);
}//>-
// If limit is zero, then that means we'll be returning NO results.
if (criteria.limit === 0) {
throw flaverr('E_WOULD_RESULT_IN_NOTHING', new Error('A criteria with `limit: 0` will never actually match any records.'));
}//-β’
// If limit is less than zero, then use the default limit.
// (But log a deprecation message.)
if (criteria.limit < 0) {
console.warn(
'Deprecated: In previous versions of Waterline, the specified `limit` '+
'(`'+util.inspect(criteria.limit,{depth:5})+'`) would work the same '+
'as if you had omitted the `limit` altogether-- i.e. defaulting to `Number.MAX_SAFE_INTEGER`. '+
'If that is what you are intending to happen, then please just omit `limit` instead, which is '+
'a more explicit and future-proof way of doing the same thing.\n'+
'> Warning: This backwards compatibility will be removed\n'+
'> in a future release of Sails/Waterline. If this usage\n'+
'> is left unchanged, then queries like this one will eventually \n'+
'> fail with an error.'
);
criteria.limit = (Number.MAX_SAFE_INTEGER||9007199254740991);
}//>-
// β¬ β¬ββββ¬βββ¬ββββ¬ β¬ ββ¬ββ¬ β¬βββββ¬β β¬ β¬ββ¬ββ¬ββ¬β β¬βββ βββββββ¬ β¬
// ββββββ€ ββ¬ββββ€ ββ¬β β βββ€βββ€ β β βββββ β ββββ ββββ ββββ
// ββ ββββ΄βββ΄β β΄ β΄ β΄ β΄β΄ β΄ β΄ β΄βββ΄β΄ β΄β΄ β΄ β΄βββ ββββββββ΄β
// βββ ββββββββββββ ββββββββ¦ββ¦ β¦β¦ββββββ¦ ββββ¦ β¦ββ¦βββ ββββ¦ββ
// βββ€ ββββ ββ£β β£ ββ£ ββββ ββ£ β β ββ β¦ββ ββ£β ββββ βββββ β©βββ£ β β¦β
// β΄ β΄ ββββ© β©β ββββ ββββ© β© β© ββββ©βββ© β©β©ββ βββββββ© β©βββββββ©ββ
// At this point, the `limit` should be a safe, natural number.
// But if that's not the case, we say that this criteria is highly irregular.
//
// > Remember, if the limit happens to have been provided as `Infinity`, we
// > already handled that special case above, and changed it to be
// > `Number.MAX_SAFE_INTEGER` instead (which is a safe, natural number).
if (!isSafeNaturalNumber(criteria.limit)) {
throw flaverr('E_HIGHLY_IRREGULAR', new Error(
'The `limit` clause in the provided criteria is invalid. '+
'If provided, it should be a safe, natural number. '+
'But instead, got: '+
util.inspect(criteria.limit, {depth:5})+''
));
}//-β’
// βββββββββββ βββββββββββββ
// βββββββββββ βββββββββββββββ
// βββββββββββββββ βββββββββββ
// βββββββββββββββ ββββββββββ
// βββββββββββ βββββββββ
// βββββββββββ βββββββββ
//
// Validate/normalize `skip` clause.
// ββ¦βββββββββββ¦ β¦β¦ ββ¦β
// ββββ£ β β£ β ββ£β ββ β
// ββ©βββββ β© β©ββββ©βββ©
// If no `skip` clause was provided, give it a default value.
if (_.isUndefined(criteria.skip)) {
criteria.skip = 0;
}//>-
// βββββββ¦ββββββββ ββββ¬βββββββ¬β βββββ¦ββ¦βββ¦ββββββ
// β βββ ββ£β β¦ββββββ£ ββ€ ββ¬ββ ββββ βββ β β β¦ββββββ β¦
// β© β© β©β©ββββββββ β β΄ββββββ΄ β΄ βββ β© β©βββ©ββββββ
// If the provided `skip` is a string, attempt to parse it into a number.
if (_.isString(criteria.skip)) {
criteria.skip = +criteria.skip;
}//>-β’
// β¬ β¬ββββ¬βββ¬ββββ¬ β¬ ββ¬ββ¬ β¬βββββ¬β ___ β¬βββ βββββββ¬ β¬
// ββββββ€ ββ¬ββββ€ ββ¬β β βββ€βββ€ β | | ββββ ββββ ββββ
// ββ ββββ΄βββ΄β β΄ β΄ β΄ β΄β΄ β΄ β΄ | | β΄βββ ββββββββ΄β
// βββ ββββββββββββ ββββββββ¦ββ¦ β¦β¦ββββββ¦ ββββ¦ β¦ββ¦βββ ββββ¦ββ
// βββ€ ββββ ββ£β β£ ββ£ ββββ ββ£ β β ββ β¦ββ ββ£β ββββ βββββ β©βββ£ β β¦β (OR zero)
// β΄ β΄ ββββ© β©β ββββ ββββ© β© β© ββββ©βββ© β©β©ββ βββββββ© β©βββββββ©ββ
// At this point, the `skip` should be either zero or a safe, natural number.
// But if that's not the case, we say that this criteria is highly irregular.
if (criteria.skip === 0) { /* skip: 0 is valid */ }
else if (isSafeNaturalNumber(criteria.skip)) { /* any safe, natural number is a valid `skip` */ }
else {
throw flaverr('E_HIGHLY_IRREGULAR', new Error(
'The `skip` clause in the provided criteria is invalid. If provided, it should be either zero (0), or a safe, natural number (e.g. 4). But instead, got: '+
util.inspect(criteria.skip, {depth:5})+''
));
}//-β’
// ββββββββ βββββββ βββββββ βββββββββ
// ββββββββββββββββββββββββββββββββββ
// βββββββββββ βββββββββββ βββ
// βββββββββββ βββββββββββ βββ
// ββββββββββββββββββββ βββ βββ
// ββββββββ βββββββ βββ βββ βββ
//
// Validate/normalize `sort` clause.
try {
criteria.sort = normalizeSortClause(criteria.sort, modelIdentity, orm, meta);
} catch (e) {
switch (e.code) {
case 'E_SORT_CLAUSE_UNUSABLE':
throw flaverr('E_HIGHLY_IRREGULAR', new Error(
'Could not use the provided `sort` clause: ' + e.message
));
// If no error code (or an unrecognized error code) was specified,
// then we assume that this was a spectacular failure do to some
// kind of unexpected, internal error on our part.
default:
throw new Error('Consistency violation: Encountered unexpected internal error when attempting to normalize/validate a provided `sort` clause:\n```\n'+util.inspect(criteria.sort, {depth:5})+'```\nHere is the error:\n```'+e.stack+'\n```');
}
}//>-β’
// βββββββββββββββββββ ββββββββ ββββββββββββββββ
// βββββββββββββββββββ βββββββββββββββββββββββββ
// ββββββββββββββ βββ ββββββ βββ βββ
// ββββββββββββββ βββ ββββββ βββ βββ
// ββββββββββββββββββββββββββββββββββββββββ βββ
// ββββββββββββββββββββββββββββββββ βββββββ βββ
// Validate/normalize `select` clause.
// ββ¦βββββββββββ¦ β¦β¦ ββ¦β
// ββββ£ β β£ β ββ£β ββ β
// ββ©βββββ β© β©ββββ©βββ©
// If no `select` clause was provided, give it a default value.
if (_.isUndefined(criteria.select)) {
criteria.select = ['*'];
}//>-
// If specified as a string, wrap it up in an array.
if (_.isString(criteria.select)) {
criteria.select = [
criteria.select
];
}//>-
// At this point, we should have an array.
// If not, then we'll bail with an error.
if (!_.isArray(criteria.select)) {
throw flaverr('E_HIGHLY_IRREGULAR', new Error(
'The `select` clause in the provided criteria is invalid. If provided, it should be an array of strings. But instead, got: '+
util.inspect(criteria.select, {depth:5})+''
));
}//-β’
// Special handling of `['*']`.
//
// > In order for special meaning to take effect, array must have exactly one item (`*`).
// > (Also note that `*` is not a valid attribute name, so there's no chance of overlap there.)
if (_.isEqual(criteria.select, ['*'])) {
// ['*'] is always valid-- it is the default value for the `select` clause.
// So we don't have to do anything here.
}
// Otherwise, we must investigate further.
else {
// Ensure the primary key is included in the `select`.
// (If it is not, then add it automatically.)
//
// > Note that compatiblity with the `populates` query key is handled back in forgeStageTwoQuery().
if (!_.contains(criteria.select, WLModel.primaryKey)) {
criteria.select.push(WLModel.primaryKey);
}//>-
// If model is `schema: false`, then prevent using a custom `select` clause.
// (This is because doing so is not yet reliable.)
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// FUTURE: Fix this & then thoroughly test with normal finds and populated finds,
// with the select clause in the main criteria and the subcriteria, using both native
// joins and polypopulates.
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
if (WLModel.hasSchema === false) {
throw flaverr('E_HIGHLY_IRREGULAR', new Error(
'The provided criteria contains a custom `select` clause, but since this model (`'+modelIdentity+'`) '+
'is `schema: false`, this cannot be relied upon... yet. In the mean time, if you\'d like to use a '+
'custom `select`, configure this model to `schema: true`. Or, better yet, since this is usually an app-wide setting,'+
'configure all of your models to have `schema: true` -- e.g. in `config/models.js`. (Note that this WILL be supported in a '+
'future, minor version release of Sails/Waterline. Want to lend a hand? http://sailsjs.com/contribute)'
));
}//-β’
// Loop through array and check each attribute name.
_.each(criteria.select, function (attrNameToKeep){
// Try to look up the attribute def.
var attrDef;
try {
attrDef = getAttribute(attrNameToKeep, modelIdentity, orm);
} catch (e){
switch (e.code) {
case 'E_ATTR_NOT_REGISTERED':
// If no matching attribute is found, `attrDef` just stays undefined
// and we keep going.
break;
default: throw e;
}
}//</catch>
// If model is `schema: true`...
if (WLModel.hasSchema === true) {
// Make sure this matched a recognized attribute name.
if (!attrDef) {
throw flaverr('E_HIGHLY_IRREGULAR', new Error(
'The `select` clause in the provided criteria contains an item (`'+attrNameToKeep+'`) which is '+
'not a recognized attribute in this model (`'+modelIdentity+'`).'
));
}//-β’
}
// Else if model is `schema: false`...
else if (WLModel.hasSchema === false) {
// Make sure this is at least a valid name for a Waterline attribute.
if (!isValidAttributeName(attrNameToKeep)) {
throw flaverr('E_HIGHLY_IRREGULAR', new Error(
'The `select` clause in the provided criteria contains an item (`'+attrNameToKeep+'`) which is not '+
'a valid name for an attribute in Sails/Waterline.'
));
}//-β’
} else { throw new Error('Consistency violation: Every instantiated Waterline model should always have a `hasSchema` property as either `true` or `false` (should have been derived from the `schema` model setting when Waterline was being initialized). But somehow, this model (`'+modelIdentity+'`) ended up with `hasSchema: '+util.inspect(WLModel.hasSchema, {depth:5})+'`'); }
// Ensure that we're not trying to `select` a plural association.
// > That's never allowed, because you can only populate a plural association-- it's a virtual attribute.
// > Note that we also do a related check when we normalize the `populates` query key back in forgeStageTwoQuery().
if (attrDef && attrDef.collection) {
throw flaverr('E_HIGHLY_IRREGULAR', new Error(
'The `select` clause in the provided criteria contains an item (`'+attrNameToKeep+'`) which is actually '+
'the name of a plural ("collection") association for this model (`'+modelIdentity+'`). But you cannot '+
'explicitly select plural association because they\'re virtual attributes (use `.populate()` instead.)'
));
}//-β’
});//</ _.each() :: each attribute name >
// ββββ¬ β¬βββββββ¬ββ βββββββ¬ββ ββ¦ββ¦ β¦ββββ¦ β¦ββββββββ¦βββββββ
// β βββ€ββ€ β ββ΄β ββ€ β βββ¬β βββ ββ βββ ββ β ββ£ β ββ£ βββ
// ββββ΄ β΄βββββββ΄ β΄ β ββββ΄ββ ββ©βββββ© β©βββ©ββββ© β© β© ββββββ
// Ensure that no two items refer to the same attribute.
criteria.select = _.uniq(criteria.select);
}//>-β’ </ else (this is something other than ['*']) >
// βββββββ ββββ ββββββββββββββββ
// ββββββββββββββ βββββββββββββββββ
// βββ βββββββββββββββββ βββ
// βββ βββββββββββββββββ βββ
// ββββββββββββ βββ ββββββ βββ
// βββββββ βββ ββββββ βββ
// ββ¦βββββββββββ¦ β¦β¦ ββ¦β
// ββββ£ β β£ β ββ£β ββ β
// ββ©βββββ β© β©ββββ©βββ©
// If no `omit` clause was provided, give it a default value.
if (_.isUndefined(criteria.omit)) {
criteria.omit = [];
}//>-
// Verify that this is an array.
if (!_.isArray(criteria.omit)) {
throw flaverr('E_HIGHLY_IRREGULAR', new Error(
'The `omit` clause in the provided criteria is invalid. If provided, it should be an array of strings. But instead, got: '+
util.inspect(criteria.omit, {depth:5})+''
));
}//-β’
// Loop through array and check each attribute name.
_.remove(criteria.omit, function (attrNameToOmit){
// Verify this is a string.
if (!_.isString(attrNameToOmit)) {
throw flaverr('E_HIGHLY_IRREGULAR', new Error(
'The `omit` clause in the provided criteria is invalid. If provided, it should be an array of strings (attribute names to omit. But one of the items is not a string: '+
util.inspect(attrNameToOmit, {depth:5})+''
));
}//-β’
// If _explicitly_ trying to omit the primary key,
// then we say this is highly irregular.
//
// > Note that compatiblity with the `populates` query key is handled back in forgeStageTwoQuery().
if (attrNameToOmit === WLModel.primaryKey) {
throw flaverr('E_HIGHLY_IRREGULAR', new Error(
'The `omit` clause in the provided criteria explicitly attempts to omit the primary key (`'+WLModel.primaryKey+'`). But in the current version of Waterline, this is not possible.'
));
}//-β’
// Try to look up the attribute def.
var attrDef;
try {
attrDef = getAttribute(attrNameToOmit, modelIdentity, orm);
} catch (e){
switch (e.code) {
case 'E_ATTR_NOT_REGISTERED':
// If no matching attribute is found, `attrDef` just stays undefined
// and we keep going.
break;
default: throw e;
}
}//</catch>
// If model is `schema: true`...
if (WLModel.hasSchema === true) {
// Make sure this matched a recognized attribute name.
if (!attrDef) {
throw flaverr('E_HIGHLY_IRREGULAR', new Error(
'The `omit` clause in the provided criteria contains an item (`'+attrNameToOmit+'`) which is not a recognized attribute in this model (`'+modelIdentity+'`).'
));
}//-β’
}
// Else if model is `schema: false`...
else if (WLModel.hasSchema === false) {
// In this case, we just give up and throw an E_HIGHLY_IRREGULAR error here
// explaining what's up.
throw flaverr('E_HIGHLY_IRREGULAR', new Error(
'Cannot use `omit`, because the referenced model (`'+modelIdentity+'`) does not declare itself `schema: true`.'
));
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// FUTURE: double-check that there's not a reasonable way to do this in a way that
// supports both SQL and noSQL adapters.
//
// Best case, we get it to work for Mongo et al somehow, in which case we'd then
// also want to verify that each item is at least a valid Waterline attribute name here.
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
} else { throw new Error('Consistency violation: Every instantiated Waterline model should always have a `hasSchema` property as either `true` or `false` (should have been derived from the `schema` model setting when Waterline was being initialized). But somehow, this model (`'+modelIdentity+'`) ended up with `hasSchema: '+util.inspect(WLModel.hasSchema, {depth:5})+'`'); }
// >-β’
// Ensure that we're not trying to `omit` a plural association.
// If so, just strip it out.
//
// > Note that we also do a related check when we normalize the `populates` query key back in forgeStageTwoQuery().
if (attrDef && attrDef.collection) {
return true;
}//-β’
// Otherwise, we'll keep this item in the `omit` clause.
return false;
});//</_.remove() :: each specified attr name to omit>
// ββββ¬ β¬βββββββ¬ββ βββββββ¬ββ ββ¦ββ¦ β¦ββββ¦ β¦ββββββββ¦βββββββ
// β βββ€ββ€ β ββ΄β ββ€ β βββ¬β βββ ββ βββ ββ β ββ£ β ββ£ βββ
// ββββ΄ β΄βββββββ΄ β΄ β ββββ΄ββ ββ©βββββ© β©βββ©ββββ© β© β© ββββββ
// Ensure that no two items refer to the same attribute.
criteria.omit = _.uniq(criteria.omit);
// --β’ At this point, we know that both `select` AND `omit` are fully valid. So...
// ββββββββββ¬ β¬β¬βββββ βββββ¦ββ¦ββ¦β β¬ βββββββ¦ ββββββββ¦β ββ¬ββββ ββββββββ¬β ββββ¬ βββββββ¬ β¬
// ββ€ βββββββ βββ¬βββ€ β βββββ β ββΌβ βββββ£ β ββ£ β β βββ β ββββ β β β β βββ€ββββββ€
// βββββββββββββ΄βββββ ββββ© β©β© β© ββ βββββββ©ββββββββ β© ββ΄ββββ ββββββ β΄ ββββ΄βββ΄ β΄ββββ΄ β΄
// Make sure that `omit` and `select` are not BOTH specified as anything
// other than their default values. If so, then fail w/ an E_HIGHLY_IRREGULAR error.
var isNoopSelect = _.isEqual(criteria.select, ['*']);
var isNoopOmit = _.isEqual(criteria.omit, []);
if (!isNoopSelect && !isNoopOmit) {
throw flaverr('E_HIGHLY_IRREGULAR', new Error('Cannot specify both `omit` AND `select`. Please use one or the other.'));
}//-β’
// IWMIH and the criteria is somehow no longer a dictionary, then freak out.
// (This is just to help us prevent present & future bugs in this utility itself.)
var isCriteriaNowValidDictionary = _.isObject(criteria) && !_.isArray(criteria) && !_.isFunction(criteria);
if (!isCriteriaNowValidDictionary) {
throw new Error('Consistency violation: At this point, the criteria should have already been normalized into a dictionary! But instead somehow it looks like this: '+util.inspect(criteria, {depth:5})+'');
}
// Return the normalized criteria dictionary.
return criteria;
}; | normalizeCriteria()
Validate and normalize the provided value (`criteria`), hammering it destructively
into the standardized format suitable to be part of a "stage 2 query" (see ARCHITECTURE.md).
This allows us to present it in a normalized fashion to lifecycle callbacks, as well to
other internal utilities within Waterline.
Since the provided value _might_ be a string, number, or some other primitive that is
NOT passed by reference, this function has a return value: a dictionary (plain JavaScript object).
But realize that this is only to allow for a handful of edge cases. Most of the time, the
provided value will be irreversibly mutated in-place, AS WELL AS returned.
--
There are many criteria normalization steps performed by Waterline.
But this function only performs some of them.
It DOES:
(β’) validate the criteria's format (particularly the `where` clause)
(β’) normalize the structure of the criteria (particularly the `where` clause)
(β’) ensure defaults exist for `limit`, `skip`, `sort`, `select`, and `omit`
(β’) apply (logical, not physical) schema-aware validations and normalizations
It DOES NOT:
(x) transform attribute names to column names
(x) check that the criteria isn't trying to use features which are not supported by the adapter(s)
--
@param {Ref} criteria
The original criteria (i.e. from a "stage 1 query").
> WARNING:
> IN SOME CASES (BUT NOT ALL!), THE PROVIDED CRITERIA WILL
> UNDERGO DESTRUCTIVE, IN-PLACE CHANGES JUST BY PASSING IT
> IN TO THIS UTILITY.
@param {String} modelIdentity
The identity of the model this criteria is referring to (e.g. "pet" or "user")
> Useful for looking up the Waterline model and accessing its attribute definitions.
@param {Ref} orm
The Waterline ORM instance.
> Useful for accessing the model definitions.
@param {Dictionary?} meta
The contents of the `meta` query key, if one was provided.
> Useful for propagating query options to low-level utilities like this one.
--
@returns {Dictionary}
The successfully-normalized criteria, ready for use in a stage 2 query.
@throws {Error} If it encounters irrecoverable problems or unsupported usage in
the provided criteria, including e.g. an invalid constraint is specified
for an association.
@property {String} code
- E_HIGHLY_IRREGULAR
@throws {Error} If the criteria indicates that it should never match anything.
@property {String} code
- E_WOULD_RESULT_IN_NOTHING
@throws {Error} If anything else unexpected occurs. | normalizeCriteria ( criteria , modelIdentity , orm , meta ) | javascript | balderdashy/waterline | lib/waterline/utils/query/private/normalize-criteria.js | https://github.com/balderdashy/waterline/blob/master/lib/waterline/utils/query/private/normalize-criteria.js | MIT |
module.exports = function validate(attrName, value) {
// Verify `this` refers to an actual Sails/Waterline model.
verifyModelMethodContext(this);
// Set up a few, common local vars for convenience / familiarity.
var orm = this.waterline;
var modelIdentity = this.identity;
if (!_.isString(attrName)) {
throw flaverr({ name: 'UsageError' }, new Error(
'Please specify the name of the attribute to validate against (1st argument).'
));
}//-β’
var normalizedVal;
try {
normalizedVal = normalizeValueToSet(value, attrName, modelIdentity, orm);
} catch (e) {
switch (e.code) {
// If it is determined that this should be ignored, it's either because
// the attr is outside of the schema or the value is undefined. In this
// case, set it to `undefined` and then continue on ahead to the checks
// below.
case 'E_SHOULD_BE_IGNORED':
normalizedVal = undefined;
break;
// Violated the attribute's validation ruleset
case 'E_VIOLATES_RULES':
throw e;
// Failed requireness guarantee
case 'E_REQUIRED':
throw e;
// Failed type safety check
case 'E_TYPE':
throw e;
// Miscellaneous incompatibility
case 'E_HIGHLY_IRREGULAR':
throw e;
// Unexpected error
default:
throw e;
}
}//>-β’
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// FUTURE: expand this logic so that it can work like it does for `.create()`
// (in addition or instead of just working like it does for .update())
//
// That entails applying required and defaultsTo down here at the bottom,
// and figuring out what makes sense to do for the auto timestamps. Note
// that we'll also need to change the `false` flag above to `true` (the one
// we pass in to normalizeValueToSet)
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// Return normalized value.
return normalizedVal;
}; | validate()
Verify that a value would be valid for a given attribute, then return it, loosely coerced.
> Note that this validates the value in the same way it would be checked
> if it was passed in to an `.update()` query-- NOT a `.create()`!!
```
// Check the given string and return a normalized version.
var normalizedBalance = BankAccount.validate('balance', '349.86');
//=> 349.86
// Note that if normalization is not possible, this throws:
var normalizedBalance;
try {
normalizedBalance = BankAccount.validate('balance', '$349.86');
} catch (e) {
switch (e.code) {
case 'E_':
console.log(e);
// => '[Error: Invalid `bankAccount`]'
throw e;
default: throw e;
}
}
// IWMIH, then it was valid...although it may have been normalized a bit (potentially in-place).
```
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
@param {String} attrName
The name of the attribute to validate against.
@param {Ref} value
The value to validate/normalize.
--
@returns {Ref}
The successfully-normalized value. (MAY or MAY NOT be the same as the original reference.)
--
@throws {Error} If it encounters incompatible usage in the provided `value`,
including e.g. the case where an invalid value is specified for
an association.
@property {String} code
- E_HIGHLY_IRREGULAR
@throws {Error} If the provided `value` has an incompatible data type.
| @property {String} code
| - E_TYPE
| @property {String} expectedType
| - string
| - number
| - boolean
| - json
|
| This is only versus the attribute's declared "type", or other similar type safety issues --
| certain failed checks for associations result in a different error code (see above).
|
| Remember:
| This is the case where a _completely incorrect type of data_ was passed in.
| This is NOT a high-level "anchor" validation failure! (see below for that)
| > Unlike anchor validation errors, this exception should never be negotiated/parsed/used
| > for delivering error messages to end users of an application-- it is carved out
| > separately purely to make things easier to follow for the developer.
@throws {Error} If the provided `value` fails the requiredness guarantee of the corresponding attribute.
| @property {String} code
| - E_REQUIRED
@throws {Error} If the provided `value` violates one or more of the high-level validation rules
| configured for the corresponding attribute.
| @property {String} code
| - E_VIOLATES_RULES
| @property {Array} ruleViolations
| e.g.
| ```
| [
| {
| rule: 'minLength', //(isEmail/isNotEmptyString/max/isNumber/etc)
| message: 'Too few characters (max 30)'
| }
| ]
| ```
@throws {Error} If anything else unexpected occurs. | validate ( attrName , value ) | javascript | balderdashy/waterline | lib/waterline/methods/validate.js | https://github.com/balderdashy/waterline/blob/master/lib/waterline/methods/validate.js | MIT |
module.exports = function avg( /* numericAttrName?, criteria?, explicitCbMaybe?, meta?, moreQueryKeys? */ ) {
// Verify `this` refers to an actual Sails/Waterline model.
verifyModelMethodContext(this);
// Set up a few, common local vars for convenience / familiarity.
var WLModel = this;
var orm = this.waterline;
var modelIdentity = this.identity;
// Build an omen for potential use in the asynchronous callback below.
var omen = buildOmen(avg);
// Build query w/ initial, universal keys.
var query = {
method: 'avg',
using: modelIdentity
};
// βββ βββ ββββββ βββββββ βββ ββββββ βββββββ βββ βββββββββββββββ
// βββ βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// βββ βββββββββββββββββββββββββββββββββ βββββββββ ββββββββ
// ββββ ββββββββββββββββββββββββββββββββββ βββββββββ ββββββββ
// βββββββ βββ ββββββ βββββββββ ββββββββββββββββββββββββββββββ
// βββββ βββ ββββββ βββββββββ ββββββββββ βββ βββββββββββββββ
//
// The `explicitCbMaybe` callback, if one was provided.
var explicitCbMaybe;
// Handle the various supported usage possibilities
// (locate the `explicitCbMaybe` callback, and extend the `query` dictionary)
//
// > Note that we define `args` to minimize the chance of this "variadics" code
// > introducing any unoptimizable performance problems. For details, see:
// > https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#32-leaking-arguments
// > β’=> `.length` is just an integer, this doesn't leak the `arguments` object itself
// > β’=> `i` is always valid index in the arguments object
var args = new Array(arguments.length);
for (var i = 0; i < args.length; ++i) {
args[i] = arguments[i];
}
// β’ avg(numericAttrName, explicitCbMaybe, ..., ...)
if (args.length >= 2 && _.isFunction(args[1])) {
query.numericAttrName = args[0];
explicitCbMaybe = args[1];
query.meta = args[2];
if (args[3]) { _.extend(query, args[3]); }
}
// β’ avg(numericAttrName, criteria, ..., ..., ...)
else {
query.numericAttrName = args[0];
query.criteria = args[1];
explicitCbMaybe = args[2];
query.meta = args[3];
if (args[4]) { _.extend(query, args[4]); }
}
// Due to the somewhat unusual variadic usage of this method, and because
// parley doesn't enforce this itself for performance reasons, make sure the
// explicit callback argument is a function, if provided.
if (explicitCbMaybe !== undefined && !_.isFunction(explicitCbMaybe)) {
throw flaverr({
name: 'UsageError',
message:
'`.avg()` received an explicit callback function argument... but it '+
'was not a function: '+explicitCbMaybe
}, omen);
}//β’
// βββββββ βββββββββββββββββββββββββββββββ
// ββββββββββββββββββββββββββββββββββββββββ
// βββ βββββββββ ββββββ ββββββ ββββββββ
// βββ βββββββββ ββββββ ββββββ ββββββββ
// βββββββββββββββββββ βββββββββββ βββ
// βββββββ βββββββββββ βββββββββββ βββ
//
// βββββββ ββββ ββββββ βββ ββββββββββ βββββββββββ
// βββββββββ βββββββββββββββββ ββββββββββββββββββββββββ
// βββ βββββββββββββββββββ βββββββ ββββββββββββββ βββ
// βββ βββββββββββββββββββ βββββ ββββββββββββββ βββ
// βββββββ βββ ββββββ βββ βββ ββββββββββββββββββββ
// ββββββ ββββββ βββ βββ βββββββ βββββββββββ
//
// ββ β¬ β¬β¬β¬ ββ¬β β¬ β¬βββββββ¬ββ¬ β¬β¬βββββ βββββββ¬ β¬ ββ¬βββββββββββ¬βββ¬βββββββ¬β
// ββ΄ββ βββ ββ ββΌβ ββ¬βββ€ β β βββ¬ββββ βββββ€ βββ ββββ€ ββ€ ββ€ ββ¬βββ¬βββ€ ββ
// βββββββ΄β΄ββββ΄β ββ β΄βββββ β΄ ββββ΄βββββ ββββββββ΄β ββ΄βββββ ββββ΄βββ΄βββββββ΄β
// ββ β¬βββ β¬ββββββ¬ ββββ¬ β¬ββββββββ¬β ββ
// ββββ βββ€ ββ¬βββ€ β ββ€ βββββββ€βββ β ββββ
// ββ β΄β β΄ββββββ΄βββββ ββ β΄ β΄βββ β΄ ββ
// If an explicit callback function was specified, then immediately run the logic below
// and trigger the explicit callback when the time comes. Otherwise, build and return
// a new Deferred now. (If/when the Deferred is executed, the logic below will run.)
return parley(
function (done){
// Otherwise, IWMIH, we know that it's time to actually do some stuff.
// So...
//
// βββββββββββ βββββββββββ ββββββββββ ββββββββββββββββββββ
// βββββββββββββββββββββββββββββββββββ ββββββββββββββββββββ
// ββββββ ββββββ ββββββ βββ βββ βββ βββ ββββββ
// ββββββ ββββββ ββββββ βββ βββ βββ βββ ββββββ
// ββββββββββββ ββββββββββββββββββββββββββββ βββ ββββββββ
// βββββββββββ βββββββββββ βββββββ βββββββ βββ ββββββββ
// βββββββ¦ββββββββ βββββ¬ββββββββββ ββ¬ββ¬ β¬βββ βββ β¬ β¬ββββ¬βββ¬ β¬
// β β£ β ββ β¦ββ β¦ββ£ βββ β βββ€β β¬ββ€ β ββββ β βββΌββ βββ€ ββ¬βββ¬β
// β ββββ©ββββββββ βββ β΄ β΄ β΄ββββββ β΄ ββ΄ββββ βββββββββββ΄ββ β΄
//
// Forge a stage 2 query (aka logical protostatement)
try {
forgeStageTwoQuery(query, orm);
} catch (e) {
switch (e.code) {
case 'E_INVALID_NUMERIC_ATTR_NAME':
return done(
flaverr({
name: 'UsageError',
code: e.code,
details: e.details,
message:
'The numeric attr name (i.e. first argument) to `.avg()` should '+
'be the name of an attribute in this model which is defined with `type: \'number\'`.\n'+
'Details:\n'+
' ' + e.details + '\n'
}, omen)
);
// ^ custom override for the standard usage error. Note that we use `.details` to get at
// the underlying, lower-level error message (instead of logging redundant stuff from
// the envelope provided by the default error msg.)
// If the criteria wouldn't match anything, that'd basically be like dividing by zero, which is impossible.
case 'E_NOOP':
return done(
flaverr({
name: 'UsageError',
code: e.code,
details: e.details,
message:
'Attempting to compute this average would be like dividing by zero, which is impossible.\n'+
'Details:\n'+
' ' + e.details + '\n'
}, omen)
);
case 'E_INVALID_CRITERIA':
case 'E_INVALID_META':
return done(
flaverr({
name: 'UsageError',
code: e.code,
details: e.details,
message: e.message
}, omen)
);
// ^ when the standard usage error message is good enough as-is, without any further customization
default:
return done(e);
// ^ when an internal, miscellaneous, or unexpected error occurs
}
} // >-β’
// βββββββ¦ββββββββ βββββ¬ββββββββββ ββ¬ββ¬ β¬β¬ββββββββ βββ β¬ β¬ββββ¬βββ¬ β¬
// β β£ β ββ β¦ββ β¦ββ£ βββ β βββ€β β¬ββ€ β βββ€ββ¬βββ€ ββ€ βββΌββ βββ€ ββ¬βββ¬β
// β ββββ©ββββββββ βββ β΄ β΄ β΄ββββββ β΄ β΄ β΄β΄ββββββββ βββββββββββ΄ββ β΄
try {
query = forgeStageThreeQuery({
stageTwoQuery: query,
identity: modelIdentity,
transformer: WLModel._transformer,
originalModels: orm.collections
});
} catch (e) { return done(e); }
// βββββββββββ¬β ββ¬ββββ βββββ¦βββββββββ¦βββββ¦ββ
// βββββ€ βββ ββ β β β β ββ£ βββ ββ£β ββ β ββ£ β β¦β
// βββββββββββ΄β β΄ βββ β© β©ββ©ββ© β©β© β© ββββ©ββ
// Grab the appropriate adapter method and call it.
var adapter = WLModel._adapter;
if (!adapter.avg) {
return done(new Error('The adapter used by this model (`' + modelIdentity + '`) doesn\'t support the `'+query.method+'` method.'));
}
adapter.avg(WLModel.datastore, query, function _afterTalkingToAdapter(err, arithmeticMean) {
if (err) {
err = forgeAdapterError(err, omen, 'avg', modelIdentity, orm);
return done(err);
}//-β’
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// FUTURE: Log a warning like the ones in `process-all-records` if
// the arithmeticMean sent back by the adapter turns out to be something
// other than a number (for example, the naive behavior of a MySQL adapter
// in circumstances where criteria does not match any records); i.e.
// ```
// !_.isNumber(arithmeticMean) || arithmeticMean === Infinity || arithmeticMean === -Infinity || _.isNaN(arithmeticMean)
// ````
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
return done(undefined, arithmeticMean);
});//</adapter.avg()>
},
explicitCbMaybe,
_.extend(DEFERRED_METHODS, {
// Provide access to this model for use in query modifier methods.
_WLModel: WLModel,
// Set up initial query metadata.
_wlQueryInfo: query,
})
);//</parley>
}; | avg()
Get the arithmetic mean of the specified attribute across all matching records.
```
// The average balance of bank accounts owned by people between
// the ages of 35 and 45.
BankAccount.avg('balance').where({
ownerAge: { '>=': 35, '<=': 45 }
}).exec(function (err, averageBalance){
// ...
});
```
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Usage without deferred object:
================================================
@param {String?} numericAttrName
@param {Dictionary?} criteria
@param {Function?} explicitCbMaybe
Callback function to run when query has either finished successfully or errored.
(If unspecified, will return a Deferred object instead of actually doing anything.)
@param {Ref?} meta
For internal use.
@param {Dictionary} moreQueryKeys
For internal use.
(A dictionary of query keys.)
@returns {Ref?} Deferred object if no `explicitCbMaybe` callback was provided
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
The underlying query keys:
==============================
@qkey {String} numericAttrName
The name of a numeric attribute.
(Must be declared as `type: 'number'`.)
@qkey {Dictionary?} criteria
@qkey {Dictionary?} meta
@qkey {String} using
@qkey {String} method
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | avg ( ) | javascript | balderdashy/waterline | lib/waterline/methods/avg.js | https://github.com/balderdashy/waterline/blob/master/lib/waterline/methods/avg.js | MIT |
module.exports = function sum( /* numericAttrName?, criteria?, explicitCbMaybe?, meta?, moreQueryKeys? */ ) {
// Verify `this` refers to an actual Sails/Waterline model.
verifyModelMethodContext(this);
// Set up a few, common local vars for convenience / familiarity.
var WLModel = this;
var orm = this.waterline;
var modelIdentity = this.identity;
// Build an omen for potential use in the asynchronous callback below.
var omen = buildOmen(sum);
// Build query w/ initial, universal keys.
var query = {
method: 'sum',
using: modelIdentity
};
// βββ βββ ββββββ βββββββ βββ ββββββ βββββββ βββ βββββββββββββββ
// βββ βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// βββ βββββββββββββββββββββββββββββββββ βββββββββ ββββββββ
// ββββ ββββββββββββββββββββββββββββββββββ βββββββββ ββββββββ
// βββββββ βββ ββββββ βββββββββ ββββββββββββββββββββββββββββββ
// βββββ βββ ββββββ βββββββββ ββββββββββ βββ βββββββββββββββ
//
// The `explicitCbMaybe` callback, if one was provided.
var explicitCbMaybe;
// Handle the various supported usage possibilities
// (locate the `explicitCbMaybe` callback, and extend the `query` dictionary)
//
// > Note that we define `args` to minimize the chance of this "variadics" code
// > introducing any unoptimizable performance problems. For details, see:
// > https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#32-leaking-arguments
// > β’=> `.length` is just an integer, this doesn't leak the `arguments` object itself
// > β’=> `i` is always valid index in the arguments object
var args = new Array(arguments.length);
for (var i = 0; i < args.length; ++i) {
args[i] = arguments[i];
}
// β’ sum(numericAttrName, explicitCbMaybe, ..., ...)
if (args.length >= 2 && _.isFunction(args[1])) {
query.numericAttrName = args[0];
explicitCbMaybe = args[1];
query.meta = args[2];
if (args[3]) { _.extend(query, args[3]); }
}
// β’ sum(numericAttrName, criteria, ..., ..., ...)
else {
query.numericAttrName = args[0];
query.criteria = args[1];
explicitCbMaybe = args[2];
query.meta = args[3];
if (args[4]) { _.extend(query, args[4]); }
}
// Due to the somewhat unusual variadic usage of this method, and because
// parley doesn't enforce this itself for performance reasons, make sure the
// explicit callback argument is a function, if provided.
if (explicitCbMaybe !== undefined && !_.isFunction(explicitCbMaybe)) {
throw flaverr({
name: 'UsageError',
message:
'`.sum()` received an explicit callback function argument... but it '+
'was not a function: '+explicitCbMaybe
}, omen);
}//β’
// βββββββ βββββββββββββββββββββββββββββββ
// ββββββββββββββββββββββββββββββββββββββββ
// βββ βββββββββ ββββββ ββββββ ββββββββ
// βββ βββββββββ ββββββ ββββββ ββββββββ
// βββββββββββββββββββ βββββββββββ βββ
// βββββββ βββββββββββ βββββββββββ βββ
//
// βββββββ ββββ ββββββ βββ ββββββββββ βββββββββββ
// βββββββββ βββββββββββββββββ ββββββββββββββββββββββββ
// βββ βββββββββββββββββββ βββββββ ββββββββββββββ βββ
// βββ βββββββββββββββββββ βββββ ββββββββββββββ βββ
// βββββββ βββ ββββββ βββ βββ ββββββββββββββββββββ
// ββββββ ββββββ βββ βββ βββββββ βββββββββββ
//
// ββ β¬ β¬β¬β¬ ββ¬β β¬ β¬βββββββ¬ββ¬ β¬β¬βββββ βββββββ¬ β¬ ββ¬βββββββββββ¬βββ¬βββββββ¬β
// ββ΄ββ βββ ββ ββΌβ ββ¬βββ€ β β βββ¬ββββ βββββ€ βββ ββββ€ ββ€ ββ€ ββ¬βββ¬βββ€ ββ
// βββββββ΄β΄ββββ΄β ββ β΄βββββ β΄ ββββ΄βββββ ββββββββ΄β ββ΄βββββ ββββ΄βββ΄βββββββ΄β
// ββ β¬βββ β¬ββββββ¬ ββββ¬ β¬ββββββββ¬β ββ
// ββββ βββ€ ββ¬βββ€ β ββ€ βββββββ€βββ β ββββ
// ββ β΄β β΄ββββββ΄βββββ ββ β΄ β΄βββ β΄ ββ
// If an explicit callback function was specified, then immediately run the logic below
// and trigger the explicit callback when the time comes. Otherwise, build and return
// a new Deferred now. (If/when the Deferred is executed, the logic below will run.)
return parley(
function (done){
// Otherwise, IWMIH, we know that it's time to actually do some stuff.
// So...
//
// βββββββββββ βββββββββββ ββββββββββ ββββββββββββββββββββ
// βββββββββββββββββββββββββββββββββββ ββββββββββββββββββββ
// ββββββ ββββββ ββββββ βββ βββ βββ βββ ββββββ
// ββββββ ββββββ ββββββ βββ βββ βββ βββ ββββββ
// ββββββββββββ ββββββββββββββββββββββββββββ βββ ββββββββ
// βββββββββββ βββββββββββ βββββββ βββββββ βββ ββββββββ
// βββββββ¦ββββββββ βββββ¬ββββββββββ ββ¬ββ¬ β¬βββ βββ β¬ β¬ββββ¬βββ¬ β¬
// β β£ β ββ β¦ββ β¦ββ£ βββ β βββ€β β¬ββ€ β ββββ β βββΌββ βββ€ ββ¬βββ¬β
// β ββββ©ββββββββ βββ β΄ β΄ β΄ββββββ β΄ ββ΄ββββ βββββββββββ΄ββ β΄
//
// Forge a stage 2 query (aka logical protostatement)
try {
forgeStageTwoQuery(query, orm);
} catch (e) {
switch (e.code) {
case 'E_INVALID_NUMERIC_ATTR_NAME':
return done(
flaverr({
name: 'UsageError',
code: e.code,
details: e.details,
message:
'The numeric attr name (i.e. first argument) to `.sum()` should '+
'be the name of an attribute in this model which is defined with `type: \'number\'`.\n'+
'Details:\n'+
' ' + e.details + '\n'
}, omen)
);
// ^ custom override for the standard usage error. Note that we use `.details` to get at
// the underlying, lower-level error message (instead of logging redundant stuff from
// the envelope provided by the default error msg.)
case 'E_INVALID_CRITERIA':
case 'E_INVALID_META':
return done(
flaverr({
name: 'UsageError',
code: e.code,
details: e.details,
message: e.message
}, omen)
);
// ^ when the standard usage error message is good enough as-is, without any further customization
case 'E_NOOP':
return done(undefined, 0);
default:
return done(e);
// ^ when an internal, miscellaneous, or unexpected error occurs
}
} // >-β’
// βββββββ¦ββββββββ βββββ¬ββββββββββ ββ¬ββ¬ β¬β¬ββββββββ βββ β¬ β¬ββββ¬βββ¬ β¬
// β β£ β ββ β¦ββ β¦ββ£ βββ β βββ€β β¬ββ€ β βββ€ββ¬βββ€ ββ€ βββΌββ βββ€ ββ¬βββ¬β
// β ββββ©ββββββββ βββ β΄ β΄ β΄ββββββ β΄ β΄ β΄β΄ββββββββ βββββββββββ΄ββ β΄
try {
query = forgeStageThreeQuery({
stageTwoQuery: query,
identity: modelIdentity,
transformer: WLModel._transformer,
originalModels: orm.collections
});
} catch (e) { return done(e); }
// βββββββββββ¬β ββ¬ββββ βββββ¦βββββββββ¦βββββ¦ββ
// βββββ€ βββ ββ β β β β ββ£ βββ ββ£β ββ β ββ£ β β¦β
// βββββββββββ΄β β΄ βββ β© β©ββ©ββ© β©β© β© ββββ©ββ
// Grab the appropriate adapter method and call it.
var adapter = WLModel._adapter;
if (!adapter.sum) {
return done(new Error('The adapter used by this model (`' + modelIdentity + '`) doesn\'t support the `'+query.method+'` method.'));
}
adapter.sum(WLModel.datastore, query, function _afterTalkingToAdapter(err, sum) {
if (err) {
err = forgeAdapterError(err, omen, 'sum', modelIdentity, orm);
return done(err);
}//-β’
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// FUTURE: Log a warning like the ones in `process-all-records` if
// the sum sent back by the adapter turns out to be something other
// than a number (for example, the naive behavior of a MySQL adapter
// in circumstances where criteria does not match any records); i.e.
// ```
// !_.isNumber(sum) || sum === Infinity || sum === -Infinity || _.isNaN(sum)
// ````
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
return done(undefined, sum);
});//</adapter.sum()>
},
explicitCbMaybe,
_.extend(DEFERRED_METHODS, {
// Provide access to this model for use in query modifier methods.
_WLModel: WLModel,
// Set up initial query metadata.
_wlQueryInfo: query,
})
);//</parley>
}; | sum()
Get the aggregate sum of the specified attribute across all matching records.
```
// The cumulative account balance of all bank accounts that have
// less than $32,000, or that are flagged as "suspended".
BankAccount.sum('balance').where({
or: [
{ balance: { '<': 32000 } },
{ suspended: true }
]
}).exec(function (err, total){
// ...
});
```
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Usage without deferred object:
================================================
@param {String?} numericAttrName
@param {Dictionary?} criteria
@param {Function?} explicitCbMaybe
Callback function to run when query has either finished successfully or errored.
(If unspecified, will return a Deferred object instead of actually doing anything.)
@param {Ref?} meta
For internal use.
@param {Dictionary} moreQueryKeys
For internal use.
(A dictionary of query keys.)
@returns {Ref?} Deferred object if no `explicitCbMaybe` callback was provided
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
The underlying query keys:
==============================
@qkey {String} numericAttrName
The name of a numeric attribute.
(Must be declared as `type: 'number'`.)
@qkey {Dictionary?} criteria
@qkey {Dictionary?} meta
@qkey {String} using
@qkey {String} method
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | sum ( ) | javascript | balderdashy/waterline | lib/waterline/methods/sum.js | https://github.com/balderdashy/waterline/blob/master/lib/waterline/methods/sum.js | MIT |
module.exports = function count( /* criteria?, explicitCbMaybe?, meta?, moreQueryKeys? */ ) {
// Verify `this` refers to an actual Sails/Waterline model.
verifyModelMethodContext(this);
// Set up a few, common local vars for convenience / familiarity.
var WLModel = this;
var orm = this.waterline;
var modelIdentity = this.identity;
// Build an omen for potential use in the asynchronous callback below.
var omen = buildOmen(count);
// Build query w/ initial, universal keys.
var query = {
method: 'count',
using: modelIdentity
};
// βββ βββ ββββββ βββββββ βββ ββββββ βββββββ βββ βββββββββββββββ
// βββ βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// βββ βββββββββββββββββββββββββββββββββ βββββββββ ββββββββ
// ββββ ββββββββββββββββββββββββββββββββββ βββββββββ ββββββββ
// βββββββ βββ ββββββ βββββββββ ββββββββββββββββββββββββββββββ
// βββββ βββ ββββββ βββββββββ ββββββββββ βββ βββββββββββββββ
//
// The `explicitCbMaybe` callback, if one was provided.
var explicitCbMaybe;
// Handle the various supported usage possibilities
// (locate the `explicitCbMaybe` callback, and extend the `query` dictionary)
//
// > Note that we define `args` to minimize the chance of this "variadics" code
// > introducing any unoptimizable performance problems. For details, see:
// > https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#32-leaking-arguments
// > β’=> `.length` is just an integer, this doesn't leak the `arguments` object itself
// > β’=> `i` is always valid index in the arguments object
var args = new Array(arguments.length);
for (var i = 0; i < args.length; ++i) {
args[i] = arguments[i];
}
// β’ count(explicitCbMaybe, ..., ...)
if (args.length >= 1 && _.isFunction(args[0])) {
explicitCbMaybe = args[0];
query.meta = args[1];
if (args[2]) { _.extend(query, args[2]); }
}
// β’ count(criteria, ..., ..., ...)
else {
query.criteria = args[0];
explicitCbMaybe = args[1];
query.meta = args[2];
if (args[3]) { _.extend(query, args[3]); }
}
// βββββββ βββββββββββββββββββββββββββββββ
// ββββββββββββββββββββββββββββββββββββββββ
// βββ βββββββββ ββββββ ββββββ ββββββββ
// βββ βββββββββ ββββββ ββββββ ββββββββ
// βββββββββββββββββββ βββββββββββ βββ
// βββββββ βββββββββββ βββββββββββ βββ
//
// βββββββ ββββ ββββββ βββ ββββββββββ βββββββββββ
// βββββββββ βββββββββββββββββ ββββββββββββββββββββββββ
// βββ βββββββββββββββββββ βββββββ ββββββββββββββ βββ
// βββ βββββββββββββββββββ βββββ ββββββββββββββ βββ
// βββββββ βββ ββββββ βββ βββ ββββββββββββββββββββ
// ββββββ ββββββ βββ βββ βββββββ βββββββββββ
//
// ββ β¬ β¬β¬β¬ ββ¬β β¬ β¬βββββββ¬ββ¬ β¬β¬βββββ βββββββ¬ β¬ ββ¬βββββββββββ¬βββ¬βββββββ¬β
// ββ΄ββ βββ ββ ββΌβ ββ¬βββ€ β β βββ¬ββββ βββββ€ βββ ββββ€ ββ€ ββ€ ββ¬βββ¬βββ€ ββ
// βββββββ΄β΄ββββ΄β ββ β΄βββββ β΄ ββββ΄βββββ ββββββββ΄β ββ΄βββββ ββββ΄βββ΄βββββββ΄β
// ββ β¬βββ β¬ββββββ¬ ββββ¬ β¬ββββββββ¬β ββ
// ββββ βββ€ ββ¬βββ€ β ββ€ βββββββ€βββ β ββββ
// ββ β΄β β΄ββββββ΄βββββ ββ β΄ β΄βββ β΄ ββ
// If an explicit callback function was specified, then immediately run the logic below
// and trigger the explicit callback when the time comes. Otherwise, build and return
// a new Deferred now. (If/when the Deferred is executed, the logic below will run.)
return parley(
function (done){
// Otherwise, IWMIH, we know that it's time to actually do some stuff.
// So...
//
// βββββββββββ βββββββββββ ββββββββββ ββββββββββββββββββββ
// βββββββββββββββββββββββββββββββββββ ββββββββββββββββββββ
// ββββββ ββββββ ββββββ βββ βββ βββ βββ ββββββ
// ββββββ ββββββ ββββββ βββ βββ βββ βββ ββββββ
// ββββββββββββ ββββββββββββββββββββββββββββ βββ ββββββββ
// βββββββββββ βββββββββββ βββββββ βββββββ βββ ββββββββ
// βββββββ¦ββββββββ βββββ¬ββββββββββ ββ¬ββ¬ β¬βββ βββ β¬ β¬ββββ¬βββ¬ β¬
// β β£ β ββ β¦ββ β¦ββ£ βββ β βββ€β β¬ββ€ β ββββ β βββΌββ βββ€ ββ¬βββ¬β
// β ββββ©ββββββββ βββ β΄ β΄ β΄ββββββ β΄ ββ΄ββββ βββββββββββ΄ββ β΄
//
// Forge a stage 2 query (aka logical protostatement)
try {
forgeStageTwoQuery(query, orm);
} catch (e) {
switch (e.code) {
case 'E_INVALID_CRITERIA':
case 'E_INVALID_META':
return done(
flaverr({
name: 'UsageError',
code: e.code,
details: e.details,
message: e.message
}, omen)
);
// ^ when the standard usage error message is good enough as-is, without any further customization
case 'E_NOOP':
return done(undefined, 0);
default:
return done(e);
// ^ when an internal, miscellaneous, or unexpected error occurs
}
} // >-β’
// βββββββ¦ββββββββ βββββ¬ββββββββββ ββ¬ββ¬ β¬β¬ββββββββ βββ β¬ β¬ββββ¬βββ¬ β¬
// β β£ β ββ β¦ββ β¦ββ£ βββ β βββ€β β¬ββ€ β βββ€ββ¬βββ€ ββ€ βββΌββ βββ€ ββ¬βββ¬β
// β ββββ©ββββββββ βββ β΄ β΄ β΄ββββββ β΄ β΄ β΄β΄ββββββββ βββββββββββ΄ββ β΄
try {
query = forgeStageThreeQuery({
stageTwoQuery: query,
identity: modelIdentity,
transformer: WLModel._transformer,
originalModels: orm.collections
});
} catch (e) { return done(e); }
// βββββββββββ¬β ββ¬ββββ βββββ¦βββββββββ¦βββββ¦ββ
// βββββ€ βββ ββ β β β β ββ£ βββ ββ£β ββ β ββ£ β β¦β
// βββββββββββ΄β β΄ βββ β© β©ββ©ββ© β©β© β© ββββ©ββ
// Grab the appropriate adapter method and call it.
var adapter = WLModel._adapter;
if (!adapter.count) {
return done(new Error('The adapter used by this model (`' + modelIdentity + '`) doesn\'t support the `'+query.method+'` method.'));
}
adapter.count(WLModel.datastore, query, function _afterTalkingToAdapter(err, numRecords) {
if (err) {
err = forgeAdapterError(err, omen, 'count', modelIdentity, orm);
return done(err);
}
return done(undefined, numRecords);
});//</adapter.count()>
},
explicitCbMaybe,
_.extend(DEFERRED_METHODS, {
// Provide access to this model for use in query modifier methods.
_WLModel: WLModel,
// Set up initial query metadata.
_wlQueryInfo: query,
})
);//</parley>
}; | count()
Get the number of matching records matching a criteria.
```
// The number of bank accounts with more than $32,000 in them.
BankAccount.count().where({
balance: { '>': 32000 }
}).exec(function(err, numBankAccounts) {
// ...
});
```
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Usage without deferred object:
================================================
@param {Dictionary?} criteria
@param {Function?} explicitCbMaybe
Callback function to run when query has either finished successfully or errored.
(If unspecified, will return a Deferred object instead of actually doing anything.)
@param {Ref?} meta
For internal use.
@param {Dictionary} moreQueryKeys
For internal use.
(A dictionary of query keys.)
@returns {Ref?} Deferred object if no `explicitCbMaybe` callback was provided
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
The underlying query keys:
==============================
@qkey {Dictionary?} criteria
@qkey {Dictionary?} meta
@qkey {String} using
@qkey {String} method
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | count ( ) | javascript | balderdashy/waterline | lib/waterline/methods/count.js | https://github.com/balderdashy/waterline/blob/master/lib/waterline/methods/count.js | MIT |
module.exports = function archive(/* criteria, explicitCbMaybe, metaContainer */) {
// Verify `this` refers to an actual Sails/Waterline model.
verifyModelMethodContext(this);
// Set up a few, common local vars for convenience / familiarity.
var WLModel = this;
var orm = this.waterline;
var modelIdentity = this.identity;
// Build an omen for potential use in the asynchronous callback below.
var omen = buildOmen(archive);
// Build initial query.
var query = {
method: 'archive',
using: modelIdentity,
criteria: undefined,
meta: undefined
};
// βββ βββ ββββββ βββββββ βββ ββββββ βββββββ βββ βββββββββββββββ
// βββ βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// βββ βββββββββββββββββββββββββββββββββ βββββββββ ββββββββ
// ββββ ββββββββββββββββββββββββββββββββββ βββββββββ ββββββββ
// βββββββ βββ ββββββ βββββββββ ββββββββββββββββββββββββββββββ
// βββββ βββ ββββββ βββββββββ ββββββββββ βββ βββββββββββββββ
//
// FUTURE: when time allows, update this to match the "VARIADICS" format
// used in the other model methods.
// The explicit callback, if one was provided.
var explicitCbMaybe;
// Handle double meaning of first argument:
//
// β’ archive(criteria, ...)
if (!_.isFunction(arguments[0])) {
query.criteria = arguments[0];
explicitCbMaybe = arguments[1];
query.meta = arguments[2];
}
// β’ archive(explicitCbMaybe, ...)
else {
explicitCbMaybe = arguments[0];
query.meta = arguments[1];
}
// βββββββ βββββββββββββββββββββββββββββββ
// ββββββββββββββββββββββββββββββββββββββββ
// βββ βββββββββ ββββββ ββββββ ββββββββ
// βββ βββββββββ ββββββ ββββββ ββββββββ
// βββββββββββββββββββ βββββββββββ βββ
// βββββββ βββββββββββ βββββββββββ βββ
//
// βββββββ ββββ ββββββ βββ ββββββββββ βββββββββββ
// βββββββββ βββββββββββββββββ ββββββββββββββββββββββββ
// βββ βββββββββββββββββββ βββββββ ββββββββββββββ βββ
// βββ βββββββββββββββββββ βββββ ββββββββββββββ βββ
// βββββββ βββ ββββββ βββ βββ ββββββββββββββββββββ
// ββββββ ββββββ βββ βββ βββββββ βββββββββββ
//
// ββ β¬ β¬β¬β¬ ββ¬β β¬ β¬βββββββ¬ββ¬ β¬β¬βββββ βββββββ¬ β¬ ββ¬βββββββββββ¬βββ¬βββββββ¬β
// ββ΄ββ βββ ββ ββΌβ ββ¬βββ€ β β βββ¬ββββ βββββ€ βββ ββββ€ ββ€ ββ€ ββ¬βββ¬βββ€ ββ
// βββββββ΄β΄ββββ΄β ββ β΄βββββ β΄ ββββ΄βββββ ββββββββ΄β ββ΄βββββ ββββ΄βββ΄βββββββ΄β
// ββ β¬βββ β¬ββββββ¬ ββββ¬ β¬ββββββββ¬β ββ
// ββββ βββ€ ββ¬βββ€ β ββ€ βββββββ€βββ β ββββ
// ββ β΄β β΄ββββββ΄βββββ ββ β΄ β΄βββ β΄ ββ
// If a callback function was not specified, then build a new Deferred and bail now.
//
// > This method will be called AGAIN automatically when the Deferred is executed.
// > and next time, it'll have a callback.
return parley(
function (done){
// Otherwise, IWMIH, we know that a callback was specified.
// So...
// βββββββββββ βββββββββββ ββββββββββ ββββββββββββββββββββ
// βββββββββββββββββββββββββββββββββββ ββββββββββββββββββββ
// ββββββ ββββββ ββββββ βββ βββ βββ βββ ββββββ
// ββββββ ββββββ ββββββ βββ βββ βββ βββ ββββββ
// ββββββββββββ ββββββββββββββββββββββββββββ βββ ββββββββ
// βββββββββββ βββββββββββ βββββββ βββββββ βββ ββββββββ
//
// βββββββ¦ββββββββ βββββ¬ββββββββββ ββ¬ββ¬ β¬βββ βββ β¬ β¬ββββ¬βββ¬ β¬
// β β£ β ββ β¦ββ β¦ββ£ βββ β βββ€β β¬ββ€ β ββββ β βββΌββ βββ€ ββ¬βββ¬β
// β ββββ©ββββββββ βββ β΄ β΄ β΄ββββββ β΄ ββ΄ββββ βββββββββββ΄ββ β΄
//
// Forge a stage 2 query (aka logical protostatement)
// This ensures a normalized format.
try {
forgeStageTwoQuery(query, orm);
} catch (err) {
switch (err.code) {
case 'E_INVALID_CRITERIA':
return done(
flaverr({
name: 'UsageError',
code: err.code,
details: err.details,
message:
'Invalid criteria.\n'+
'Details:\n'+
' '+err.details+'\n'
}, omen)
);
case 'E_NOOP':
// Determine the appropriate no-op result.
// If `fetch` meta key is set, use `[]`-- otherwise use `undefined`.
var noopResult = undefined;
if (query.meta && query.meta.fetch) {
noopResult = [];
}//>-
return done(undefined, noopResult);
default:
return done(err);
}
}//ο¬
// Bail now if archiving has been disabled.
if (!WLModel.archiveModelIdentity) {
return done(flaverr({
name: 'UsageError',
message: 'Since the `archiveModelIdentity` setting was explicitly disabled, .archive() cannot be used.'
}, omen));
}//β’
// Look up the Archive model.
var Archive = WLModel.archiveModelIdentity;
try {
Archive = getModel(WLModel.archiveModelIdentity, orm);
} catch (err) { return done(err); }//ο¬
// - - - - - - - - - - - - - - - - - - - - - - - - - - -
// FUTURE: pass through the `omen` in the metadata.
// - - - - - - - - - - - - - - - - - - - - - - - - - - -
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// FUTURE: Maybe refactor this into more-generic `.move()` and/or
// `.copy()` methods for migrating data between models/datastores.
// Then just leverage those methods here in `.archive()`.
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// βββββ β¦βββββββ¦ β¦ββ¦ββββ ββββ¬βββββ¬β βββ β¬ β¬ββββ¬βββ¬ β¬
// ββ£ ββ©β¦βββ£ β β β β ββ£ ββ€ ββββ ββ βββΌββ βββ€ ββ¬βββ¬β
// ββββ© βββββββββββ β© βββ β β΄βββββ΄β βββββββββββ΄ββ β΄
// Note that we pass in `meta` here, as well as in the other queries
// below. (This ensures we're on the same db connection, provided one
// was explicitly passed in!)
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// WARNING:
//
// Before proceeding with calling an additional model method that relies
// on criteria other than the primary .destroy(), we'll want to back up a
// copy of our s2q's criteria (`query.criteria`).
//
// This is important because, in an effort to improve performance,
// Waterline methods destructively mutate criteria when forging queries
// for use in the adapter(s). Since we'll be reusing criteria, we need
// to insulate ourselves from those destructive changes in case there are
// custom column names involved. (e.g. Mongo's `_id``)
//
// > While the criteria might contain big crazy stuff for comparing with
// > type:ref attributes, a deep clone is the best option we have.
//
// FUTURE: in s2q forge logic, for "archive" method, reject with an error
// if deep refs (non-JSON-serializable data) are discovered in criteria.
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
var s2qCriteriaForFind = _.cloneDeep(query.criteria);
WLModel.find(s2qCriteriaForFind, function _afterFinding(err, foundRecords) {
if (err) { return done(err); }
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// FUTURE: as an optimization, fetch records batch-at-a-time
// using .stream() instead of just doing a naΓ―ve `.find()`.
// (This would allow you to potentially archive millions of records
// at a time without overflowing RAM.)
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
var archives = [];
_.each(foundRecords, function(record){
archives.push({
originalRecord: record,
originalRecordId: record[WLModel.primaryKey],
fromModel: WLModel.identity,
});
});//β
// βββββ β¦βββββββ¦ β¦ββ¦ββββ ββββ¬ββββββββββ¬ββββββββββββββ¬ β¬ βββ β¬ β¬ββββ¬βββ¬ β¬
// ββ£ ββ©β¦βββ£ β β β β ββ£ β ββ¬βββ€ βββ€ β ββ€ ββ€ βββ€β βββ€ βββΌββ βββ€ ββ¬βββ¬β
// ββββ© βββββββββββ β© βββ ββββ΄ββββββ΄ β΄ β΄ βββββββ΄ β΄ββββ΄ β΄ βββββββββββ΄ββ β΄
Archive.createEach(archives, function _afterCreatingEach(err) {
if (err) { return done(err); }
// Remove the `limit`, `skip`, `sort`, `select`, and `omit` clauses so
// that our `destroy` query is valid.
// (This is because they were automatically attached above in the forging.)
delete query.criteria.limit;
delete query.criteria.skip;
delete query.criteria.sort;
delete query.criteria.select;
delete query.criteria.omit;
// βββββ β¦βββββββ¦ β¦ββ¦ββββ ββ¬βββββββββ¬ββ¬ββββββ¬ β¬ βββ β¬ β¬ββββ¬βββ¬ β¬
// ββ£ ββ©β¦βββ£ β β β β ββ£ ββββ€ βββ β ββ¬ββ βββ¬β βββΌββ βββ€ ββ¬βββ¬β
// ββββ© βββββββββββ β© βββ ββ΄βββββββ β΄ β΄βββββ β΄ βββββββββββ΄ββ β΄
WLModel.destroy(query.criteria, function _afterDestroying(err) {
if (err) { return done(err); }
if (query.meta&&query.meta.fetch){
return done(undefined, foundRecords);
}
else {
return done();
}
}, query.meta);//</.destroy()>
}, query.meta);//</.createEach()>
}, query.meta);//</.find()>
},
explicitCbMaybe,
_.extend(DEFERRED_METHODS, {
// Provide access to this model for use in query modifier methods.
_WLModel: WLModel,
// Set up initial query metadata.
_wlQueryInfo: query,
})
);//</parley>
}; | archive()
Archive (s.k.a. "soft-delete") records that match the specified criteria,
saving them as new records in the built-in Archive model, then destroying
the originals.
```
// Archive all bank accounts with more than $32,000 in them.
BankAccount.archive().where({
balance: { '>': 32000 }
}).exec(function(err) {
// ...
});
```
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Usage without deferred object:
================================================
@param {Dictionary?} criteria
@param {Function?} explicitCbMaybe
Callback function to run when query has either finished successfully or errored.
(If unspecified, will return a Deferred object instead of actually doing anything.)
@param {Ref?} meta
For internal use.
@returns {Ref?} Deferred object if no `explicitCbMaybe` callback was provided
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
The underlying query keys:
==============================
@qkey {Dictionary?} criteria
@qkey {Dictionary?} meta
@qkey {String} using
@qkey {String} method
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | archive ( ) | javascript | balderdashy/waterline | lib/waterline/methods/archive.js | https://github.com/balderdashy/waterline/blob/master/lib/waterline/methods/archive.js | MIT |
module.exports = function find( /* criteria?, populates?, explicitCbMaybe?, meta? */ ) {
// Verify `this` refers to an actual Sails/Waterline model.
verifyModelMethodContext(this);
// Set up a few, common local vars for convenience / familiarity.
var WLModel = this;
var orm = this.waterline;
var modelIdentity = this.identity;
// Build an omen for potential use in the asynchronous callbacks below.
var omen = buildOmen(find);
// Build query w/ initial, universal keys.
var query = {
method: 'find',
using: modelIdentity
};
// βββ βββ ββββββ βββββββ βββ ββββββ βββββββ βββ βββββββββββββββ
// βββ βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// βββ βββββββββββββββββββββββββββββββββ βββββββββ ββββββββ
// ββββ ββββββββββββββββββββββββββββββββββ βββββββββ ββββββββ
// βββββββ βββ ββββββ βββββββββ ββββββββββββββββββββββββββββββ
// βββββ βββ ββββββ βββββββββ ββββββββββ βββ βββββββββββββββ
//
// The `explicitCbMaybe` callback, if one was provided.
var explicitCbMaybe;
// Handle the various supported usage possibilities
// (locate the `explicitCbMaybe` callback, and extend the `query` dictionary)
//
// > Note that we define `args` to minimize the chance of this "variadics" code
// > introducing any unoptimizable performance problems. For details, see:
// > https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#32-leaking-arguments
// > β’=> `.length` is just an integer, this doesn't leak the `arguments` object itself
// > β’=> `i` is always valid index in the arguments object
var args = new Array(arguments.length);
for (var i = 0; i < args.length; ++i) {
args[i] = arguments[i];
}
// β’ find(explicitCbMaybe, ...)
if (args.length >= 1 && _.isFunction(args[0])) {
explicitCbMaybe = args[0];
query.meta = args[1];
}
// β’ find(criteria, explicitCbMaybe, ...)
else if (args.length >= 2 && _.isFunction(args[1])) {
query.criteria = args[0];
explicitCbMaybe = args[1];
query.meta = args[2];
}
// β’ find()
// β’ find(criteria)
// β’ find(criteria, populates, ...)
else {
query.criteria = args[0];
query.populates = args[1];
explicitCbMaybe = args[2];
query.meta = args[3];
}
// βββββββ βββββββββββββββββββββββββββββββ
// ββββββββββββββββββββββββββββββββββββββββ
// βββ βββββββββ ββββββ ββββββ ββββββββ
// βββ βββββββββ ββββββ ββββββ ββββββββ
// βββββββββββββββββββ βββββββββββ βββ
// βββββββ βββββββββββ βββββββββββ βββ
//
// βββββββ ββββ ββββββ βββ ββββββββββ βββββββββββ
// βββββββββ βββββββββββββββββ ββββββββββββββββββββββββ
// βββ βββββββββββββββββββ βββββββ ββββββββββββββ βββ
// βββ βββββββββββββββββββ βββββ ββββββββββββββ βββ
// βββββββ βββ ββββββ βββ βββ ββββββββββββββββββββ
// ββββββ ββββββ βββ βββ βββββββ βββββββββββ
//
// ββ β¬ β¬β¬β¬ ββ¬β β¬ β¬βββββββ¬ββ¬ β¬β¬βββββ βββββββ¬ β¬ ββ¬βββββββββββ¬βββ¬βββββββ¬β
// ββ΄ββ βββ ββ ββΌβ ββ¬βββ€ β β βββ¬ββββ βββββ€ βββ ββββ€ ββ€ ββ€ ββ¬βββ¬βββ€ ββ
// βββββββ΄β΄ββββ΄β ββ β΄βββββ β΄ ββββ΄βββββ ββββββββ΄β ββ΄βββββ ββββ΄βββ΄βββββββ΄β
// ββ β¬βββ β¬ββββββ¬ ββββ¬ β¬ββββββββ¬β ββ
// ββββ βββ€ ββ¬βββ€ β ββ€ βββββββ€βββ β ββββ
// ββ β΄β β΄ββββββ΄βββββ ββ β΄ β΄βββ β΄ ββ
// If a callback function was not specified, then build a new Deferred and bail now.
//
// > This method will be called AGAIN automatically when the Deferred is executed.
// > and next time, it'll have a callback.
return parley(
function (done){
// Otherwise, IWMIH, we know that a callback was specified.
// So...
// βββββββββββ βββββββββββ ββββββββββ ββββββββββββββββββββ
// βββββββββββββββββββββββββββββββββββ ββββββββββββββββββββ
// ββββββ ββββββ ββββββ βββ βββ βββ βββ ββββββ
// ββββββ ββββββ ββββββ βββ βββ βββ βββ ββββββ
// ββββββββββββ ββββββββββββββββββββββββββββ βββ ββββββββ
// βββββββββββ βββββββββββ βββββββ βββββββ βββ ββββββββ
// βββββββ¦ββββββββ βββββ¬ββββββββββ ββ¬ββ¬ β¬βββ βββ β¬ β¬ββββ¬βββ¬ β¬
// β β£ β ββ β¦ββ β¦ββ£ βββ β βββ€β β¬ββ€ β ββββ β βββΌββ βββ€ ββ¬βββ¬β
// β ββββ©ββββββββ βββ β΄ β΄ β΄ββββββ β΄ ββ΄ββββ βββββββββββ΄ββ β΄
//
// Forge a stage 2 query (aka logical protostatement)
try {
forgeStageTwoQuery(query, orm);
} catch (e) {
switch (e.code) {
case 'E_INVALID_CRITERIA':
return done(
flaverr({
name: 'UsageError',
code: e.code,
details: e.details,
message:
'Invalid criteria.\n' +
'Details:\n' +
' ' + e.details + '\n'
}, omen)
);
case 'E_INVALID_POPULATES':
return done(
flaverr({
name: 'UsageError',
code: e.code,
details: e.details,
message:
'Invalid populate(s).\n' +
'Details:\n' +
' ' + e.details + '\n'
}, omen)
);
case 'E_NOOP':
return done(undefined, []);
default:
return done(e);
}
} // >-β’
// β¬ β¬ββββββββ¬ββ¬ βββ ββ ββββββββββ¦βββββ β¬ β¬ββββββββββ¬ β¬ββββ¬ βββ βββββββ¬ β¬ ββ βββββββ¬ββ
// βββ€βββ€βββ βββ ββ€ β β©βββ£ β β£ β ββ β¦βββ£ β βββ€ ββ€ β ββ¬ββ β ββ€ β βββ€β β ββ΄ββββ€β ββ΄β
// β΄ β΄β΄ β΄βββββ΄ββ΄βββββ βββββββ ββββ©βββββ β΄βββ΄β ββββββ β΄ ββββ΄βββββ ββββ΄ β΄β΄βββ΄ββββββ΄ β΄ββββ΄ β΄
// Determine what to do about running any lifecycle callbacks
(function _maybeRunBeforeLC(proceed) {
// If the `skipAllLifecycleCallbacks` meta flag was set, don't run any of
// the methods.
if (_.has(query.meta, 'skipAllLifecycleCallbacks') && query.meta.skipAllLifecycleCallbacks) {
return proceed(undefined, query);
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// FUTURE: This is where the `beforeFind()` lifecycle callback would go
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
return proceed(undefined, query);
})(function _afterPotentiallyRunningBeforeLC(err, query) {
if (err) {
return done(err);
}
// ================================================================================
// FUTURE: potentially bring this back (but also would need the `omit clause`)
// ================================================================================
// // Before we get to forging again, save a copy of the stage 2 query's
// // `select` clause. We'll need this later on when processing the resulting
// // records, and if we don't copy it now, it might be damaged by the forging.
// //
// // > Note that we don't need a deep clone.
// // > (That's because the `select` clause is only 1 level deep.)
// var s2QSelectClause = _.clone(query.criteria.select);
// ================================================================================
// βββββββββββ¬β ββ¬ββββ βββββ¦βββββββββ¦βββββ¦ββ
// βββββ€ βββ ββ β β β β ββ£ βββ ββ£β ββ β ββ£ β β¦β
// βββββββββββ΄β β΄ βββ β© β©ββ©ββ© β©β© β© ββββ©ββ
// Use `helpFind()` to forge stage 3 quer(y/ies) and then call the appropriate adapters' method(s).
// > Note: `helpFind` is responsible for running the `transformer`.
// > (i.e. so that column names are transformed back into attribute names, amongst other things)
helpFind(WLModel, query, omen, function _afterFetchingRecords(err, populatedRecords) {
if (err) {
return done(err);
}//-β’
// Perform post-processing on the populated (no longer "physical"!) records.
try {
processAllRecords(populatedRecords, query.meta, modelIdentity, orm);
} catch (err) { return done(err); }
// β¬ β¬ββββββββ¬ββ¬ βββ ββββββββ¦βββββ¦ββ β¬ β¬ββββββββββ¬ β¬ββββ¬ βββ βββββββ¬ β¬ ββ βββββββ¬ββ
// βββ€βββ€βββ βββ ββ€ β ββ£β β£ β ββ£ β β¦β β βββ€ ββ€ β ββ¬ββ β ββ€ β βββ€β β ββ΄ββββ€β ββ΄β
// β΄ β΄β΄ β΄βββββ΄ββ΄βββββ β© β©β β© ββββ©ββ β΄βββ΄β ββββββ β΄ ββββ΄βββββ ββββ΄ β΄β΄βββ΄ββββββ΄ β΄ββββ΄ β΄
(function _maybeRunAfterLC(proceed){
// If the `skipAllLifecycleCallbacks` meta key was enabled, then don't run this LC.
if (_.has(query.meta, 'skipAllLifecycleCallbacks') && query.meta.skipAllLifecycleCallbacks) {
return proceed(undefined, populatedRecords);
}//-β’
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// FUTURE: This is where the `afterFind()` lifecycle callback would go
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
return proceed(undefined, populatedRecords);
})(function _afterPotentiallyRunningAfterLC(err, populatedRecords) {
if (err) { return done(err); }
// All done.
return done(undefined, populatedRecords);
});//</ self-calling functionto handle "after" lifecycle callback >
}); //</ helpFind() >
}); //</ self-calling function to handle "before" lifecycle callback >
},
explicitCbMaybe,
_.extend(DEFERRED_METHODS, {
// Provide access to this model for use in query modifier methods.
_WLModel: WLModel,
// Set up initial query metadata.
_wlQueryInfo: query,
})
);//</ parley() >
}; | find()
Find records that match the specified criteria.
```
// Look up all bank accounts with more than $32,000 in them.
BankAccount.find().where({
balance: { '>': 32000 }
}).exec(function(err, bankAccounts) {
// ...
});
```
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Usage without deferred object:
================================================
@param {Dictionary?} criteria
@param {Dictionary} populates
@param {Function?} explicitCbMaybe
Callback function to run when query has either finished successfully or errored.
(If unspecified, will return a Deferred object instead of actually doing anything.)
@param {Ref?} meta
For internal use.
@returns {Ref?} Deferred object if no `explicitCbMaybe` callback was provided
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
The underlying query keys:
==============================
@qkey {Dictionary?} criteria
@qkey {Dictionary?} populates
@qkey {Dictionary?} meta
@qkey {String} using
@qkey {String} method
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | find ( ) | javascript | balderdashy/waterline | lib/waterline/methods/find.js | https://github.com/balderdashy/waterline/blob/master/lib/waterline/methods/find.js | MIT |
module.exports = function stream( /* criteria?, eachRecordFn?, explicitCbMaybe?, meta?, moreQueryKeys? */ ) {
// Verify `this` refers to an actual Sails/Waterline model.
verifyModelMethodContext(this);
// Set up a few, common local vars for convenience / familiarity.
var WLModel = this;
var orm = this.waterline;
var modelIdentity = this.identity;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// FUTURE: Potentially build an omen here for potential use in an
// asynchronous callback below if/when an error occurs. This would
// provide for a better stack trace, since it would be based off of
// the original method call, rather than containing extra stack entries
// from various utilities calling each other within Waterline itself.
//
// > Note that it'd need to be passed in to the other model methods that
// > get called internally.
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// Build query w/ initial, universal keys.
var query = {
method: 'stream',
using: modelIdentity
};
// βββ βββ ββββββ βββββββ βββ ββββββ βββββββ βββ βββββββββββββββ
// βββ βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// βββ βββββββββββββββββββββββββββββββββ βββββββββ ββββββββ
// ββββ ββββββββββββββββββββββββββββββββββ βββββββββ ββββββββ
// βββββββ βββ ββββββ βββββββββ ββββββββββββββββββββββββββββββ
// βββββ βββ ββββββ βββββββββ ββββββββββ βββ βββββββββββββββ
//
// The `explicitCbMaybe` callback, if one was provided.
var explicitCbMaybe;
// Handle the various supported usage possibilities
// (locate the `explicitCbMaybe` callback, and extend the `query` dictionary)
//
// > Note that we define `args` to minimize the chance of this "variadics" code
// > introducing any unoptimizable performance problems. For details, see:
// > https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#32-leaking-arguments
// > β’=> `.length` is just an integer, this doesn't leak the `arguments` object itself
// > β’=> `i` is always valid index in the arguments object
var args = new Array(arguments.length);
for (var i = 0; i < args.length; ++i) {
args[i] = arguments[i];
}
// β’ stream(eachRecordFn, ..., ..., ...)
// β’ stream(eachRecordFn, explicitCbMaybe, ..., ...)
if (args.length >= 1 && _.isFunction(args[0])) {
query.eachRecordFn = args[0];
explicitCbMaybe = args[1];
query.meta = args[2];
if (args[3]) {
_.extend(query, args[3]);
}
}
// β’ stream(criteria, ..., ..., ..., ...)
// β’ stream(criteria, eachRecordFn, ..., ..., ...)
// β’ stream()
else {
query.criteria = args[0];
query.eachRecordFn = args[1];
explicitCbMaybe = args[2];
query.meta = args[3];
if (args[4]) {
_.extend(query, args[4]);
}
}
// βββββββ βββββββββββββββββββββββββββββββ
// ββββββββββββββββββββββββββββββββββββββββ
// βββ βββββββββ ββββββ ββββββ ββββββββ
// βββ βββββββββ ββββββ ββββββ ββββββββ
// βββββββββββββββββββ βββββββββββ βββ
// βββββββ βββββββββββ βββββββββββ βββ
//
// βββββββ ββββ ββββββ βββ ββββββββββ βββββββββββ
// βββββββββ βββββββββββββββββ ββββββββββββββββββββββββ
// βββ βββββββββββββββββββ βββββββ ββββββββββββββ βββ
// βββ βββββββββββββββββββ βββββ ββββββββββββββ βββ
// βββββββ βββ ββββββ βββ βββ ββββββββββββββββββββ
// ββββββ ββββββ βββ βββ βββββββ βββββββββββ
//
// ββ β¬ β¬β¬β¬ ββ¬β β¬ β¬βββββββ¬ββ¬ β¬β¬βββββ βββββββ¬ β¬ ββ¬βββββββββββ¬βββ¬βββββββ¬β
// ββ΄ββ βββ ββ ββΌβ ββ¬βββ€ β β βββ¬ββββ βββββ€ βββ ββββ€ ββ€ ββ€ ββ¬βββ¬βββ€ ββ
// βββββββ΄β΄ββββ΄β ββ β΄βββββ β΄ ββββ΄βββββ ββββββββ΄β ββ΄βββββ ββββ΄βββ΄βββββββ΄β
// ββ β¬βββ β¬ββββββ¬ ββββ¬ β¬ββββββββ¬β ββ
// ββββ βββ€ ββ¬βββ€ β ββ€ βββββββ€βββ β ββββ
// ββ β΄β β΄ββββββ΄βββββ ββ β΄ β΄βββ β΄ ββ
// If an explicit callback function was specified, then immediately run the logic below
// and trigger the explicit callback when the time comes. Otherwise, build and return
// a new Deferred now. (If/when the Deferred is executed, the logic below will run.)
return parley(
function (done){
// Otherwise, IWMIH, we know that it's time to actually do some stuff.
// So...
//
// βββββββββββ βββββββββββ ββββββββββ ββββββββββββββββββββ
// βββββββββββββββββββββββββββββββββββ ββββββββββββββββββββ
// ββββββ ββββββ ββββββ βββ βββ βββ βββ ββββββ
// ββββββ ββββββ ββββββ βββ βββ βββ βββ ββββββ
// ββββββββββββ ββββββββββββββββββββββββββββ βββ ββββββββ
// βββββββββββ βββββββββββ βββββββ βββββββ βββ ββββββββ
// βββββββ¦ββββββββ βββββ¬ββββββββββ ββ¬ββ¬ β¬βββ βββ β¬ β¬ββββ¬βββ¬ β¬
// β β£ β ββ β¦ββ β¦ββ£ βββ β βββ€β β¬ββ€ β ββββ β βββΌββ βββ€ ββ¬βββ¬β
// β ββββ©ββββββββ βββ β΄ β΄ β΄ββββββ β΄ ββ΄ββββ βββββββββββ΄ββ β΄
//
// Forge a stage 2 query (aka logical protostatement)
try {
forgeStageTwoQuery(query, orm);
} catch (e) {
switch (e.code) {
case 'E_INVALID_STREAM_ITERATEE':
return done(
flaverr(
{
name: 'UsageError',
code: e.code,
details: e.details,
},
new Error(
'Missing or invalid iteratee function for `.stream()`.\n'+
'Details:\n' +
' ' + e.details + '\n'
)
)
);
case 'E_INVALID_CRITERIA':
case 'E_INVALID_POPULATES':
case 'E_INVALID_META':
return done(e);
// ^ when the standard usage error is good enough as-is, without any further customization
case 'E_NOOP':
return done();
default:
return done(e);
// ^ when an internal, miscellaneous, or unexpected error occurs
}
} //>-β’
// βββββββ¬ β¬ ββββββββ¦ββ¦ β¦ββββ¦ β¦ β¦ β¦ ββ¬βββββ¬ β¬ββ ββ¬ββββ ββ¬ββ¬ β¬βββ ββ¬βββ βββ
// ββββ ββββ β ββ£β β β ββ ββ£β β ββ¦β β βββ€β ββ΄β β β β β βββ€ββ€ ββββ΄ββββ
// ββββββββ΄β β© β©βββ β© ββββ© β©β©βββ©βββ© β΄ β΄ β΄β΄βββ΄ β΄ β΄ βββ β΄ β΄ β΄βββ ββ΄βββββββ
//
// When running a `.stream()`, Waterline grabs batches (pages) of 30
// records at a time, by default. (This can be overridden using the
// "batchSize" meta key.)
var DEFAULT_BATCH_SIZE = 30;
var batchSize = (query.meta && query.meta.batchSize !== undefined) ? query.meta.batchSize : DEFAULT_BATCH_SIZE;
// A flag that will be set to true after we've reached the VERY last batch.
var reachedLastBatch;
// The index of the current batch.
var i = 0;
async.whilst(function _checkHasntReachedLastBatchYet(){
if (!reachedLastBatch) { return true; }
else { return false; }
},// ~β%Β°
function _beginBatchMaybe(next) {
// 0 => 15
// 15 => 15
// 30 => 15
// 45 => 5
// 50
var numRecordsLeftUntilAbsLimit = query.criteria.limit - ( i*batchSize );
var limitForThisBatch = Math.min(numRecordsLeftUntilAbsLimit, batchSize);
var skipForThisBatch = query.criteria.skip + ( i*batchSize );
// |_initial offset + |_relative offset from end of previous batch
// If we've exceeded the absolute limit, then we go ahead and stop.
if (limitForThisBatch <= 0) {
reachedLastBatch = true;
return next();
}//-β’
// Build the criteria + deferred object to do a `.find()` for this batch.
var criteriaForThisBatch = {
skip: skipForThisBatch,
limit: limitForThisBatch,
sort: query.criteria.sort,
select: query.criteria.select,
omit: query.criteria.omit,
where: query.criteria.where
};
// console.log('---iterating---');
// console.log('i:',i);
// console.log(' batchSize:',batchSize);
// console.log(' query.criteria.limit:',query.criteria.limit);
// console.log(' query.criteria.skip:',query.criteria.skip);
// console.log(' query.criteria.sort:',query.criteria.sort);
// console.log(' query.criteria.where:',query.criteria.where);
// console.log(' query.criteria.select:',query.criteria.select);
// console.log(' query.criteria.omit:',query.criteria.omit);
// console.log(' --');
// console.log(' criteriaForThisBatch.limit:',criteriaForThisBatch.limit);
// console.log(' criteriaForThisBatch.skip:',criteriaForThisBatch.skip);
// console.log(' criteriaForThisBatch.sort:',criteriaForThisBatch.sort);
// console.log(' criteriaForThisBatch.where:',criteriaForThisBatch.where);
// console.log(' criteriaForThisBatch.select:',criteriaForThisBatch.select);
// console.log(' criteriaForThisBatch.omit:',criteriaForThisBatch.omit);
// console.log('---β’β’β’β’β’β’β’β’β’---');
var deferredForThisBatch = WLModel.find(criteriaForThisBatch);
_.each(query.populates, function (assocCriteria, assocName){
deferredForThisBatch = deferredForThisBatch.populate(assocName, assocCriteria);
});
// Pass through `meta` so we're sure to use the same db connection
// and settings (esp. relevant if we happen to be inside a transaction).
// > Note that we trim out `batchSize` to avoid tripping assertions about
// > method compatibility.
deferredForThisBatch.meta(query.meta ? _.omit(query.meta, ['batchSize']) : undefined);
deferredForThisBatch.exec(function (err, batchOfRecords){
if (err) { return next(err); }
// If there were no records returned, then we have already reached the last batch of results.
// (i.e. it was the previous batch-- since this batch was empty)
// In this case, we'll set the `reachedLastBatch` flag and trigger our callback,
// allowing `async.whilst()` to call _its_ callback, which will pass control back
// to userland.
if (batchOfRecords.length === 0) {
reachedLastBatch = true;
return next();
}// --β’
// But otherwise, we need to go ahead and call the appropriate
// iteratee for this batch. If it's eachBatchFn, we'll call it
// once. If it's eachRecordFn, we'll call it once per record.
(function _makeCallOrCallsToAppropriateIteratee(proceed){
// Check if the iteratee declares a callback parameter
var seemsToExpectCallback = (function(){
var fn = query.eachBatchFn || query.eachRecordFn;
var fnStr = fn.toString().replace(STRIP_COMMENTS_RX, '');
var parametersAsString = fnStr.slice(fnStr.indexOf('(')+1, fnStr.indexOf(')'));
// console.log(':seemsToExpectCallback:',parametersAsString, !!parametersAsString.match(/\,\s*([^,\{\}\[\]\s]+)\s*$/));
return !! parametersAsString.match(/\,\s*([^,\{\}\[\]\s]+)\s*$/);
})();//β
// If an `eachBatchFn` iteratee was provided, we'll call it.
// > At this point we already know it's a function, because
// > we validated usage at the very beginning.
if (query.eachBatchFn) {
// Note that, if you try to call next() more than once in the iteratee, Waterline
// logs a warning explaining what's up, ignoring all subsequent calls to next()
// that occur after the first.
var didIterateeAlreadyHalt;
try {
var promiseMaybe = query.eachBatchFn(batchOfRecords, function (err) {
if (!seemsToExpectCallback) { return proceed(new Error('Unexpected attempt to invoke callback. Since this per-batch iteratee function does not appear to expect a callback parameter, this stub callback was provided instead. Please either explicitly list the callback parameter among the arguments or change this code to no longer use a callback.')); }//β’
if (err) { return proceed(err); }//β’
if (didIterateeAlreadyHalt) {
console.warn(
'Warning: The per-batch iteratee provided to `.stream()` triggered its callback \n'+
'again-- after already triggering it once! Please carefully check your iteratee\'s \n'+
'code to figure out why this is happening. (Ignoring this subsequent invocation...)'
);
return;
}//-β’
didIterateeAlreadyHalt = true;
return proceed();
});//_β_ </ invoked per-batch iteratee >
// Take care of unhandled promise rejections from `await` (if appropriate)
if (query.eachBatchFn.constructor.name === 'AsyncFunction') {
if (!seemsToExpectCallback) {
promiseMaybe = promiseMaybe.then(function(){
didIterateeAlreadyHalt = true;
proceed();
});//_β_
}//ο¬
promiseMaybe.catch(function(e){ proceed(e); });//_β_
} else {
if (!seemsToExpectCallback) {
didIterateeAlreadyHalt = true;
return proceed();
}
}
} catch (e) { return proceed(e); }//>-β’
return;
}//_β_.
// Otherwise `eachRecordFn` iteratee must have been provided.
// We'll call it once per record in this batch.
// > We validated usage at the very beginning, so we know that
// > one or the other iteratee must have been provided as a
// > valid function if we made it here.
async.eachSeries(batchOfRecords, function _eachRecordInBatch(record, next) {
// Note that, if you try to call next() more than once in the iteratee, Waterline
// logs a warning explaining what's up, ignoring all subsequent calls to next()
// that occur after the first.
var didIterateeAlreadyHalt;
try {
var promiseMaybe = query.eachRecordFn(record, function (err) {
if (!seemsToExpectCallback) { return next(new Error('Unexpected attempt to invoke callback. Since this per-record iteratee function does not appear to expect a callback parameter, this stub callback was provided instead. Please either explicitly list the callback parameter among the arguments or change this code to no longer use a callback.')); }//β’
if (err) { return next(err); }
if (didIterateeAlreadyHalt) {
console.warn(
'Warning: The per-record iteratee provided to `.stream()` triggered its callback\n'+
'again-- after already triggering it once! Please carefully check your iteratee\'s\n'+
'code to figure out why this is happening. (Ignoring this subsequent invocation...)'
);
return;
}//-β’
didIterateeAlreadyHalt = true;
return next();
});//_β_ </ invoked per-record iteratee >
// Take care of unhandled promise rejections from `await` (if appropriate)
if (query.eachRecordFn.constructor.name === 'AsyncFunction') {
if (!seemsToExpectCallback) {
promiseMaybe = promiseMaybe.then(function(){
didIterateeAlreadyHalt = true;
next();
});//_β_
}//ο¬
promiseMaybe.catch(function(e){ next(e); });//_β_
} else {
if (!seemsToExpectCallback) {
didIterateeAlreadyHalt = true;
return next();
}
}//ο¬
} catch (e) { return next(e); }
},// ~β%Β°
function _afterIteratingOverRecordsInBatch(err) {
if (err) { return proceed(err); }
return proceed();
});//</async.eachSeries()>
})(function _afterCallingIteratee(err){
if (err) {
return next(err);
}
// Increment the batch counter.
i++;
// On to the next batch!
return next();
});//</self-calling function :: process this batch by making either one call or multiple calls to the appropriate iteratee>
});//</deferredForThisBatch.exec()>
},// ~β%Β°
function _afterAsyncWhilst(err) {
if (err) { return done(err); }//-β’
// console.log('finished `.whilst()` successfully');
return done();
});//</async.whilst()>
},
explicitCbMaybe,
_.extend(DEFERRED_METHODS, {
// Provide access to this model for use in query modifier methods.
_WLModel: WLModel,
// Set up initial query metadata.
_wlQueryInfo: query,
})
);//</parley>
}; | stream()
Iterate over individual records (or batches of records) that match
the specified criteria, populating associations if instructed.
```
BlogPost.stream()
.limit(50000)
.sort('title ASC')
.eachRecord(function (blogPost, next){ ... })
.exec(function (err){ ... });
// For more usage info (/history), see:
// https://gist.github.com/mikermcneil/d1e612cd1a8564a79f61e1f556fc49a6#examples
```
----------------------------------
~β’ This is the "new .stream()". β’~
----------------------------------
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Usage without deferred object:
================================================
@param {Dictionary?} criteria
@param {Function?} eachRecordFn
@param {Function?} explicitCbMaybe
Callback function to run when query has either finished successfully or errored.
(If unspecified, will return a Deferred object instead of actually doing anything.)
@param {Ref?} meta
For internal use.
@param {Dictionary} moreQueryKeys
For internal use.
(A dictionary of query keys.)
@returns {Ref?} Deferred object if no `explicitCbMaybe` callback was provided
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
The underlying query keys:
==============================
@qkey {Dictionary?} criteria
@qkey {Dictionary?} populates
@qkey {Function?} eachRecordFn
An iteratee function to run for each record.
(If specified, then `eachBatchFn` should not ALSO be set.)
@qkey {Function?} eachBatchFn
An iteratee function to run for each batch of records.
(If specified, then `eachRecordFn` should not ALSO be set.)
@qkey {Dictionary?} meta
@qkey {String} using
@qkey {String} method
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | stream ( ) | javascript | balderdashy/waterline | lib/waterline/methods/stream.js | https://github.com/balderdashy/waterline/blob/master/lib/waterline/methods/stream.js | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.