repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
sequence
docstring
stringlengths
4
11.8k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
86
226
partition
stringclasses
1 value
IndigoUnited/js-dejavu
dist/amd/strict/Interface.js
checkClass
function checkClass(target) { /*jshint validthis:true*/ var key, value; // Check normal functions for (key in this[$interface].methods) { value = this[$interface].methods[key]; if (!target[$class].methods[key]) { throw new Error('Class "' + target.prototype.$name + '" does not implement interface "' + this.prototype.$name + '" correctly, method "' + key + '" was not found.'); } if (!isFunctionCompatible(target[$class].methods[key], value)) { throw new Error('Method "' + key + '(' + target[$class].methods[key].signature + ')" defined in class "' + target.prototype.$name + '" is not compatible with the one found in interface "' + this.prototype.$name + '": "' + key + '(' + value.signature + ')".'); } } // Check static functions for (key in this[$interface].staticMethods) { value = this[$interface].staticMethods[key]; if (!target[$class].staticMethods[key]) { throw new Error('Class "' + target.prototype.$name + '" does not implement interface "' + this.prototype.$name + '" correctly, static method "' + key + '" was not found.'); } if (!isFunctionCompatible(target[$class].staticMethods[key], value)) { throw new Error('Static method "' + key + '(' + target[$class].staticMethods[key].signature + ')" defined in class "' + target.prototype.$name + '" is not compatible with the one found in interface "' + this.prototype.$name + '": "' + key + '(' + value.signature + ')".'); } } }
javascript
function checkClass(target) { /*jshint validthis:true*/ var key, value; // Check normal functions for (key in this[$interface].methods) { value = this[$interface].methods[key]; if (!target[$class].methods[key]) { throw new Error('Class "' + target.prototype.$name + '" does not implement interface "' + this.prototype.$name + '" correctly, method "' + key + '" was not found.'); } if (!isFunctionCompatible(target[$class].methods[key], value)) { throw new Error('Method "' + key + '(' + target[$class].methods[key].signature + ')" defined in class "' + target.prototype.$name + '" is not compatible with the one found in interface "' + this.prototype.$name + '": "' + key + '(' + value.signature + ')".'); } } // Check static functions for (key in this[$interface].staticMethods) { value = this[$interface].staticMethods[key]; if (!target[$class].staticMethods[key]) { throw new Error('Class "' + target.prototype.$name + '" does not implement interface "' + this.prototype.$name + '" correctly, static method "' + key + '" was not found.'); } if (!isFunctionCompatible(target[$class].staticMethods[key], value)) { throw new Error('Static method "' + key + '(' + target[$class].staticMethods[key].signature + ')" defined in class "' + target.prototype.$name + '" is not compatible with the one found in interface "' + this.prototype.$name + '": "' + key + '(' + value.signature + ')".'); } } }
[ "function", "checkClass", "(", "target", ")", "{", "/*jshint validthis:true*/", "var", "key", ",", "value", ";", "// Check normal functions", "for", "(", "key", "in", "this", "[", "$interface", "]", ".", "methods", ")", "{", "value", "=", "this", "[", "$interface", "]", ".", "methods", "[", "key", "]", ";", "if", "(", "!", "target", "[", "$class", "]", ".", "methods", "[", "key", "]", ")", "{", "throw", "new", "Error", "(", "'Class \"'", "+", "target", ".", "prototype", ".", "$name", "+", "'\" does not implement interface \"'", "+", "this", ".", "prototype", ".", "$name", "+", "'\" correctly, method \"'", "+", "key", "+", "'\" was not found.'", ")", ";", "}", "if", "(", "!", "isFunctionCompatible", "(", "target", "[", "$class", "]", ".", "methods", "[", "key", "]", ",", "value", ")", ")", "{", "throw", "new", "Error", "(", "'Method \"'", "+", "key", "+", "'('", "+", "target", "[", "$class", "]", ".", "methods", "[", "key", "]", ".", "signature", "+", "')\" defined in class \"'", "+", "target", ".", "prototype", ".", "$name", "+", "'\" is not compatible with the one found in interface \"'", "+", "this", ".", "prototype", ".", "$name", "+", "'\": \"'", "+", "key", "+", "'('", "+", "value", ".", "signature", "+", "')\".'", ")", ";", "}", "}", "// Check static functions", "for", "(", "key", "in", "this", "[", "$interface", "]", ".", "staticMethods", ")", "{", "value", "=", "this", "[", "$interface", "]", ".", "staticMethods", "[", "key", "]", ";", "if", "(", "!", "target", "[", "$class", "]", ".", "staticMethods", "[", "key", "]", ")", "{", "throw", "new", "Error", "(", "'Class \"'", "+", "target", ".", "prototype", ".", "$name", "+", "'\" does not implement interface \"'", "+", "this", ".", "prototype", ".", "$name", "+", "'\" correctly, static method \"'", "+", "key", "+", "'\" was not found.'", ")", ";", "}", "if", "(", "!", "isFunctionCompatible", "(", "target", "[", "$class", "]", ".", "staticMethods", "[", "key", "]", ",", "value", ")", ")", "{", "throw", "new", "Error", "(", "'Static method \"'", "+", "key", "+", "'('", "+", "target", "[", "$class", "]", ".", "staticMethods", "[", "key", "]", ".", "signature", "+", "')\" defined in class \"'", "+", "target", ".", "prototype", ".", "$name", "+", "'\" is not compatible with the one found in interface \"'", "+", "this", ".", "prototype", ".", "$name", "+", "'\": \"'", "+", "key", "+", "'('", "+", "value", ".", "signature", "+", "')\".'", ")", ";", "}", "}", "}" ]
Checks if an interface is well implemented in a class. In order to this function to work, it must be bound to an interface definition. @param {Function} target The class to be checked
[ "Checks", "if", "an", "interface", "is", "well", "implemented", "in", "a", "class", ".", "In", "order", "to", "this", "function", "to", "work", "it", "must", "be", "bound", "to", "an", "interface", "definition", "." ]
b251d5e8508bb05854081968528e6a3b2ec68d33
https://github.com/IndigoUnited/js-dejavu/blob/b251d5e8508bb05854081968528e6a3b2ec68d33/dist/amd/strict/Interface.js#L64-L93
train
IndigoUnited/js-dejavu
dist/amd/strict/Interface.js
assignConstant
function assignConstant(name, value, interf) { if (hasDefineProperty) { Object.defineProperty(interf, name, { get: function () { return value; }, set: function () { throw new Error('Cannot change value of constant property "' + name + '" of interface "' + this.prototype.$name + '".'); }, configurable: false, enumerable: true }); } else { interf[name] = value; } }
javascript
function assignConstant(name, value, interf) { if (hasDefineProperty) { Object.defineProperty(interf, name, { get: function () { return value; }, set: function () { throw new Error('Cannot change value of constant property "' + name + '" of interface "' + this.prototype.$name + '".'); }, configurable: false, enumerable: true }); } else { interf[name] = value; } }
[ "function", "assignConstant", "(", "name", ",", "value", ",", "interf", ")", "{", "if", "(", "hasDefineProperty", ")", "{", "Object", ".", "defineProperty", "(", "interf", ",", "name", ",", "{", "get", ":", "function", "(", ")", "{", "return", "value", ";", "}", ",", "set", ":", "function", "(", ")", "{", "throw", "new", "Error", "(", "'Cannot change value of constant property \"'", "+", "name", "+", "'\" of interface \"'", "+", "this", ".", "prototype", ".", "$name", "+", "'\".'", ")", ";", "}", ",", "configurable", ":", "false", ",", "enumerable", ":", "true", "}", ")", ";", "}", "else", "{", "interf", "[", "name", "]", "=", "value", ";", "}", "}" ]
Assigns a constant to the interface. This method will protect the constant from being changed. @param {String} name The constant name @param {Function} value The constant value @param {Function} interf The interface in which the constant will be saved
[ "Assigns", "a", "constant", "to", "the", "interface", ".", "This", "method", "will", "protect", "the", "constant", "from", "being", "changed", "." ]
b251d5e8508bb05854081968528e6a3b2ec68d33
https://github.com/IndigoUnited/js-dejavu/blob/b251d5e8508bb05854081968528e6a3b2ec68d33/dist/amd/strict/Interface.js#L149-L164
train
IndigoUnited/js-dejavu
dist/amd/strict/Interface.js
addConstant
function addConstant(name, value, interf) { var target; // Check if it is public if (name.charAt(0) === '_') { throw new Error('Interface "' + interf.prototype.$name + '" contains an unallowed non public method: "' + name + '".'); } // Check if it is a primitive value if (!isImmutable(value)) { throw new Error('Value for constant property "' + name + '" defined in interface "' + interf.prototype.$name + '" must be a primitive type.'); } target = interf[$interface].constants; // Check if the constant already exists if (target[name]) { throw new Error('Cannot override constant property "' + name + '" in interface "' + interf.prototype.$name + '".'); } target[name] = true; assignConstant(name, value, interf); }
javascript
function addConstant(name, value, interf) { var target; // Check if it is public if (name.charAt(0) === '_') { throw new Error('Interface "' + interf.prototype.$name + '" contains an unallowed non public method: "' + name + '".'); } // Check if it is a primitive value if (!isImmutable(value)) { throw new Error('Value for constant property "' + name + '" defined in interface "' + interf.prototype.$name + '" must be a primitive type.'); } target = interf[$interface].constants; // Check if the constant already exists if (target[name]) { throw new Error('Cannot override constant property "' + name + '" in interface "' + interf.prototype.$name + '".'); } target[name] = true; assignConstant(name, value, interf); }
[ "function", "addConstant", "(", "name", ",", "value", ",", "interf", ")", "{", "var", "target", ";", "// Check if it is public", "if", "(", "name", ".", "charAt", "(", "0", ")", "===", "'_'", ")", "{", "throw", "new", "Error", "(", "'Interface \"'", "+", "interf", ".", "prototype", ".", "$name", "+", "'\" contains an unallowed non public method: \"'", "+", "name", "+", "'\".'", ")", ";", "}", "// Check if it is a primitive value", "if", "(", "!", "isImmutable", "(", "value", ")", ")", "{", "throw", "new", "Error", "(", "'Value for constant property \"'", "+", "name", "+", "'\" defined in interface \"'", "+", "interf", ".", "prototype", ".", "$name", "+", "'\" must be a primitive type.'", ")", ";", "}", "target", "=", "interf", "[", "$interface", "]", ".", "constants", ";", "// Check if the constant already exists", "if", "(", "target", "[", "name", "]", ")", "{", "throw", "new", "Error", "(", "'Cannot override constant property \"'", "+", "name", "+", "'\" in interface \"'", "+", "interf", ".", "prototype", ".", "$name", "+", "'\".'", ")", ";", "}", "target", "[", "name", "]", "=", "true", ";", "assignConstant", "(", "name", ",", "value", ",", "interf", ")", ";", "}" ]
Adds a constant to an interface. This method will throw an error if something is not right. @param {String} name The constant name @param {Function} value The constant value @param {Function} interf The interface in which the constant will be saved
[ "Adds", "a", "constant", "to", "an", "interface", ".", "This", "method", "will", "throw", "an", "error", "if", "something", "is", "not", "right", "." ]
b251d5e8508bb05854081968528e6a3b2ec68d33
https://github.com/IndigoUnited/js-dejavu/blob/b251d5e8508bb05854081968528e6a3b2ec68d33/dist/amd/strict/Interface.js#L174-L195
train
nathschmidt/restify-cookies
index.js
parseCookies
function parseCookies(req, res, next) { var self = this; var cookieHeader = req.headers.cookie; if (cookieHeader) { req.cookies = cookie.parse(cookieHeader); } else { req.cookies = {}; } /** * Add a cookie to our response. Uses a Set-Cookie header * per cookie added. * * @param {String} key - Cookie name * @param {String} val - Cookie value * @param {[type]} opts - Options object can contain path, secure, * expires, domain, http */ res.setCookie = function setCookie(key, val, opts) { var HEADER = "Set-Cookie"; if (res.header(HEADER)) { var curCookies = res.header(HEADER); if (!(curCookies instanceof Array)) { curCookies = [curCookies]; } curCookies.push(cookie.serialize(key, val, opts)); res.setHeader(HEADER, curCookies); } else { res.setHeader(HEADER, cookie.serialize(key, val, opts)); } }; res.clearCookie = function clearCookie (key, opts) { var options = merge({ expires: new Date(1) }, opts); res.setCookie(key, '', options) } next(); }
javascript
function parseCookies(req, res, next) { var self = this; var cookieHeader = req.headers.cookie; if (cookieHeader) { req.cookies = cookie.parse(cookieHeader); } else { req.cookies = {}; } /** * Add a cookie to our response. Uses a Set-Cookie header * per cookie added. * * @param {String} key - Cookie name * @param {String} val - Cookie value * @param {[type]} opts - Options object can contain path, secure, * expires, domain, http */ res.setCookie = function setCookie(key, val, opts) { var HEADER = "Set-Cookie"; if (res.header(HEADER)) { var curCookies = res.header(HEADER); if (!(curCookies instanceof Array)) { curCookies = [curCookies]; } curCookies.push(cookie.serialize(key, val, opts)); res.setHeader(HEADER, curCookies); } else { res.setHeader(HEADER, cookie.serialize(key, val, opts)); } }; res.clearCookie = function clearCookie (key, opts) { var options = merge({ expires: new Date(1) }, opts); res.setCookie(key, '', options) } next(); }
[ "function", "parseCookies", "(", "req", ",", "res", ",", "next", ")", "{", "var", "self", "=", "this", ";", "var", "cookieHeader", "=", "req", ".", "headers", ".", "cookie", ";", "if", "(", "cookieHeader", ")", "{", "req", ".", "cookies", "=", "cookie", ".", "parse", "(", "cookieHeader", ")", ";", "}", "else", "{", "req", ".", "cookies", "=", "{", "}", ";", "}", "/**\n\t\t * Add a cookie to our response. Uses a Set-Cookie header\n\t\t * per cookie added.\n\t\t * \n\t\t * @param {String} key - Cookie name\n\t\t * @param {String} val - Cookie value\n\t\t * @param {[type]} opts - Options object can contain path, secure, \n\t\t * expires, domain, http\n\t\t */", "res", ".", "setCookie", "=", "function", "setCookie", "(", "key", ",", "val", ",", "opts", ")", "{", "var", "HEADER", "=", "\"Set-Cookie\"", ";", "if", "(", "res", ".", "header", "(", "HEADER", ")", ")", "{", "var", "curCookies", "=", "res", ".", "header", "(", "HEADER", ")", ";", "if", "(", "!", "(", "curCookies", "instanceof", "Array", ")", ")", "{", "curCookies", "=", "[", "curCookies", "]", ";", "}", "curCookies", ".", "push", "(", "cookie", ".", "serialize", "(", "key", ",", "val", ",", "opts", ")", ")", ";", "res", ".", "setHeader", "(", "HEADER", ",", "curCookies", ")", ";", "}", "else", "{", "res", ".", "setHeader", "(", "HEADER", ",", "cookie", ".", "serialize", "(", "key", ",", "val", ",", "opts", ")", ")", ";", "}", "}", ";", "res", ".", "clearCookie", "=", "function", "clearCookie", "(", "key", ",", "opts", ")", "{", "var", "options", "=", "merge", "(", "{", "expires", ":", "new", "Date", "(", "1", ")", "}", ",", "opts", ")", ";", "res", ".", "setCookie", "(", "key", ",", "''", ",", "options", ")", "}", "next", "(", ")", ";", "}" ]
Parse function to be handed to restify server.use @param {object} req @param {object} res @param {Function} next @return {undefined}
[ "Parse", "function", "to", "be", "handed", "to", "restify", "server", ".", "use" ]
7aabcc930adc506837e2ce2cae655f997dedf6ec
https://github.com/nathschmidt/restify-cookies/blob/7aabcc930adc506837e2ce2cae655f997dedf6ec/index.js#L20-L70
train
GoogleCloudPlatform/cloud-errors-nodejs
lib/interfaces/manual.js
reportManualError
function reportManualError(err, request, additionalMessage, callback) { if (isString(request)) { // no request given callback = additionalMessage; additionalMessage = request; request = undefined; } else if (isFunction(request)) { // neither request nor additionalMessage given callback = request; request = undefined; additionalMessage = undefined; } if (isFunction(additionalMessage)) { callback = additionalMessage; additionalMessage = undefined; } var em = new ErrorMessage(); em.setServiceContext(config.getServiceContext().service, config.getServiceContext().version); errorHandlerRouter(err, em); if (isObject(request)) { em.consumeRequestInformation(manualRequestInformationExtractor(request)); } if (isString(additionalMessage)) { em.setMessage(additionalMessage); } client.sendError(em, callback); return em; }
javascript
function reportManualError(err, request, additionalMessage, callback) { if (isString(request)) { // no request given callback = additionalMessage; additionalMessage = request; request = undefined; } else if (isFunction(request)) { // neither request nor additionalMessage given callback = request; request = undefined; additionalMessage = undefined; } if (isFunction(additionalMessage)) { callback = additionalMessage; additionalMessage = undefined; } var em = new ErrorMessage(); em.setServiceContext(config.getServiceContext().service, config.getServiceContext().version); errorHandlerRouter(err, em); if (isObject(request)) { em.consumeRequestInformation(manualRequestInformationExtractor(request)); } if (isString(additionalMessage)) { em.setMessage(additionalMessage); } client.sendError(em, callback); return em; }
[ "function", "reportManualError", "(", "err", ",", "request", ",", "additionalMessage", ",", "callback", ")", "{", "if", "(", "isString", "(", "request", ")", ")", "{", "// no request given", "callback", "=", "additionalMessage", ";", "additionalMessage", "=", "request", ";", "request", "=", "undefined", ";", "}", "else", "if", "(", "isFunction", "(", "request", ")", ")", "{", "// neither request nor additionalMessage given", "callback", "=", "request", ";", "request", "=", "undefined", ";", "additionalMessage", "=", "undefined", ";", "}", "if", "(", "isFunction", "(", "additionalMessage", ")", ")", "{", "callback", "=", "additionalMessage", ";", "additionalMessage", "=", "undefined", ";", "}", "var", "em", "=", "new", "ErrorMessage", "(", ")", ";", "em", ".", "setServiceContext", "(", "config", ".", "getServiceContext", "(", ")", ".", "service", ",", "config", ".", "getServiceContext", "(", ")", ".", "version", ")", ";", "errorHandlerRouter", "(", "err", ",", "em", ")", ";", "if", "(", "isObject", "(", "request", ")", ")", "{", "em", ".", "consumeRequestInformation", "(", "manualRequestInformationExtractor", "(", "request", ")", ")", ";", "}", "if", "(", "isString", "(", "additionalMessage", ")", ")", "{", "em", ".", "setMessage", "(", "additionalMessage", ")", ";", "}", "client", ".", "sendError", "(", "em", ",", "callback", ")", ";", "return", "em", ";", "}" ]
The interface for manually reporting errors to the Google Error API in application code. @param {Any} err - error information of any type or content. This can be of any type but better errors will be logged given a valid instance of Error class. @param {Object} [request] - an object containing request information. This is expected to be an object similar to the Node/Express request object. @param {String} [additionalMessage] - a string containing error message information to override the builtin message given by an Error/Exception @param {Function} [callback] - a callback to be invoked once the message has been successfully submitted to the error reporting API or has failed after four attempts with the success or error response. @returns {ErrorMessage} - returns the error message created through with the parameters given.
[ "The", "interface", "for", "manually", "reporting", "errors", "to", "the", "Google", "Error", "API", "in", "application", "code", "." ]
fda2218759cd8754a096dbe437e8a668321f5ba6
https://github.com/GoogleCloudPlatform/cloud-errors-nodejs/blob/fda2218759cd8754a096dbe437e8a668321f5ba6/lib/interfaces/manual.js#L56-L90
train
IndigoUnited/js-dejavu
dist/regular/loose/dejavu.js
isImmutable
function isImmutable(value) { return value == null || isBoolean(value) || isNumber(value) || isString(value); }
javascript
function isImmutable(value) { return value == null || isBoolean(value) || isNumber(value) || isString(value); }
[ "function", "isImmutable", "(", "value", ")", "{", "return", "value", "==", "null", "||", "isBoolean", "(", "value", ")", "||", "isNumber", "(", "value", ")", "||", "isString", "(", "value", ")", ";", "}" ]
Checks if a value is immutable. @param {Mixed} value The value @return {Boolean} True if it is, false otherwise
[ "Checks", "if", "a", "value", "is", "immutable", "." ]
b251d5e8508bb05854081968528e6a3b2ec68d33
https://github.com/IndigoUnited/js-dejavu/blob/b251d5e8508bb05854081968528e6a3b2ec68d33/dist/regular/loose/dejavu.js#L617-L619
train
IndigoUnited/js-dejavu
dist/regular/loose/dejavu.js
mixIn
function mixIn(target, objects){ var i = 0, n = arguments.length, obj; while(++i < n){ obj = arguments[i]; if (obj != null) { forOwn(obj, copyProp, target); } } return target; }
javascript
function mixIn(target, objects){ var i = 0, n = arguments.length, obj; while(++i < n){ obj = arguments[i]; if (obj != null) { forOwn(obj, copyProp, target); } } return target; }
[ "function", "mixIn", "(", "target", ",", "objects", ")", "{", "var", "i", "=", "0", ",", "n", "=", "arguments", ".", "length", ",", "obj", ";", "while", "(", "++", "i", "<", "n", ")", "{", "obj", "=", "arguments", "[", "i", "]", ";", "if", "(", "obj", "!=", "null", ")", "{", "forOwn", "(", "obj", ",", "copyProp", ",", "target", ")", ";", "}", "}", "return", "target", ";", "}" ]
Combine properties from all the objects into first one. - This method affects target object in place, if you want to create a new Object pass an empty object as first param. @param {object} target Target Object @param {...object} objects Objects to be combined (0...n objects). @return {object} Target Object.
[ "Combine", "properties", "from", "all", "the", "objects", "into", "first", "one", ".", "-", "This", "method", "affects", "target", "object", "in", "place", "if", "you", "want", "to", "create", "a", "new", "Object", "pass", "an", "empty", "object", "as", "first", "param", "." ]
b251d5e8508bb05854081968528e6a3b2ec68d33
https://github.com/IndigoUnited/js-dejavu/blob/b251d5e8508bb05854081968528e6a3b2ec68d33/dist/regular/loose/dejavu.js#L793-L804
train
IndigoUnited/js-dejavu
dist/regular/loose/dejavu.js
indexOf
function indexOf(arr, item, fromIndex) { fromIndex = fromIndex || 0; if (arr == null) { return -1; } var len = arr.length, i = fromIndex < 0 ? len + fromIndex : fromIndex; while (i < len) { // we iterate over sparse items since there is no way to make it // work properly on IE 7-8. see #64 if (arr[i] === item) { return i; } i++; } return -1; }
javascript
function indexOf(arr, item, fromIndex) { fromIndex = fromIndex || 0; if (arr == null) { return -1; } var len = arr.length, i = fromIndex < 0 ? len + fromIndex : fromIndex; while (i < len) { // we iterate over sparse items since there is no way to make it // work properly on IE 7-8. see #64 if (arr[i] === item) { return i; } i++; } return -1; }
[ "function", "indexOf", "(", "arr", ",", "item", ",", "fromIndex", ")", "{", "fromIndex", "=", "fromIndex", "||", "0", ";", "if", "(", "arr", "==", "null", ")", "{", "return", "-", "1", ";", "}", "var", "len", "=", "arr", ".", "length", ",", "i", "=", "fromIndex", "<", "0", "?", "len", "+", "fromIndex", ":", "fromIndex", ";", "while", "(", "i", "<", "len", ")", "{", "// we iterate over sparse items since there is no way to make it", "// work properly on IE 7-8. see #64", "if", "(", "arr", "[", "i", "]", "===", "item", ")", "{", "return", "i", ";", "}", "i", "++", ";", "}", "return", "-", "1", ";", "}" ]
Array.indexOf
[ "Array", ".", "indexOf" ]
b251d5e8508bb05854081968528e6a3b2ec68d33
https://github.com/IndigoUnited/js-dejavu/blob/b251d5e8508bb05854081968528e6a3b2ec68d33/dist/regular/loose/dejavu.js#L841-L860
train
IndigoUnited/js-dejavu
dist/regular/loose/dejavu.js
combine
function combine(arr1, arr2) { if (arr2 == null) { return arr1; } var i = -1, len = arr2.length; while (++i < len) { if (indexOf(arr1, arr2[i]) === -1) { arr1.push(arr2[i]); } } return arr1; }
javascript
function combine(arr1, arr2) { if (arr2 == null) { return arr1; } var i = -1, len = arr2.length; while (++i < len) { if (indexOf(arr1, arr2[i]) === -1) { arr1.push(arr2[i]); } } return arr1; }
[ "function", "combine", "(", "arr1", ",", "arr2", ")", "{", "if", "(", "arr2", "==", "null", ")", "{", "return", "arr1", ";", "}", "var", "i", "=", "-", "1", ",", "len", "=", "arr2", ".", "length", ";", "while", "(", "++", "i", "<", "len", ")", "{", "if", "(", "indexOf", "(", "arr1", ",", "arr2", "[", "i", "]", ")", "===", "-", "1", ")", "{", "arr1", ".", "push", "(", "arr2", "[", "i", "]", ")", ";", "}", "}", "return", "arr1", ";", "}" ]
Combines an array with all the items of another. Does not allow duplicates and is case and type sensitive.
[ "Combines", "an", "array", "with", "all", "the", "items", "of", "another", ".", "Does", "not", "allow", "duplicates", "and", "is", "case", "and", "type", "sensitive", "." ]
b251d5e8508bb05854081968528e6a3b2ec68d33
https://github.com/IndigoUnited/js-dejavu/blob/b251d5e8508bb05854081968528e6a3b2ec68d33/dist/regular/loose/dejavu.js#L873-L886
train
IndigoUnited/js-dejavu
dist/regular/loose/dejavu.js
clone
function clone(val){ switch (kindOf(val)) { case 'Object': return cloneObject(val); case 'Array': return cloneArray(val); case 'RegExp': return cloneRegExp(val); case 'Date': return cloneDate(val); default: return val; } }
javascript
function clone(val){ switch (kindOf(val)) { case 'Object': return cloneObject(val); case 'Array': return cloneArray(val); case 'RegExp': return cloneRegExp(val); case 'Date': return cloneDate(val); default: return val; } }
[ "function", "clone", "(", "val", ")", "{", "switch", "(", "kindOf", "(", "val", ")", ")", "{", "case", "'Object'", ":", "return", "cloneObject", "(", "val", ")", ";", "case", "'Array'", ":", "return", "cloneArray", "(", "val", ")", ";", "case", "'RegExp'", ":", "return", "cloneRegExp", "(", "val", ")", ";", "case", "'Date'", ":", "return", "cloneDate", "(", "val", ")", ";", "default", ":", "return", "val", ";", "}", "}" ]
Clone native types.
[ "Clone", "native", "types", "." ]
b251d5e8508bb05854081968528e6a3b2ec68d33
https://github.com/IndigoUnited/js-dejavu/blob/b251d5e8508bb05854081968528e6a3b2ec68d33/dist/regular/loose/dejavu.js#L928-L941
train
IndigoUnited/js-dejavu
dist/regular/loose/dejavu.js
deepClone
function deepClone(val, instanceClone) { switch ( kindOf(val) ) { case 'Object': return cloneObject(val, instanceClone); case 'Array': return cloneArray(val, instanceClone); default: return clone(val); } }
javascript
function deepClone(val, instanceClone) { switch ( kindOf(val) ) { case 'Object': return cloneObject(val, instanceClone); case 'Array': return cloneArray(val, instanceClone); default: return clone(val); } }
[ "function", "deepClone", "(", "val", ",", "instanceClone", ")", "{", "switch", "(", "kindOf", "(", "val", ")", ")", "{", "case", "'Object'", ":", "return", "cloneObject", "(", "val", ",", "instanceClone", ")", ";", "case", "'Array'", ":", "return", "cloneArray", "(", "val", ",", "instanceClone", ")", ";", "default", ":", "return", "clone", "(", "val", ")", ";", "}", "}" ]
Recursively clone native types.
[ "Recursively", "clone", "native", "types", "." ]
b251d5e8508bb05854081968528e6a3b2ec68d33
https://github.com/IndigoUnited/js-dejavu/blob/b251d5e8508bb05854081968528e6a3b2ec68d33/dist/regular/loose/dejavu.js#L981-L990
train
IndigoUnited/js-dejavu
dist/regular/loose/dejavu.js
append
function append(arr1, arr2) { if (arr2 == null) { return arr1; } var pad = arr1.length, i = -1, len = arr2.length; while (++i < len) { arr1[pad + i] = arr2[i]; } return arr1; }
javascript
function append(arr1, arr2) { if (arr2 == null) { return arr1; } var pad = arr1.length, i = -1, len = arr2.length; while (++i < len) { arr1[pad + i] = arr2[i]; } return arr1; }
[ "function", "append", "(", "arr1", ",", "arr2", ")", "{", "if", "(", "arr2", "==", "null", ")", "{", "return", "arr1", ";", "}", "var", "pad", "=", "arr1", ".", "length", ",", "i", "=", "-", "1", ",", "len", "=", "arr2", ".", "length", ";", "while", "(", "++", "i", "<", "len", ")", "{", "arr1", "[", "pad", "+", "i", "]", "=", "arr2", "[", "i", "]", ";", "}", "return", "arr1", ";", "}" ]
Appends an array to the end of another. The first array will be modified.
[ "Appends", "an", "array", "to", "the", "end", "of", "another", ".", "The", "first", "array", "will", "be", "modified", "." ]
b251d5e8508bb05854081968528e6a3b2ec68d33
https://github.com/IndigoUnited/js-dejavu/blob/b251d5e8508bb05854081968528e6a3b2ec68d33/dist/regular/loose/dejavu.js#L1065-L1077
train
IndigoUnited/js-dejavu
dist/regular/loose/dejavu.js
bind
function bind(fn, context, args){ var argsArr = slice(arguments, 2); //curried args return function(){ return fn.apply(context, argsArr.concat(slice(arguments))); }; }
javascript
function bind(fn, context, args){ var argsArr = slice(arguments, 2); //curried args return function(){ return fn.apply(context, argsArr.concat(slice(arguments))); }; }
[ "function", "bind", "(", "fn", ",", "context", ",", "args", ")", "{", "var", "argsArr", "=", "slice", "(", "arguments", ",", "2", ")", ";", "//curried args", "return", "function", "(", ")", "{", "return", "fn", ".", "apply", "(", "context", ",", "argsArr", ".", "concat", "(", "slice", "(", "arguments", ")", ")", ")", ";", "}", ";", "}" ]
Return a function that will execute in the given context, optionally adding any additional supplied parameters to the beginning of the arguments collection. @param {Function} fn Function. @param {object} context Execution context. @param {rest} args Arguments (0...n arguments). @return {Function} Wrapped Function.
[ "Return", "a", "function", "that", "will", "execute", "in", "the", "given", "context", "optionally", "adding", "any", "additional", "supplied", "parameters", "to", "the", "beginning", "of", "the", "arguments", "collection", "." ]
b251d5e8508bb05854081968528e6a3b2ec68d33
https://github.com/IndigoUnited/js-dejavu/blob/b251d5e8508bb05854081968528e6a3b2ec68d33/dist/regular/loose/dejavu.js#L1130-L1135
train
IndigoUnited/js-dejavu
dist/regular/loose/dejavu.js
toArray
function toArray(val){ var ret = [], kind = kindOf(val), n; if (val != null) { if ( val.length == null || kind === 'String' || kind === 'Function' || kind === 'RegExp' || val === _win ) { //string, regexp, function have .length but user probably just want //to wrap value into an array.. ret[ret.length] = val; } else { //window returns true on isObject in IE7 and may have length //property. `typeof NodeList` returns `function` on Safari so //we can't use it (#58) n = val.length; while (n--) { ret[n] = val[n]; } } } return ret; }
javascript
function toArray(val){ var ret = [], kind = kindOf(val), n; if (val != null) { if ( val.length == null || kind === 'String' || kind === 'Function' || kind === 'RegExp' || val === _win ) { //string, regexp, function have .length but user probably just want //to wrap value into an array.. ret[ret.length] = val; } else { //window returns true on isObject in IE7 and may have length //property. `typeof NodeList` returns `function` on Safari so //we can't use it (#58) n = val.length; while (n--) { ret[n] = val[n]; } } } return ret; }
[ "function", "toArray", "(", "val", ")", "{", "var", "ret", "=", "[", "]", ",", "kind", "=", "kindOf", "(", "val", ")", ",", "n", ";", "if", "(", "val", "!=", "null", ")", "{", "if", "(", "val", ".", "length", "==", "null", "||", "kind", "===", "'String'", "||", "kind", "===", "'Function'", "||", "kind", "===", "'RegExp'", "||", "val", "===", "_win", ")", "{", "//string, regexp, function have .length but user probably just want", "//to wrap value into an array..", "ret", "[", "ret", ".", "length", "]", "=", "val", ";", "}", "else", "{", "//window returns true on isObject in IE7 and may have length", "//property. `typeof NodeList` returns `function` on Safari so", "//we can't use it (#58)", "n", "=", "val", ".", "length", ";", "while", "(", "n", "--", ")", "{", "ret", "[", "n", "]", "=", "val", "[", "n", "]", ";", "}", "}", "}", "return", "ret", ";", "}" ]
Convert array-like object into array
[ "Convert", "array", "-", "like", "object", "into", "array" ]
b251d5e8508bb05854081968528e6a3b2ec68d33
https://github.com/IndigoUnited/js-dejavu/blob/b251d5e8508bb05854081968528e6a3b2ec68d33/dist/regular/loose/dejavu.js#L1150-L1171
train
IndigoUnited/js-dejavu
dist/regular/loose/dejavu.js
deepMatches
function deepMatches(target, pattern){ if (target && typeof target === 'object') { if (isArray(target) && isArray(pattern)) { return matchArray(target, pattern); } else { return matchObject(target, pattern); } } else { return target === pattern; } }
javascript
function deepMatches(target, pattern){ if (target && typeof target === 'object') { if (isArray(target) && isArray(pattern)) { return matchArray(target, pattern); } else { return matchObject(target, pattern); } } else { return target === pattern; } }
[ "function", "deepMatches", "(", "target", ",", "pattern", ")", "{", "if", "(", "target", "&&", "typeof", "target", "===", "'object'", ")", "{", "if", "(", "isArray", "(", "target", ")", "&&", "isArray", "(", "pattern", ")", ")", "{", "return", "matchArray", "(", "target", ",", "pattern", ")", ";", "}", "else", "{", "return", "matchObject", "(", "target", ",", "pattern", ")", ";", "}", "}", "else", "{", "return", "target", "===", "pattern", ";", "}", "}" ]
Recursively check if the objects match.
[ "Recursively", "check", "if", "the", "objects", "match", "." ]
b251d5e8508bb05854081968528e6a3b2ec68d33
https://github.com/IndigoUnited/js-dejavu/blob/b251d5e8508bb05854081968528e6a3b2ec68d33/dist/regular/loose/dejavu.js#L1249-L1259
train
IndigoUnited/js-dejavu
dist/regular/loose/dejavu.js
difference
function difference(arr) { var arrs = slice(arguments, 1), result = filter(unique(arr), function(needle){ return !some(arrs, function(haystack){ return contains(haystack, needle); }); }); return result; }
javascript
function difference(arr) { var arrs = slice(arguments, 1), result = filter(unique(arr), function(needle){ return !some(arrs, function(haystack){ return contains(haystack, needle); }); }); return result; }
[ "function", "difference", "(", "arr", ")", "{", "var", "arrs", "=", "slice", "(", "arguments", ",", "1", ")", ",", "result", "=", "filter", "(", "unique", "(", "arr", ")", ",", "function", "(", "needle", ")", "{", "return", "!", "some", "(", "arrs", ",", "function", "(", "haystack", ")", "{", "return", "contains", "(", "haystack", ",", "needle", ")", ";", "}", ")", ";", "}", ")", ";", "return", "result", ";", "}" ]
Return a new Array with elements that aren't present in the other Arrays.
[ "Return", "a", "new", "Array", "with", "elements", "that", "aren", "t", "present", "in", "the", "other", "Arrays", "." ]
b251d5e8508bb05854081968528e6a3b2ec68d33
https://github.com/IndigoUnited/js-dejavu/blob/b251d5e8508bb05854081968528e6a3b2ec68d33/dist/regular/loose/dejavu.js#L1401-L1409
train
IndigoUnited/js-dejavu
dist/regular/loose/dejavu.js
insert
function insert(arr, rest_items) { var diff = difference(slice(arguments, 1), arr); if (diff.length) { Array.prototype.push.apply(arr, diff); } return arr.length; }
javascript
function insert(arr, rest_items) { var diff = difference(slice(arguments, 1), arr); if (diff.length) { Array.prototype.push.apply(arr, diff); } return arr.length; }
[ "function", "insert", "(", "arr", ",", "rest_items", ")", "{", "var", "diff", "=", "difference", "(", "slice", "(", "arguments", ",", "1", ")", ",", "arr", ")", ";", "if", "(", "diff", ".", "length", ")", "{", "Array", ".", "prototype", ".", "push", ".", "apply", "(", "arr", ",", "diff", ")", ";", "}", "return", "arr", ".", "length", ";", "}" ]
Insert item into array if not already present.
[ "Insert", "item", "into", "array", "if", "not", "already", "present", "." ]
b251d5e8508bb05854081968528e6a3b2ec68d33
https://github.com/IndigoUnited/js-dejavu/blob/b251d5e8508bb05854081968528e6a3b2ec68d33/dist/regular/loose/dejavu.js#L1423-L1429
train
IndigoUnited/js-dejavu
dist/regular/loose/dejavu.js
interfaceDescendantOf
function interfaceDescendantOf(interf1, interf2) { var x, parents = interf1[$interface].parents; for (x = parents.length - 1; x >= 0; x -= 1) { if (parents[x] === interf2) { return true; } if (interfaceDescendantOf(interf1, parents[x])) { return true; } } return false; }
javascript
function interfaceDescendantOf(interf1, interf2) { var x, parents = interf1[$interface].parents; for (x = parents.length - 1; x >= 0; x -= 1) { if (parents[x] === interf2) { return true; } if (interfaceDescendantOf(interf1, parents[x])) { return true; } } return false; }
[ "function", "interfaceDescendantOf", "(", "interf1", ",", "interf2", ")", "{", "var", "x", ",", "parents", "=", "interf1", "[", "$interface", "]", ".", "parents", ";", "for", "(", "x", "=", "parents", ".", "length", "-", "1", ";", "x", ">=", "0", ";", "x", "-=", "1", ")", "{", "if", "(", "parents", "[", "x", "]", "===", "interf2", ")", "{", "return", "true", ";", "}", "if", "(", "interfaceDescendantOf", "(", "interf1", ",", "parents", "[", "x", "]", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Check if an interface is descendant of another. @param {Function} interf1 The interface to be checked @param {Function} interf2 The interface to be expected as the ancestor @return {Boolean} True if it's a descendant, false otherwise
[ "Check", "if", "an", "interface", "is", "descendant", "of", "another", "." ]
b251d5e8508bb05854081968528e6a3b2ec68d33
https://github.com/IndigoUnited/js-dejavu/blob/b251d5e8508bb05854081968528e6a3b2ec68d33/dist/regular/loose/dejavu.js#L2421-L2435
train
IndigoUnited/js-dejavu
dist/regular/loose/dejavu.js
instanceOfInterface
function instanceOfInterface(instance, target) { var x, interfaces = instance.$static[$class].interfaces; for (x = interfaces.length - 1; x >= 0; x -= 1) { if (interfaces[x] === target || interfaceDescendantOf(interfaces[x], target)) { return true; } } return false; }
javascript
function instanceOfInterface(instance, target) { var x, interfaces = instance.$static[$class].interfaces; for (x = interfaces.length - 1; x >= 0; x -= 1) { if (interfaces[x] === target || interfaceDescendantOf(interfaces[x], target)) { return true; } } return false; }
[ "function", "instanceOfInterface", "(", "instance", ",", "target", ")", "{", "var", "x", ",", "interfaces", "=", "instance", ".", "$static", "[", "$class", "]", ".", "interfaces", ";", "for", "(", "x", "=", "interfaces", ".", "length", "-", "1", ";", "x", ">=", "0", ";", "x", "-=", "1", ")", "{", "if", "(", "interfaces", "[", "x", "]", "===", "target", "||", "interfaceDescendantOf", "(", "interfaces", "[", "x", "]", ",", "target", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Check if an instance of a class is an instance of an interface. @param {Object} instance The instance to be checked @param {Function} target The interface @return {Boolean} True if it is, false otherwise
[ "Check", "if", "an", "instance", "of", "a", "class", "is", "an", "instance", "of", "an", "interface", "." ]
b251d5e8508bb05854081968528e6a3b2ec68d33
https://github.com/IndigoUnited/js-dejavu/blob/b251d5e8508bb05854081968528e6a3b2ec68d33/dist/regular/loose/dejavu.js#L2445-L2456
train
IndigoUnited/js-dejavu
dist/regular/loose/dejavu.js
instanceOf
function instanceOf(instance, target) { if (!isFunction(target)) { return false; } if (instance instanceof target) { return true; } if (instance && instance.$static && instance.$static[$class] && target && target[$interface]) { return instanceOfInterface(instance, target); } return false; }
javascript
function instanceOf(instance, target) { if (!isFunction(target)) { return false; } if (instance instanceof target) { return true; } if (instance && instance.$static && instance.$static[$class] && target && target[$interface]) { return instanceOfInterface(instance, target); } return false; }
[ "function", "instanceOf", "(", "instance", ",", "target", ")", "{", "if", "(", "!", "isFunction", "(", "target", ")", ")", "{", "return", "false", ";", "}", "if", "(", "instance", "instanceof", "target", ")", "{", "return", "true", ";", "}", "if", "(", "instance", "&&", "instance", ".", "$static", "&&", "instance", ".", "$static", "[", "$class", "]", "&&", "target", "&&", "target", "[", "$interface", "]", ")", "{", "return", "instanceOfInterface", "(", "instance", ",", "target", ")", ";", "}", "return", "false", ";", "}" ]
Custom instanceOf that also works on interfaces. @param {Object} instance The instance to be checked @param {Function} target The target @return {Boolean} True if it is a valid instance of target, false otherwise
[ "Custom", "instanceOf", "that", "also", "works", "on", "interfaces", "." ]
b251d5e8508bb05854081968528e6a3b2ec68d33
https://github.com/IndigoUnited/js-dejavu/blob/b251d5e8508bb05854081968528e6a3b2ec68d33/dist/regular/loose/dejavu.js#L2466-L2480
train
IndigoUnited/js-dejavu
dist/amd/strict/lib/functionMeta.js
functionMeta
function functionMeta(func, name) { var matches = /^function(\s+[a-zA-Z0-9_\$]*)*\s*\(([^\(]*)\)/m.exec(func.toString()), ret, split, optionalReached = false, length, x; // Analyze arguments if (!matches) { return null; } split = (matches[2] || '').split(/\s*,\s*/gm); length = split.length; ret = { mandatory: 0, optional: 0, signature: '' }; if (split[0] !== '') { for (x = 0; x < length; x += 1) { if (split[x].charAt(0) === '$') { ret.optional += 1; ret.signature += split[x] + ', '; optionalReached = true; } else if (!optionalReached) { ret.mandatory += 1; ret.signature += split[x] + ', '; } else { return null; } } ret.signature = ret.signature.substr(0, ret.signature.length - 2); } // Analyze visibility if (name) { if (name.charAt(0) === '_') { if (name.charAt(1) === '_') { ret.isPrivate = true; } else { ret.isProtected = true; } } else { ret.isPublic = true; } } return ret; }
javascript
function functionMeta(func, name) { var matches = /^function(\s+[a-zA-Z0-9_\$]*)*\s*\(([^\(]*)\)/m.exec(func.toString()), ret, split, optionalReached = false, length, x; // Analyze arguments if (!matches) { return null; } split = (matches[2] || '').split(/\s*,\s*/gm); length = split.length; ret = { mandatory: 0, optional: 0, signature: '' }; if (split[0] !== '') { for (x = 0; x < length; x += 1) { if (split[x].charAt(0) === '$') { ret.optional += 1; ret.signature += split[x] + ', '; optionalReached = true; } else if (!optionalReached) { ret.mandatory += 1; ret.signature += split[x] + ', '; } else { return null; } } ret.signature = ret.signature.substr(0, ret.signature.length - 2); } // Analyze visibility if (name) { if (name.charAt(0) === '_') { if (name.charAt(1) === '_') { ret.isPrivate = true; } else { ret.isProtected = true; } } else { ret.isPublic = true; } } return ret; }
[ "function", "functionMeta", "(", "func", ",", "name", ")", "{", "var", "matches", "=", "/", "^function(\\s+[a-zA-Z0-9_\\$]*)*\\s*\\(([^\\(]*)\\)", "/", "m", ".", "exec", "(", "func", ".", "toString", "(", ")", ")", ",", "ret", ",", "split", ",", "optionalReached", "=", "false", ",", "length", ",", "x", ";", "// Analyze arguments", "if", "(", "!", "matches", ")", "{", "return", "null", ";", "}", "split", "=", "(", "matches", "[", "2", "]", "||", "''", ")", ".", "split", "(", "/", "\\s*,\\s*", "/", "gm", ")", ";", "length", "=", "split", ".", "length", ";", "ret", "=", "{", "mandatory", ":", "0", ",", "optional", ":", "0", ",", "signature", ":", "''", "}", ";", "if", "(", "split", "[", "0", "]", "!==", "''", ")", "{", "for", "(", "x", "=", "0", ";", "x", "<", "length", ";", "x", "+=", "1", ")", "{", "if", "(", "split", "[", "x", "]", ".", "charAt", "(", "0", ")", "===", "'$'", ")", "{", "ret", ".", "optional", "+=", "1", ";", "ret", ".", "signature", "+=", "split", "[", "x", "]", "+", "', '", ";", "optionalReached", "=", "true", ";", "}", "else", "if", "(", "!", "optionalReached", ")", "{", "ret", ".", "mandatory", "+=", "1", ";", "ret", ".", "signature", "+=", "split", "[", "x", "]", "+", "', '", ";", "}", "else", "{", "return", "null", ";", "}", "}", "ret", ".", "signature", "=", "ret", ".", "signature", ".", "substr", "(", "0", ",", "ret", ".", "signature", ".", "length", "-", "2", ")", ";", "}", "// Analyze visibility", "if", "(", "name", ")", "{", "if", "(", "name", ".", "charAt", "(", "0", ")", "===", "'_'", ")", "{", "if", "(", "name", ".", "charAt", "(", "1", ")", "===", "'_'", ")", "{", "ret", ".", "isPrivate", "=", "true", ";", "}", "else", "{", "ret", ".", "isProtected", "=", "true", ";", "}", "}", "else", "{", "ret", ".", "isPublic", "=", "true", ";", "}", "}", "return", "ret", ";", "}" ]
Extract meta data from a function. It returns an object containing the number of normal arguments, the number of optional arguments, the function signature, the function name and the visibility. Will return null if the function arguments are invalid. @param {Function} func The function @param {String} name The name of the function @return {Object|null} An object containg the function metadata
[ "Extract", "meta", "data", "from", "a", "function", ".", "It", "returns", "an", "object", "containing", "the", "number", "of", "normal", "arguments", "the", "number", "of", "optional", "arguments", "the", "function", "signature", "the", "function", "name", "and", "the", "visibility", "." ]
b251d5e8508bb05854081968528e6a3b2ec68d33
https://github.com/IndigoUnited/js-dejavu/blob/b251d5e8508bb05854081968528e6a3b2ec68d33/dist/amd/strict/lib/functionMeta.js#L19-L68
train
GoogleCloudPlatform/cloud-errors-nodejs
lib/error-handlers/error.js
handleErrorClassError
function handleErrorClassError(err, errorMessage) { if (err instanceof Error) { extractFromErrorClass(err, errorMessage); } else { handleUnknownAsError(err, errorMessage); } }
javascript
function handleErrorClassError(err, errorMessage) { if (err instanceof Error) { extractFromErrorClass(err, errorMessage); } else { handleUnknownAsError(err, errorMessage); } }
[ "function", "handleErrorClassError", "(", "err", ",", "errorMessage", ")", "{", "if", "(", "err", "instanceof", "Error", ")", "{", "extractFromErrorClass", "(", "err", ",", "errorMessage", ")", ";", "}", "else", "{", "handleUnknownAsError", "(", "err", ",", "errorMessage", ")", ";", "}", "}" ]
Handles routing and validation for parsing an errorMessage that was flagged as an instance of the Error class. This function does not discriminate against regular objects, checking only to see if the err parameter is itself a basic object and has the function property hasOwnProperty. Given that the input passes this basic test the input will undergo extraction by the extractFromErrorClass function, otherwise it will be treated and processed as an unknown. @function handleErrorClassError @param {Error} err - the error instance to extract information from @param {ErrorMessage} errorMessage - the error message to marshal error information into. @returns {Undefined} - does not return anything
[ "Handles", "routing", "and", "validation", "for", "parsing", "an", "errorMessage", "that", "was", "flagged", "as", "an", "instance", "of", "the", "Error", "class", ".", "This", "function", "does", "not", "discriminate", "against", "regular", "objects", "checking", "only", "to", "see", "if", "the", "err", "parameter", "is", "itself", "a", "basic", "object", "and", "has", "the", "function", "property", "hasOwnProperty", ".", "Given", "that", "the", "input", "passes", "this", "basic", "test", "the", "input", "will", "undergo", "extraction", "by", "the", "extractFromErrorClass", "function", "otherwise", "it", "will", "be", "treated", "and", "processed", "as", "an", "unknown", "." ]
fda2218759cd8754a096dbe437e8a668321f5ba6
https://github.com/GoogleCloudPlatform/cloud-errors-nodejs/blob/fda2218759cd8754a096dbe437e8a668321f5ba6/lib/error-handlers/error.js#L35-L44
train
GoogleCloudPlatform/cloud-errors-nodejs
lib/interfaces/hapi.js
hapiErrorHandler
function hapiErrorHandler(req, err, config) { var service = ''; var version = ''; if (isObject(config)) { service = config.getServiceContext().service; version = config.getServiceContext().version; } var em = new ErrorMessage() .consumeRequestInformation(hapiRequestInformationExtractor(req)) .setServiceContext(service, version); errorHandlerRouter(err, em); return em; }
javascript
function hapiErrorHandler(req, err, config) { var service = ''; var version = ''; if (isObject(config)) { service = config.getServiceContext().service; version = config.getServiceContext().version; } var em = new ErrorMessage() .consumeRequestInformation(hapiRequestInformationExtractor(req)) .setServiceContext(service, version); errorHandlerRouter(err, em); return em; }
[ "function", "hapiErrorHandler", "(", "req", ",", "err", ",", "config", ")", "{", "var", "service", "=", "''", ";", "var", "version", "=", "''", ";", "if", "(", "isObject", "(", "config", ")", ")", "{", "service", "=", "config", ".", "getServiceContext", "(", ")", ".", "service", ";", "version", "=", "config", ".", "getServiceContext", "(", ")", ".", "version", ";", "}", "var", "em", "=", "new", "ErrorMessage", "(", ")", ".", "consumeRequestInformation", "(", "hapiRequestInformationExtractor", "(", "req", ")", ")", ".", "setServiceContext", "(", "service", ",", "version", ")", ";", "errorHandlerRouter", "(", "err", ",", "em", ")", ";", "return", "em", ";", "}" ]
The Hapi error handler function serves simply to create an error message and begin that error message on the path of correct population. @function hapiErrorHandler @param {Object} req - The Hapi request object @param {Any} err - The error input @param {Object} config - the env configuration @returns {ErrorMessage} - a partially or fully populated instance of ErrorMessage
[ "The", "Hapi", "error", "handler", "function", "serves", "simply", "to", "create", "an", "error", "message", "and", "begin", "that", "error", "message", "on", "the", "path", "of", "correct", "population", "." ]
fda2218759cd8754a096dbe437e8a668321f5ba6
https://github.com/GoogleCloudPlatform/cloud-errors-nodejs/blob/fda2218759cd8754a096dbe437e8a668321f5ba6/lib/interfaces/hapi.js#L36-L52
train
GoogleCloudPlatform/cloud-errors-nodejs
lib/interfaces/hapi.js
makeHapiPlugin
function makeHapiPlugin(client, config) { /** * The register function serves to attach the hapiErrorHandler to specific * points in the hapi request-response lifecycle. Namely: it attaches to the * 'request-error' event in Hapi which is emitted when a plugin or receiver * throws an error while executing and the 'onPreResponse' event to intercept * error code carrying requests before they are sent back to the client so * that the errors can be logged to the Error Reporting API. * @function hapiRegisterFunction * @param {Hapi.Server} server - A Hapi server instance * @param {Object} options - The server configuration options object * @param {Function} next - The Hapi callback to move execution to the next * plugin * @returns {Undefined} - returns the execution of the next callback */ function hapiRegisterFunction(server, options, next) { if (isObject(server)) { if (isFunction(server.on)) { server.on('request-error', function(req, err) { var em = hapiErrorHandler(req, err, config); client.sendError(em); }); } if (isFunction(server.ext)) { server.ext('onPreResponse', function(request, reply) { var em = null; if (isObject(request) && isObject(request.response) && request.response.isBoom) { em = hapiErrorHandler(request, new Error(request.response.message), config); client.sendError(em); } if (isObject(reply) && isFunction(reply.continue)) { reply.continue(); } }); } } if (isFunction(next)) { return next(); } } var hapiPlugin = {register : hapiRegisterFunction}; var version = (isPlainObject(config) && config.getVersion()) ? config.getVersion() : '0.0.0'; hapiPlugin.register.attributes = { name : '@google/cloud-errors', version : version }; return hapiPlugin; }
javascript
function makeHapiPlugin(client, config) { /** * The register function serves to attach the hapiErrorHandler to specific * points in the hapi request-response lifecycle. Namely: it attaches to the * 'request-error' event in Hapi which is emitted when a plugin or receiver * throws an error while executing and the 'onPreResponse' event to intercept * error code carrying requests before they are sent back to the client so * that the errors can be logged to the Error Reporting API. * @function hapiRegisterFunction * @param {Hapi.Server} server - A Hapi server instance * @param {Object} options - The server configuration options object * @param {Function} next - The Hapi callback to move execution to the next * plugin * @returns {Undefined} - returns the execution of the next callback */ function hapiRegisterFunction(server, options, next) { if (isObject(server)) { if (isFunction(server.on)) { server.on('request-error', function(req, err) { var em = hapiErrorHandler(req, err, config); client.sendError(em); }); } if (isFunction(server.ext)) { server.ext('onPreResponse', function(request, reply) { var em = null; if (isObject(request) && isObject(request.response) && request.response.isBoom) { em = hapiErrorHandler(request, new Error(request.response.message), config); client.sendError(em); } if (isObject(reply) && isFunction(reply.continue)) { reply.continue(); } }); } } if (isFunction(next)) { return next(); } } var hapiPlugin = {register : hapiRegisterFunction}; var version = (isPlainObject(config) && config.getVersion()) ? config.getVersion() : '0.0.0'; hapiPlugin.register.attributes = { name : '@google/cloud-errors', version : version }; return hapiPlugin; }
[ "function", "makeHapiPlugin", "(", "client", ",", "config", ")", "{", "/**\n * The register function serves to attach the hapiErrorHandler to specific\n * points in the hapi request-response lifecycle. Namely: it attaches to the\n * 'request-error' event in Hapi which is emitted when a plugin or receiver\n * throws an error while executing and the 'onPreResponse' event to intercept\n * error code carrying requests before they are sent back to the client so\n * that the errors can be logged to the Error Reporting API.\n * @function hapiRegisterFunction\n * @param {Hapi.Server} server - A Hapi server instance\n * @param {Object} options - The server configuration options object\n * @param {Function} next - The Hapi callback to move execution to the next\n * plugin\n * @returns {Undefined} - returns the execution of the next callback\n */", "function", "hapiRegisterFunction", "(", "server", ",", "options", ",", "next", ")", "{", "if", "(", "isObject", "(", "server", ")", ")", "{", "if", "(", "isFunction", "(", "server", ".", "on", ")", ")", "{", "server", ".", "on", "(", "'request-error'", ",", "function", "(", "req", ",", "err", ")", "{", "var", "em", "=", "hapiErrorHandler", "(", "req", ",", "err", ",", "config", ")", ";", "client", ".", "sendError", "(", "em", ")", ";", "}", ")", ";", "}", "if", "(", "isFunction", "(", "server", ".", "ext", ")", ")", "{", "server", ".", "ext", "(", "'onPreResponse'", ",", "function", "(", "request", ",", "reply", ")", "{", "var", "em", "=", "null", ";", "if", "(", "isObject", "(", "request", ")", "&&", "isObject", "(", "request", ".", "response", ")", "&&", "request", ".", "response", ".", "isBoom", ")", "{", "em", "=", "hapiErrorHandler", "(", "request", ",", "new", "Error", "(", "request", ".", "response", ".", "message", ")", ",", "config", ")", ";", "client", ".", "sendError", "(", "em", ")", ";", "}", "if", "(", "isObject", "(", "reply", ")", "&&", "isFunction", "(", "reply", ".", "continue", ")", ")", "{", "reply", ".", "continue", "(", ")", ";", "}", "}", ")", ";", "}", "}", "if", "(", "isFunction", "(", "next", ")", ")", "{", "return", "next", "(", ")", ";", "}", "}", "var", "hapiPlugin", "=", "{", "register", ":", "hapiRegisterFunction", "}", ";", "var", "version", "=", "(", "isPlainObject", "(", "config", ")", "&&", "config", ".", "getVersion", "(", ")", ")", "?", "config", ".", "getVersion", "(", ")", ":", "'0.0.0'", ";", "hapiPlugin", ".", "register", ".", "attributes", "=", "{", "name", ":", "'@google/cloud-errors'", ",", "version", ":", "version", "}", ";", "return", "hapiPlugin", ";", "}" ]
Creates a Hapi plugin object which can be used to handle errors in Hapi. @param {AuthClient} client - an inited auth client instance @param {NormalizedConfigurationVariables} config - the environmental configuration @returns {Object} - the actual Hapi plugin
[ "Creates", "a", "Hapi", "plugin", "object", "which", "can", "be", "used", "to", "handle", "errors", "in", "Hapi", "." ]
fda2218759cd8754a096dbe437e8a668321f5ba6
https://github.com/GoogleCloudPlatform/cloud-errors-nodejs/blob/fda2218759cd8754a096dbe437e8a668321f5ba6/lib/interfaces/hapi.js#L62-L122
train
GoogleCloudPlatform/cloud-errors-nodejs
lib/error-extractors/error.js
extractFromErrorClass
function extractFromErrorClass(err, errorMessage) { errorMessage.setMessage(err.stack); if (has(err, 'user')) { errorMessage.setUser(err.user); } if (has(err, 'serviceContext') && isObject(err.serviceContext)) { errorMessage.setServiceContext(err.serviceContext.service, err.serviceContext.version); } }
javascript
function extractFromErrorClass(err, errorMessage) { errorMessage.setMessage(err.stack); if (has(err, 'user')) { errorMessage.setUser(err.user); } if (has(err, 'serviceContext') && isObject(err.serviceContext)) { errorMessage.setServiceContext(err.serviceContext.service, err.serviceContext.version); } }
[ "function", "extractFromErrorClass", "(", "err", ",", "errorMessage", ")", "{", "errorMessage", ".", "setMessage", "(", "err", ".", "stack", ")", ";", "if", "(", "has", "(", "err", ",", "'user'", ")", ")", "{", "errorMessage", ".", "setUser", "(", "err", ".", "user", ")", ";", "}", "if", "(", "has", "(", "err", ",", "'serviceContext'", ")", "&&", "isObject", "(", "err", ".", "serviceContext", ")", ")", "{", "errorMessage", ".", "setServiceContext", "(", "err", ".", "serviceContext", ".", "service", ",", "err", ".", "serviceContext", ".", "version", ")", ";", "}", "}" ]
Extracts error information from an instance of the Error class and marshals that information into the provided instance of error message. This function will check before accessing any part of the error for propety presence but will not check the types of these property values that is instead work that is allocated to the error message instance itself. @param {Error} err - the error instance @param {ErrorMessage} errorMessage - the error message instance to have the error information marshaled into @returns {Undefined} - does not return anything
[ "Extracts", "error", "information", "from", "an", "instance", "of", "the", "Error", "class", "and", "marshals", "that", "information", "into", "the", "provided", "instance", "of", "error", "message", ".", "This", "function", "will", "check", "before", "accessing", "any", "part", "of", "the", "error", "for", "propety", "presence", "but", "will", "not", "check", "the", "types", "of", "these", "property", "values", "that", "is", "instead", "work", "that", "is", "allocated", "to", "the", "error", "message", "instance", "itself", "." ]
fda2218759cd8754a096dbe437e8a668321f5ba6
https://github.com/GoogleCloudPlatform/cloud-errors-nodejs/blob/fda2218759cd8754a096dbe437e8a668321f5ba6/lib/error-extractors/error.js#L33-L47
train
GoogleCloudPlatform/cloud-errors-nodejs
lib/classes/error-message.js
ErrorMessage
function ErrorMessage() { this.eventTime = (new Date()).toISOString(); this.serviceContext = {service : 'node', version : undefined}; this.message = ''; this.context = { httpRequest : { method : '', url : '', userAgent : '', referrer : '', responseStatusCode : 0, remoteIp : '' }, user : '', reportLocation : {filePath : '', lineNumber : 0, functionName : ''} }; }
javascript
function ErrorMessage() { this.eventTime = (new Date()).toISOString(); this.serviceContext = {service : 'node', version : undefined}; this.message = ''; this.context = { httpRequest : { method : '', url : '', userAgent : '', referrer : '', responseStatusCode : 0, remoteIp : '' }, user : '', reportLocation : {filePath : '', lineNumber : 0, functionName : ''} }; }
[ "function", "ErrorMessage", "(", ")", "{", "this", ".", "eventTime", "=", "(", "new", "Date", "(", ")", ")", ".", "toISOString", "(", ")", ";", "this", ".", "serviceContext", "=", "{", "service", ":", "'node'", ",", "version", ":", "undefined", "}", ";", "this", ".", "message", "=", "''", ";", "this", ".", "context", "=", "{", "httpRequest", ":", "{", "method", ":", "''", ",", "url", ":", "''", ",", "userAgent", ":", "''", ",", "referrer", ":", "''", ",", "responseStatusCode", ":", "0", ",", "remoteIp", ":", "''", "}", ",", "user", ":", "''", ",", "reportLocation", ":", "{", "filePath", ":", "''", ",", "lineNumber", ":", "0", ",", "functionName", ":", "''", "}", "}", ";", "}" ]
The constructor for ErrorMessage takes no arguments and is solely meant to to instantiate properties on the instance. Each property should be externally set using the corresponding set function with the exception of eventTime which can be set externally but does not need to be since it is inited to an ISO-8601 compliant time string. @type {Object} @class ErrorMessage @classdesc ErrorMessage is a class which is meant to store and control-for Stackdriver Error API submittable values. Meant to be JSON string-ifiable representation of the final values which will be submitted to the Error API this class enforces type-checking on every setter function and will write default type-friendly values to instance properties if given values which are type-incompatible to expectations. These type-friendly default substitutions will occur silently and no errors will be thrown on attempted invalid input under the premise that during misassignment some error information sent to the Error API is better than no error information due to the Error library failing under invalid input. @property {String} eventTime - an ISO-8601 compliant string representing when the error was created @property {Object} serviceContext - The service information for the error @property {String} serviceContext.service - The service that the error was was produced on @property {String|Undefined} serviceContext.version - The service version that the error was produced on @property {String} message - The error message @property {Object} context - the request, user and report context @property {Object} context.httpRequest - the request context @property {String} context.httpRequest.method - the request method (e.g. GET) @property {String} context.httpRequest.url - the request url or path @property {String} context.httpRequest.userAgent - the requesting user-agent @property {String} context.httpRequest.referrer - the request referrer @property {Number} context.httpRequest.responseStatusCode - the request status-code @property {String} context.httpRequest.remoteIp - the requesting remote ip @property {String} context.user - the vm instances user @property {Object} context.reportLocation - the report context @property {String} context.reportLocation.filePath - the file path of the report site @property {Number} context.reportLocation.lineNumber - the line number of the report site @property {String} context.reportLocation.functionName - the function name of the report site
[ "The", "constructor", "for", "ErrorMessage", "takes", "no", "arguments", "and", "is", "solely", "meant", "to", "to", "instantiate", "properties", "on", "the", "instance", ".", "Each", "property", "should", "be", "externally", "set", "using", "the", "corresponding", "set", "function", "with", "the", "exception", "of", "eventTime", "which", "can", "be", "set", "externally", "but", "does", "not", "need", "to", "be", "since", "it", "is", "inited", "to", "an", "ISO", "-", "8601", "compliant", "time", "string", "." ]
fda2218759cd8754a096dbe437e8a668321f5ba6
https://github.com/GoogleCloudPlatform/cloud-errors-nodejs/blob/fda2218759cd8754a096dbe437e8a668321f5ba6/lib/classes/error-message.js#L67-L84
train
GoogleCloudPlatform/cloud-errors-nodejs
lib/error-handlers/object.js
handleObjectAsError
function handleObjectAsError(err, errorMessage) { if (isPlainObject(err)) { extractFromObject(err, errorMessage); } else { handleUnknownAsError(err, errorMessage); } }
javascript
function handleObjectAsError(err, errorMessage) { if (isPlainObject(err)) { extractFromObject(err, errorMessage); } else { handleUnknownAsError(err, errorMessage); } }
[ "function", "handleObjectAsError", "(", "err", ",", "errorMessage", ")", "{", "if", "(", "isPlainObject", "(", "err", ")", ")", "{", "extractFromObject", "(", "err", ",", "errorMessage", ")", ";", "}", "else", "{", "handleUnknownAsError", "(", "err", ",", "errorMessage", ")", ";", "}", "}" ]
Handles routing and validation for parsing an error that has been indicated to be of type object. If the value submitted for err passes a basic check for being of type Object than the input will extracted as such, otherwise the input will be treated as unknown. @function handleObjectAsError @param {Object} err - the error information object to extract from @param {ErrorMessage} errorMessage - the error message instance to marshal error information into @returns {Undefined} - does not return anything
[ "Handles", "routing", "and", "validation", "for", "parsing", "an", "error", "that", "has", "been", "indicated", "to", "be", "of", "type", "object", ".", "If", "the", "value", "submitted", "for", "err", "passes", "a", "basic", "check", "for", "being", "of", "type", "Object", "than", "the", "input", "will", "extracted", "as", "such", "otherwise", "the", "input", "will", "be", "treated", "as", "unknown", "." ]
fda2218759cd8754a096dbe437e8a668321f5ba6
https://github.com/GoogleCloudPlatform/cloud-errors-nodejs/blob/fda2218759cd8754a096dbe437e8a668321f5ba6/lib/error-handlers/object.js#L34-L43
train
GoogleCloudPlatform/cloud-errors-nodejs
lib/error-parsing-utils.js
extractStructuredCallList
function extractStructuredCallList(structuredStackTrace) { /** * A function which walks the structuredStackTrace variable of its parent * and produces a JSON representation of the array of CallSites. * @function * @inner * @returns {String} - A JSON representation of the array of CallSites */ return function() { var structuredCallList = []; var index = 0; if (!Array.isArray(structuredStackTrace)) { return JSON.stringify(structuredCallList); } for (index; index < structuredStackTrace.length; index += 1) { structuredCallList.push({ functionName : structuredStackTrace[index].getFunctionName(), methodName : structuredStackTrace[index].getMethodName(), fileName : structuredStackTrace[index].getFileName(), lineNumber : structuredStackTrace[index].getLineNumber(), columnNumber : structuredStackTrace[index].getColumnNumber() }); } return JSON.stringify(structuredCallList); }; }
javascript
function extractStructuredCallList(structuredStackTrace) { /** * A function which walks the structuredStackTrace variable of its parent * and produces a JSON representation of the array of CallSites. * @function * @inner * @returns {String} - A JSON representation of the array of CallSites */ return function() { var structuredCallList = []; var index = 0; if (!Array.isArray(structuredStackTrace)) { return JSON.stringify(structuredCallList); } for (index; index < structuredStackTrace.length; index += 1) { structuredCallList.push({ functionName : structuredStackTrace[index].getFunctionName(), methodName : structuredStackTrace[index].getMethodName(), fileName : structuredStackTrace[index].getFileName(), lineNumber : structuredStackTrace[index].getLineNumber(), columnNumber : structuredStackTrace[index].getColumnNumber() }); } return JSON.stringify(structuredCallList); }; }
[ "function", "extractStructuredCallList", "(", "structuredStackTrace", ")", "{", "/**\n * A function which walks the structuredStackTrace variable of its parent\n * and produces a JSON representation of the array of CallSites.\n * @function\n * @inner\n * @returns {String} - A JSON representation of the array of CallSites\n */", "return", "function", "(", ")", "{", "var", "structuredCallList", "=", "[", "]", ";", "var", "index", "=", "0", ";", "if", "(", "!", "Array", ".", "isArray", "(", "structuredStackTrace", ")", ")", "{", "return", "JSON", ".", "stringify", "(", "structuredCallList", ")", ";", "}", "for", "(", "index", ";", "index", "<", "structuredStackTrace", ".", "length", ";", "index", "+=", "1", ")", "{", "structuredCallList", ".", "push", "(", "{", "functionName", ":", "structuredStackTrace", "[", "index", "]", ".", "getFunctionName", "(", ")", ",", "methodName", ":", "structuredStackTrace", "[", "index", "]", ".", "getMethodName", "(", ")", ",", "fileName", ":", "structuredStackTrace", "[", "index", "]", ".", "getFileName", "(", ")", ",", "lineNumber", ":", "structuredStackTrace", "[", "index", "]", ".", "getLineNumber", "(", ")", ",", "columnNumber", ":", "structuredStackTrace", "[", "index", "]", ".", "getColumnNumber", "(", ")", "}", ")", ";", "}", "return", "JSON", ".", "stringify", "(", "structuredCallList", ")", ";", "}", ";", "}" ]
A function which returns a closure which itself creates a JSON representation of an array of callSites generated by an Error stack trace. Since many errors may be created and only some requiring a string-ification of the entire callsite list it advantageous from a performance perspective to evaluate this string-ification when only actually necessary and not per error generated. When calling the enclosing function an array of CallSites must be supplied othwise an empty JSON array will be returned. @function extractStructuredCallList @param {Array<CallSite>} structuredStackTrace - an array of CallSite objects @returns {Function} - a closure which produces a JSON representation of an array of CallSites
[ "A", "function", "which", "returns", "a", "closure", "which", "itself", "creates", "a", "JSON", "representation", "of", "an", "array", "of", "callSites", "generated", "by", "an", "Error", "stack", "trace", ".", "Since", "many", "errors", "may", "be", "created", "and", "only", "some", "requiring", "a", "string", "-", "ification", "of", "the", "entire", "callsite", "list", "it", "advantageous", "from", "a", "performance", "perspective", "to", "evaluate", "this", "string", "-", "ification", "when", "only", "actually", "necessary", "and", "not", "per", "error", "generated", ".", "When", "calling", "the", "enclosing", "function", "an", "array", "of", "CallSites", "must", "be", "supplied", "othwise", "an", "empty", "JSON", "array", "will", "be", "returned", "." ]
fda2218759cd8754a096dbe437e8a668321f5ba6
https://github.com/GoogleCloudPlatform/cloud-errors-nodejs/blob/fda2218759cd8754a096dbe437e8a668321f5ba6/lib/error-parsing-utils.js#L33-L65
train
GoogleCloudPlatform/cloud-errors-nodejs
lib/error-parsing-utils.js
prepareStackTraceError
function prepareStackTraceError(err, structuredStackTrace) { var returnObj = new CustomStackTrace(); var topFrame = {}; if (!Array.isArray(structuredStackTrace)) { return returnObj; } // Get the topframe of the CallSite array topFrame = structuredStackTrace[0]; returnObj.setFilePath(topFrame.getFileName()) .setLineNumber(topFrame.getLineNumber()) .setFunctionName(topFrame.getFunctionName()) .setStringifyStructuredCallList( extractStructuredCallList(structuredStackTrace)); return returnObj; }
javascript
function prepareStackTraceError(err, structuredStackTrace) { var returnObj = new CustomStackTrace(); var topFrame = {}; if (!Array.isArray(structuredStackTrace)) { return returnObj; } // Get the topframe of the CallSite array topFrame = structuredStackTrace[0]; returnObj.setFilePath(topFrame.getFileName()) .setLineNumber(topFrame.getLineNumber()) .setFunctionName(topFrame.getFunctionName()) .setStringifyStructuredCallList( extractStructuredCallList(structuredStackTrace)); return returnObj; }
[ "function", "prepareStackTraceError", "(", "err", ",", "structuredStackTrace", ")", "{", "var", "returnObj", "=", "new", "CustomStackTrace", "(", ")", ";", "var", "topFrame", "=", "{", "}", ";", "if", "(", "!", "Array", ".", "isArray", "(", "structuredStackTrace", ")", ")", "{", "return", "returnObj", ";", "}", "// Get the topframe of the CallSite array", "topFrame", "=", "structuredStackTrace", "[", "0", "]", ";", "returnObj", ".", "setFilePath", "(", "topFrame", ".", "getFileName", "(", ")", ")", ".", "setLineNumber", "(", "topFrame", ".", "getLineNumber", "(", ")", ")", ".", "setFunctionName", "(", "topFrame", ".", "getFunctionName", "(", ")", ")", ".", "setStringifyStructuredCallList", "(", "extractStructuredCallList", "(", "structuredStackTrace", ")", ")", ";", "return", "returnObj", ";", "}" ]
A function which is built to override the Error.prepareStackTraceError builtin formatter. This substitution produces a object with the last frames file-path, line number and function name. Additionally a fourth property, named stringifyStucturedCallList contains a function which can produce the entirety of the stack trace in JSON form when called. @function prepareStackTraceError @param {Error} err - an instantiation of the Error class @param {Array<CallSite>} structuredStackTrace - an array of CallSite objects @returns {CustomStackTrace} - A custom stack trace instance
[ "A", "function", "which", "is", "built", "to", "override", "the", "Error", ".", "prepareStackTraceError", "builtin", "formatter", ".", "This", "substitution", "produces", "a", "object", "with", "the", "last", "frames", "file", "-", "path", "line", "number", "and", "function", "name", ".", "Additionally", "a", "fourth", "property", "named", "stringifyStucturedCallList", "contains", "a", "function", "which", "can", "produce", "the", "entirety", "of", "the", "stack", "trace", "in", "JSON", "form", "when", "called", "." ]
fda2218759cd8754a096dbe437e8a668321f5ba6
https://github.com/GoogleCloudPlatform/cloud-errors-nodejs/blob/fda2218759cd8754a096dbe437e8a668321f5ba6/lib/error-parsing-utils.js#L78-L96
train
IndigoUnited/js-dejavu
dist/regular/strict/dejavu.js
intersection
function intersection(arr) { var arrs = slice(arguments, 1), result = filter(unique(arr), function(needle){ return every(arrs, function(haystack){ return contains(haystack, needle); }); }); return result; }
javascript
function intersection(arr) { var arrs = slice(arguments, 1), result = filter(unique(arr), function(needle){ return every(arrs, function(haystack){ return contains(haystack, needle); }); }); return result; }
[ "function", "intersection", "(", "arr", ")", "{", "var", "arrs", "=", "slice", "(", "arguments", ",", "1", ")", ",", "result", "=", "filter", "(", "unique", "(", "arr", ")", ",", "function", "(", "needle", ")", "{", "return", "every", "(", "arrs", ",", "function", "(", "haystack", ")", "{", "return", "contains", "(", "haystack", ",", "needle", ")", ";", "}", ")", ";", "}", ")", ";", "return", "result", ";", "}" ]
Return a new Array with elements common to all Arrays. - based on underscore.js implementation
[ "Return", "a", "new", "Array", "with", "elements", "common", "to", "all", "Arrays", ".", "-", "based", "on", "underscore", ".", "js", "implementation" ]
b251d5e8508bb05854081968528e6a3b2ec68d33
https://github.com/IndigoUnited/js-dejavu/blob/b251d5e8508bb05854081968528e6a3b2ec68d33/dist/regular/strict/dejavu.js#L905-L913
train
IndigoUnited/js-dejavu
dist/regular/strict/dejavu.js
randomAccessor
function randomAccessor(caller) { if (nrAccesses > nrAllowed || !contains(allowed, caller)) { throw new Error('Can\'t access random identifier.'); } nrAccesses += 1; return random; }
javascript
function randomAccessor(caller) { if (nrAccesses > nrAllowed || !contains(allowed, caller)) { throw new Error('Can\'t access random identifier.'); } nrAccesses += 1; return random; }
[ "function", "randomAccessor", "(", "caller", ")", "{", "if", "(", "nrAccesses", ">", "nrAllowed", "||", "!", "contains", "(", "allowed", ",", "caller", ")", ")", "{", "throw", "new", "Error", "(", "'Can\\'t access random identifier.'", ")", ";", "}", "nrAccesses", "+=", "1", ";", "return", "random", ";", "}" ]
Provides access to a random string that allows acceess to some hidden properties used through this library. @param {Function} caller The function that is trying to access @return {String} The random string
[ "Provides", "access", "to", "a", "random", "string", "that", "allows", "acceess", "to", "some", "hidden", "properties", "used", "through", "this", "library", "." ]
b251d5e8508bb05854081968528e6a3b2ec68d33
https://github.com/IndigoUnited/js-dejavu/blob/b251d5e8508bb05854081968528e6a3b2ec68d33/dist/regular/strict/dejavu.js#L1445-L1453
train
IndigoUnited/js-dejavu
dist/regular/strict/dejavu.js
fetchCache
function fetchCache(target, cache) { var x, length = cache.length, curr; for (x = 0; x < length; x += 1) { curr = cache[x]; if (curr.target === target) { return curr.inspect; } } return null; }
javascript
function fetchCache(target, cache) { var x, length = cache.length, curr; for (x = 0; x < length; x += 1) { curr = cache[x]; if (curr.target === target) { return curr.inspect; } } return null; }
[ "function", "fetchCache", "(", "target", ",", "cache", ")", "{", "var", "x", ",", "length", "=", "cache", ".", "length", ",", "curr", ";", "for", "(", "x", "=", "0", ";", "x", "<", "length", ";", "x", "+=", "1", ")", "{", "curr", "=", "cache", "[", "x", "]", ";", "if", "(", "curr", ".", "target", "===", "target", ")", "{", "return", "curr", ".", "inspect", ";", "}", "}", "return", "null", ";", "}" ]
Fetches an already inspected target from the cache. Returns null if not in the cache. @param {Object|Function} target The instance or constructor. @param {Array} cache The cache @return {Object|Function} The inspected target
[ "Fetches", "an", "already", "inspected", "target", "from", "the", "cache", ".", "Returns", "null", "if", "not", "in", "the", "cache", "." ]
b251d5e8508bb05854081968528e6a3b2ec68d33
https://github.com/IndigoUnited/js-dejavu/blob/b251d5e8508bb05854081968528e6a3b2ec68d33/dist/regular/strict/dejavu.js#L1578-L1591
train
IndigoUnited/js-dejavu
dist/regular/strict/dejavu.js
inspectInstance
function inspectInstance(target, cache) { // If browser has no define property it means it is too old and // in that case we return the target itself. // This could be improved but I think it does not worth the trouble if (!hasDefineProperty) { return target; } var def, simpleConstructor, methodsCache, propertiesCache, obj, tmp, key; obj = fetchCache(target, cache.instances); if (obj) { return obj; } def = target.$static[$class]; simpleConstructor = def.simpleConstructor; methodsCache = target[cacheKeyword].methods; propertiesCache = target[cacheKeyword].properties; obj = createObject(simpleConstructor.prototype); cache.instances.push({ target: target, inspect: obj }); // Methods for (key in target[redefinedCacheKeyword].methods) { obj[key] = inspect(methodsCache[key], cache, true); } // Properties for (key in target[redefinedCacheKeyword].properties) { tmp = hasOwn(propertiesCache, key) ? propertiesCache[key] : target[key]; obj[key] = inspect(tmp, cache, true); } // Handle undeclared properties methodsCache = def.methods; propertiesCache = def.properties; for (key in target) { if (hasOwn(target, key) && !hasOwn(obj, key) && !propertiesCache[key] && !methodsCache[key]) { obj[key] = inspect(target[key], cache, true); } } // Fix the .constructor tmp = obj.constructor.$constructor; while (tmp) { inspectConstructor(tmp, cache, true); tmp = tmp.$parent; } return obj; }
javascript
function inspectInstance(target, cache) { // If browser has no define property it means it is too old and // in that case we return the target itself. // This could be improved but I think it does not worth the trouble if (!hasDefineProperty) { return target; } var def, simpleConstructor, methodsCache, propertiesCache, obj, tmp, key; obj = fetchCache(target, cache.instances); if (obj) { return obj; } def = target.$static[$class]; simpleConstructor = def.simpleConstructor; methodsCache = target[cacheKeyword].methods; propertiesCache = target[cacheKeyword].properties; obj = createObject(simpleConstructor.prototype); cache.instances.push({ target: target, inspect: obj }); // Methods for (key in target[redefinedCacheKeyword].methods) { obj[key] = inspect(methodsCache[key], cache, true); } // Properties for (key in target[redefinedCacheKeyword].properties) { tmp = hasOwn(propertiesCache, key) ? propertiesCache[key] : target[key]; obj[key] = inspect(tmp, cache, true); } // Handle undeclared properties methodsCache = def.methods; propertiesCache = def.properties; for (key in target) { if (hasOwn(target, key) && !hasOwn(obj, key) && !propertiesCache[key] && !methodsCache[key]) { obj[key] = inspect(target[key], cache, true); } } // Fix the .constructor tmp = obj.constructor.$constructor; while (tmp) { inspectConstructor(tmp, cache, true); tmp = tmp.$parent; } return obj; }
[ "function", "inspectInstance", "(", "target", ",", "cache", ")", "{", "// If browser has no define property it means it is too old and", "// in that case we return the target itself.", "// This could be improved but I think it does not worth the trouble", "if", "(", "!", "hasDefineProperty", ")", "{", "return", "target", ";", "}", "var", "def", ",", "simpleConstructor", ",", "methodsCache", ",", "propertiesCache", ",", "obj", ",", "tmp", ",", "key", ";", "obj", "=", "fetchCache", "(", "target", ",", "cache", ".", "instances", ")", ";", "if", "(", "obj", ")", "{", "return", "obj", ";", "}", "def", "=", "target", ".", "$static", "[", "$class", "]", ";", "simpleConstructor", "=", "def", ".", "simpleConstructor", ";", "methodsCache", "=", "target", "[", "cacheKeyword", "]", ".", "methods", ";", "propertiesCache", "=", "target", "[", "cacheKeyword", "]", ".", "properties", ";", "obj", "=", "createObject", "(", "simpleConstructor", ".", "prototype", ")", ";", "cache", ".", "instances", ".", "push", "(", "{", "target", ":", "target", ",", "inspect", ":", "obj", "}", ")", ";", "// Methods", "for", "(", "key", "in", "target", "[", "redefinedCacheKeyword", "]", ".", "methods", ")", "{", "obj", "[", "key", "]", "=", "inspect", "(", "methodsCache", "[", "key", "]", ",", "cache", ",", "true", ")", ";", "}", "// Properties", "for", "(", "key", "in", "target", "[", "redefinedCacheKeyword", "]", ".", "properties", ")", "{", "tmp", "=", "hasOwn", "(", "propertiesCache", ",", "key", ")", "?", "propertiesCache", "[", "key", "]", ":", "target", "[", "key", "]", ";", "obj", "[", "key", "]", "=", "inspect", "(", "tmp", ",", "cache", ",", "true", ")", ";", "}", "// Handle undeclared properties", "methodsCache", "=", "def", ".", "methods", ";", "propertiesCache", "=", "def", ".", "properties", ";", "for", "(", "key", "in", "target", ")", "{", "if", "(", "hasOwn", "(", "target", ",", "key", ")", "&&", "!", "hasOwn", "(", "obj", ",", "key", ")", "&&", "!", "propertiesCache", "[", "key", "]", "&&", "!", "methodsCache", "[", "key", "]", ")", "{", "obj", "[", "key", "]", "=", "inspect", "(", "target", "[", "key", "]", ",", "cache", ",", "true", ")", ";", "}", "}", "// Fix the .constructor", "tmp", "=", "obj", ".", "constructor", ".", "$constructor", ";", "while", "(", "tmp", ")", "{", "inspectConstructor", "(", "tmp", ",", "cache", ",", "true", ")", ";", "tmp", "=", "tmp", ".", "$parent", ";", "}", "return", "obj", ";", "}" ]
Inspects an instance. @param {Object} target The instance @param {Array} cache The cache @return {Object} The inspected instance
[ "Inspects", "an", "instance", "." ]
b251d5e8508bb05854081968528e6a3b2ec68d33
https://github.com/IndigoUnited/js-dejavu/blob/b251d5e8508bb05854081968528e6a3b2ec68d33/dist/regular/strict/dejavu.js#L1601-L1658
train
IndigoUnited/js-dejavu
dist/regular/strict/dejavu.js
inspectConstructor
function inspectConstructor(target, cache) { // If browser has no define property it means it is too old and // in that case we return the target itself. // This could be improved but I think it does not worth the trouble if (!hasDefineProperty) { return target; } var def, methodsCache, propertiesCache, membersCache, obj, tmp, key; obj = fetchCache(target, cache.constructors); if (obj) { return obj; } def = target[$class]; obj = def.simpleConstructor; methodsCache = target[cacheKeyword].methods; propertiesCache = target[cacheKeyword].properties; cache.constructors.push({ target: target, inspect: obj }); // Constructor methods for (key in methodsCache) { obj[key] = inspect(methodsCache[key], cache, true); } // Constructor properties for (key in propertiesCache) { tmp = propertiesCache[key]; obj[key] = inspect(tmp, cache, true); } // Handle constructor undeclared properties methodsCache = def.methods; propertiesCache = def.properties; for (key in target) { if (hasOwn(target, key) && !hasOwn(obj, key) && !propertiesCache[key] && !methodsCache[key]) { obj[key] = inspect(target[key], cache, true); } } obj = obj.prototype; // Prototype members target = target.prototype; membersCache = def.ownMembers; methodsCache = def.methods; propertiesCache = def.properties; for (key in membersCache) { tmp = methodsCache[key] ? methodsCache[key].implementation : propertiesCache[key].value; obj[key] = inspect(tmp, cache, true); } // Handle undeclared prototype members for (key in target) { if (hasOwn(target, key) && !hasOwn(obj, key) && !membersCache[key]) { obj[key] = inspect(target[key], cache, true); } } return obj; }
javascript
function inspectConstructor(target, cache) { // If browser has no define property it means it is too old and // in that case we return the target itself. // This could be improved but I think it does not worth the trouble if (!hasDefineProperty) { return target; } var def, methodsCache, propertiesCache, membersCache, obj, tmp, key; obj = fetchCache(target, cache.constructors); if (obj) { return obj; } def = target[$class]; obj = def.simpleConstructor; methodsCache = target[cacheKeyword].methods; propertiesCache = target[cacheKeyword].properties; cache.constructors.push({ target: target, inspect: obj }); // Constructor methods for (key in methodsCache) { obj[key] = inspect(methodsCache[key], cache, true); } // Constructor properties for (key in propertiesCache) { tmp = propertiesCache[key]; obj[key] = inspect(tmp, cache, true); } // Handle constructor undeclared properties methodsCache = def.methods; propertiesCache = def.properties; for (key in target) { if (hasOwn(target, key) && !hasOwn(obj, key) && !propertiesCache[key] && !methodsCache[key]) { obj[key] = inspect(target[key], cache, true); } } obj = obj.prototype; // Prototype members target = target.prototype; membersCache = def.ownMembers; methodsCache = def.methods; propertiesCache = def.properties; for (key in membersCache) { tmp = methodsCache[key] ? methodsCache[key].implementation : propertiesCache[key].value; obj[key] = inspect(tmp, cache, true); } // Handle undeclared prototype members for (key in target) { if (hasOwn(target, key) && !hasOwn(obj, key) && !membersCache[key]) { obj[key] = inspect(target[key], cache, true); } } return obj; }
[ "function", "inspectConstructor", "(", "target", ",", "cache", ")", "{", "// If browser has no define property it means it is too old and", "// in that case we return the target itself.", "// This could be improved but I think it does not worth the trouble", "if", "(", "!", "hasDefineProperty", ")", "{", "return", "target", ";", "}", "var", "def", ",", "methodsCache", ",", "propertiesCache", ",", "membersCache", ",", "obj", ",", "tmp", ",", "key", ";", "obj", "=", "fetchCache", "(", "target", ",", "cache", ".", "constructors", ")", ";", "if", "(", "obj", ")", "{", "return", "obj", ";", "}", "def", "=", "target", "[", "$class", "]", ";", "obj", "=", "def", ".", "simpleConstructor", ";", "methodsCache", "=", "target", "[", "cacheKeyword", "]", ".", "methods", ";", "propertiesCache", "=", "target", "[", "cacheKeyword", "]", ".", "properties", ";", "cache", ".", "constructors", ".", "push", "(", "{", "target", ":", "target", ",", "inspect", ":", "obj", "}", ")", ";", "// Constructor methods", "for", "(", "key", "in", "methodsCache", ")", "{", "obj", "[", "key", "]", "=", "inspect", "(", "methodsCache", "[", "key", "]", ",", "cache", ",", "true", ")", ";", "}", "// Constructor properties", "for", "(", "key", "in", "propertiesCache", ")", "{", "tmp", "=", "propertiesCache", "[", "key", "]", ";", "obj", "[", "key", "]", "=", "inspect", "(", "tmp", ",", "cache", ",", "true", ")", ";", "}", "// Handle constructor undeclared properties", "methodsCache", "=", "def", ".", "methods", ";", "propertiesCache", "=", "def", ".", "properties", ";", "for", "(", "key", "in", "target", ")", "{", "if", "(", "hasOwn", "(", "target", ",", "key", ")", "&&", "!", "hasOwn", "(", "obj", ",", "key", ")", "&&", "!", "propertiesCache", "[", "key", "]", "&&", "!", "methodsCache", "[", "key", "]", ")", "{", "obj", "[", "key", "]", "=", "inspect", "(", "target", "[", "key", "]", ",", "cache", ",", "true", ")", ";", "}", "}", "obj", "=", "obj", ".", "prototype", ";", "// Prototype members", "target", "=", "target", ".", "prototype", ";", "membersCache", "=", "def", ".", "ownMembers", ";", "methodsCache", "=", "def", ".", "methods", ";", "propertiesCache", "=", "def", ".", "properties", ";", "for", "(", "key", "in", "membersCache", ")", "{", "tmp", "=", "methodsCache", "[", "key", "]", "?", "methodsCache", "[", "key", "]", ".", "implementation", ":", "propertiesCache", "[", "key", "]", ".", "value", ";", "obj", "[", "key", "]", "=", "inspect", "(", "tmp", ",", "cache", ",", "true", ")", ";", "}", "// Handle undeclared prototype members", "for", "(", "key", "in", "target", ")", "{", "if", "(", "hasOwn", "(", "target", ",", "key", ")", "&&", "!", "hasOwn", "(", "obj", ",", "key", ")", "&&", "!", "membersCache", "[", "key", "]", ")", "{", "obj", "[", "key", "]", "=", "inspect", "(", "target", "[", "key", "]", ",", "cache", ",", "true", ")", ";", "}", "}", "return", "obj", ";", "}" ]
Inspects an constructor. @param {Function} target The constructor @return {Object} The inspected constructor
[ "Inspects", "an", "constructor", "." ]
b251d5e8508bb05854081968528e6a3b2ec68d33
https://github.com/IndigoUnited/js-dejavu/blob/b251d5e8508bb05854081968528e6a3b2ec68d33/dist/regular/strict/dejavu.js#L1667-L1736
train
IndigoUnited/js-dejavu
dist/regular/strict/dejavu.js
protectInstance
function protectInstance(instance) { var key; obfuscateProperty(instance, cacheKeyword, { properties: {}, methods: {} }); obfuscateProperty(instance, redefinedCacheKeyword, { properties: {}, methods: {} }); // This is for the inspect for (key in instance.$static[$class].methods) { protectMethod(key, instance.$static[$class].methods[key], instance); } for (key in instance.$static[$class].properties) { protectProperty(key, instance.$static[$class].properties[key], instance); } }
javascript
function protectInstance(instance) { var key; obfuscateProperty(instance, cacheKeyword, { properties: {}, methods: {} }); obfuscateProperty(instance, redefinedCacheKeyword, { properties: {}, methods: {} }); // This is for the inspect for (key in instance.$static[$class].methods) { protectMethod(key, instance.$static[$class].methods[key], instance); } for (key in instance.$static[$class].properties) { protectProperty(key, instance.$static[$class].properties[key], instance); } }
[ "function", "protectInstance", "(", "instance", ")", "{", "var", "key", ";", "obfuscateProperty", "(", "instance", ",", "cacheKeyword", ",", "{", "properties", ":", "{", "}", ",", "methods", ":", "{", "}", "}", ")", ";", "obfuscateProperty", "(", "instance", ",", "redefinedCacheKeyword", ",", "{", "properties", ":", "{", "}", ",", "methods", ":", "{", "}", "}", ")", ";", "// This is for the inspect", "for", "(", "key", "in", "instance", ".", "$static", "[", "$class", "]", ".", "methods", ")", "{", "protectMethod", "(", "key", ",", "instance", ".", "$static", "[", "$class", "]", ".", "methods", "[", "key", "]", ",", "instance", ")", ";", "}", "for", "(", "key", "in", "instance", ".", "$static", "[", "$class", "]", ".", "properties", ")", "{", "protectProperty", "(", "key", ",", "instance", ".", "$static", "[", "$class", "]", ".", "properties", "[", "key", "]", ",", "instance", ")", ";", "}", "}" ]
Protects an instance. All its methods and properties will be secured according to their visibility. @param {Object} instance The instance to be protected
[ "Protects", "an", "instance", "." ]
b251d5e8508bb05854081968528e6a3b2ec68d33
https://github.com/IndigoUnited/js-dejavu/blob/b251d5e8508bb05854081968528e6a3b2ec68d33/dist/regular/strict/dejavu.js#L3384-L3397
train
IndigoUnited/js-dejavu
dist/regular/strict/dejavu.js
protectConstructor
function protectConstructor(constructor) { var key, target, meta, prototype = constructor.prototype; obfuscateProperty(constructor, cacheKeyword, { properties: {}, methods: {} }); for (key in constructor[$class].staticMethods) { protectStaticMethod(key, constructor[$class].staticMethods[key], constructor); } for (key in constructor[$class].staticProperties) { protectStaticProperty(key, constructor[$class].staticProperties[key], constructor); } // Prevent any properties/methods from being added and deleted to the constructor/prototype if (isFunction(Object.seal) && constructor[$class].locked && !constructor[$class].forceUnlocked) { Object.seal(constructor); Object.seal(prototype); } }
javascript
function protectConstructor(constructor) { var key, target, meta, prototype = constructor.prototype; obfuscateProperty(constructor, cacheKeyword, { properties: {}, methods: {} }); for (key in constructor[$class].staticMethods) { protectStaticMethod(key, constructor[$class].staticMethods[key], constructor); } for (key in constructor[$class].staticProperties) { protectStaticProperty(key, constructor[$class].staticProperties[key], constructor); } // Prevent any properties/methods from being added and deleted to the constructor/prototype if (isFunction(Object.seal) && constructor[$class].locked && !constructor[$class].forceUnlocked) { Object.seal(constructor); Object.seal(prototype); } }
[ "function", "protectConstructor", "(", "constructor", ")", "{", "var", "key", ",", "target", ",", "meta", ",", "prototype", "=", "constructor", ".", "prototype", ";", "obfuscateProperty", "(", "constructor", ",", "cacheKeyword", ",", "{", "properties", ":", "{", "}", ",", "methods", ":", "{", "}", "}", ")", ";", "for", "(", "key", "in", "constructor", "[", "$class", "]", ".", "staticMethods", ")", "{", "protectStaticMethod", "(", "key", ",", "constructor", "[", "$class", "]", ".", "staticMethods", "[", "key", "]", ",", "constructor", ")", ";", "}", "for", "(", "key", "in", "constructor", "[", "$class", "]", ".", "staticProperties", ")", "{", "protectStaticProperty", "(", "key", ",", "constructor", "[", "$class", "]", ".", "staticProperties", "[", "key", "]", ",", "constructor", ")", ";", "}", "// Prevent any properties/methods from being added and deleted to the constructor/prototype", "if", "(", "isFunction", "(", "Object", ".", "seal", ")", "&&", "constructor", "[", "$class", "]", ".", "locked", "&&", "!", "constructor", "[", "$class", "]", ".", "forceUnlocked", ")", "{", "Object", ".", "seal", "(", "constructor", ")", ";", "Object", ".", "seal", "(", "prototype", ")", ";", "}", "}" ]
Protects a constructor. All its methods and properties will be secured according to their visibility. @param {Function} constructor The constructor to be protected
[ "Protects", "a", "constructor", "." ]
b251d5e8508bb05854081968528e6a3b2ec68d33
https://github.com/IndigoUnited/js-dejavu/blob/b251d5e8508bb05854081968528e6a3b2ec68d33/dist/regular/strict/dejavu.js#L3406-L3427
train
IndigoUnited/js-dejavu
dist/regular/strict/dejavu.js
parseAbstracts
function parseAbstracts(abstracts, constructor) { var optsStatic = { isStatic: true }, key, value, unallowed; // Check argument if (!isObject(abstracts)) { throw new Error('$abstracts defined in abstract class "' + constructor.prototype.$name + '" must be an object.'); } // Check reserved keywords checkKeywords(abstracts); // Check unallowed keywords unallowed = testKeywords(abstracts, ['$statics']); if (unallowed) { throw new Error('$statics inside $abstracts of abstract class "' + constructor.prototype.$name + '" contains an unallowed keyword: "' + unallowed + '".'); } if (hasOwn(abstracts, '$statics')) { // Check argument if (!isObject(abstracts.$statics)) { throw new Error('$statics definition in $abstracts of abstract class "' + constructor.prototype.$name + '" must be an object.'); } // Check keywords checkKeywords(abstracts.$statics, 'statics'); // Check unallowed keywords unallowed = testKeywords(abstracts.$statics); if (unallowed) { throw new Error('$statics inside $abstracts of abstract class "' + constructor.prototype.$name + '" contains an unallowed keyword: "' + unallowed + '".'); } for (key in abstracts.$statics) { value = abstracts.$statics[key]; // Check if it is not a function if (!isFunction(value) || value[$interface] || value[$class]) { throw new Error('Abstract member "' + key + '" found in abstract class "' + constructor.prototype.$name + '" is not a function.'); } addMethod(key, value, constructor, optsStatic); } delete abstracts.$statics; } for (key in abstracts) { value = abstracts[key]; // Check if it is not a function if (!isFunction(value) || value[$interface] || value[$class]) { throw new Error('Abstract member "' + key + '" found in abstract class "' + constructor.prototype.$name + '" is not a function.'); } addMethod(key, value, constructor); } }
javascript
function parseAbstracts(abstracts, constructor) { var optsStatic = { isStatic: true }, key, value, unallowed; // Check argument if (!isObject(abstracts)) { throw new Error('$abstracts defined in abstract class "' + constructor.prototype.$name + '" must be an object.'); } // Check reserved keywords checkKeywords(abstracts); // Check unallowed keywords unallowed = testKeywords(abstracts, ['$statics']); if (unallowed) { throw new Error('$statics inside $abstracts of abstract class "' + constructor.prototype.$name + '" contains an unallowed keyword: "' + unallowed + '".'); } if (hasOwn(abstracts, '$statics')) { // Check argument if (!isObject(abstracts.$statics)) { throw new Error('$statics definition in $abstracts of abstract class "' + constructor.prototype.$name + '" must be an object.'); } // Check keywords checkKeywords(abstracts.$statics, 'statics'); // Check unallowed keywords unallowed = testKeywords(abstracts.$statics); if (unallowed) { throw new Error('$statics inside $abstracts of abstract class "' + constructor.prototype.$name + '" contains an unallowed keyword: "' + unallowed + '".'); } for (key in abstracts.$statics) { value = abstracts.$statics[key]; // Check if it is not a function if (!isFunction(value) || value[$interface] || value[$class]) { throw new Error('Abstract member "' + key + '" found in abstract class "' + constructor.prototype.$name + '" is not a function.'); } addMethod(key, value, constructor, optsStatic); } delete abstracts.$statics; } for (key in abstracts) { value = abstracts[key]; // Check if it is not a function if (!isFunction(value) || value[$interface] || value[$class]) { throw new Error('Abstract member "' + key + '" found in abstract class "' + constructor.prototype.$name + '" is not a function.'); } addMethod(key, value, constructor); } }
[ "function", "parseAbstracts", "(", "abstracts", ",", "constructor", ")", "{", "var", "optsStatic", "=", "{", "isStatic", ":", "true", "}", ",", "key", ",", "value", ",", "unallowed", ";", "// Check argument", "if", "(", "!", "isObject", "(", "abstracts", ")", ")", "{", "throw", "new", "Error", "(", "'$abstracts defined in abstract class \"'", "+", "constructor", ".", "prototype", ".", "$name", "+", "'\" must be an object.'", ")", ";", "}", "// Check reserved keywords", "checkKeywords", "(", "abstracts", ")", ";", "// Check unallowed keywords", "unallowed", "=", "testKeywords", "(", "abstracts", ",", "[", "'$statics'", "]", ")", ";", "if", "(", "unallowed", ")", "{", "throw", "new", "Error", "(", "'$statics inside $abstracts of abstract class \"'", "+", "constructor", ".", "prototype", ".", "$name", "+", "'\" contains an unallowed keyword: \"'", "+", "unallowed", "+", "'\".'", ")", ";", "}", "if", "(", "hasOwn", "(", "abstracts", ",", "'$statics'", ")", ")", "{", "// Check argument", "if", "(", "!", "isObject", "(", "abstracts", ".", "$statics", ")", ")", "{", "throw", "new", "Error", "(", "'$statics definition in $abstracts of abstract class \"'", "+", "constructor", ".", "prototype", ".", "$name", "+", "'\" must be an object.'", ")", ";", "}", "// Check keywords", "checkKeywords", "(", "abstracts", ".", "$statics", ",", "'statics'", ")", ";", "// Check unallowed keywords", "unallowed", "=", "testKeywords", "(", "abstracts", ".", "$statics", ")", ";", "if", "(", "unallowed", ")", "{", "throw", "new", "Error", "(", "'$statics inside $abstracts of abstract class \"'", "+", "constructor", ".", "prototype", ".", "$name", "+", "'\" contains an unallowed keyword: \"'", "+", "unallowed", "+", "'\".'", ")", ";", "}", "for", "(", "key", "in", "abstracts", ".", "$statics", ")", "{", "value", "=", "abstracts", ".", "$statics", "[", "key", "]", ";", "// Check if it is not a function", "if", "(", "!", "isFunction", "(", "value", ")", "||", "value", "[", "$interface", "]", "||", "value", "[", "$class", "]", ")", "{", "throw", "new", "Error", "(", "'Abstract member \"'", "+", "key", "+", "'\" found in abstract class \"'", "+", "constructor", ".", "prototype", ".", "$name", "+", "'\" is not a function.'", ")", ";", "}", "addMethod", "(", "key", ",", "value", ",", "constructor", ",", "optsStatic", ")", ";", "}", "delete", "abstracts", ".", "$statics", ";", "}", "for", "(", "key", "in", "abstracts", ")", "{", "value", "=", "abstracts", "[", "key", "]", ";", "// Check if it is not a function", "if", "(", "!", "isFunction", "(", "value", ")", "||", "value", "[", "$interface", "]", "||", "value", "[", "$class", "]", ")", "{", "throw", "new", "Error", "(", "'Abstract member \"'", "+", "key", "+", "'\" found in abstract class \"'", "+", "constructor", ".", "prototype", ".", "$name", "+", "'\" is not a function.'", ")", ";", "}", "addMethod", "(", "key", ",", "value", ",", "constructor", ")", ";", "}", "}" ]
Parse abstract methods. @param {Object} abstracts The object that contains the abstract methods @param {Function} constructor The constructor
[ "Parse", "abstract", "methods", "." ]
b251d5e8508bb05854081968528e6a3b2ec68d33
https://github.com/IndigoUnited/js-dejavu/blob/b251d5e8508bb05854081968528e6a3b2ec68d33/dist/regular/strict/dejavu.js#L4164-L4223
train
IndigoUnited/js-dejavu
dist/regular/strict/dejavu.js
parseInterfaces
function parseInterfaces(interfaces, constructor) { var interfs = toArray(interfaces), x = interfs.length, interf, key, value; for (x -= 1; x >= 0; x -= 1) { interf = interfs[x]; // Grab methods for (key in interf[$interface].methods) { value = interf[$interface].methods[key]; // Check if method is already defined as abstract and is compatible if (constructor[$abstract].methods[key]) { if (!isFunctionCompatible(constructor[$abstract].methods[key], value)) { throw new Error('Method "' + key + '( ' + value.signature + ')" described in interface "' + interf.prototype.$name + '" is not compatible with the one already defined in "' + constructor.prototype.$name + '": "' + key + '(' + constructor[$abstract].methods[key].signature + ')".'); } } else { constructor[$abstract].methods[key] = interf[$interface].methods[key]; } } // Grab static methods for (key in interf[$interface].staticMethods) { value = interf[$interface].staticMethods[key]; // Check if method is already defined as abstract and is compatible if (constructor[$abstract].staticMethods[key]) { if (!isFunctionCompatible(constructor[$abstract].staticMethods[key], value)) { throw new Error('Static method "' + key + '( ' + value.signature + ')" described in interface "' + interf.prototype.$name + '" is not compatible with the one already defined in "' + constructor.prototype.$name + '": "' + key + '(' + constructor[$abstract].staticMethods[key].signature + ')".'); } } else { constructor[$abstract].staticMethods[key] = value; } } } }
javascript
function parseInterfaces(interfaces, constructor) { var interfs = toArray(interfaces), x = interfs.length, interf, key, value; for (x -= 1; x >= 0; x -= 1) { interf = interfs[x]; // Grab methods for (key in interf[$interface].methods) { value = interf[$interface].methods[key]; // Check if method is already defined as abstract and is compatible if (constructor[$abstract].methods[key]) { if (!isFunctionCompatible(constructor[$abstract].methods[key], value)) { throw new Error('Method "' + key + '( ' + value.signature + ')" described in interface "' + interf.prototype.$name + '" is not compatible with the one already defined in "' + constructor.prototype.$name + '": "' + key + '(' + constructor[$abstract].methods[key].signature + ')".'); } } else { constructor[$abstract].methods[key] = interf[$interface].methods[key]; } } // Grab static methods for (key in interf[$interface].staticMethods) { value = interf[$interface].staticMethods[key]; // Check if method is already defined as abstract and is compatible if (constructor[$abstract].staticMethods[key]) { if (!isFunctionCompatible(constructor[$abstract].staticMethods[key], value)) { throw new Error('Static method "' + key + '( ' + value.signature + ')" described in interface "' + interf.prototype.$name + '" is not compatible with the one already defined in "' + constructor.prototype.$name + '": "' + key + '(' + constructor[$abstract].staticMethods[key].signature + ')".'); } } else { constructor[$abstract].staticMethods[key] = value; } } } }
[ "function", "parseInterfaces", "(", "interfaces", ",", "constructor", ")", "{", "var", "interfs", "=", "toArray", "(", "interfaces", ")", ",", "x", "=", "interfs", ".", "length", ",", "interf", ",", "key", ",", "value", ";", "for", "(", "x", "-=", "1", ";", "x", ">=", "0", ";", "x", "-=", "1", ")", "{", "interf", "=", "interfs", "[", "x", "]", ";", "// Grab methods", "for", "(", "key", "in", "interf", "[", "$interface", "]", ".", "methods", ")", "{", "value", "=", "interf", "[", "$interface", "]", ".", "methods", "[", "key", "]", ";", "// Check if method is already defined as abstract and is compatible", "if", "(", "constructor", "[", "$abstract", "]", ".", "methods", "[", "key", "]", ")", "{", "if", "(", "!", "isFunctionCompatible", "(", "constructor", "[", "$abstract", "]", ".", "methods", "[", "key", "]", ",", "value", ")", ")", "{", "throw", "new", "Error", "(", "'Method \"'", "+", "key", "+", "'( '", "+", "value", ".", "signature", "+", "')\" described in interface \"'", "+", "interf", ".", "prototype", ".", "$name", "+", "'\" is not compatible with the one already defined in \"'", "+", "constructor", ".", "prototype", ".", "$name", "+", "'\": \"'", "+", "key", "+", "'('", "+", "constructor", "[", "$abstract", "]", ".", "methods", "[", "key", "]", ".", "signature", "+", "')\".'", ")", ";", "}", "}", "else", "{", "constructor", "[", "$abstract", "]", ".", "methods", "[", "key", "]", "=", "interf", "[", "$interface", "]", ".", "methods", "[", "key", "]", ";", "}", "}", "// Grab static methods", "for", "(", "key", "in", "interf", "[", "$interface", "]", ".", "staticMethods", ")", "{", "value", "=", "interf", "[", "$interface", "]", ".", "staticMethods", "[", "key", "]", ";", "// Check if method is already defined as abstract and is compatible", "if", "(", "constructor", "[", "$abstract", "]", ".", "staticMethods", "[", "key", "]", ")", "{", "if", "(", "!", "isFunctionCompatible", "(", "constructor", "[", "$abstract", "]", ".", "staticMethods", "[", "key", "]", ",", "value", ")", ")", "{", "throw", "new", "Error", "(", "'Static method \"'", "+", "key", "+", "'( '", "+", "value", ".", "signature", "+", "')\" described in interface \"'", "+", "interf", ".", "prototype", ".", "$name", "+", "'\" is not compatible with the one already defined in \"'", "+", "constructor", ".", "prototype", ".", "$name", "+", "'\": \"'", "+", "key", "+", "'('", "+", "constructor", "[", "$abstract", "]", ".", "staticMethods", "[", "key", "]", ".", "signature", "+", "')\".'", ")", ";", "}", "}", "else", "{", "constructor", "[", "$abstract", "]", ".", "staticMethods", "[", "key", "]", "=", "value", ";", "}", "}", "}", "}" ]
Parse interfaces. @param {Array} interfaces The interfaces @param {Function} constructor The constructor
[ "Parse", "interfaces", "." ]
b251d5e8508bb05854081968528e6a3b2ec68d33
https://github.com/IndigoUnited/js-dejavu/blob/b251d5e8508bb05854081968528e6a3b2ec68d33/dist/regular/strict/dejavu.js#L4231-L4271
train
IndigoUnited/js-dejavu
dist/regular/strict/dejavu.js
createFinalClass
function createFinalClass(params, constructor) { var def = Class.$create(params, constructor); def[$class].finalClass = true; return def; }
javascript
function createFinalClass(params, constructor) { var def = Class.$create(params, constructor); def[$class].finalClass = true; return def; }
[ "function", "createFinalClass", "(", "params", ",", "constructor", ")", "{", "var", "def", "=", "Class", ".", "$create", "(", "params", ",", "constructor", ")", ";", "def", "[", "$class", "]", ".", "finalClass", "=", "true", ";", "return", "def", ";", "}" ]
Create a final class definition. @param {Object} params An object containing methods and properties @param {Constructor} [constructor] Assume the passed constructor @return {Function} The constructor
[ "Create", "a", "final", "class", "definition", "." ]
b251d5e8508bb05854081968528e6a3b2ec68d33
https://github.com/IndigoUnited/js-dejavu/blob/b251d5e8508bb05854081968528e6a3b2ec68d33/dist/regular/strict/dejavu.js#L4828-L4833
train
GoogleCloudPlatform/cloud-errors-nodejs
lib/interfaces/express.js
makeExpressHandler
function makeExpressHandler(client, config) { /** * The Express Error Handler function is an interface for the error handler * stack into the Express architecture. * @function expressErrorHandler * @param {Any} err - a error of some type propagated by the express plugin * stack * @param {Object} req - an Express request object * @param {Object} res - an Express response object * @param {Function} next - an Express continuation callback * @returns {ErrorMessage} - Returns the ErrorMessage instance */ function expressErrorHandler(err, req, res, next) { var ctxService = ''; var ctxVersion = ''; if (isObject(config)) { ctxService = config.getServiceContext().service; ctxVersion = config.getServiceContext().version; } var em = new ErrorMessage() .consumeRequestInformation( expressRequestInformationExtractor(req, res)) .setServiceContext(ctxService, ctxVersion); errorHandlerRouter(err, em); if (isObject(client) && isFunction(client.sendError)) { client.sendError(em); } if (isFunction(next)) { next(err); } return em; } return expressErrorHandler; }
javascript
function makeExpressHandler(client, config) { /** * The Express Error Handler function is an interface for the error handler * stack into the Express architecture. * @function expressErrorHandler * @param {Any} err - a error of some type propagated by the express plugin * stack * @param {Object} req - an Express request object * @param {Object} res - an Express response object * @param {Function} next - an Express continuation callback * @returns {ErrorMessage} - Returns the ErrorMessage instance */ function expressErrorHandler(err, req, res, next) { var ctxService = ''; var ctxVersion = ''; if (isObject(config)) { ctxService = config.getServiceContext().service; ctxVersion = config.getServiceContext().version; } var em = new ErrorMessage() .consumeRequestInformation( expressRequestInformationExtractor(req, res)) .setServiceContext(ctxService, ctxVersion); errorHandlerRouter(err, em); if (isObject(client) && isFunction(client.sendError)) { client.sendError(em); } if (isFunction(next)) { next(err); } return em; } return expressErrorHandler; }
[ "function", "makeExpressHandler", "(", "client", ",", "config", ")", "{", "/**\n * The Express Error Handler function is an interface for the error handler\n * stack into the Express architecture.\n * @function expressErrorHandler\n * @param {Any} err - a error of some type propagated by the express plugin\n * stack\n * @param {Object} req - an Express request object\n * @param {Object} res - an Express response object\n * @param {Function} next - an Express continuation callback\n * @returns {ErrorMessage} - Returns the ErrorMessage instance\n */", "function", "expressErrorHandler", "(", "err", ",", "req", ",", "res", ",", "next", ")", "{", "var", "ctxService", "=", "''", ";", "var", "ctxVersion", "=", "''", ";", "if", "(", "isObject", "(", "config", ")", ")", "{", "ctxService", "=", "config", ".", "getServiceContext", "(", ")", ".", "service", ";", "ctxVersion", "=", "config", ".", "getServiceContext", "(", ")", ".", "version", ";", "}", "var", "em", "=", "new", "ErrorMessage", "(", ")", ".", "consumeRequestInformation", "(", "expressRequestInformationExtractor", "(", "req", ",", "res", ")", ")", ".", "setServiceContext", "(", "ctxService", ",", "ctxVersion", ")", ";", "errorHandlerRouter", "(", "err", ",", "em", ")", ";", "if", "(", "isObject", "(", "client", ")", "&&", "isFunction", "(", "client", ".", "sendError", ")", ")", "{", "client", ".", "sendError", "(", "em", ")", ";", "}", "if", "(", "isFunction", "(", "next", ")", ")", "{", "next", "(", "err", ")", ";", "}", "return", "em", ";", "}", "return", "expressErrorHandler", ";", "}" ]
Returns a function that can be used as an express error handling middleware. @function makeExpressHandler @param {AuthClient} client - an inited Auth Client instance @param {NormalizedConfigurationVariables} config - the environmental configuration @returns {expressErrorHandler} - a function that can be used as an express error handling middleware.
[ "Returns", "a", "function", "that", "can", "be", "used", "as", "an", "express", "error", "handling", "middleware", "." ]
fda2218759cd8754a096dbe437e8a668321f5ba6
https://github.com/GoogleCloudPlatform/cloud-errors-nodejs/blob/fda2218759cd8754a096dbe437e8a668321f5ba6/lib/interfaces/express.js#L35-L75
train
GoogleCloudPlatform/cloud-errors-nodejs
lib/request-extractors/manual.js
manualRequestInformationExtractor
function manualRequestInformationExtractor(req) { var returnObject = new RequestInformationContainer(); if (!isObject(req) || isArray(req) || isFunction(req)) { return returnObject; } if (has(req, 'method')) { returnObject.setMethod(req.method); } if (has(req, 'url')) { returnObject.setUrl(req.url); } if (has(req, 'userAgent')) { returnObject.setUserAgent(req.userAgent); } if (has(req, 'referrer')) { returnObject.setReferrer(req.referrer); } if (has(req, 'statusCode')) { returnObject.setStatusCode(req.statusCode); } if (has(req, 'remoteAddress')) { returnObject.setRemoteAddress(req.remoteAddress); } return returnObject; }
javascript
function manualRequestInformationExtractor(req) { var returnObject = new RequestInformationContainer(); if (!isObject(req) || isArray(req) || isFunction(req)) { return returnObject; } if (has(req, 'method')) { returnObject.setMethod(req.method); } if (has(req, 'url')) { returnObject.setUrl(req.url); } if (has(req, 'userAgent')) { returnObject.setUserAgent(req.userAgent); } if (has(req, 'referrer')) { returnObject.setReferrer(req.referrer); } if (has(req, 'statusCode')) { returnObject.setStatusCode(req.statusCode); } if (has(req, 'remoteAddress')) { returnObject.setRemoteAddress(req.remoteAddress); } return returnObject; }
[ "function", "manualRequestInformationExtractor", "(", "req", ")", "{", "var", "returnObject", "=", "new", "RequestInformationContainer", "(", ")", ";", "if", "(", "!", "isObject", "(", "req", ")", "||", "isArray", "(", "req", ")", "||", "isFunction", "(", "req", ")", ")", "{", "return", "returnObject", ";", "}", "if", "(", "has", "(", "req", ",", "'method'", ")", ")", "{", "returnObject", ".", "setMethod", "(", "req", ".", "method", ")", ";", "}", "if", "(", "has", "(", "req", ",", "'url'", ")", ")", "{", "returnObject", ".", "setUrl", "(", "req", ".", "url", ")", ";", "}", "if", "(", "has", "(", "req", ",", "'userAgent'", ")", ")", "{", "returnObject", ".", "setUserAgent", "(", "req", ".", "userAgent", ")", ";", "}", "if", "(", "has", "(", "req", ",", "'referrer'", ")", ")", "{", "returnObject", ".", "setReferrer", "(", "req", ".", "referrer", ")", ";", "}", "if", "(", "has", "(", "req", ",", "'statusCode'", ")", ")", "{", "returnObject", ".", "setStatusCode", "(", "req", ".", "statusCode", ")", ";", "}", "if", "(", "has", "(", "req", ",", "'remoteAddress'", ")", ")", "{", "returnObject", ".", "setRemoteAddress", "(", "req", ".", "remoteAddress", ")", ";", "}", "return", "returnObject", ";", "}" ]
The manualRequestInformationExtractor is meant to take a standard object and extract request information based on the inclusion of several properties. This function will check the presence of properties before attempting to access them on the object but it will not attempt to check for these properties types as this is allocated to the RequestInformationContainer. @function manualRequestInformationExtractor @param {Object} req - the request information object to extract from @param {String} [req.method] - the request method (ex GET, PUT, POST, DELETE) @param {String} [req.url] - the request url @param {String} [req.userAgent] - the requesters user-agent @param {String} [req.referrer] - the requesters referrer @param {Number} [req.statusCode] - the status code given in response to the request @param {String} [req.remoteAddress] - the remote address of the requester @returns {RequestInformationContainer} - an object containing the request information in a standardized format
[ "The", "manualRequestInformationExtractor", "is", "meant", "to", "take", "a", "standard", "object", "and", "extract", "request", "information", "based", "on", "the", "inclusion", "of", "several", "properties", ".", "This", "function", "will", "check", "the", "presence", "of", "properties", "before", "attempting", "to", "access", "them", "on", "the", "object", "but", "it", "will", "not", "attempt", "to", "check", "for", "these", "properties", "types", "as", "this", "is", "allocated", "to", "the", "RequestInformationContainer", "." ]
fda2218759cd8754a096dbe437e8a668321f5ba6
https://github.com/GoogleCloudPlatform/cloud-errors-nodejs/blob/fda2218759cd8754a096dbe437e8a668321f5ba6/lib/request-extractors/manual.js#L43-L83
train
GoogleCloudPlatform/cloud-errors-nodejs
lib/configuration.js
function(givenConfig, logger) { /** * The _logger property caches the logger instance created at the top-level * for configuration logging purposes. * @memberof Configuration * @private * @type {Object} * @defaultvalue Object */ this._logger = logger; /** * The _reportUncaughtExceptions property is meant to contain the optional * runtime configuration property reportUncaughtExceptions. This property will * default to true if not given false through the runtime configuration * meaning that the default behavior is to catch uncaught exceptions, report * them to the Stackdriver Errors API and then exit. If given false uncaught * exceptions will not be listened for and not be caught or reported. * @memberof Configuration * @private * @type {Boolean} * @defaultvalue true */ this._reportUncaughtExceptions = true; /** * The _shouldReportErrorsToAPI property is meant to denote whether or not * the Stackdriver error reporting library will actually try to report Errors * to the Stackdriver Error API. The value of this property is derived from * the `NODE_ENV` environmental variable or the value of the ignoreEnvironmentCheck * property if present in the runtime configuration. If either the `NODE_ENV` * variable is set to 'production' or the ignoreEnvironmentCheck propery on * the runtime configuration is set to true then the error reporting library will * attempt to send errors to the Error API. Otherwise the value will remain * false and errors will not be reported to the API. * @memberof Configuration * @private * @type {Boolean} * @defaultvalue false */ this._shouldReportErrorsToAPI = false; /** * The _projectId property is meant to contain the string project id that the * hosting application is running under. The project id is a unique string * identifier for the project. If the Configuration instance is not able to * retrieve a project id from the metadata service or the runtime-given * configuration then the property will remain null. If given both a project * id through the metadata service and the runtime configuration then the * instance will assign the value given by the metadata service over the * runtime configuration. If the instance is unable to retrieve a valid * project id or number from runtime configuration and the metadata service * then this will trigger the `error` event in which listening components must * operate in 'offline' mode. * {@link https://cloud.google.com/compute/docs/storing-retrieving-metadata} * @memberof Configuration * @private * @type {String|Null} * @defaultvalue null */ this._projectId = null; /** * The _key property is meant to contain the optional Stackdriver API key that * may be used in place of default application credentials to authenticate * with the Stackdriver Error API. This property will remain null if a key * is not given in the runtime configuration or an invalid type is given as * the runtime configuration. * {@link https://support.google.com/cloud/answer/6158862?hl=en} * @memberof Configuration * @private * @type {String|Null} * @defaultvalue null */ this._key = null; /** * The _keyFilename property is meant to contain a path to a file containing * user or service account credentials, which will be used in place of * application default credentials. This property will remain null if no * value for keyFilename is given in the runtime configuration. * @memberof Configuration * @private * @type {String|Null} * @defaultvalue null */ this._keyFilename = null; /** * The _credentials property is meant to contain an object representation of * user or service account credentials, which will be used in place of * application default credentials. This property will remain null if no * value for credentials is given in the runtime configuration. * @memberof Configuration * @private * @type {Credentials|Null} * @defaultvalue null */ this._credentials = null; /** * The _serviceContext property is meant to contain the optional service * context information which may be given in the runtime configuration. If * not given in the runtime configuration then the property value will remain * null. * @memberof Configuration * @private * @type {Object} */ this._serviceContext = {service: 'nodejs', version: ''}; /** * The _version of the Error reporting library that is currently being run. * This information will be logged in errors communicated to the Stackdriver * Error API. * @memberof Configuration * @private * @type {String} */ this._version = version; /** * The _givenConfiguration property holds a ConfigurationOptions object * which, if valid, will be merged against by the values taken from the meta- * data service. If the _givenConfiguration property is not valid then only * metadata values will be used in the Configuration instance. * @memberof Configuration * @private * @type {Object|Null} * @defaultvalue null */ this._givenConfiguration = isPlainObject(givenConfig) ? givenConfig : {}; this._checkLocalServiceContext(); this._gatherLocalConfiguration(); }
javascript
function(givenConfig, logger) { /** * The _logger property caches the logger instance created at the top-level * for configuration logging purposes. * @memberof Configuration * @private * @type {Object} * @defaultvalue Object */ this._logger = logger; /** * The _reportUncaughtExceptions property is meant to contain the optional * runtime configuration property reportUncaughtExceptions. This property will * default to true if not given false through the runtime configuration * meaning that the default behavior is to catch uncaught exceptions, report * them to the Stackdriver Errors API and then exit. If given false uncaught * exceptions will not be listened for and not be caught or reported. * @memberof Configuration * @private * @type {Boolean} * @defaultvalue true */ this._reportUncaughtExceptions = true; /** * The _shouldReportErrorsToAPI property is meant to denote whether or not * the Stackdriver error reporting library will actually try to report Errors * to the Stackdriver Error API. The value of this property is derived from * the `NODE_ENV` environmental variable or the value of the ignoreEnvironmentCheck * property if present in the runtime configuration. If either the `NODE_ENV` * variable is set to 'production' or the ignoreEnvironmentCheck propery on * the runtime configuration is set to true then the error reporting library will * attempt to send errors to the Error API. Otherwise the value will remain * false and errors will not be reported to the API. * @memberof Configuration * @private * @type {Boolean} * @defaultvalue false */ this._shouldReportErrorsToAPI = false; /** * The _projectId property is meant to contain the string project id that the * hosting application is running under. The project id is a unique string * identifier for the project. If the Configuration instance is not able to * retrieve a project id from the metadata service or the runtime-given * configuration then the property will remain null. If given both a project * id through the metadata service and the runtime configuration then the * instance will assign the value given by the metadata service over the * runtime configuration. If the instance is unable to retrieve a valid * project id or number from runtime configuration and the metadata service * then this will trigger the `error` event in which listening components must * operate in 'offline' mode. * {@link https://cloud.google.com/compute/docs/storing-retrieving-metadata} * @memberof Configuration * @private * @type {String|Null} * @defaultvalue null */ this._projectId = null; /** * The _key property is meant to contain the optional Stackdriver API key that * may be used in place of default application credentials to authenticate * with the Stackdriver Error API. This property will remain null if a key * is not given in the runtime configuration or an invalid type is given as * the runtime configuration. * {@link https://support.google.com/cloud/answer/6158862?hl=en} * @memberof Configuration * @private * @type {String|Null} * @defaultvalue null */ this._key = null; /** * The _keyFilename property is meant to contain a path to a file containing * user or service account credentials, which will be used in place of * application default credentials. This property will remain null if no * value for keyFilename is given in the runtime configuration. * @memberof Configuration * @private * @type {String|Null} * @defaultvalue null */ this._keyFilename = null; /** * The _credentials property is meant to contain an object representation of * user or service account credentials, which will be used in place of * application default credentials. This property will remain null if no * value for credentials is given in the runtime configuration. * @memberof Configuration * @private * @type {Credentials|Null} * @defaultvalue null */ this._credentials = null; /** * The _serviceContext property is meant to contain the optional service * context information which may be given in the runtime configuration. If * not given in the runtime configuration then the property value will remain * null. * @memberof Configuration * @private * @type {Object} */ this._serviceContext = {service: 'nodejs', version: ''}; /** * The _version of the Error reporting library that is currently being run. * This information will be logged in errors communicated to the Stackdriver * Error API. * @memberof Configuration * @private * @type {String} */ this._version = version; /** * The _givenConfiguration property holds a ConfigurationOptions object * which, if valid, will be merged against by the values taken from the meta- * data service. If the _givenConfiguration property is not valid then only * metadata values will be used in the Configuration instance. * @memberof Configuration * @private * @type {Object|Null} * @defaultvalue null */ this._givenConfiguration = isPlainObject(givenConfig) ? givenConfig : {}; this._checkLocalServiceContext(); this._gatherLocalConfiguration(); }
[ "function", "(", "givenConfig", ",", "logger", ")", "{", "/**\n * The _logger property caches the logger instance created at the top-level\n * for configuration logging purposes.\n * @memberof Configuration\n * @private\n * @type {Object}\n * @defaultvalue Object\n */", "this", ".", "_logger", "=", "logger", ";", "/**\n * The _reportUncaughtExceptions property is meant to contain the optional\n * runtime configuration property reportUncaughtExceptions. This property will\n * default to true if not given false through the runtime configuration\n * meaning that the default behavior is to catch uncaught exceptions, report\n * them to the Stackdriver Errors API and then exit. If given false uncaught\n * exceptions will not be listened for and not be caught or reported.\n * @memberof Configuration\n * @private\n * @type {Boolean}\n * @defaultvalue true\n */", "this", ".", "_reportUncaughtExceptions", "=", "true", ";", "/**\n * The _shouldReportErrorsToAPI property is meant to denote whether or not\n * the Stackdriver error reporting library will actually try to report Errors\n * to the Stackdriver Error API. The value of this property is derived from\n * the `NODE_ENV` environmental variable or the value of the ignoreEnvironmentCheck\n * property if present in the runtime configuration. If either the `NODE_ENV` \n * variable is set to 'production' or the ignoreEnvironmentCheck propery on \n * the runtime configuration is set to true then the error reporting library will \n * attempt to send errors to the Error API. Otherwise the value will remain \n * false and errors will not be reported to the API.\n * @memberof Configuration\n * @private\n * @type {Boolean}\n * @defaultvalue false\n */", "this", ".", "_shouldReportErrorsToAPI", "=", "false", ";", "/**\n * The _projectId property is meant to contain the string project id that the\n * hosting application is running under. The project id is a unique string\n * identifier for the project. If the Configuration instance is not able to\n * retrieve a project id from the metadata service or the runtime-given\n * configuration then the property will remain null. If given both a project\n * id through the metadata service and the runtime configuration then the\n * instance will assign the value given by the metadata service over the\n * runtime configuration. If the instance is unable to retrieve a valid\n * project id or number from runtime configuration and the metadata service\n * then this will trigger the `error` event in which listening components must\n * operate in 'offline' mode.\n * {@link https://cloud.google.com/compute/docs/storing-retrieving-metadata}\n * @memberof Configuration\n * @private\n * @type {String|Null}\n * @defaultvalue null\n */", "this", ".", "_projectId", "=", "null", ";", "/**\n * The _key property is meant to contain the optional Stackdriver API key that\n * may be used in place of default application credentials to authenticate\n * with the Stackdriver Error API. This property will remain null if a key\n * is not given in the runtime configuration or an invalid type is given as\n * the runtime configuration.\n * {@link https://support.google.com/cloud/answer/6158862?hl=en}\n * @memberof Configuration\n * @private\n * @type {String|Null}\n * @defaultvalue null\n */", "this", ".", "_key", "=", "null", ";", "/**\n * The _keyFilename property is meant to contain a path to a file containing\n * user or service account credentials, which will be used in place of\n * application default credentials. This property will remain null if no\n * value for keyFilename is given in the runtime configuration.\n * @memberof Configuration\n * @private\n * @type {String|Null}\n * @defaultvalue null\n */", "this", ".", "_keyFilename", "=", "null", ";", "/**\n * The _credentials property is meant to contain an object representation of\n * user or service account credentials, which will be used in place of\n * application default credentials. This property will remain null if no\n * value for credentials is given in the runtime configuration.\n * @memberof Configuration\n * @private\n * @type {Credentials|Null}\n * @defaultvalue null\n */", "this", ".", "_credentials", "=", "null", ";", "/**\n * The _serviceContext property is meant to contain the optional service\n * context information which may be given in the runtime configuration. If\n * not given in the runtime configuration then the property value will remain\n * null.\n * @memberof Configuration\n * @private\n * @type {Object}\n */", "this", ".", "_serviceContext", "=", "{", "service", ":", "'nodejs'", ",", "version", ":", "''", "}", ";", "/**\n * The _version of the Error reporting library that is currently being run.\n * This information will be logged in errors communicated to the Stackdriver\n * Error API.\n * @memberof Configuration\n * @private\n * @type {String}\n */", "this", ".", "_version", "=", "version", ";", "/**\n * The _givenConfiguration property holds a ConfigurationOptions object\n * which, if valid, will be merged against by the values taken from the meta-\n * data service. If the _givenConfiguration property is not valid then only\n * metadata values will be used in the Configuration instance.\n * @memberof Configuration\n * @private\n * @type {Object|Null}\n * @defaultvalue null\n */", "this", ".", "_givenConfiguration", "=", "isPlainObject", "(", "givenConfig", ")", "?", "givenConfig", ":", "{", "}", ";", "this", ".", "_checkLocalServiceContext", "(", ")", ";", "this", ".", "_gatherLocalConfiguration", "(", ")", ";", "}" ]
The Configuration constructor function initializes several internal properties on the Configuration instance and accepts a runtime-given configuration object which may be used by the Configuration instance depending on the initialization transaction that occurs with the meta-data service. @class Configuration @classdesc The Configuration class represents the runtime configuration of the Stackdriver error handling library. This Configuration class accepts the configuration options potentially given through the application interface but it also preferences values received from the metadata service over values given through the application interface. Becuase the Configuration class must handle async network I/O it exposes some methods as async functions which may cache their interactions results to speed access to properties. @param {ConfigurationOptions} givenConfig - The config given by the hosting application at runtime. Configuration values will only be observed if they are given as a plain JS object; all other values will be ignored. @param {Object} logger - The logger instance created when the library API has been initialized.
[ "The", "Configuration", "constructor", "function", "initializes", "several", "internal", "properties", "on", "the", "Configuration", "instance", "and", "accepts", "a", "runtime", "-", "given", "configuration", "object", "which", "may", "be", "used", "by", "the", "Configuration", "instance", "depending", "on", "the", "initialization", "transaction", "that", "occurs", "with", "the", "meta", "-", "data", "service", "." ]
fda2218759cd8754a096dbe437e8a668321f5ba6
https://github.com/GoogleCloudPlatform/cloud-errors-nodejs/blob/fda2218759cd8754a096dbe437e8a668321f5ba6/lib/configuration.js#L52-L177
train
GoogleCloudPlatform/cloud-errors-nodejs
lib/interfaces/restify.js
restifyErrorHandler
function restifyErrorHandler(client, config, err, em) { var svc = config.getServiceContext(); em.setServiceContext(svc.service, svc.version); errorHandlerRouter(err, em); client.sendError(em); }
javascript
function restifyErrorHandler(client, config, err, em) { var svc = config.getServiceContext(); em.setServiceContext(svc.service, svc.version); errorHandlerRouter(err, em); client.sendError(em); }
[ "function", "restifyErrorHandler", "(", "client", ",", "config", ",", "err", ",", "em", ")", "{", "var", "svc", "=", "config", ".", "getServiceContext", "(", ")", ";", "em", ".", "setServiceContext", "(", "svc", ".", "service", ",", "svc", ".", "version", ")", ";", "errorHandlerRouter", "(", "err", ",", "em", ")", ";", "client", ".", "sendError", "(", "em", ")", ";", "}" ]
The restifyErrorHandler is responsible for taking the captured error, setting the serviceContext property on the corresponding ErrorMessage instance, routing the captured error to the right handler so that it can be correctly marshaled into the ErrorMessage instance and then attempting to send it to the Stackdriver API via the given API client instance. @function restifyErrorHandler @param {AuthClient} client - the API client @param {NormalizedConfigurationVariables} config - the application configuration @param {Any} err - the error being handled @param {ErrorMessage} - the error message instance container @returns {Undefined} - does not return anything
[ "The", "restifyErrorHandler", "is", "responsible", "for", "taking", "the", "captured", "error", "setting", "the", "serviceContext", "property", "on", "the", "corresponding", "ErrorMessage", "instance", "routing", "the", "captured", "error", "to", "the", "right", "handler", "so", "that", "it", "can", "be", "correctly", "marshaled", "into", "the", "ErrorMessage", "instance", "and", "then", "attempting", "to", "send", "it", "to", "the", "Stackdriver", "API", "via", "the", "given", "API", "client", "instance", "." ]
fda2218759cd8754a096dbe437e8a668321f5ba6
https://github.com/GoogleCloudPlatform/cloud-errors-nodejs/blob/fda2218759cd8754a096dbe437e8a668321f5ba6/lib/interfaces/restify.js#L40-L47
train
GoogleCloudPlatform/cloud-errors-nodejs
lib/interfaces/restify.js
restifyRequestFinishHandler
function restifyRequestFinishHandler(client, config, req, res) { var em; if (res._body instanceof Error || res.statusCode > 309 && res.statusCode < 512) { em = new ErrorMessage().consumeRequestInformation( expressRequestInformationExtractor(req, res)); restifyErrorHandler(client, config, res._body, em); } }
javascript
function restifyRequestFinishHandler(client, config, req, res) { var em; if (res._body instanceof Error || res.statusCode > 309 && res.statusCode < 512) { em = new ErrorMessage().consumeRequestInformation( expressRequestInformationExtractor(req, res)); restifyErrorHandler(client, config, res._body, em); } }
[ "function", "restifyRequestFinishHandler", "(", "client", ",", "config", ",", "req", ",", "res", ")", "{", "var", "em", ";", "if", "(", "res", ".", "_body", "instanceof", "Error", "||", "res", ".", "statusCode", ">", "309", "&&", "res", ".", "statusCode", "<", "512", ")", "{", "em", "=", "new", "ErrorMessage", "(", ")", ".", "consumeRequestInformation", "(", "expressRequestInformationExtractor", "(", "req", ",", "res", ")", ")", ";", "restifyErrorHandler", "(", "client", ",", "config", ",", "res", ".", "_body", ",", "em", ")", ";", "}", "}" ]
The restifyRequestFinishHandler will be called once the response has emitted the `finish` event and is now in its finalized state. This function will attempt to determine whether or not the body of response is an instance of the Error class or its status codes indicate that the response ended in an error state. If either of the preceding are true then the restifyErrorHandler will be called with the error to be routed to the Stackdriver service. @function restifyRequestFinishHandler @param {AuthClient} client - the API client @param {NormalizedConfigurationVariables} config - the application configuration @param {Object} req - the restify request @param {Object} res - the restify response @returns {Undefined} - does not return anything
[ "The", "restifyRequestFinishHandler", "will", "be", "called", "once", "the", "response", "has", "emitted", "the", "finish", "event", "and", "is", "now", "in", "its", "finalized", "state", ".", "This", "function", "will", "attempt", "to", "determine", "whether", "or", "not", "the", "body", "of", "response", "is", "an", "instance", "of", "the", "Error", "class", "or", "its", "status", "codes", "indicate", "that", "the", "response", "ended", "in", "an", "error", "state", ".", "If", "either", "of", "the", "preceding", "are", "true", "then", "the", "restifyErrorHandler", "will", "be", "called", "with", "the", "error", "to", "be", "routed", "to", "the", "Stackdriver", "service", "." ]
fda2218759cd8754a096dbe437e8a668321f5ba6
https://github.com/GoogleCloudPlatform/cloud-errors-nodejs/blob/fda2218759cd8754a096dbe437e8a668321f5ba6/lib/interfaces/restify.js#L64-L74
train
GoogleCloudPlatform/cloud-errors-nodejs
lib/interfaces/restify.js
restifyRequestHandler
function restifyRequestHandler(client, config, req, res, next) { var listener = {}; if (isObject(res) && isFunction(res.on) && isFunction(res.removeListener)) { listener = function() { restifyRequestFinishHandler(client, config, req, res); res.removeListener('finish', listener); }; res.on('finish', listener); } return next(); }
javascript
function restifyRequestHandler(client, config, req, res, next) { var listener = {}; if (isObject(res) && isFunction(res.on) && isFunction(res.removeListener)) { listener = function() { restifyRequestFinishHandler(client, config, req, res); res.removeListener('finish', listener); }; res.on('finish', listener); } return next(); }
[ "function", "restifyRequestHandler", "(", "client", ",", "config", ",", "req", ",", "res", ",", "next", ")", "{", "var", "listener", "=", "{", "}", ";", "if", "(", "isObject", "(", "res", ")", "&&", "isFunction", "(", "res", ".", "on", ")", "&&", "isFunction", "(", "res", ".", "removeListener", ")", ")", "{", "listener", "=", "function", "(", ")", "{", "restifyRequestFinishHandler", "(", "client", ",", "config", ",", "req", ",", "res", ")", ";", "res", ".", "removeListener", "(", "'finish'", ",", "listener", ")", ";", "}", ";", "res", ".", "on", "(", "'finish'", ",", "listener", ")", ";", "}", "return", "next", "(", ")", ";", "}" ]
The restifyRequestHandler attaches the restifyRequestFinishHandler to each responses 'finish' event wherein the callback function will determine whether or not the response is an error response or not. The finish event is used since the restify response object will not have any error information contained within it until the downstream request handlers have had the opportunity to deal with the request and create a contextually significant response. @function restifyRequestHandler @param {AuthClient} client - the API client @param {NormalizedConfigurationVariables} config - the application configuration @param {Object} req - the current request @param {Object} res - the current response @param {Function} next - the callback function to pass the request onto the downstream request handlers @returns {Any} - the result of the next function
[ "The", "restifyRequestHandler", "attaches", "the", "restifyRequestFinishHandler", "to", "each", "responses", "finish", "event", "wherein", "the", "callback", "function", "will", "determine", "whether", "or", "not", "the", "response", "is", "an", "error", "response", "or", "not", ".", "The", "finish", "event", "is", "used", "since", "the", "restify", "response", "object", "will", "not", "have", "any", "error", "information", "contained", "within", "it", "until", "the", "downstream", "request", "handlers", "have", "had", "the", "opportunity", "to", "deal", "with", "the", "request", "and", "create", "a", "contextually", "significant", "response", "." ]
fda2218759cd8754a096dbe437e8a668321f5ba6
https://github.com/GoogleCloudPlatform/cloud-errors-nodejs/blob/fda2218759cd8754a096dbe437e8a668321f5ba6/lib/interfaces/restify.js#L94-L109
train
GoogleCloudPlatform/cloud-errors-nodejs
lib/request-extractors/express.js
extractRemoteAddressFromRequest
function extractRemoteAddressFromRequest(req) { if (typeof req.header('x-forwarded-for') !== 'undefined') { return req.header('x-forwarded-for'); } else if (isObject(req.connection)) { return req.connection.remoteAddress; } return ''; }
javascript
function extractRemoteAddressFromRequest(req) { if (typeof req.header('x-forwarded-for') !== 'undefined') { return req.header('x-forwarded-for'); } else if (isObject(req.connection)) { return req.connection.remoteAddress; } return ''; }
[ "function", "extractRemoteAddressFromRequest", "(", "req", ")", "{", "if", "(", "typeof", "req", ".", "header", "(", "'x-forwarded-for'", ")", "!==", "'undefined'", ")", "{", "return", "req", ".", "header", "(", "'x-forwarded-for'", ")", ";", "}", "else", "if", "(", "isObject", "(", "req", ".", "connection", ")", ")", "{", "return", "req", ".", "connection", ".", "remoteAddress", ";", "}", "return", "''", ";", "}" ]
This function checks for the presence of an `x-forwarded-for` header on the request to check for remote address forwards, if that is header is not present in the request then the function will attempt to extract the remote address from the express request object. @function extractRemoteAddressFromRequest @param {Object} req - the express request object @returns {String} - the remote address or, if one cannot be found, an empty string
[ "This", "function", "checks", "for", "the", "presence", "of", "an", "x", "-", "forwarded", "-", "for", "header", "on", "the", "request", "to", "check", "for", "remote", "address", "forwards", "if", "that", "is", "header", "is", "not", "present", "in", "the", "request", "then", "the", "function", "will", "attempt", "to", "extract", "the", "remote", "address", "from", "the", "express", "request", "object", "." ]
fda2218759cd8754a096dbe437e8a668321f5ba6
https://github.com/GoogleCloudPlatform/cloud-errors-nodejs/blob/fda2218759cd8754a096dbe437e8a668321f5ba6/lib/request-extractors/express.js#L33-L44
train
GoogleCloudPlatform/cloud-errors-nodejs
lib/request-extractors/express.js
expressRequestInformationExtractor
function expressRequestInformationExtractor(req, res) { var returnObject = new RequestInformationContainer(); if (!isObject(req) || !isFunction(req.header) || !isObject(res)) { return returnObject; } returnObject.setMethod(req.method) .setUrl(req.url) .setUserAgent(req.header('user-agent')) .setReferrer(req.header('referrer')) .setStatusCode(res.statusCode) .setRemoteAddress(extractRemoteAddressFromRequest(req)); return returnObject; }
javascript
function expressRequestInformationExtractor(req, res) { var returnObject = new RequestInformationContainer(); if (!isObject(req) || !isFunction(req.header) || !isObject(res)) { return returnObject; } returnObject.setMethod(req.method) .setUrl(req.url) .setUserAgent(req.header('user-agent')) .setReferrer(req.header('referrer')) .setStatusCode(res.statusCode) .setRemoteAddress(extractRemoteAddressFromRequest(req)); return returnObject; }
[ "function", "expressRequestInformationExtractor", "(", "req", ",", "res", ")", "{", "var", "returnObject", "=", "new", "RequestInformationContainer", "(", ")", ";", "if", "(", "!", "isObject", "(", "req", ")", "||", "!", "isFunction", "(", "req", ".", "header", ")", "||", "!", "isObject", "(", "res", ")", ")", "{", "return", "returnObject", ";", "}", "returnObject", ".", "setMethod", "(", "req", ".", "method", ")", ".", "setUrl", "(", "req", ".", "url", ")", ".", "setUserAgent", "(", "req", ".", "header", "(", "'user-agent'", ")", ")", ".", "setReferrer", "(", "req", ".", "header", "(", "'referrer'", ")", ")", ".", "setStatusCode", "(", "res", ".", "statusCode", ")", ".", "setRemoteAddress", "(", "extractRemoteAddressFromRequest", "(", "req", ")", ")", ";", "return", "returnObject", ";", "}" ]
The expressRequestInformationExtractor is a function which is made to extract request information from a express request object. This function will do a basic check for type and method presence but will not check for the presence of properties on the request object. @function expressRequestInformationExtractor @param {Object} req - the express request object @param {Object} res - the express response object @returns {RequestInformationContainer} - an object containing the request information in a standardized format
[ "The", "expressRequestInformationExtractor", "is", "a", "function", "which", "is", "made", "to", "extract", "request", "information", "from", "a", "express", "request", "object", ".", "This", "function", "will", "do", "a", "basic", "check", "for", "type", "and", "method", "presence", "but", "will", "not", "check", "for", "the", "presence", "of", "properties", "on", "the", "request", "object", "." ]
fda2218759cd8754a096dbe437e8a668321f5ba6
https://github.com/GoogleCloudPlatform/cloud-errors-nodejs/blob/fda2218759cd8754a096dbe437e8a668321f5ba6/lib/request-extractors/express.js#L57-L74
train
GoogleCloudPlatform/cloud-errors-nodejs
lib/error-handlers/number.js
handleNumberAsError
function handleNumberAsError(err, errorMessage) { var fauxError = new Error(); var errChecked = fauxError.stack; if (isNumber(err) && isFunction(err.toString)) { errChecked = err.toString(); } errorMessage.setMessage(errChecked); }
javascript
function handleNumberAsError(err, errorMessage) { var fauxError = new Error(); var errChecked = fauxError.stack; if (isNumber(err) && isFunction(err.toString)) { errChecked = err.toString(); } errorMessage.setMessage(errChecked); }
[ "function", "handleNumberAsError", "(", "err", ",", "errorMessage", ")", "{", "var", "fauxError", "=", "new", "Error", "(", ")", ";", "var", "errChecked", "=", "fauxError", ".", "stack", ";", "if", "(", "isNumber", "(", "err", ")", "&&", "isFunction", "(", "err", ".", "toString", ")", ")", "{", "errChecked", "=", "err", ".", "toString", "(", ")", ";", "}", "errorMessage", ".", "setMessage", "(", "errChecked", ")", ";", "}" ]
Handles routing and validation for parsing an error which has been indicated to be of type Number. This handler will manufacture a new Error to create a stack-trace for submission to the Error API and will attempt to caste the given number to a string for submission to the Error API. @function handleNumberAsError @param {Number} err - the number submitted as content for the error message @param {ErrorMessage} errorMessage - the error messag instance to marshall error information into. @returns {Undefined} - does not return anything
[ "Handles", "routing", "and", "validation", "for", "parsing", "an", "error", "which", "has", "been", "indicated", "to", "be", "of", "type", "Number", ".", "This", "handler", "will", "manufacture", "a", "new", "Error", "to", "create", "a", "stack", "-", "trace", "for", "submission", "to", "the", "Error", "API", "and", "will", "attempt", "to", "caste", "the", "given", "number", "to", "a", "string", "for", "submission", "to", "the", "Error", "API", "." ]
fda2218759cd8754a096dbe437e8a668321f5ba6
https://github.com/GoogleCloudPlatform/cloud-errors-nodejs/blob/fda2218759cd8754a096dbe437e8a668321f5ba6/lib/error-handlers/number.js#L33-L43
train
mattkrick/fast-bitset
app/BitSet.js
_msb
function _msb(word) { word |= word >> 1; word |= word >> 2; word |= word >> 4; word |= word >> 8; word |= word >> 16; word = (word >> 1) + 1; return multiplyDeBruijnBitPosition[(word * 0x077CB531) >>> 27]; }
javascript
function _msb(word) { word |= word >> 1; word |= word >> 2; word |= word >> 4; word |= word >> 8; word |= word >> 16; word = (word >> 1) + 1; return multiplyDeBruijnBitPosition[(word * 0x077CB531) >>> 27]; }
[ "function", "_msb", "(", "word", ")", "{", "word", "|=", "word", ">>", "1", ";", "word", "|=", "word", ">>", "2", ";", "word", "|=", "word", ">>", "4", ";", "word", "|=", "word", ">>", "8", ";", "word", "|=", "word", ">>", "16", ";", "word", "=", "(", "word", ">>", "1", ")", "+", "1", ";", "return", "multiplyDeBruijnBitPosition", "[", "(", "word", "*", "0x077CB531", ")", ">>>", "27", "]", ";", "}" ]
Returns the least signifcant bit, or 0 if none set, so a prior check to see if the word > 0 is required @param word the current array @returns {number} the index of the most significant bit in the current array @private
[ "Returns", "the", "least", "signifcant", "bit", "or", "0", "if", "none", "set", "so", "a", "prior", "check", "to", "see", "if", "the", "word", ">", "0", "is", "required" ]
14c7510ab4ebe1a4f8576b9c5d266f6e8a72a615
https://github.com/mattkrick/fast-bitset/blob/14c7510ab4ebe1a4f8576b9c5d266f6e8a72a615/app/BitSet.js#L577-L585
train
IndigoUnited/js-dejavu
dist/node/strict/Class.js
doMember
function doMember(func) { /*jshint validthis:true*/ func = func || this; // Check if it is a named func already if (func[$name]) { return func; } var caller = process._dejavu.caller; // Check if outside the instance/class if (!caller) { throw new Error('Attempting to mark a function as a member outside an instance/class.'); } // Check if already marked as anonymous if (func[$anonymous]) { throw new Error('Function is already marked as an member.'); } func[$anonymous] = true; func = wrapMethod(null, func, caller.constructor); func[$anonymous] = true; return func; }
javascript
function doMember(func) { /*jshint validthis:true*/ func = func || this; // Check if it is a named func already if (func[$name]) { return func; } var caller = process._dejavu.caller; // Check if outside the instance/class if (!caller) { throw new Error('Attempting to mark a function as a member outside an instance/class.'); } // Check if already marked as anonymous if (func[$anonymous]) { throw new Error('Function is already marked as an member.'); } func[$anonymous] = true; func = wrapMethod(null, func, caller.constructor); func[$anonymous] = true; return func; }
[ "function", "doMember", "(", "func", ")", "{", "/*jshint validthis:true*/", "func", "=", "func", "||", "this", ";", "// Check if it is a named func already", "if", "(", "func", "[", "$name", "]", ")", "{", "return", "func", ";", "}", "var", "caller", "=", "process", ".", "_dejavu", ".", "caller", ";", "// Check if outside the instance/class", "if", "(", "!", "caller", ")", "{", "throw", "new", "Error", "(", "'Attempting to mark a function as a member outside an instance/class.'", ")", ";", "}", "// Check if already marked as anonymous", "if", "(", "func", "[", "$anonymous", "]", ")", "{", "throw", "new", "Error", "(", "'Function is already marked as an member.'", ")", ";", "}", "func", "[", "$anonymous", "]", "=", "true", ";", "func", "=", "wrapMethod", "(", "null", ",", "func", ",", "caller", ".", "constructor", ")", ";", "func", "[", "$anonymous", "]", "=", "true", ";", "return", "func", ";", "}" ]
Marks a function as part of the class. @param {Function} func The function
[ "Marks", "a", "function", "as", "part", "of", "the", "class", "." ]
b251d5e8508bb05854081968528e6a3b2ec68d33
https://github.com/IndigoUnited/js-dejavu/blob/b251d5e8508bb05854081968528e6a3b2ec68d33/dist/node/strict/Class.js#L1347-L1373
train
GoogleCloudPlatform/cloud-errors-nodejs
lib/error-router.js
errorHandlerRouter
function errorHandlerRouter(err, em) { if (err instanceof Error) { handleErrorClassError(err, em); return; } switch (typeof err) { case 'object': handleObjectAsError(err, em); break; case 'string': handleStringAsError(err, em); break; case 'number': handleNumberAsError(err, em); break; default: handleUnknownAsError(err, em); } }
javascript
function errorHandlerRouter(err, em) { if (err instanceof Error) { handleErrorClassError(err, em); return; } switch (typeof err) { case 'object': handleObjectAsError(err, em); break; case 'string': handleStringAsError(err, em); break; case 'number': handleNumberAsError(err, em); break; default: handleUnknownAsError(err, em); } }
[ "function", "errorHandlerRouter", "(", "err", ",", "em", ")", "{", "if", "(", "err", "instanceof", "Error", ")", "{", "handleErrorClassError", "(", "err", ",", "em", ")", ";", "return", ";", "}", "switch", "(", "typeof", "err", ")", "{", "case", "'object'", ":", "handleObjectAsError", "(", "err", ",", "em", ")", ";", "break", ";", "case", "'string'", ":", "handleStringAsError", "(", "err", ",", "em", ")", ";", "break", ";", "case", "'number'", ":", "handleNumberAsError", "(", "err", ",", "em", ")", ";", "break", ";", "default", ":", "handleUnknownAsError", "(", "err", ",", "em", ")", ";", "}", "}" ]
The Error handler router is responsible for taking an error of some type and and Error message container, analyzing the type of the error and routing it to the proper handler so that the error information can be marshaled into the the error message container. @function errorHandlerRouter @param {Any} err - the error information to extract from @param {ErrorMessage} em - an instance of ErrorMessage to marshal error information into @returns {Undefined} - does not return a value
[ "The", "Error", "handler", "router", "is", "responsible", "for", "taking", "an", "error", "of", "some", "type", "and", "and", "Error", "message", "container", "analyzing", "the", "type", "of", "the", "error", "and", "routing", "it", "to", "the", "proper", "handler", "so", "that", "the", "error", "information", "can", "be", "marshaled", "into", "the", "the", "error", "message", "container", "." ]
fda2218759cd8754a096dbe437e8a668321f5ba6
https://github.com/GoogleCloudPlatform/cloud-errors-nodejs/blob/fda2218759cd8754a096dbe437e8a668321f5ba6/lib/error-router.js#L35-L61
train
GoogleCloudPlatform/cloud-errors-nodejs
lib/error-handlers/string.js
handleStringAsError
function handleStringAsError(err, errorMessage) { var fauxError = new Error(); var fullStack = fauxError.stack.split('\n'); var cleanedStack = fullStack.slice(0, 1).concat(fullStack.slice(4)); var errChecked = ''; if (isString(err)) { // Replace the generic error message with the user-provided string cleanedStack[0] = err; } errChecked = cleanedStack.join('\n'); errorMessage.setMessage(errChecked); }
javascript
function handleStringAsError(err, errorMessage) { var fauxError = new Error(); var fullStack = fauxError.stack.split('\n'); var cleanedStack = fullStack.slice(0, 1).concat(fullStack.slice(4)); var errChecked = ''; if (isString(err)) { // Replace the generic error message with the user-provided string cleanedStack[0] = err; } errChecked = cleanedStack.join('\n'); errorMessage.setMessage(errChecked); }
[ "function", "handleStringAsError", "(", "err", ",", "errorMessage", ")", "{", "var", "fauxError", "=", "new", "Error", "(", ")", ";", "var", "fullStack", "=", "fauxError", ".", "stack", ".", "split", "(", "'\\n'", ")", ";", "var", "cleanedStack", "=", "fullStack", ".", "slice", "(", "0", ",", "1", ")", ".", "concat", "(", "fullStack", ".", "slice", "(", "4", ")", ")", ";", "var", "errChecked", "=", "''", ";", "if", "(", "isString", "(", "err", ")", ")", "{", "// Replace the generic error message with the user-provided string", "cleanedStack", "[", "0", "]", "=", "err", ";", "}", "errChecked", "=", "cleanedStack", ".", "join", "(", "'\\n'", ")", ";", "errorMessage", ".", "setMessage", "(", "errChecked", ")", ";", "}" ]
Handles validation of an error which has been indicated to be of type String. This function will create a new instance of the Error class to produce a stack trace for submission to the API and check to confirm that the given value is of type string. @function handleStringAsError @param {String} err - the String indicated as the content of the error @param {ErrorMessage} errorMessage - the error message instance to marshal error information into. @returns {Undefined} - does not return anything
[ "Handles", "validation", "of", "an", "error", "which", "has", "been", "indicated", "to", "be", "of", "type", "String", ".", "This", "function", "will", "create", "a", "new", "instance", "of", "the", "Error", "class", "to", "produce", "a", "stack", "trace", "for", "submission", "to", "the", "API", "and", "check", "to", "confirm", "that", "the", "given", "value", "is", "of", "type", "string", "." ]
fda2218759cd8754a096dbe437e8a668321f5ba6
https://github.com/GoogleCloudPlatform/cloud-errors-nodejs/blob/fda2218759cd8754a096dbe437e8a668321f5ba6/lib/error-handlers/string.js#L31-L45
train
GoogleCloudPlatform/cloud-errors-nodejs
lib/google-apis/auth-client.js
RequestHandler
function RequestHandler(config, logger) { this._request = commonDiag.utils.authorizedRequestFactory(SCOPES, { keyFile: config.getKeyFilename(), credentials: config.getCredentials() }); this._config = config; this._logger = logger; }
javascript
function RequestHandler(config, logger) { this._request = commonDiag.utils.authorizedRequestFactory(SCOPES, { keyFile: config.getKeyFilename(), credentials: config.getCredentials() }); this._config = config; this._logger = logger; }
[ "function", "RequestHandler", "(", "config", ",", "logger", ")", "{", "this", ".", "_request", "=", "commonDiag", ".", "utils", ".", "authorizedRequestFactory", "(", "SCOPES", ",", "{", "keyFile", ":", "config", ".", "getKeyFilename", "(", ")", ",", "credentials", ":", "config", ".", "getCredentials", "(", ")", "}", ")", ";", "this", ".", "_config", "=", "config", ";", "this", ".", "_logger", "=", "logger", ";", "}" ]
The RequestHandler constructor initializes several properties on the RequestHandler instance and create a new request factory for requesting against the Error Reporting API. @param {Configuration} config - The configuration instance @param {Object} logger - the logger instance @class RequestHandler @classdesc The RequestHandler class provides a centralized way of managing a pool of ongoing requests and routing there callback execution to the right handlers. The RequestHandler relies on the diag-common request factory and therefore only manages the routing of execution to the proper callback and does not do any queueing/batching. The RequestHandler instance has several properties: the projectId property is used to create a correct url for interacting with the API and key property can be optionally provided a value which can be used in place of default application authentication. The shouldReportErrors property will dictate whether or not the handler instance will attempt to send payloads to the API. If it is false the handler will immediately call back to the completion callback with a constant error value. @property {Function} _request - a npm.im/request style request function that provides the transport layer for requesting against the Error Reporting API. It includes retry and authorization logic. @property {String} _projectId - the project id used to uniquely identify and address the correct project in the Error Reporting API @property {Object} _logger - the instance-cached logger instance
[ "The", "RequestHandler", "constructor", "initializes", "several", "properties", "on", "the", "RequestHandler", "instance", "and", "create", "a", "new", "request", "factory", "for", "requesting", "against", "the", "Error", "Reporting", "API", "." ]
fda2218759cd8754a096dbe437e8a668321f5ba6
https://github.com/GoogleCloudPlatform/cloud-errors-nodejs/blob/fda2218759cd8754a096dbe437e8a668321f5ba6/lib/google-apis/auth-client.js#L55-L62
train
GoogleCloudPlatform/cloud-errors-nodejs
lib/google-apis/auth-client.js
getErrorReportURL
function getErrorReportURL(projectId, key) { var url = [API, projectId, 'events:report'].join('/'); if (isString(key)) { url += '?key=' + key; } return url; }
javascript
function getErrorReportURL(projectId, key) { var url = [API, projectId, 'events:report'].join('/'); if (isString(key)) { url += '?key=' + key; } return url; }
[ "function", "getErrorReportURL", "(", "projectId", ",", "key", ")", "{", "var", "url", "=", "[", "API", ",", "projectId", ",", "'events:report'", "]", ".", "join", "(", "'/'", ")", ";", "if", "(", "isString", "(", "key", ")", ")", "{", "url", "+=", "'?key='", "+", "key", ";", "}", "return", "url", ";", "}" ]
Compute the URL that errors should be reported to given the projectId and optional key. @param {String} projectId - the project id of the application. @param {String|Null} [key] - the API key used to authenticate against the service in place of application default credentials. @returns {String} computed URL that the errors should be reported to. @private
[ "Compute", "the", "URL", "that", "errors", "should", "be", "reported", "to", "given", "the", "projectId", "and", "optional", "key", "." ]
fda2218759cd8754a096dbe437e8a668321f5ba6
https://github.com/GoogleCloudPlatform/cloud-errors-nodejs/blob/fda2218759cd8754a096dbe437e8a668321f5ba6/lib/google-apis/auth-client.js#L73-L79
train
GoogleCloudPlatform/cloud-errors-nodejs
lib/interfaces/uncaught.js
handlerSetup
function handlerSetup(client, config) { /** * The actual exception handler creates a new instance of `ErrorMessage`, * extracts infomation from the propagated `Error` and marshals it into the * `ErrorMessage` instance, attempts to send this `ErrorMessage` instance to * the Stackdriver Error Reporting API. Subsequently the process is * terminated. * @function uncaughtExceptionHandler * @listens module:process~event:uncaughtException * @param {Error} err - The error that has been uncaught to this point * @returns {Undefined} - does not return a value */ function uncaughtExceptionHandler(err) { var em = new ErrorMessage(); errorHandlerRouter(err, em); client.sendError(em, handleProcessExit); setTimeout(handleProcessExit, 2000); } if (!config.getReportUncaughtExceptions()) { // Do not attach a listener to the process return null; } return process.on('uncaughtException', uncaughtExceptionHandler); }
javascript
function handlerSetup(client, config) { /** * The actual exception handler creates a new instance of `ErrorMessage`, * extracts infomation from the propagated `Error` and marshals it into the * `ErrorMessage` instance, attempts to send this `ErrorMessage` instance to * the Stackdriver Error Reporting API. Subsequently the process is * terminated. * @function uncaughtExceptionHandler * @listens module:process~event:uncaughtException * @param {Error} err - The error that has been uncaught to this point * @returns {Undefined} - does not return a value */ function uncaughtExceptionHandler(err) { var em = new ErrorMessage(); errorHandlerRouter(err, em); client.sendError(em, handleProcessExit); setTimeout(handleProcessExit, 2000); } if (!config.getReportUncaughtExceptions()) { // Do not attach a listener to the process return null; } return process.on('uncaughtException', uncaughtExceptionHandler); }
[ "function", "handlerSetup", "(", "client", ",", "config", ")", "{", "/**\n * The actual exception handler creates a new instance of `ErrorMessage`,\n * extracts infomation from the propagated `Error` and marshals it into the\n * `ErrorMessage` instance, attempts to send this `ErrorMessage` instance to\n * the Stackdriver Error Reporting API. Subsequently the process is\n * terminated.\n * @function uncaughtExceptionHandler\n * @listens module:process~event:uncaughtException\n * @param {Error} err - The error that has been uncaught to this point\n * @returns {Undefined} - does not return a value\n */", "function", "uncaughtExceptionHandler", "(", "err", ")", "{", "var", "em", "=", "new", "ErrorMessage", "(", ")", ";", "errorHandlerRouter", "(", "err", ",", "em", ")", ";", "client", ".", "sendError", "(", "em", ",", "handleProcessExit", ")", ";", "setTimeout", "(", "handleProcessExit", ",", "2000", ")", ";", "}", "if", "(", "!", "config", ".", "getReportUncaughtExceptions", "(", ")", ")", "{", "// Do not attach a listener to the process", "return", "null", ";", "}", "return", "process", ".", "on", "(", "'uncaughtException'", ",", "uncaughtExceptionHandler", ")", ";", "}" ]
If the configuraiton allows, install an uncaught exception handler that will report the uncaught error to the API and then terminate the process. @function handlerSetup @param {AuthClient} client - the API client for communication with the Stackdriver Error API @param {Configuration} config - the init configuration @returns {Null|process} - Returns null if the config demands ignoring uncaught exceptions, otherwise return the process instance
[ "If", "the", "configuraiton", "allows", "install", "an", "uncaught", "exception", "handler", "that", "will", "report", "the", "uncaught", "error", "to", "the", "API", "and", "then", "terminate", "the", "process", "." ]
fda2218759cd8754a096dbe437e8a668321f5ba6
https://github.com/GoogleCloudPlatform/cloud-errors-nodejs/blob/fda2218759cd8754a096dbe437e8a668321f5ba6/lib/interfaces/uncaught.js#L40-L66
train
GoogleCloudPlatform/cloud-errors-nodejs
lib/interfaces/uncaught.js
uncaughtExceptionHandler
function uncaughtExceptionHandler(err) { var em = new ErrorMessage(); errorHandlerRouter(err, em); client.sendError(em, handleProcessExit); setTimeout(handleProcessExit, 2000); }
javascript
function uncaughtExceptionHandler(err) { var em = new ErrorMessage(); errorHandlerRouter(err, em); client.sendError(em, handleProcessExit); setTimeout(handleProcessExit, 2000); }
[ "function", "uncaughtExceptionHandler", "(", "err", ")", "{", "var", "em", "=", "new", "ErrorMessage", "(", ")", ";", "errorHandlerRouter", "(", "err", ",", "em", ")", ";", "client", ".", "sendError", "(", "em", ",", "handleProcessExit", ")", ";", "setTimeout", "(", "handleProcessExit", ",", "2000", ")", ";", "}" ]
The actual exception handler creates a new instance of `ErrorMessage`, extracts infomation from the propagated `Error` and marshals it into the `ErrorMessage` instance, attempts to send this `ErrorMessage` instance to the Stackdriver Error Reporting API. Subsequently the process is terminated. @function uncaughtExceptionHandler @listens module:process~event:uncaughtException @param {Error} err - The error that has been uncaught to this point @returns {Undefined} - does not return a value
[ "The", "actual", "exception", "handler", "creates", "a", "new", "instance", "of", "ErrorMessage", "extracts", "infomation", "from", "the", "propagated", "Error", "and", "marshals", "it", "into", "the", "ErrorMessage", "instance", "attempts", "to", "send", "this", "ErrorMessage", "instance", "to", "the", "Stackdriver", "Error", "Reporting", "API", ".", "Subsequently", "the", "process", "is", "terminated", "." ]
fda2218759cd8754a096dbe437e8a668321f5ba6
https://github.com/GoogleCloudPlatform/cloud-errors-nodejs/blob/fda2218759cd8754a096dbe437e8a668321f5ba6/lib/interfaces/uncaught.js#L52-L58
train
tiaanduplessis/react-native-modest-storage
src/index.js
get
function get (key, def) { if (Array.isArray(key)) { return AsyncStorage.multiGet(key) .then((values) => values.map(([_, value]) => { return useDefault(def, value) ? def : parse(value) })) .then(results => Promise.all(results)) } return AsyncStorage.getItem(key).then(value => useDefault(def, value) ? def : parse(value)) }
javascript
function get (key, def) { if (Array.isArray(key)) { return AsyncStorage.multiGet(key) .then((values) => values.map(([_, value]) => { return useDefault(def, value) ? def : parse(value) })) .then(results => Promise.all(results)) } return AsyncStorage.getItem(key).then(value => useDefault(def, value) ? def : parse(value)) }
[ "function", "get", "(", "key", ",", "def", ")", "{", "if", "(", "Array", ".", "isArray", "(", "key", ")", ")", "{", "return", "AsyncStorage", ".", "multiGet", "(", "key", ")", ".", "then", "(", "(", "values", ")", "=>", "values", ".", "map", "(", "(", "[", "_", ",", "value", "]", ")", "=>", "{", "return", "useDefault", "(", "def", ",", "value", ")", "?", "def", ":", "parse", "(", "value", ")", "}", ")", ")", ".", "then", "(", "results", "=>", "Promise", ".", "all", "(", "results", ")", ")", "}", "return", "AsyncStorage", ".", "getItem", "(", "key", ")", ".", "then", "(", "value", "=>", "useDefault", "(", "def", ",", "value", ")", "?", "def", ":", "parse", "(", "value", ")", ")", "}" ]
Retreive value from AsyncStorage based on key. Wrapper around getItem & multiGet. @param {String, Array} key Key to lookup @param {Any} def Default value @returns {Promise} value of key @example storage.get('foo').then(console.log).catch(console.error)
[ "Retreive", "value", "from", "AsyncStorage", "based", "on", "key", ".", "Wrapper", "around", "getItem", "&", "multiGet", "." ]
95e21cba4f917b27d198fbed0ef9676790163cd9
https://github.com/tiaanduplessis/react-native-modest-storage/blob/95e21cba4f917b27d198fbed0ef9676790163cd9/src/index.js#L34-L44
train
tiaanduplessis/react-native-modest-storage
src/index.js
set
function set (key, value) { if (Array.isArray(key)) { const items = key.map(([key, value]) => [key, JSON.stringify(value)]) return AsyncStorage.multiSet(items) } return AsyncStorage.setItem(key, JSON.stringify(value)) }
javascript
function set (key, value) { if (Array.isArray(key)) { const items = key.map(([key, value]) => [key, JSON.stringify(value)]) return AsyncStorage.multiSet(items) } return AsyncStorage.setItem(key, JSON.stringify(value)) }
[ "function", "set", "(", "key", ",", "value", ")", "{", "if", "(", "Array", ".", "isArray", "(", "key", ")", ")", "{", "const", "items", "=", "key", ".", "map", "(", "(", "[", "key", ",", "value", "]", ")", "=>", "[", "key", ",", "JSON", ".", "stringify", "(", "value", ")", "]", ")", "return", "AsyncStorage", ".", "multiSet", "(", "items", ")", "}", "return", "AsyncStorage", ".", "setItem", "(", "key", ",", "JSON", ".", "stringify", "(", "value", ")", ")", "}" ]
Persist a value to AsyncStorage. Wrapper around setItem & multiSet. @param {String, Array} key for value @param {Any} value to persist @returns {Promise}
[ "Persist", "a", "value", "to", "AsyncStorage", ".", "Wrapper", "around", "setItem", "&", "multiSet", "." ]
95e21cba4f917b27d198fbed0ef9676790163cd9
https://github.com/tiaanduplessis/react-native-modest-storage/blob/95e21cba4f917b27d198fbed0ef9676790163cd9/src/index.js#L53-L60
train
tiaanduplessis/react-native-modest-storage
src/index.js
update
function update (key, value) { if (Array.isArray(key)) { return AsyncStorage.multiMerge(key.map(([key, val]) => [key, JSON.stringify(val)])) } return AsyncStorage.mergeItem(key, JSON.stringify(value)) }
javascript
function update (key, value) { if (Array.isArray(key)) { return AsyncStorage.multiMerge(key.map(([key, val]) => [key, JSON.stringify(val)])) } return AsyncStorage.mergeItem(key, JSON.stringify(value)) }
[ "function", "update", "(", "key", ",", "value", ")", "{", "if", "(", "Array", ".", "isArray", "(", "key", ")", ")", "{", "return", "AsyncStorage", ".", "multiMerge", "(", "key", ".", "map", "(", "(", "[", "key", ",", "val", "]", ")", "=>", "[", "key", ",", "JSON", ".", "stringify", "(", "val", ")", "]", ")", ")", "}", "return", "AsyncStorage", ".", "mergeItem", "(", "key", ",", "JSON", ".", "stringify", "(", "value", ")", ")", "}" ]
Update key with value by merging. Wrapper around mergeItem & multiMerge. @param {String, Array} key for value @param {any} value to update @returns {Promise}
[ "Update", "key", "with", "value", "by", "merging", ".", "Wrapper", "around", "mergeItem", "&", "multiMerge", "." ]
95e21cba4f917b27d198fbed0ef9676790163cd9
https://github.com/tiaanduplessis/react-native-modest-storage/blob/95e21cba4f917b27d198fbed0ef9676790163cd9/src/index.js#L69-L75
train
Yodata/yodata
packages/cli/lib/util/print-result.js
transformResponse
function transformResponse(value, options, context) { if (options.transform === true) { assert.func(context.transform, 'context.transform') return context.transform(value) } return value }
javascript
function transformResponse(value, options, context) { if (options.transform === true) { assert.func(context.transform, 'context.transform') return context.transform(value) } return value }
[ "function", "transformResponse", "(", "value", ",", "options", ",", "context", ")", "{", "if", "(", "options", ".", "transform", "===", "true", ")", "{", "assert", ".", "func", "(", "context", ".", "transform", ",", "'context.transform'", ")", "return", "context", ".", "transform", "(", "value", ")", "}", "return", "value", "}" ]
If options.transform is true, transform the result with context.transform @param {*} value @param {object} options @param {boolean} options.transform @param {object} context @param {function} [context.transform] - transformation handler
[ "If", "options", ".", "transform", "is", "true", "transform", "the", "result", "with", "context", ".", "transform" ]
d7aedd03e49ce5da6e45ab821f54b16d4d4409df
https://github.com/Yodata/yodata/blob/d7aedd03e49ce5da6e45ab821f54b16d4d4409df/packages/cli/lib/util/print-result.js#L56-L63
train
Yodata/yodata
packages/client/lib/event/publish.js
publish
async function publish(props) { const message = getData(props) return createClient() .post('/publish/', { json: true, body: message }) }
javascript
async function publish(props) { const message = getData(props) return createClient() .post('/publish/', { json: true, body: message }) }
[ "async", "function", "publish", "(", "props", ")", "{", "const", "message", "=", "getData", "(", "props", ")", "return", "createClient", "(", ")", ".", "post", "(", "'/publish/'", ",", "{", "json", ":", "true", ",", "body", ":", "message", "}", ")", "}" ]
publish an event @param {object} props @param {string} [props.recipient] @param {string} [props.topic] @param {object} [props.data] @param {string} [props.filepath] @returns {Promise}
[ "publish", "an", "event" ]
d7aedd03e49ce5da6e45ab821f54b16d4d4409df
https://github.com/Yodata/yodata/blob/d7aedd03e49ce5da6e45ab821f54b16d4d4409df/packages/client/lib/event/publish.js#L18-L25
train
linzjs/linz
middleware/configList.js
function (records, cb) { // loop through each record async.each(records, function (record, recordDone) { // loop through each field async.each(Object.keys(req.linz.configList.fields), function (field, fieldDone) { req.linz.configList.fields[field].renderer(record[field], record, field, req.linz.configs[record._id], function (err, value) { if (err) { return fieldDone(err, records); } var index = records.indexOf(record); records[index][field] = value; return fieldDone(null, records); }); }, function (err) { return recordDone(err, records); }); }, function (err) { return cb(err, records); }); }
javascript
function (records, cb) { // loop through each record async.each(records, function (record, recordDone) { // loop through each field async.each(Object.keys(req.linz.configList.fields), function (field, fieldDone) { req.linz.configList.fields[field].renderer(record[field], record, field, req.linz.configs[record._id], function (err, value) { if (err) { return fieldDone(err, records); } var index = records.indexOf(record); records[index][field] = value; return fieldDone(null, records); }); }, function (err) { return recordDone(err, records); }); }, function (err) { return cb(err, records); }); }
[ "function", "(", "records", ",", "cb", ")", "{", "// loop through each record", "async", ".", "each", "(", "records", ",", "function", "(", "record", ",", "recordDone", ")", "{", "// loop through each field", "async", ".", "each", "(", "Object", ".", "keys", "(", "req", ".", "linz", ".", "configList", ".", "fields", ")", ",", "function", "(", "field", ",", "fieldDone", ")", "{", "req", ".", "linz", ".", "configList", ".", "fields", "[", "field", "]", ".", "renderer", "(", "record", "[", "field", "]", ",", "record", ",", "field", ",", "req", ".", "linz", ".", "configs", "[", "record", ".", "_id", "]", ",", "function", "(", "err", ",", "value", ")", "{", "if", "(", "err", ")", "{", "return", "fieldDone", "(", "err", ",", "records", ")", ";", "}", "var", "index", "=", "records", ".", "indexOf", "(", "record", ")", ";", "records", "[", "index", "]", "[", "field", "]", "=", "value", ";", "return", "fieldDone", "(", "null", ",", "records", ")", ";", "}", ")", ";", "}", ",", "function", "(", "err", ")", "{", "return", "recordDone", "(", "err", ",", "records", ")", ";", "}", ")", ";", "}", ",", "function", "(", "err", ")", "{", "return", "cb", "(", "err", ",", "records", ")", ";", "}", ")", ";", "}" ]
apply renderer to values of each configs
[ "apply", "renderer", "to", "values", "of", "each", "configs" ]
0ac03e722747406d29f9e1eed7e96b6be04456e8
https://github.com/linzjs/linz/blob/0ac03e722747406d29f9e1eed7e96b6be04456e8/middleware/configList.js#L85-L119
train
linzjs/linz
lib/formtools/renderers-list.js
grid
function grid (data, callback) { linz.app.render(linz.api.views.viewPath('modelIndex/grid.jade'), data, (err, html) => { if (err) { return callback(err); } return callback(null, html); }); }
javascript
function grid (data, callback) { linz.app.render(linz.api.views.viewPath('modelIndex/grid.jade'), data, (err, html) => { if (err) { return callback(err); } return callback(null, html); }); }
[ "function", "grid", "(", "data", ",", "callback", ")", "{", "linz", ".", "app", ".", "render", "(", "linz", ".", "api", ".", "views", ".", "viewPath", "(", "'modelIndex/grid.jade'", ")", ",", "data", ",", "(", "err", ",", "html", ")", "=>", "{", "if", "(", "err", ")", "{", "return", "callback", "(", "err", ")", ";", "}", "return", "callback", "(", "null", ",", "html", ")", ";", "}", ")", ";", "}" ]
Grid list renderer. @param {Object} data Data passed to the template. @param {Function} callback Callback function. @return {String} Rendered HTML content.
[ "Grid", "list", "renderer", "." ]
0ac03e722747406d29f9e1eed7e96b6be04456e8
https://github.com/linzjs/linz/blob/0ac03e722747406d29f9e1eed7e96b6be04456e8/lib/formtools/renderers-list.js#L11-L23
train
linzjs/linz
middleware/recordOverview.js
function (cb) { let actions = req.linz.model.linz.formtools.overview.actions; if (!actions.length) { return cb(null); } parseDisabledProperties(req.linz.record, actions) .then((parsedActions) => { actions = parsedActions; return cb(); }) .catch(cb); }
javascript
function (cb) { let actions = req.linz.model.linz.formtools.overview.actions; if (!actions.length) { return cb(null); } parseDisabledProperties(req.linz.record, actions) .then((parsedActions) => { actions = parsedActions; return cb(); }) .catch(cb); }
[ "function", "(", "cb", ")", "{", "let", "actions", "=", "req", ".", "linz", ".", "model", ".", "linz", ".", "formtools", ".", "overview", ".", "actions", ";", "if", "(", "!", "actions", ".", "length", ")", "{", "return", "cb", "(", "null", ")", ";", "}", "parseDisabledProperties", "(", "req", ".", "linz", ".", "record", ",", "actions", ")", ".", "then", "(", "(", "parsedActions", ")", "=>", "{", "actions", "=", "parsedActions", ";", "return", "cb", "(", ")", ";", "}", ")", ".", "catch", "(", "cb", ")", ";", "}" ]
Check if we need to process custom actions.
[ "Check", "if", "we", "need", "to", "process", "custom", "actions", "." ]
0ac03e722747406d29f9e1eed7e96b6be04456e8
https://github.com/linzjs/linz/blob/0ac03e722747406d29f9e1eed7e96b6be04456e8/middleware/recordOverview.js#L24-L42
train
linzjs/linz
middleware/recordOverview.js
function (cb) { let footerActions = req.linz.model.linz.formtools.overview.footerActions; if (!footerActions.length) { return cb(); } parseDisabledProperties(req.linz.record, footerActions) .then((parsedActions) => { footerActions = parsedActions; return cb(); }) .catch(cb); }
javascript
function (cb) { let footerActions = req.linz.model.linz.formtools.overview.footerActions; if (!footerActions.length) { return cb(); } parseDisabledProperties(req.linz.record, footerActions) .then((parsedActions) => { footerActions = parsedActions; return cb(); }) .catch(cb); }
[ "function", "(", "cb", ")", "{", "let", "footerActions", "=", "req", ".", "linz", ".", "model", ".", "linz", ".", "formtools", ".", "overview", ".", "footerActions", ";", "if", "(", "!", "footerActions", ".", "length", ")", "{", "return", "cb", "(", ")", ";", "}", "parseDisabledProperties", "(", "req", ".", "linz", ".", "record", ",", "footerActions", ")", ".", "then", "(", "(", "parsedActions", ")", "=>", "{", "footerActions", "=", "parsedActions", ";", "return", "cb", "(", ")", ";", "}", ")", ".", "catch", "(", "cb", ")", ";", "}" ]
Check if we need to process custom footer actions.
[ "Check", "if", "we", "need", "to", "process", "custom", "footer", "actions", "." ]
0ac03e722747406d29f9e1eed7e96b6be04456e8
https://github.com/linzjs/linz/blob/0ac03e722747406d29f9e1eed7e96b6be04456e8/middleware/recordOverview.js#L45-L63
train
Yodata/yodata
packages/cli/lib/util/create-response-handler.js
createResponseHandler
function createResponseHandler(fn, key, context) { // Assert.func(fn,'createResponseHandler:fn') return function (props) { const param = key ? props[key] : props print(fn(param), props, context) } }
javascript
function createResponseHandler(fn, key, context) { // Assert.func(fn,'createResponseHandler:fn') return function (props) { const param = key ? props[key] : props print(fn(param), props, context) } }
[ "function", "createResponseHandler", "(", "fn", ",", "key", ",", "context", ")", "{", "// Assert.func(fn,'createResponseHandler:fn')", "return", "function", "(", "props", ")", "{", "const", "param", "=", "key", "?", "props", "[", "key", "]", ":", "props", "print", "(", "fn", "(", "param", ")", ",", "props", ",", "context", ")", "}", "}" ]
Creates an async response handler @param {function} fn - function to be called @param {string} [key] - function will be called with props[key] if not specified, the function will be called with the props object @param {object} [context] - handlers used in print @returns
[ "Creates", "an", "async", "response", "handler" ]
d7aedd03e49ce5da6e45ab821f54b16d4d4409df
https://github.com/Yodata/yodata/blob/d7aedd03e49ce5da6e45ab821f54b16d4d4409df/packages/cli/lib/util/create-response-handler.js#L14-L20
train
linzjs/linz
lib/api/configs.js
get
function get (configName, copy) { if (copy) { return clone(linz.get('configs')[configName]); } return linz.get('configs')[configName]; }
javascript
function get (configName, copy) { if (copy) { return clone(linz.get('configs')[configName]); } return linz.get('configs')[configName]; }
[ "function", "get", "(", "configName", ",", "copy", ")", "{", "if", "(", "copy", ")", "{", "return", "clone", "(", "linz", ".", "get", "(", "'configs'", ")", "[", "configName", "]", ")", ";", "}", "return", "linz", ".", "get", "(", "'configs'", ")", "[", "configName", "]", ";", "}" ]
Get linz config by reference or by cloning a copy @param {String} configName Name of config @param {Boolean} copy Specify if result should be a cloned copy or by reference. Default to return a reference. @return {Object} Config object either by a cloned copy or by reference
[ "Get", "linz", "config", "by", "reference", "or", "by", "cloning", "a", "copy" ]
0ac03e722747406d29f9e1eed7e96b6be04456e8
https://github.com/linzjs/linz/blob/0ac03e722747406d29f9e1eed7e96b6be04456e8/lib/api/configs.js#L11-L18
train
linzjs/linz
lib/api/configs.js
permissions
function permissions (user, configName, callback) { return get(configName).schema.statics.getPermissions(user, callback); }
javascript
function permissions (user, configName, callback) { return get(configName).schema.statics.getPermissions(user, callback); }
[ "function", "permissions", "(", "user", ",", "configName", ",", "callback", ")", "{", "return", "get", "(", "configName", ")", ".", "schema", ".", "statics", ".", "getPermissions", "(", "user", ",", "callback", ")", ";", "}" ]
Retrieve the permissions DSL for a config @param {Object} user The user to which the permissions DSL should be customised @param {String} configName The name of the config @param {Function} callback A callback to return the permissions DSL to @return {Void}
[ "Retrieve", "the", "permissions", "DSL", "for", "a", "config" ]
0ac03e722747406d29f9e1eed7e96b6be04456e8
https://github.com/linzjs/linz/blob/0ac03e722747406d29f9e1eed7e96b6be04456e8/lib/api/configs.js#L48-L50
train
linzjs/linz
lib/api/configs.js
form
function form (req, configName, callback) { return get(configName).schema.statics.getForm(req, callback); }
javascript
function form (req, configName, callback) { return get(configName).schema.statics.getForm(req, callback); }
[ "function", "form", "(", "req", ",", "configName", ",", "callback", ")", "{", "return", "get", "(", "configName", ")", ".", "schema", ".", "statics", ".", "getForm", "(", "req", ",", "callback", ")", ";", "}" ]
Retrieve the form DSL for a config @param {Object} req A HTTP request object which should be used to customise the DSL @param {String} configName The name of the config @param {Function} callback A callback to return the form DSL to @return {Void}
[ "Retrieve", "the", "form", "DSL", "for", "a", "config" ]
0ac03e722747406d29f9e1eed7e96b6be04456e8
https://github.com/linzjs/linz/blob/0ac03e722747406d29f9e1eed7e96b6be04456e8/lib/api/configs.js#L59-L61
train
linzjs/linz
lib/api/configs.js
overview
function overview (req, configName, callback) { return get(configName).schema.statics.getOverview(req, callback); }
javascript
function overview (req, configName, callback) { return get(configName).schema.statics.getOverview(req, callback); }
[ "function", "overview", "(", "req", ",", "configName", ",", "callback", ")", "{", "return", "get", "(", "configName", ")", ".", "schema", ".", "statics", ".", "getOverview", "(", "req", ",", "callback", ")", ";", "}" ]
Retrieve the overview DSL for a config @param {Object} req A HTTP request object which can be used to customise the DSL @param {String} configName The name of the config @param {Function} callback A callback to return the overview DSL to @return {Void}
[ "Retrieve", "the", "overview", "DSL", "for", "a", "config" ]
0ac03e722747406d29f9e1eed7e96b6be04456e8
https://github.com/linzjs/linz/blob/0ac03e722747406d29f9e1eed7e96b6be04456e8/lib/api/configs.js#L70-L72
train
linzjs/linz
lib/api/configs.js
labels
function labels (configName, callback) { if (callback) { return get(configName).schema.statics.getLabels(callback); } return get(configName).schema.statics.getLabels(); }
javascript
function labels (configName, callback) { if (callback) { return get(configName).schema.statics.getLabels(callback); } return get(configName).schema.statics.getLabels(); }
[ "function", "labels", "(", "configName", ",", "callback", ")", "{", "if", "(", "callback", ")", "{", "return", "get", "(", "configName", ")", ".", "schema", ".", "statics", ".", "getLabels", "(", "callback", ")", ";", "}", "return", "get", "(", "configName", ")", ".", "schema", ".", "statics", ".", "getLabels", "(", ")", ";", "}" ]
Retrieve the labels for a config @param {String} configName The name of the config @param {Function} callback An optional callback to return the labels object to @return {Void}
[ "Retrieve", "the", "labels", "for", "a", "config" ]
0ac03e722747406d29f9e1eed7e96b6be04456e8
https://github.com/linzjs/linz/blob/0ac03e722747406d29f9e1eed7e96b6be04456e8/lib/api/configs.js#L80-L87
train
linzjs/linz
middleware/_modelIndex.js
handleQueryError
function handleQueryError (err) { queryErrorCount++; // Something has gone terribly wrong. Break from loop. if (queryErrorCount > 1) { // Reset all filters. session.list.formData = {}; // Notify the user that an error has occured. req.linz.notifications.push(linz.api.views.notification({ text: 'One of the filters is repeatedly generating an error. All filters have been removed.', type: 'error' })); // Rerun the query at the last known working state. // eslint-disable-next-line no-use-before-define return getModelIndex(); } // Reset the last known working state. session.list.formData = session.list.previous.formData; // If we're in development mode, return the error // so that the developers are aware of it and can fix it. if (isDevelopment) { return next(err); } // Notify the user that an error has occured. req.linz.notifications.push(linz.api.views.notification({ text: 'An error has occured with one of the filters you added. It has been removed.', type: 'error' })); // Rerun the query at the last known working state. // eslint-disable-next-line no-use-before-define return getModelIndex(); }
javascript
function handleQueryError (err) { queryErrorCount++; // Something has gone terribly wrong. Break from loop. if (queryErrorCount > 1) { // Reset all filters. session.list.formData = {}; // Notify the user that an error has occured. req.linz.notifications.push(linz.api.views.notification({ text: 'One of the filters is repeatedly generating an error. All filters have been removed.', type: 'error' })); // Rerun the query at the last known working state. // eslint-disable-next-line no-use-before-define return getModelIndex(); } // Reset the last known working state. session.list.formData = session.list.previous.formData; // If we're in development mode, return the error // so that the developers are aware of it and can fix it. if (isDevelopment) { return next(err); } // Notify the user that an error has occured. req.linz.notifications.push(linz.api.views.notification({ text: 'An error has occured with one of the filters you added. It has been removed.', type: 'error' })); // Rerun the query at the last known working state. // eslint-disable-next-line no-use-before-define return getModelIndex(); }
[ "function", "handleQueryError", "(", "err", ")", "{", "queryErrorCount", "++", ";", "// Something has gone terribly wrong. Break from loop.", "if", "(", "queryErrorCount", ">", "1", ")", "{", "// Reset all filters.", "session", ".", "list", ".", "formData", "=", "{", "}", ";", "// Notify the user that an error has occured.", "req", ".", "linz", ".", "notifications", ".", "push", "(", "linz", ".", "api", ".", "views", ".", "notification", "(", "{", "text", ":", "'One of the filters is repeatedly generating an error. All filters have been removed.'", ",", "type", ":", "'error'", "}", ")", ")", ";", "// Rerun the query at the last known working state.", "// eslint-disable-next-line no-use-before-define", "return", "getModelIndex", "(", ")", ";", "}", "// Reset the last known working state.", "session", ".", "list", ".", "formData", "=", "session", ".", "list", ".", "previous", ".", "formData", ";", "// If we're in development mode, return the error", "// so that the developers are aware of it and can fix it.", "if", "(", "isDevelopment", ")", "{", "return", "next", "(", "err", ")", ";", "}", "// Notify the user that an error has occured.", "req", ".", "linz", ".", "notifications", ".", "push", "(", "linz", ".", "api", ".", "views", ".", "notification", "(", "{", "text", ":", "'An error has occured with one of the filters you added. It has been removed.'", ",", "type", ":", "'error'", "}", ")", ")", ";", "// Rerun the query at the last known working state.", "// eslint-disable-next-line no-use-before-define", "return", "getModelIndex", "(", ")", ";", "}" ]
This method should be executed when a query error is returned. It will abort the current query and return the results of the previous query instead. @return {Void}
[ "This", "method", "should", "be", "executed", "when", "a", "query", "error", "is", "returned", ".", "It", "will", "abort", "the", "current", "query", "and", "return", "the", "results", "of", "the", "previous", "query", "instead", "." ]
0ac03e722747406d29f9e1eed7e96b6be04456e8
https://github.com/linzjs/linz/blob/0ac03e722747406d29f9e1eed7e96b6be04456e8/middleware/_modelIndex.js#L32-L73
train
linzjs/linz
middleware/_modelIndex.js
function (cb) { formtoolsAPI.list.renderToolbarItems(req, res, req.params.model, function (err, result) { if (err) { return cb(err); } req.linz.model.list.toolbarItems = result; return cb(null); }); }
javascript
function (cb) { formtoolsAPI.list.renderToolbarItems(req, res, req.params.model, function (err, result) { if (err) { return cb(err); } req.linz.model.list.toolbarItems = result; return cb(null); }); }
[ "function", "(", "cb", ")", "{", "formtoolsAPI", ".", "list", ".", "renderToolbarItems", "(", "req", ",", "res", ",", "req", ".", "params", ".", "model", ",", "function", "(", "err", ",", "result", ")", "{", "if", "(", "err", ")", "{", "return", "cb", "(", "err", ")", ";", "}", "req", ".", "linz", ".", "model", ".", "list", ".", "toolbarItems", "=", "result", ";", "return", "cb", "(", "null", ")", ";", "}", ")", ";", "}" ]
check if there are toolbar items required
[ "check", "if", "there", "are", "toolbar", "items", "required" ]
0ac03e722747406d29f9e1eed7e96b6be04456e8
https://github.com/linzjs/linz/blob/0ac03e722747406d29f9e1eed7e96b6be04456e8/middleware/_modelIndex.js#L102-L116
train
linzjs/linz
middleware/_modelIndex.js
function (cb) { // check if we need to render the filters if (!Object.keys(req.linz.model.list.filters).length) { return cb(null); } formtoolsAPI.list.renderFilters(req, req.params.model, function (err, result) { if (err) { return cb(err); } req.linz.model.list.filters = result; return cb(null); }); }
javascript
function (cb) { // check if we need to render the filters if (!Object.keys(req.linz.model.list.filters).length) { return cb(null); } formtoolsAPI.list.renderFilters(req, req.params.model, function (err, result) { if (err) { return cb(err); } req.linz.model.list.filters = result; return cb(null); }); }
[ "function", "(", "cb", ")", "{", "// check if we need to render the filters", "if", "(", "!", "Object", ".", "keys", "(", "req", ".", "linz", ".", "model", ".", "list", ".", "filters", ")", ".", "length", ")", "{", "return", "cb", "(", "null", ")", ";", "}", "formtoolsAPI", ".", "list", ".", "renderFilters", "(", "req", ",", "req", ".", "params", ".", "model", ",", "function", "(", "err", ",", "result", ")", "{", "if", "(", "err", ")", "{", "return", "cb", "(", "err", ")", ";", "}", "req", ".", "linz", ".", "model", ".", "list", ".", "filters", "=", "result", ";", "return", "cb", "(", "null", ")", ";", "}", ")", ";", "}" ]
render the filters
[ "render", "the", "filters" ]
0ac03e722747406d29f9e1eed7e96b6be04456e8
https://github.com/linzjs/linz/blob/0ac03e722747406d29f9e1eed7e96b6be04456e8/middleware/_modelIndex.js#L119-L137
train
linzjs/linz
middleware/_modelIndex.js
function (cb) { const filters = req.linz.model.list.filters; const formData = session.list.formData; // Make sure we have some filters. if (!filters) { return cb(null); } // Find the alwaysOn filters, that have a default. const alwaysOnWithDefault = Object.keys(filters).filter((key) => filters[key].alwaysOn === true && Object.keys(filters[key]).includes('default')); if (!alwaysOnWithDefault) { return cb(null); } // If it already exists, turn it into an array for easy manipulation. if (formData.selectedFilters && formData.selectedFilters.length) { formData.selectedFilters = formData.selectedFilters.split(','); } // If it doesn't exist create a default array. if (!formData.selectedFilters || !formData.selectedFilters.length) { formData.selectedFilters = []; } // Make sure the alwaysOnWithDefault filters have entries in session.list.formData.selectedFilters. alwaysOnWithDefault.forEach((key) => { const filter = filters[key]; if (!formData.selectedFilters.includes(key)) { // Add to the selected filters list. formData.selectedFilters.push(key); formData[key] = filter.default; } }); formData.selectedFilters = formData.selectedFilters.join(','); return cb(null); }
javascript
function (cb) { const filters = req.linz.model.list.filters; const formData = session.list.formData; // Make sure we have some filters. if (!filters) { return cb(null); } // Find the alwaysOn filters, that have a default. const alwaysOnWithDefault = Object.keys(filters).filter((key) => filters[key].alwaysOn === true && Object.keys(filters[key]).includes('default')); if (!alwaysOnWithDefault) { return cb(null); } // If it already exists, turn it into an array for easy manipulation. if (formData.selectedFilters && formData.selectedFilters.length) { formData.selectedFilters = formData.selectedFilters.split(','); } // If it doesn't exist create a default array. if (!formData.selectedFilters || !formData.selectedFilters.length) { formData.selectedFilters = []; } // Make sure the alwaysOnWithDefault filters have entries in session.list.formData.selectedFilters. alwaysOnWithDefault.forEach((key) => { const filter = filters[key]; if (!formData.selectedFilters.includes(key)) { // Add to the selected filters list. formData.selectedFilters.push(key); formData[key] = filter.default; } }); formData.selectedFilters = formData.selectedFilters.join(','); return cb(null); }
[ "function", "(", "cb", ")", "{", "const", "filters", "=", "req", ".", "linz", ".", "model", ".", "list", ".", "filters", ";", "const", "formData", "=", "session", ".", "list", ".", "formData", ";", "// Make sure we have some filters.", "if", "(", "!", "filters", ")", "{", "return", "cb", "(", "null", ")", ";", "}", "// Find the alwaysOn filters, that have a default.", "const", "alwaysOnWithDefault", "=", "Object", ".", "keys", "(", "filters", ")", ".", "filter", "(", "(", "key", ")", "=>", "filters", "[", "key", "]", ".", "alwaysOn", "===", "true", "&&", "Object", ".", "keys", "(", "filters", "[", "key", "]", ")", ".", "includes", "(", "'default'", ")", ")", ";", "if", "(", "!", "alwaysOnWithDefault", ")", "{", "return", "cb", "(", "null", ")", ";", "}", "// If it already exists, turn it into an array for easy manipulation.", "if", "(", "formData", ".", "selectedFilters", "&&", "formData", ".", "selectedFilters", ".", "length", ")", "{", "formData", ".", "selectedFilters", "=", "formData", ".", "selectedFilters", ".", "split", "(", "','", ")", ";", "}", "// If it doesn't exist create a default array.", "if", "(", "!", "formData", ".", "selectedFilters", "||", "!", "formData", ".", "selectedFilters", ".", "length", ")", "{", "formData", ".", "selectedFilters", "=", "[", "]", ";", "}", "// Make sure the alwaysOnWithDefault filters have entries in session.list.formData.selectedFilters.", "alwaysOnWithDefault", ".", "forEach", "(", "(", "key", ")", "=>", "{", "const", "filter", "=", "filters", "[", "key", "]", ";", "if", "(", "!", "formData", ".", "selectedFilters", ".", "includes", "(", "key", ")", ")", "{", "// Add to the selected filters list.", "formData", ".", "selectedFilters", ".", "push", "(", "key", ")", ";", "formData", "[", "key", "]", "=", "filter", ".", "default", ";", "}", "}", ")", ";", "formData", ".", "selectedFilters", "=", "formData", ".", "selectedFilters", ".", "join", "(", "','", ")", ";", "return", "cb", "(", "null", ")", ";", "}" ]
Add in alwaysOn filters that have default values, that aren't already present.
[ "Add", "in", "alwaysOn", "filters", "that", "have", "default", "values", "that", "aren", "t", "already", "present", "." ]
0ac03e722747406d29f9e1eed7e96b6be04456e8
https://github.com/linzjs/linz/blob/0ac03e722747406d29f9e1eed7e96b6be04456e8/middleware/_modelIndex.js#L140-L188
train
linzjs/linz
middleware/_modelIndex.js
function (cb) { req.linz.model.list.activeFilters = {}; // check if there are any filters in the form post if (!session.list.formData.selectedFilters) { return cb(null); } formtoolsAPI.list.getActiveFilters(req, session.list.formData.selectedFilters.split(','), session.list.formData, req.params.model, function (err, result) { if (err) { return cb(err); } req.linz.model.list.activeFilters = result; return cb(null); }); }
javascript
function (cb) { req.linz.model.list.activeFilters = {}; // check if there are any filters in the form post if (!session.list.formData.selectedFilters) { return cb(null); } formtoolsAPI.list.getActiveFilters(req, session.list.formData.selectedFilters.split(','), session.list.formData, req.params.model, function (err, result) { if (err) { return cb(err); } req.linz.model.list.activeFilters = result; return cb(null); }); }
[ "function", "(", "cb", ")", "{", "req", ".", "linz", ".", "model", ".", "list", ".", "activeFilters", "=", "{", "}", ";", "// check if there are any filters in the form post", "if", "(", "!", "session", ".", "list", ".", "formData", ".", "selectedFilters", ")", "{", "return", "cb", "(", "null", ")", ";", "}", "formtoolsAPI", ".", "list", ".", "getActiveFilters", "(", "req", ",", "session", ".", "list", ".", "formData", ".", "selectedFilters", ".", "split", "(", "','", ")", ",", "session", ".", "list", ".", "formData", ",", "req", ".", "params", ".", "model", ",", "function", "(", "err", ",", "result", ")", "{", "if", "(", "err", ")", "{", "return", "cb", "(", "err", ")", ";", "}", "req", ".", "linz", ".", "model", ".", "list", ".", "activeFilters", "=", "result", ";", "return", "cb", "(", "null", ")", ";", "}", ")", ";", "}" ]
render the active filters
[ "render", "the", "active", "filters" ]
0ac03e722747406d29f9e1eed7e96b6be04456e8
https://github.com/linzjs/linz/blob/0ac03e722747406d29f9e1eed7e96b6be04456e8/middleware/_modelIndex.js#L191-L211
train
linzjs/linz
middleware/_modelIndex.js
function (cb) { // check if there are any filters in the form post if (!session.list.formData.selectedFilters) { return cb(null); } formtoolsAPI.list.renderSearchFilters(req, session.list.formData.selectedFilters.split(','), session.list.formData, req.params.model, function (err, result) { if (err) { return cb(err); } filters = result; return cb(null); }); }
javascript
function (cb) { // check if there are any filters in the form post if (!session.list.formData.selectedFilters) { return cb(null); } formtoolsAPI.list.renderSearchFilters(req, session.list.formData.selectedFilters.split(','), session.list.formData, req.params.model, function (err, result) { if (err) { return cb(err); } filters = result; return cb(null); }); }
[ "function", "(", "cb", ")", "{", "// check if there are any filters in the form post", "if", "(", "!", "session", ".", "list", ".", "formData", ".", "selectedFilters", ")", "{", "return", "cb", "(", "null", ")", ";", "}", "formtoolsAPI", ".", "list", ".", "renderSearchFilters", "(", "req", ",", "session", ".", "list", ".", "formData", ".", "selectedFilters", ".", "split", "(", "','", ")", ",", "session", ".", "list", ".", "formData", ",", "req", ".", "params", ".", "model", ",", "function", "(", "err", ",", "result", ")", "{", "if", "(", "err", ")", "{", "return", "cb", "(", "err", ")", ";", "}", "filters", "=", "result", ";", "return", "cb", "(", "null", ")", ";", "}", ")", ";", "}" ]
get the filters
[ "get", "the", "filters" ]
0ac03e722747406d29f9e1eed7e96b6be04456e8
https://github.com/linzjs/linz/blob/0ac03e722747406d29f9e1eed7e96b6be04456e8/middleware/_modelIndex.js#L214-L233
train
linzjs/linz
middleware/_modelIndex.js
function (cb) { if (!session.list.formData.search || !session.list.formData.search.length || !req.linz.model.list.search || !Array.isArray(req.linz.model.list.search)) { return cb(null); } // Default the `$and` key. if (!filters.$and) { filters.$and = []; } async.map(req.linz.model.list.search, (field, fieldCallback) => { linz.api.model.titleField(req.params.model, field, (err, titleField) => { if (err) { return fieldCallback(err); } fieldCallback(null, linz.api.query.fieldRegexp(titleField, session.list.formData.search)); }); }, (err, $or) => { filters.$and.push({ $or }); return cb(null); }); }
javascript
function (cb) { if (!session.list.formData.search || !session.list.formData.search.length || !req.linz.model.list.search || !Array.isArray(req.linz.model.list.search)) { return cb(null); } // Default the `$and` key. if (!filters.$and) { filters.$and = []; } async.map(req.linz.model.list.search, (field, fieldCallback) => { linz.api.model.titleField(req.params.model, field, (err, titleField) => { if (err) { return fieldCallback(err); } fieldCallback(null, linz.api.query.fieldRegexp(titleField, session.list.formData.search)); }); }, (err, $or) => { filters.$and.push({ $or }); return cb(null); }); }
[ "function", "(", "cb", ")", "{", "if", "(", "!", "session", ".", "list", ".", "formData", ".", "search", "||", "!", "session", ".", "list", ".", "formData", ".", "search", ".", "length", "||", "!", "req", ".", "linz", ".", "model", ".", "list", ".", "search", "||", "!", "Array", ".", "isArray", "(", "req", ".", "linz", ".", "model", ".", "list", ".", "search", ")", ")", "{", "return", "cb", "(", "null", ")", ";", "}", "// Default the `$and` key.", "if", "(", "!", "filters", ".", "$and", ")", "{", "filters", ".", "$and", "=", "[", "]", ";", "}", "async", ".", "map", "(", "req", ".", "linz", ".", "model", ".", "list", ".", "search", ",", "(", "field", ",", "fieldCallback", ")", "=>", "{", "linz", ".", "api", ".", "model", ".", "titleField", "(", "req", ".", "params", ".", "model", ",", "field", ",", "(", "err", ",", "titleField", ")", "=>", "{", "if", "(", "err", ")", "{", "return", "fieldCallback", "(", "err", ")", ";", "}", "fieldCallback", "(", "null", ",", "linz", ".", "api", ".", "query", ".", "fieldRegexp", "(", "titleField", ",", "session", ".", "list", ".", "formData", ".", "search", ")", ")", ";", "}", ")", ";", "}", ",", "(", "err", ",", "$or", ")", "=>", "{", "filters", ".", "$and", ".", "push", "(", "{", "$or", "}", ")", ";", "return", "cb", "(", "null", ")", ";", "}", ")", ";", "}" ]
add the seach filters
[ "add", "the", "seach", "filters" ]
0ac03e722747406d29f9e1eed7e96b6be04456e8
https://github.com/linzjs/linz/blob/0ac03e722747406d29f9e1eed7e96b6be04456e8/middleware/_modelIndex.js#L236-L267
train
linzjs/linz
middleware/_modelIndex.js
function (cb) { req.linz.model.getQuery(req, filters, function (err, result) { if (err) { return cb(err); } query = result; return cb(null); }); }
javascript
function (cb) { req.linz.model.getQuery(req, filters, function (err, result) { if (err) { return cb(err); } query = result; return cb(null); }); }
[ "function", "(", "cb", ")", "{", "req", ".", "linz", ".", "model", ".", "getQuery", "(", "req", ",", "filters", ",", "function", "(", "err", ",", "result", ")", "{", "if", "(", "err", ")", "{", "return", "cb", "(", "err", ")", ";", "}", "query", "=", "result", ";", "return", "cb", "(", "null", ")", ";", "}", ")", ";", "}" ]
create the query
[ "create", "the", "query" ]
0ac03e722747406d29f9e1eed7e96b6be04456e8
https://github.com/linzjs/linz/blob/0ac03e722747406d29f9e1eed7e96b6be04456e8/middleware/_modelIndex.js#L270-L284
train
linzjs/linz
middleware/_modelIndex.js
function (cb) { let fields = Object.keys(req.linz.model.list.fields); // Work in the title field linz.api.model.titleField(req.params.model, 'title', (err, titleField) => { if (err) { return cb(err); } fields.push(titleField); const select = fields.join(' '); query.select(select); // If they've provided the `listQuery` static, use it to allow customisation of the fields we'll retrieve. if (!req.linz.model.listQuery) { return cb(); } req.linz.model.listQuery(req, query, cb); }); }
javascript
function (cb) { let fields = Object.keys(req.linz.model.list.fields); // Work in the title field linz.api.model.titleField(req.params.model, 'title', (err, titleField) => { if (err) { return cb(err); } fields.push(titleField); const select = fields.join(' '); query.select(select); // If they've provided the `listQuery` static, use it to allow customisation of the fields we'll retrieve. if (!req.linz.model.listQuery) { return cb(); } req.linz.model.listQuery(req, query, cb); }); }
[ "function", "(", "cb", ")", "{", "let", "fields", "=", "Object", ".", "keys", "(", "req", ".", "linz", ".", "model", ".", "list", ".", "fields", ")", ";", "// Work in the title field", "linz", ".", "api", ".", "model", ".", "titleField", "(", "req", ".", "params", ".", "model", ",", "'title'", ",", "(", "err", ",", "titleField", ")", "=>", "{", "if", "(", "err", ")", "{", "return", "cb", "(", "err", ")", ";", "}", "fields", ".", "push", "(", "titleField", ")", ";", "const", "select", "=", "fields", ".", "join", "(", "' '", ")", ";", "query", ".", "select", "(", "select", ")", ";", "// If they've provided the `listQuery` static, use it to allow customisation of the fields we'll retrieve.", "if", "(", "!", "req", ".", "linz", ".", "model", ".", "listQuery", ")", "{", "return", "cb", "(", ")", ";", "}", "req", ".", "linz", ".", "model", ".", "listQuery", "(", "req", ",", "query", ",", "cb", ")", ";", "}", ")", ";", "}" ]
minimise the fields we're selecting
[ "minimise", "the", "fields", "we", "re", "selecting" ]
0ac03e722747406d29f9e1eed7e96b6be04456e8
https://github.com/linzjs/linz/blob/0ac03e722747406d29f9e1eed7e96b6be04456e8/middleware/_modelIndex.js#L287-L313
train
linzjs/linz
middleware/_modelIndex.js
function (cb) { req.linz.model.getCount(req, query, function (err, countQuery) { if (err) { return cb(err); } countQuery.exec(function (countQueryErr, count) { // A query error has occured, let's short circuit this entire process // and start again from the last known working state. if (countQueryErr) { return handleQueryError(countQueryErr); } if (!countQueryErr && count === 0) { return cb(new Error('No records found')); } if (!countQueryErr) { totalRecords = count; } return cb(countQueryErr); }); }); }
javascript
function (cb) { req.linz.model.getCount(req, query, function (err, countQuery) { if (err) { return cb(err); } countQuery.exec(function (countQueryErr, count) { // A query error has occured, let's short circuit this entire process // and start again from the last known working state. if (countQueryErr) { return handleQueryError(countQueryErr); } if (!countQueryErr && count === 0) { return cb(new Error('No records found')); } if (!countQueryErr) { totalRecords = count; } return cb(countQueryErr); }); }); }
[ "function", "(", "cb", ")", "{", "req", ".", "linz", ".", "model", ".", "getCount", "(", "req", ",", "query", ",", "function", "(", "err", ",", "countQuery", ")", "{", "if", "(", "err", ")", "{", "return", "cb", "(", "err", ")", ";", "}", "countQuery", ".", "exec", "(", "function", "(", "countQueryErr", ",", "count", ")", "{", "// A query error has occured, let's short circuit this entire process", "// and start again from the last known working state.", "if", "(", "countQueryErr", ")", "{", "return", "handleQueryError", "(", "countQueryErr", ")", ";", "}", "if", "(", "!", "countQueryErr", "&&", "count", "===", "0", ")", "{", "return", "cb", "(", "new", "Error", "(", "'No records found'", ")", ")", ";", "}", "if", "(", "!", "countQueryErr", ")", "{", "totalRecords", "=", "count", ";", "}", "return", "cb", "(", "countQueryErr", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
get page total
[ "get", "page", "total" ]
0ac03e722747406d29f9e1eed7e96b6be04456e8
https://github.com/linzjs/linz/blob/0ac03e722747406d29f9e1eed7e96b6be04456e8/middleware/_modelIndex.js#L316-L347
train
linzjs/linz
middleware/_modelIndex.js
function (cb) { const getDefaultOrder = field => field.defaultOrder.toLowerCase() === 'desc' ? '-' : ''; if (!session.list.formData.sort && req.linz.model.list.sortBy.length) { req.linz.model.list.sortingBy = req.linz.model.list.sortBy[0]; // set default form sort session.list.formData.sort = `${getDefaultOrder(req.linz.model.list.sortingBy)}${req.linz.model.list.sortingBy.field}`; } else { req.linz.model.list.sortBy.forEach(function (sort) { if (sort.field === session.list.formData.sort || '-' + sort.field === session.list.formData.sort) { req.linz.model.list.sortingBy = sort; } }); } query.sort(session.list.formData.sort); if (req.linz.model.list.paging.active === true) { // add in paging skip and limit query.skip(pageIndex*pageSize-pageSize).limit(pageSize); } query.exec(function (err, docs) { // A query error has occured, let's short circuit this entire process // and start again from the last known working state. if (err) { return handleQueryError(err); } if (!err && docs.length === 0) { return cb(new Error('No records found')); } if (!err) { mongooseRecords = docs; // convert mongoose documents to plain javascript objects mongooseRecords.forEach(function (record) { records.push(record.toObject({ virtuals: true})); }); } cb(err); }); }
javascript
function (cb) { const getDefaultOrder = field => field.defaultOrder.toLowerCase() === 'desc' ? '-' : ''; if (!session.list.formData.sort && req.linz.model.list.sortBy.length) { req.linz.model.list.sortingBy = req.linz.model.list.sortBy[0]; // set default form sort session.list.formData.sort = `${getDefaultOrder(req.linz.model.list.sortingBy)}${req.linz.model.list.sortingBy.field}`; } else { req.linz.model.list.sortBy.forEach(function (sort) { if (sort.field === session.list.formData.sort || '-' + sort.field === session.list.formData.sort) { req.linz.model.list.sortingBy = sort; } }); } query.sort(session.list.formData.sort); if (req.linz.model.list.paging.active === true) { // add in paging skip and limit query.skip(pageIndex*pageSize-pageSize).limit(pageSize); } query.exec(function (err, docs) { // A query error has occured, let's short circuit this entire process // and start again from the last known working state. if (err) { return handleQueryError(err); } if (!err && docs.length === 0) { return cb(new Error('No records found')); } if (!err) { mongooseRecords = docs; // convert mongoose documents to plain javascript objects mongooseRecords.forEach(function (record) { records.push(record.toObject({ virtuals: true})); }); } cb(err); }); }
[ "function", "(", "cb", ")", "{", "const", "getDefaultOrder", "=", "field", "=>", "field", ".", "defaultOrder", ".", "toLowerCase", "(", ")", "===", "'desc'", "?", "'-'", ":", "''", ";", "if", "(", "!", "session", ".", "list", ".", "formData", ".", "sort", "&&", "req", ".", "linz", ".", "model", ".", "list", ".", "sortBy", ".", "length", ")", "{", "req", ".", "linz", ".", "model", ".", "list", ".", "sortingBy", "=", "req", ".", "linz", ".", "model", ".", "list", ".", "sortBy", "[", "0", "]", ";", "// set default form sort", "session", ".", "list", ".", "formData", ".", "sort", "=", "`", "${", "getDefaultOrder", "(", "req", ".", "linz", ".", "model", ".", "list", ".", "sortingBy", ")", "}", "${", "req", ".", "linz", ".", "model", ".", "list", ".", "sortingBy", ".", "field", "}", "`", ";", "}", "else", "{", "req", ".", "linz", ".", "model", ".", "list", ".", "sortBy", ".", "forEach", "(", "function", "(", "sort", ")", "{", "if", "(", "sort", ".", "field", "===", "session", ".", "list", ".", "formData", ".", "sort", "||", "'-'", "+", "sort", ".", "field", "===", "session", ".", "list", ".", "formData", ".", "sort", ")", "{", "req", ".", "linz", ".", "model", ".", "list", ".", "sortingBy", "=", "sort", ";", "}", "}", ")", ";", "}", "query", ".", "sort", "(", "session", ".", "list", ".", "formData", ".", "sort", ")", ";", "if", "(", "req", ".", "linz", ".", "model", ".", "list", ".", "paging", ".", "active", "===", "true", ")", "{", "// add in paging skip and limit", "query", ".", "skip", "(", "pageIndex", "*", "pageSize", "-", "pageSize", ")", ".", "limit", "(", "pageSize", ")", ";", "}", "query", ".", "exec", "(", "function", "(", "err", ",", "docs", ")", "{", "// A query error has occured, let's short circuit this entire process", "// and start again from the last known working state.", "if", "(", "err", ")", "{", "return", "handleQueryError", "(", "err", ")", ";", "}", "if", "(", "!", "err", "&&", "docs", ".", "length", "===", "0", ")", "{", "return", "cb", "(", "new", "Error", "(", "'No records found'", ")", ")", ";", "}", "if", "(", "!", "err", ")", "{", "mongooseRecords", "=", "docs", ";", "// convert mongoose documents to plain javascript objects", "mongooseRecords", ".", "forEach", "(", "function", "(", "record", ")", "{", "records", ".", "push", "(", "record", ".", "toObject", "(", "{", "virtuals", ":", "true", "}", ")", ")", ";", "}", ")", ";", "}", "cb", "(", "err", ")", ";", "}", ")", ";", "}" ]
find the docs
[ "find", "the", "docs" ]
0ac03e722747406d29f9e1eed7e96b6be04456e8
https://github.com/linzjs/linz/blob/0ac03e722747406d29f9e1eed7e96b6be04456e8/middleware/_modelIndex.js#L350-L408
train
linzjs/linz
middleware/_modelIndex.js
function (cb) { // skip this if canEdit is not define for model if (!mongooseRecords[0].canEdit) { return cb(null); } async.each(Object.keys(mongooseRecords), function (index, recordDone) { mongooseRecords[index].canEdit(req, function (err, result, message) { if (err) { return recordDone(err); } records[index].edit = { disabled: !result, message: message }; return recordDone(null); }); }, function (err) { cb(err); }); }
javascript
function (cb) { // skip this if canEdit is not define for model if (!mongooseRecords[0].canEdit) { return cb(null); } async.each(Object.keys(mongooseRecords), function (index, recordDone) { mongooseRecords[index].canEdit(req, function (err, result, message) { if (err) { return recordDone(err); } records[index].edit = { disabled: !result, message: message }; return recordDone(null); }); }, function (err) { cb(err); }); }
[ "function", "(", "cb", ")", "{", "// skip this if canEdit is not define for model", "if", "(", "!", "mongooseRecords", "[", "0", "]", ".", "canEdit", ")", "{", "return", "cb", "(", "null", ")", ";", "}", "async", ".", "each", "(", "Object", ".", "keys", "(", "mongooseRecords", ")", ",", "function", "(", "index", ",", "recordDone", ")", "{", "mongooseRecords", "[", "index", "]", ".", "canEdit", "(", "req", ",", "function", "(", "err", ",", "result", ",", "message", ")", "{", "if", "(", "err", ")", "{", "return", "recordDone", "(", "err", ")", ";", "}", "records", "[", "index", "]", ".", "edit", "=", "{", "disabled", ":", "!", "result", ",", "message", ":", "message", "}", ";", "return", "recordDone", "(", "null", ")", ";", "}", ")", ";", "}", ",", "function", "(", "err", ")", "{", "cb", "(", "err", ")", ";", "}", ")", ";", "}" ]
check if each doc can be edited
[ "check", "if", "each", "doc", "can", "be", "edited" ]
0ac03e722747406d29f9e1eed7e96b6be04456e8
https://github.com/linzjs/linz/blob/0ac03e722747406d29f9e1eed7e96b6be04456e8/middleware/_modelIndex.js#L411-L438
train
linzjs/linz
middleware/_modelIndex.js
function (cb) { // loop through each record async.each(Object.keys(records), function (index, recordDone) { // store the rendered content into a separate property records[index]['rendered'] = {}; // loop through each field async.each(Object.keys(req.linz.model.list.fields), function (field, fieldDone) { // Skip this field if we have a falsy value if (!req.linz.model.list.fields[field]) { return fieldDone(); } // If we have a reference field, data has been pre-rendered. // Let's grab it from there. if (req.linz.model.schema.tree[field] && req.linz.model.schema.tree[field].ref) { // The default value, but could be replaced below if the conditions are right. records[index]['rendered'][field] = records[index][field]; // Do we have a rendered result for this field in this particular record? // Support multiple types ref fields. if (refColData[field].rendered && records[index][field] && refColData[field].rendered[linz.api.model.getObjectIdFromRefField(records[index][field]).toString()]) { records[index]['rendered'][field] = refColData[field].rendered[linz.api.model.getObjectIdFromRefField(records[index][field]).toString()]; } // We're all done here. return fieldDone(); } // This will only execute if we don't have a ref field. let args = []; // value is not applicable for virtual field if (!req.linz.model.list.fields[field].virtual) { args.push(records[index][field]); } args.push(mongooseRecords[index]); args.push(field); args.push(req.linz.model); args.push(function (err, value) { if (!err) { records[index]['rendered'][field] = value; } return fieldDone(err); }); // call the cell renderer and update the content with the result // val, record, fieldname, model, callback req.linz.model.list.fields[field].renderer.apply(this, args); }, function (err) { recordDone(err); }); }, function (err) { cb(err); }); }
javascript
function (cb) { // loop through each record async.each(Object.keys(records), function (index, recordDone) { // store the rendered content into a separate property records[index]['rendered'] = {}; // loop through each field async.each(Object.keys(req.linz.model.list.fields), function (field, fieldDone) { // Skip this field if we have a falsy value if (!req.linz.model.list.fields[field]) { return fieldDone(); } // If we have a reference field, data has been pre-rendered. // Let's grab it from there. if (req.linz.model.schema.tree[field] && req.linz.model.schema.tree[field].ref) { // The default value, but could be replaced below if the conditions are right. records[index]['rendered'][field] = records[index][field]; // Do we have a rendered result for this field in this particular record? // Support multiple types ref fields. if (refColData[field].rendered && records[index][field] && refColData[field].rendered[linz.api.model.getObjectIdFromRefField(records[index][field]).toString()]) { records[index]['rendered'][field] = refColData[field].rendered[linz.api.model.getObjectIdFromRefField(records[index][field]).toString()]; } // We're all done here. return fieldDone(); } // This will only execute if we don't have a ref field. let args = []; // value is not applicable for virtual field if (!req.linz.model.list.fields[field].virtual) { args.push(records[index][field]); } args.push(mongooseRecords[index]); args.push(field); args.push(req.linz.model); args.push(function (err, value) { if (!err) { records[index]['rendered'][field] = value; } return fieldDone(err); }); // call the cell renderer and update the content with the result // val, record, fieldname, model, callback req.linz.model.list.fields[field].renderer.apply(this, args); }, function (err) { recordDone(err); }); }, function (err) { cb(err); }); }
[ "function", "(", "cb", ")", "{", "// loop through each record", "async", ".", "each", "(", "Object", ".", "keys", "(", "records", ")", ",", "function", "(", "index", ",", "recordDone", ")", "{", "// store the rendered content into a separate property", "records", "[", "index", "]", "[", "'rendered'", "]", "=", "{", "}", ";", "// loop through each field", "async", ".", "each", "(", "Object", ".", "keys", "(", "req", ".", "linz", ".", "model", ".", "list", ".", "fields", ")", ",", "function", "(", "field", ",", "fieldDone", ")", "{", "// Skip this field if we have a falsy value", "if", "(", "!", "req", ".", "linz", ".", "model", ".", "list", ".", "fields", "[", "field", "]", ")", "{", "return", "fieldDone", "(", ")", ";", "}", "// If we have a reference field, data has been pre-rendered.", "// Let's grab it from there.", "if", "(", "req", ".", "linz", ".", "model", ".", "schema", ".", "tree", "[", "field", "]", "&&", "req", ".", "linz", ".", "model", ".", "schema", ".", "tree", "[", "field", "]", ".", "ref", ")", "{", "// The default value, but could be replaced below if the conditions are right.", "records", "[", "index", "]", "[", "'rendered'", "]", "[", "field", "]", "=", "records", "[", "index", "]", "[", "field", "]", ";", "// Do we have a rendered result for this field in this particular record?", "// Support multiple types ref fields.", "if", "(", "refColData", "[", "field", "]", ".", "rendered", "&&", "records", "[", "index", "]", "[", "field", "]", "&&", "refColData", "[", "field", "]", ".", "rendered", "[", "linz", ".", "api", ".", "model", ".", "getObjectIdFromRefField", "(", "records", "[", "index", "]", "[", "field", "]", ")", ".", "toString", "(", ")", "]", ")", "{", "records", "[", "index", "]", "[", "'rendered'", "]", "[", "field", "]", "=", "refColData", "[", "field", "]", ".", "rendered", "[", "linz", ".", "api", ".", "model", ".", "getObjectIdFromRefField", "(", "records", "[", "index", "]", "[", "field", "]", ")", ".", "toString", "(", ")", "]", ";", "}", "// We're all done here.", "return", "fieldDone", "(", ")", ";", "}", "// This will only execute if we don't have a ref field.", "let", "args", "=", "[", "]", ";", "// value is not applicable for virtual field", "if", "(", "!", "req", ".", "linz", ".", "model", ".", "list", ".", "fields", "[", "field", "]", ".", "virtual", ")", "{", "args", ".", "push", "(", "records", "[", "index", "]", "[", "field", "]", ")", ";", "}", "args", ".", "push", "(", "mongooseRecords", "[", "index", "]", ")", ";", "args", ".", "push", "(", "field", ")", ";", "args", ".", "push", "(", "req", ".", "linz", ".", "model", ")", ";", "args", ".", "push", "(", "function", "(", "err", ",", "value", ")", "{", "if", "(", "!", "err", ")", "{", "records", "[", "index", "]", "[", "'rendered'", "]", "[", "field", "]", "=", "value", ";", "}", "return", "fieldDone", "(", "err", ")", ";", "}", ")", ";", "// call the cell renderer and update the content with the result", "// val, record, fieldname, model, callback", "req", ".", "linz", ".", "model", ".", "list", ".", "fields", "[", "field", "]", ".", "renderer", ".", "apply", "(", "this", ",", "args", ")", ";", "}", ",", "function", "(", "err", ")", "{", "recordDone", "(", "err", ")", ";", "}", ")", ";", "}", ",", "function", "(", "err", ")", "{", "cb", "(", "err", ")", ";", "}", ")", ";", "}" ]
create the values for the datalists for each doc
[ "create", "the", "values", "for", "the", "datalists", "for", "each", "doc" ]
0ac03e722747406d29f9e1eed7e96b6be04456e8
https://github.com/linzjs/linz/blob/0ac03e722747406d29f9e1eed7e96b6be04456e8/middleware/_modelIndex.js#L528-L604
train
linzjs/linz
middleware/_modelIndex.js
function (cb) { if (!req.linz.model.list.recordActions.length) { return cb(null); } async.each(req.linz.model.list.recordActions, function (action, actionDone) { if (!action.disabled) { return actionDone(null); } if (typeof action.disabled !== 'function') { throw new Error('Invalid type for record.action.disabled. It must be a function'); } async.each(Object.keys(records), function (index, recordDone) { action.disabled(mongooseRecords[index], function (err, isDisabled, message) { records[index].recordActions = records[index].recordActions || {}; records[index].recordActions[action.label] = { disabled: isDisabled, message: message }; return recordDone(null); }); }, function (err) { return actionDone(err); }); }, function (err) { return cb(err); }); }
javascript
function (cb) { if (!req.linz.model.list.recordActions.length) { return cb(null); } async.each(req.linz.model.list.recordActions, function (action, actionDone) { if (!action.disabled) { return actionDone(null); } if (typeof action.disabled !== 'function') { throw new Error('Invalid type for record.action.disabled. It must be a function'); } async.each(Object.keys(records), function (index, recordDone) { action.disabled(mongooseRecords[index], function (err, isDisabled, message) { records[index].recordActions = records[index].recordActions || {}; records[index].recordActions[action.label] = { disabled: isDisabled, message: message }; return recordDone(null); }); }, function (err) { return actionDone(err); }); }, function (err) { return cb(err); }); }
[ "function", "(", "cb", ")", "{", "if", "(", "!", "req", ".", "linz", ".", "model", ".", "list", ".", "recordActions", ".", "length", ")", "{", "return", "cb", "(", "null", ")", ";", "}", "async", ".", "each", "(", "req", ".", "linz", ".", "model", ".", "list", ".", "recordActions", ",", "function", "(", "action", ",", "actionDone", ")", "{", "if", "(", "!", "action", ".", "disabled", ")", "{", "return", "actionDone", "(", "null", ")", ";", "}", "if", "(", "typeof", "action", ".", "disabled", "!==", "'function'", ")", "{", "throw", "new", "Error", "(", "'Invalid type for record.action.disabled. It must be a function'", ")", ";", "}", "async", ".", "each", "(", "Object", ".", "keys", "(", "records", ")", ",", "function", "(", "index", ",", "recordDone", ")", "{", "action", ".", "disabled", "(", "mongooseRecords", "[", "index", "]", ",", "function", "(", "err", ",", "isDisabled", ",", "message", ")", "{", "records", "[", "index", "]", ".", "recordActions", "=", "records", "[", "index", "]", ".", "recordActions", "||", "{", "}", ";", "records", "[", "index", "]", ".", "recordActions", "[", "action", ".", "label", "]", "=", "{", "disabled", ":", "isDisabled", ",", "message", ":", "message", "}", ";", "return", "recordDone", "(", "null", ")", ";", "}", ")", ";", "}", ",", "function", "(", "err", ")", "{", "return", "actionDone", "(", "err", ")", ";", "}", ")", ";", "}", ",", "function", "(", "err", ")", "{", "return", "cb", "(", "err", ")", ";", "}", ")", ";", "}" ]
check if we need to process each record again record actions
[ "check", "if", "we", "need", "to", "process", "each", "record", "again", "record", "actions" ]
0ac03e722747406d29f9e1eed7e96b6be04456e8
https://github.com/linzjs/linz/blob/0ac03e722747406d29f9e1eed7e96b6be04456e8/middleware/_modelIndex.js#L607-L650
train
linzjs/linz
public/js/multiselect.min.js
function() { this.$button = $(this.options.templates.button).addClass(this.options.buttonClass); // Adopt active state. if (this.$select.prop('disabled')) { this.disable(); } else { this.enable(); } // Manually add button width if set. if (this.options.buttonWidth && this.options.buttonWidth !== 'auto') { this.$button.css({ 'width' : this.options.buttonWidth }); this.$container.css({ 'width': this.options.buttonWidth }); } // Keep the tab index from the select. var tabindex = this.$select.attr('tabindex'); if (tabindex) { this.$button.attr('tabindex', tabindex); } this.$container.prepend(this.$button); }
javascript
function() { this.$button = $(this.options.templates.button).addClass(this.options.buttonClass); // Adopt active state. if (this.$select.prop('disabled')) { this.disable(); } else { this.enable(); } // Manually add button width if set. if (this.options.buttonWidth && this.options.buttonWidth !== 'auto') { this.$button.css({ 'width' : this.options.buttonWidth }); this.$container.css({ 'width': this.options.buttonWidth }); } // Keep the tab index from the select. var tabindex = this.$select.attr('tabindex'); if (tabindex) { this.$button.attr('tabindex', tabindex); } this.$container.prepend(this.$button); }
[ "function", "(", ")", "{", "this", ".", "$button", "=", "$", "(", "this", ".", "options", ".", "templates", ".", "button", ")", ".", "addClass", "(", "this", ".", "options", ".", "buttonClass", ")", ";", "// Adopt active state.", "if", "(", "this", ".", "$select", ".", "prop", "(", "'disabled'", ")", ")", "{", "this", ".", "disable", "(", ")", ";", "}", "else", "{", "this", ".", "enable", "(", ")", ";", "}", "// Manually add button width if set.", "if", "(", "this", ".", "options", ".", "buttonWidth", "&&", "this", ".", "options", ".", "buttonWidth", "!==", "'auto'", ")", "{", "this", ".", "$button", ".", "css", "(", "{", "'width'", ":", "this", ".", "options", ".", "buttonWidth", "}", ")", ";", "this", ".", "$container", ".", "css", "(", "{", "'width'", ":", "this", ".", "options", ".", "buttonWidth", "}", ")", ";", "}", "// Keep the tab index from the select.", "var", "tabindex", "=", "this", ".", "$select", ".", "attr", "(", "'tabindex'", ")", ";", "if", "(", "tabindex", ")", "{", "this", ".", "$button", ".", "attr", "(", "'tabindex'", ",", "tabindex", ")", ";", "}", "this", ".", "$container", ".", "prepend", "(", "this", ".", "$button", ")", ";", "}" ]
Builds the button of the multiselect.
[ "Builds", "the", "button", "of", "the", "multiselect", "." ]
0ac03e722747406d29f9e1eed7e96b6be04456e8
https://github.com/linzjs/linz/blob/0ac03e722747406d29f9e1eed7e96b6be04456e8/public/js/multiselect.min.js#L251-L279
train
linzjs/linz
public/js/multiselect.min.js
function() { // Build ul. this.$ul = $(this.options.templates.ul); if (this.options.dropRight) { this.$ul.addClass('pull-right'); } // Set max height of dropdown menu to activate auto scrollbar. if (this.options.maxHeight) { // TODO: Add a class for this option to move the css declarations. this.$ul.css({ 'max-height': this.options.maxHeight + 'px', 'overflow-y': 'auto', 'overflow-x': 'hidden' }); } this.$container.append(this.$ul); }
javascript
function() { // Build ul. this.$ul = $(this.options.templates.ul); if (this.options.dropRight) { this.$ul.addClass('pull-right'); } // Set max height of dropdown menu to activate auto scrollbar. if (this.options.maxHeight) { // TODO: Add a class for this option to move the css declarations. this.$ul.css({ 'max-height': this.options.maxHeight + 'px', 'overflow-y': 'auto', 'overflow-x': 'hidden' }); } this.$container.append(this.$ul); }
[ "function", "(", ")", "{", "// Build ul.", "this", ".", "$ul", "=", "$", "(", "this", ".", "options", ".", "templates", ".", "ul", ")", ";", "if", "(", "this", ".", "options", ".", "dropRight", ")", "{", "this", ".", "$ul", ".", "addClass", "(", "'pull-right'", ")", ";", "}", "// Set max height of dropdown menu to activate auto scrollbar.", "if", "(", "this", ".", "options", ".", "maxHeight", ")", "{", "// TODO: Add a class for this option to move the css declarations.", "this", ".", "$ul", ".", "css", "(", "{", "'max-height'", ":", "this", ".", "options", ".", "maxHeight", "+", "'px'", ",", "'overflow-y'", ":", "'auto'", ",", "'overflow-x'", ":", "'hidden'", "}", ")", ";", "}", "this", ".", "$container", ".", "append", "(", "this", ".", "$ul", ")", ";", "}" ]
Builds the ul representing the dropdown menu.
[ "Builds", "the", "ul", "representing", "the", "dropdown", "menu", "." ]
0ac03e722747406d29f9e1eed7e96b6be04456e8
https://github.com/linzjs/linz/blob/0ac03e722747406d29f9e1eed7e96b6be04456e8/public/js/multiselect.min.js#L284-L304
train
linzjs/linz
public/js/multiselect.min.js
function(group) { var groupName = $(group).prop('label'); // Add a header for the group. var $li = $(this.options.templates.liGroup); $('label', $li).text(groupName); this.$ul.append($li); if ($(group).is(':disabled')) { $li.addClass('disabled'); } // Add the options of the group. $('option', group).each($.proxy(function(index, element) { this.createOptionValue(element); }, this)); }
javascript
function(group) { var groupName = $(group).prop('label'); // Add a header for the group. var $li = $(this.options.templates.liGroup); $('label', $li).text(groupName); this.$ul.append($li); if ($(group).is(':disabled')) { $li.addClass('disabled'); } // Add the options of the group. $('option', group).each($.proxy(function(index, element) { this.createOptionValue(element); }, this)); }
[ "function", "(", "group", ")", "{", "var", "groupName", "=", "$", "(", "group", ")", ".", "prop", "(", "'label'", ")", ";", "// Add a header for the group.", "var", "$li", "=", "$", "(", "this", ".", "options", ".", "templates", ".", "liGroup", ")", ";", "$", "(", "'label'", ",", "$li", ")", ".", "text", "(", "groupName", ")", ";", "this", ".", "$ul", ".", "append", "(", "$li", ")", ";", "if", "(", "$", "(", "group", ")", ".", "is", "(", "':disabled'", ")", ")", "{", "$li", ".", "addClass", "(", "'disabled'", ")", ";", "}", "// Add the options of the group.", "$", "(", "'option'", ",", "group", ")", ".", "each", "(", "$", ".", "proxy", "(", "function", "(", "index", ",", "element", ")", "{", "this", ".", "createOptionValue", "(", "element", ")", ";", "}", ",", "this", ")", ")", ";", "}" ]
Creates an optgroup. @param {jQuery} group
[ "Creates", "an", "optgroup", "." ]
0ac03e722747406d29f9e1eed7e96b6be04456e8
https://github.com/linzjs/linz/blob/0ac03e722747406d29f9e1eed7e96b6be04456e8/public/js/multiselect.min.js#L568-L585
train
linzjs/linz
public/js/multiselect.min.js
function() { var alreadyHasSelectAll = this.hasSelectAll(); if (!alreadyHasSelectAll && this.options.includeSelectAllOption && this.options.multiple && $('option', this.$select).length > this.options.includeSelectAllIfMoreThan) { // Check whether to add a divider after the select all. if (this.options.includeSelectAllDivider) { this.$ul.prepend($(this.options.templates.divider)); } var $li = $(this.options.templates.li); $('label', $li).addClass("checkbox"); $('label', $li).append('<input type="checkbox" name="' + this.options.checkboxName + '" />'); var $checkbox = $('input', $li); $checkbox.val(this.options.selectAllValue); $li.addClass("multiselect-item multiselect-all"); $checkbox.parent().parent() .addClass('multiselect-all'); $('label', $li).append(" " + this.options.selectAllText); this.$ul.prepend($li); $checkbox.prop('checked', false); } }
javascript
function() { var alreadyHasSelectAll = this.hasSelectAll(); if (!alreadyHasSelectAll && this.options.includeSelectAllOption && this.options.multiple && $('option', this.$select).length > this.options.includeSelectAllIfMoreThan) { // Check whether to add a divider after the select all. if (this.options.includeSelectAllDivider) { this.$ul.prepend($(this.options.templates.divider)); } var $li = $(this.options.templates.li); $('label', $li).addClass("checkbox"); $('label', $li).append('<input type="checkbox" name="' + this.options.checkboxName + '" />'); var $checkbox = $('input', $li); $checkbox.val(this.options.selectAllValue); $li.addClass("multiselect-item multiselect-all"); $checkbox.parent().parent() .addClass('multiselect-all'); $('label', $li).append(" " + this.options.selectAllText); this.$ul.prepend($li); $checkbox.prop('checked', false); } }
[ "function", "(", ")", "{", "var", "alreadyHasSelectAll", "=", "this", ".", "hasSelectAll", "(", ")", ";", "if", "(", "!", "alreadyHasSelectAll", "&&", "this", ".", "options", ".", "includeSelectAllOption", "&&", "this", ".", "options", ".", "multiple", "&&", "$", "(", "'option'", ",", "this", ".", "$select", ")", ".", "length", ">", "this", ".", "options", ".", "includeSelectAllIfMoreThan", ")", "{", "// Check whether to add a divider after the select all.", "if", "(", "this", ".", "options", ".", "includeSelectAllDivider", ")", "{", "this", ".", "$ul", ".", "prepend", "(", "$", "(", "this", ".", "options", ".", "templates", ".", "divider", ")", ")", ";", "}", "var", "$li", "=", "$", "(", "this", ".", "options", ".", "templates", ".", "li", ")", ";", "$", "(", "'label'", ",", "$li", ")", ".", "addClass", "(", "\"checkbox\"", ")", ";", "$", "(", "'label'", ",", "$li", ")", ".", "append", "(", "'<input type=\"checkbox\" name=\"'", "+", "this", ".", "options", ".", "checkboxName", "+", "'\" />'", ")", ";", "var", "$checkbox", "=", "$", "(", "'input'", ",", "$li", ")", ";", "$checkbox", ".", "val", "(", "this", ".", "options", ".", "selectAllValue", ")", ";", "$li", ".", "addClass", "(", "\"multiselect-item multiselect-all\"", ")", ";", "$checkbox", ".", "parent", "(", ")", ".", "parent", "(", ")", ".", "addClass", "(", "'multiselect-all'", ")", ";", "$", "(", "'label'", ",", "$li", ")", ".", "append", "(", "\" \"", "+", "this", ".", "options", ".", "selectAllText", ")", ";", "this", ".", "$ul", ".", "prepend", "(", "$li", ")", ";", "$checkbox", ".", "prop", "(", "'checked'", ",", "false", ")", ";", "}", "}" ]
Build the selct all. Checks if a select all has already been created.
[ "Build", "the", "selct", "all", ".", "Checks", "if", "a", "select", "all", "has", "already", "been", "created", "." ]
0ac03e722747406d29f9e1eed7e96b6be04456e8
https://github.com/linzjs/linz/blob/0ac03e722747406d29f9e1eed7e96b6be04456e8/public/js/multiselect.min.js#L591-L619
train
linzjs/linz
public/js/multiselect.min.js
function() { $('option', this.$select).each($.proxy(function(index, element) { var $input = $('li input', this.$ul).filter(function() { return $(this).val() === $(element).val(); }); if ($(element).is(':selected')) { $input.prop('checked', true); if (this.options.selectedClass) { $input.parents('li') .addClass(this.options.selectedClass); } } else { $input.prop('checked', false); if (this.options.selectedClass) { $input.parents('li') .removeClass(this.options.selectedClass); } } if ($(element).is(":disabled")) { $input.attr('disabled', 'disabled') .prop('disabled', true) .parents('li') .addClass('disabled'); } else { $input.prop('disabled', false) .parents('li') .removeClass('disabled'); } }, this)); this.updateButtonText(); this.updateSelectAll(); }
javascript
function() { $('option', this.$select).each($.proxy(function(index, element) { var $input = $('li input', this.$ul).filter(function() { return $(this).val() === $(element).val(); }); if ($(element).is(':selected')) { $input.prop('checked', true); if (this.options.selectedClass) { $input.parents('li') .addClass(this.options.selectedClass); } } else { $input.prop('checked', false); if (this.options.selectedClass) { $input.parents('li') .removeClass(this.options.selectedClass); } } if ($(element).is(":disabled")) { $input.attr('disabled', 'disabled') .prop('disabled', true) .parents('li') .addClass('disabled'); } else { $input.prop('disabled', false) .parents('li') .removeClass('disabled'); } }, this)); this.updateButtonText(); this.updateSelectAll(); }
[ "function", "(", ")", "{", "$", "(", "'option'", ",", "this", ".", "$select", ")", ".", "each", "(", "$", ".", "proxy", "(", "function", "(", "index", ",", "element", ")", "{", "var", "$input", "=", "$", "(", "'li input'", ",", "this", ".", "$ul", ")", ".", "filter", "(", "function", "(", ")", "{", "return", "$", "(", "this", ")", ".", "val", "(", ")", "===", "$", "(", "element", ")", ".", "val", "(", ")", ";", "}", ")", ";", "if", "(", "$", "(", "element", ")", ".", "is", "(", "':selected'", ")", ")", "{", "$input", ".", "prop", "(", "'checked'", ",", "true", ")", ";", "if", "(", "this", ".", "options", ".", "selectedClass", ")", "{", "$input", ".", "parents", "(", "'li'", ")", ".", "addClass", "(", "this", ".", "options", ".", "selectedClass", ")", ";", "}", "}", "else", "{", "$input", ".", "prop", "(", "'checked'", ",", "false", ")", ";", "if", "(", "this", ".", "options", ".", "selectedClass", ")", "{", "$input", ".", "parents", "(", "'li'", ")", ".", "removeClass", "(", "this", ".", "options", ".", "selectedClass", ")", ";", "}", "}", "if", "(", "$", "(", "element", ")", ".", "is", "(", "\":disabled\"", ")", ")", "{", "$input", ".", "attr", "(", "'disabled'", ",", "'disabled'", ")", ".", "prop", "(", "'disabled'", ",", "true", ")", ".", "parents", "(", "'li'", ")", ".", "addClass", "(", "'disabled'", ")", ";", "}", "else", "{", "$input", ".", "prop", "(", "'disabled'", ",", "false", ")", ".", "parents", "(", "'li'", ")", ".", "removeClass", "(", "'disabled'", ")", ";", "}", "}", ",", "this", ")", ")", ";", "this", ".", "updateButtonText", "(", ")", ";", "this", ".", "updateSelectAll", "(", ")", ";", "}" ]
Refreshs the multiselect based on the selected options of the select.
[ "Refreshs", "the", "multiselect", "based", "on", "the", "selected", "options", "of", "the", "select", "." ]
0ac03e722747406d29f9e1eed7e96b6be04456e8
https://github.com/linzjs/linz/blob/0ac03e722747406d29f9e1eed7e96b6be04456e8/public/js/multiselect.min.js#L703-L741
train
linzjs/linz
public/js/multiselect.min.js
function() { this.$ul.html(''); // Important to distinguish between radios and checkboxes. this.options.multiple = this.$select.attr('multiple') === "multiple"; this.buildSelectAll(); this.buildDropdownOptions(); this.buildFilter(); this.updateButtonText(); this.updateSelectAll(); if (this.options.dropRight) { this.$ul.addClass('pull-right'); } }
javascript
function() { this.$ul.html(''); // Important to distinguish between radios and checkboxes. this.options.multiple = this.$select.attr('multiple') === "multiple"; this.buildSelectAll(); this.buildDropdownOptions(); this.buildFilter(); this.updateButtonText(); this.updateSelectAll(); if (this.options.dropRight) { this.$ul.addClass('pull-right'); } }
[ "function", "(", ")", "{", "this", ".", "$ul", ".", "html", "(", "''", ")", ";", "// Important to distinguish between radios and checkboxes.", "this", ".", "options", ".", "multiple", "=", "this", ".", "$select", ".", "attr", "(", "'multiple'", ")", "===", "\"multiple\"", ";", "this", ".", "buildSelectAll", "(", ")", ";", "this", ".", "buildDropdownOptions", "(", ")", ";", "this", ".", "buildFilter", "(", ")", ";", "this", ".", "updateButtonText", "(", ")", ";", "this", ".", "updateSelectAll", "(", ")", ";", "if", "(", "this", ".", "options", ".", "dropRight", ")", "{", "this", ".", "$ul", ".", "addClass", "(", "'pull-right'", ")", ";", "}", "}" ]
Rebuild the plugin. Rebuilds the dropdown, the filter and the select all option.
[ "Rebuild", "the", "plugin", ".", "Rebuilds", "the", "dropdown", "the", "filter", "and", "the", "select", "all", "option", "." ]
0ac03e722747406d29f9e1eed7e96b6be04456e8
https://github.com/linzjs/linz/blob/0ac03e722747406d29f9e1eed7e96b6be04456e8/public/js/multiselect.min.js#L875-L891
train
linzjs/linz
public/js/multiselect.min.js
function (value) { var options = $('option', this.$select); var valueToCompare = value.toString(); for (var i = 0; i < options.length; i = i + 1) { var option = options[i]; if (option.value === valueToCompare) { return $(option); } } }
javascript
function (value) { var options = $('option', this.$select); var valueToCompare = value.toString(); for (var i = 0; i < options.length; i = i + 1) { var option = options[i]; if (option.value === valueToCompare) { return $(option); } } }
[ "function", "(", "value", ")", "{", "var", "options", "=", "$", "(", "'option'", ",", "this", ".", "$select", ")", ";", "var", "valueToCompare", "=", "value", ".", "toString", "(", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "options", ".", "length", ";", "i", "=", "i", "+", "1", ")", "{", "var", "option", "=", "options", "[", "i", "]", ";", "if", "(", "option", ".", "value", "===", "valueToCompare", ")", "{", "return", "$", "(", "option", ")", ";", "}", "}", "}" ]
Gets a select option by its value. @param {String} value @returns {jQuery}
[ "Gets", "a", "select", "option", "by", "its", "value", "." ]
0ac03e722747406d29f9e1eed7e96b6be04456e8
https://github.com/linzjs/linz/blob/0ac03e722747406d29f9e1eed7e96b6be04456e8/public/js/multiselect.min.js#L1019-L1030
train
ssbc/ssb-blobs
inject.js
hasLegacy
function hasLegacy (hashes) { var ary = Object.keys(hashes).filter(function (k) { return hashes[k] < 0 }) if(ary.length) peer.blobs.has(ary, function (err, haves) { if(err) drain.abort(err) //ERROR: abort this stream. else haves.forEach(function (have, i) { if(have) has(peer.id, ary[i], have) }) }) }
javascript
function hasLegacy (hashes) { var ary = Object.keys(hashes).filter(function (k) { return hashes[k] < 0 }) if(ary.length) peer.blobs.has(ary, function (err, haves) { if(err) drain.abort(err) //ERROR: abort this stream. else haves.forEach(function (have, i) { if(have) has(peer.id, ary[i], have) }) }) }
[ "function", "hasLegacy", "(", "hashes", ")", "{", "var", "ary", "=", "Object", ".", "keys", "(", "hashes", ")", ".", "filter", "(", "function", "(", "k", ")", "{", "return", "hashes", "[", "k", "]", "<", "0", "}", ")", "if", "(", "ary", ".", "length", ")", "peer", ".", "blobs", ".", "has", "(", "ary", ",", "function", "(", "err", ",", "haves", ")", "{", "if", "(", "err", ")", "drain", ".", "abort", "(", "err", ")", "//ERROR: abort this stream.", "else", "haves", ".", "forEach", "(", "function", "(", "have", ",", "i", ")", "{", "if", "(", "have", ")", "has", "(", "peer", ".", "id", ",", "ary", "[", "i", "]", ",", "have", ")", "}", ")", "}", ")", "}" ]
so we can abort it when we get an error.
[ "so", "we", "can", "abort", "it", "when", "we", "get", "an", "error", "." ]
6ce1c7a46a602deb3d160023e673d9999775aa7a
https://github.com/ssbc/ssb-blobs/blob/6ce1c7a46a602deb3d160023e673d9999775aa7a/inject.js#L171-L182
train
linzjs/linz
middleware/modelExport.js
function (exports) { var exp = undefined; // retrieve the export object exports.forEach(function (_export) { // Linz's default export function is called export if (_export.action && _export.action === 'export') { exp = _export; } }); // if the export object could not be found, throw an error if (!exp) { throw new Error('The export was using Linz default export method, yet the model\'s list.export object could not be found.'); } return exp; }
javascript
function (exports) { var exp = undefined; // retrieve the export object exports.forEach(function (_export) { // Linz's default export function is called export if (_export.action && _export.action === 'export') { exp = _export; } }); // if the export object could not be found, throw an error if (!exp) { throw new Error('The export was using Linz default export method, yet the model\'s list.export object could not be found.'); } return exp; }
[ "function", "(", "exports", ")", "{", "var", "exp", "=", "undefined", ";", "// retrieve the export object", "exports", ".", "forEach", "(", "function", "(", "_export", ")", "{", "// Linz's default export function is called export", "if", "(", "_export", ".", "action", "&&", "_export", ".", "action", "===", "'export'", ")", "{", "exp", "=", "_export", ";", "}", "}", ")", ";", "// if the export object could not be found, throw an error", "if", "(", "!", "exp", ")", "{", "throw", "new", "Error", "(", "'The export was using Linz default export method, yet the model\\'s list.export object could not be found.'", ")", ";", "}", "return", "exp", ";", "}" ]
this will retrieve the export object, using Linz's default export handler amongst custom export handlers this is based on the knowledge that only Linz's default export handler can have an `action` of `export` `exports` should be model.list.export
[ "this", "will", "retrieve", "the", "export", "object", "using", "Linz", "s", "default", "export", "handler", "amongst", "custom", "export", "handlers", "this", "is", "based", "on", "the", "knowledge", "that", "only", "Linz", "s", "default", "export", "handler", "can", "have", "an", "action", "of", "export", "exports", "should", "be", "model", ".", "list", ".", "export" ]
0ac03e722747406d29f9e1eed7e96b6be04456e8
https://github.com/linzjs/linz/blob/0ac03e722747406d29f9e1eed7e96b6be04456e8/middleware/modelExport.js#L224-L245
train
linzjs/linz
lib/versions/renderers/overview.js
function (cb) { model.VersionedModel.find({ refId: record._id }, 'dateCreated modifiedBy', { lean: 1, sort: { dateCreated: -1 } }, function (err, result) { return cb(err, result); }); }
javascript
function (cb) { model.VersionedModel.find({ refId: record._id }, 'dateCreated modifiedBy', { lean: 1, sort: { dateCreated: -1 } }, function (err, result) { return cb(err, result); }); }
[ "function", "(", "cb", ")", "{", "model", ".", "VersionedModel", ".", "find", "(", "{", "refId", ":", "record", ".", "_id", "}", ",", "'dateCreated modifiedBy'", ",", "{", "lean", ":", "1", ",", "sort", ":", "{", "dateCreated", ":", "-", "1", "}", "}", ",", "function", "(", "err", ",", "result", ")", "{", "return", "cb", "(", "err", ",", "result", ")", ";", "}", ")", ";", "}" ]
get a list of all the versions from the archived
[ "get", "a", "list", "of", "all", "the", "versions", "from", "the", "archived" ]
0ac03e722747406d29f9e1eed7e96b6be04456e8
https://github.com/linzjs/linz/blob/0ac03e722747406d29f9e1eed7e96b6be04456e8/lib/versions/renderers/overview.js#L11-L17
train
linzjs/linz
lib/api/permissions.js
hasPermission
function hasPermission (user, context, permission, cb) { var _context = context; /** * Support three types of permissions: * - navigation * - models and model * - configs and config * * Context can either be an object, or a string. If context is a string, no other data need be passed through. * If context is an object, it must have a type and a related property. Linz supports the following: * - 'models' * - 'configs' * - {type: 'model', model: {string}} * - {type: 'config', config: {string}} */ if (typeof context === 'string') { _context = { type: context }; } if (_context.type.toLowerCase() === 'models' || _context.type.toLowerCase() === 'configs') { return linz.get('permissions')(user, _context.type, permission, cb); } if (_context.type.toLowerCase() === 'model') { return linz.api.model.hasPermission(user, _context.model, permission, cb); } if (_context.type.toLowerCase() === 'config') { return linz.api.configs.hasPermission(user, _context.config, permission, cb); } }
javascript
function hasPermission (user, context, permission, cb) { var _context = context; /** * Support three types of permissions: * - navigation * - models and model * - configs and config * * Context can either be an object, or a string. If context is a string, no other data need be passed through. * If context is an object, it must have a type and a related property. Linz supports the following: * - 'models' * - 'configs' * - {type: 'model', model: {string}} * - {type: 'config', config: {string}} */ if (typeof context === 'string') { _context = { type: context }; } if (_context.type.toLowerCase() === 'models' || _context.type.toLowerCase() === 'configs') { return linz.get('permissions')(user, _context.type, permission, cb); } if (_context.type.toLowerCase() === 'model') { return linz.api.model.hasPermission(user, _context.model, permission, cb); } if (_context.type.toLowerCase() === 'config') { return linz.api.configs.hasPermission(user, _context.config, permission, cb); } }
[ "function", "hasPermission", "(", "user", ",", "context", ",", "permission", ",", "cb", ")", "{", "var", "_context", "=", "context", ";", "/**\n * Support three types of permissions:\n * - navigation\n * - models and model\n * - configs and config\n *\n * Context can either be an object, or a string. If context is a string, no other data need be passed through.\n * If context is an object, it must have a type and a related property. Linz supports the following:\n * - 'models'\n * - 'configs'\n * - {type: 'model', model: {string}}\n * - {type: 'config', config: {string}}\n */", "if", "(", "typeof", "context", "===", "'string'", ")", "{", "_context", "=", "{", "type", ":", "context", "}", ";", "}", "if", "(", "_context", ".", "type", ".", "toLowerCase", "(", ")", "===", "'models'", "||", "_context", ".", "type", ".", "toLowerCase", "(", ")", "===", "'configs'", ")", "{", "return", "linz", ".", "get", "(", "'permissions'", ")", "(", "user", ",", "_context", ".", "type", ",", "permission", ",", "cb", ")", ";", "}", "if", "(", "_context", ".", "type", ".", "toLowerCase", "(", ")", "===", "'model'", ")", "{", "return", "linz", ".", "api", ".", "model", ".", "hasPermission", "(", "user", ",", "_context", ".", "model", ",", "permission", ",", "cb", ")", ";", "}", "if", "(", "_context", ".", "type", ".", "toLowerCase", "(", ")", "===", "'config'", ")", "{", "return", "linz", ".", "api", ".", "configs", ".", "hasPermission", "(", "user", ",", "_context", ".", "config", ",", "permission", ",", "cb", ")", ";", "}", "}" ]
Determine if a user has access to a route, model or config @param {object} user The user object in which the context of the permission should be based. @param {String|object} context The context for the permission. One of 'models', 'configs', {type:'model', model:{object}} or {type:'config': config:{config}} @param {string} permission The permission being requested. @param {Function} cb The callback with the result. Accepts true or false only.
[ "Determine", "if", "a", "user", "has", "access", "to", "a", "route", "model", "or", "config" ]
0ac03e722747406d29f9e1eed7e96b6be04456e8
https://github.com/linzjs/linz/blob/0ac03e722747406d29f9e1eed7e96b6be04456e8/lib/api/permissions.js#L11-L47
train
linzjs/linz
public/js/utils.js
addLoadEvent
function addLoadEvent (func) { if (window.attachEvent) { return window.attachEvent('onload', func); } if (window.addEventListener) { return window.addEventListener('load', func, false); } return document.addEventListener('load', func, false); }
javascript
function addLoadEvent (func) { if (window.attachEvent) { return window.attachEvent('onload', func); } if (window.addEventListener) { return window.addEventListener('load', func, false); } return document.addEventListener('load', func, false); }
[ "function", "addLoadEvent", "(", "func", ")", "{", "if", "(", "window", ".", "attachEvent", ")", "{", "return", "window", ".", "attachEvent", "(", "'onload'", ",", "func", ")", ";", "}", "if", "(", "window", ".", "addEventListener", ")", "{", "return", "window", ".", "addEventListener", "(", "'load'", ",", "func", ",", "false", ")", ";", "}", "return", "document", ".", "addEventListener", "(", "'load'", ",", "func", ",", "false", ")", ";", "}" ]
Append instead of replace the onload process.
[ "Append", "instead", "of", "replace", "the", "onload", "process", "." ]
0ac03e722747406d29f9e1eed7e96b6be04456e8
https://github.com/linzjs/linz/blob/0ac03e722747406d29f9e1eed7e96b6be04456e8/public/js/utils.js#L10-L22
train
Yodata/yodata
packages/context-sdk/lib/transform/index.js
transform
async function transform({ datapath, filepath, inverse = false }) { assert.string(datapath) assert.string(filepath) const data = await loadData(datapath) const contextdoc = await loadData(filepath) assert.object(data) assert.object(contextdoc) const result = new Context(contextdoc).use(viewPlugin).map(data) return result }
javascript
async function transform({ datapath, filepath, inverse = false }) { assert.string(datapath) assert.string(filepath) const data = await loadData(datapath) const contextdoc = await loadData(filepath) assert.object(data) assert.object(contextdoc) const result = new Context(contextdoc).use(viewPlugin).map(data) return result }
[ "async", "function", "transform", "(", "{", "datapath", ",", "filepath", ",", "inverse", "=", "false", "}", ")", "{", "assert", ".", "string", "(", "datapath", ")", "assert", ".", "string", "(", "filepath", ")", "const", "data", "=", "await", "loadData", "(", "datapath", ")", "const", "contextdoc", "=", "await", "loadData", "(", "filepath", ")", "assert", ".", "object", "(", "data", ")", "assert", ".", "object", "(", "contextdoc", ")", "const", "result", "=", "new", "Context", "(", "contextdoc", ")", ".", "use", "(", "viewPlugin", ")", ".", "map", "(", "data", ")", "return", "result", "}" ]
transforms data at datapath with context at filepath @param {object} props @param {string} props.datapath - path to data @param {string} [props.filepath] - path to context definition file @param {boolean} [props.inverse] - true for outbound (subscription) transformation @returns
[ "transforms", "data", "at", "datapath", "with", "context", "at", "filepath" ]
d7aedd03e49ce5da6e45ab821f54b16d4d4409df
https://github.com/Yodata/yodata/blob/d7aedd03e49ce5da6e45ab821f54b16d4d4409df/packages/context-sdk/lib/transform/index.js#L18-L27
train
linzjs/linz
lib/api/formtools/list.js
renderFilters
function renderFilters (req, modelName, cb) { if (!req) { throw new Error('req is required.'); } if (typeof modelName !== 'string' || !modelName.length) { throw new Error('modelName is required and must be of type String and cannot be empty.'); } linz.api.model.list(req, modelName, function (err, list) { if (err) { return cb(err); } if (!Object.keys(list.filters).length) { return cb(null); } async.each(Object.keys(list.filters), function (fieldName, filtersDone) { // call the filter renderer and update the content with the result list.filters[fieldName].filter.renderer(fieldName, function (filterErr, result) { if (filterErr) { return filtersDone(filterErr); } list.filters[fieldName].formControls = result; return filtersDone(null); }); }, function (filterErr) { return cb(filterErr, list.filters); }); }); }
javascript
function renderFilters (req, modelName, cb) { if (!req) { throw new Error('req is required.'); } if (typeof modelName !== 'string' || !modelName.length) { throw new Error('modelName is required and must be of type String and cannot be empty.'); } linz.api.model.list(req, modelName, function (err, list) { if (err) { return cb(err); } if (!Object.keys(list.filters).length) { return cb(null); } async.each(Object.keys(list.filters), function (fieldName, filtersDone) { // call the filter renderer and update the content with the result list.filters[fieldName].filter.renderer(fieldName, function (filterErr, result) { if (filterErr) { return filtersDone(filterErr); } list.filters[fieldName].formControls = result; return filtersDone(null); }); }, function (filterErr) { return cb(filterErr, list.filters); }); }); }
[ "function", "renderFilters", "(", "req", ",", "modelName", ",", "cb", ")", "{", "if", "(", "!", "req", ")", "{", "throw", "new", "Error", "(", "'req is required.'", ")", ";", "}", "if", "(", "typeof", "modelName", "!==", "'string'", "||", "!", "modelName", ".", "length", ")", "{", "throw", "new", "Error", "(", "'modelName is required and must be of type String and cannot be empty.'", ")", ";", "}", "linz", ".", "api", ".", "model", ".", "list", "(", "req", ",", "modelName", ",", "function", "(", "err", ",", "list", ")", "{", "if", "(", "err", ")", "{", "return", "cb", "(", "err", ")", ";", "}", "if", "(", "!", "Object", ".", "keys", "(", "list", ".", "filters", ")", ".", "length", ")", "{", "return", "cb", "(", "null", ")", ";", "}", "async", ".", "each", "(", "Object", ".", "keys", "(", "list", ".", "filters", ")", ",", "function", "(", "fieldName", ",", "filtersDone", ")", "{", "// call the filter renderer and update the content with the result", "list", ".", "filters", "[", "fieldName", "]", ".", "filter", ".", "renderer", "(", "fieldName", ",", "function", "(", "filterErr", ",", "result", ")", "{", "if", "(", "filterErr", ")", "{", "return", "filtersDone", "(", "filterErr", ")", ";", "}", "list", ".", "filters", "[", "fieldName", "]", ".", "formControls", "=", "result", ";", "return", "filtersDone", "(", "null", ")", ";", "}", ")", ";", "}", ",", "function", "(", "filterErr", ")", "{", "return", "cb", "(", "filterErr", ",", "list", ".", "filters", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Get list filter settings and execute render method to obtain the HTML markup @param {String} req A HTTP request object. @param {String} modelName Name of model @param {Function} cb Callback function @return {Object} or undefined @api public
[ "Get", "list", "filter", "settings", "and", "execute", "render", "method", "to", "obtain", "the", "HTML", "markup" ]
0ac03e722747406d29f9e1eed7e96b6be04456e8
https://github.com/linzjs/linz/blob/0ac03e722747406d29f9e1eed7e96b6be04456e8/lib/api/formtools/list.js#L64-L107
train
linzjs/linz
lib/api/formtools/list.js
renderSearchFilters
function renderSearchFilters(req, fieldNames, data, modelName, cb) { if (!req) { throw new Error('req is required.'); } if (!Array.isArray(fieldNames) || !fieldNames.length) { throw new Error('fieldNames is required and must be of type Array and cannot be empty.'); } if (typeof modelName !== 'string' || !modelName.length) { throw new Error('modelName is required and must be of type String and cannot be empty.'); } if (!(!Object.is(data, null) && !Array.isArray(data) && data === Object(data))) { throw new Error('data is required and must be of type Object.'); } // Sort fieldNames (to make MongoDB queries more predictable, and therefore easier to create indexes for), remove duplicates, and remove anything that doesn't have associated data. fieldNames = dedupe(fieldNames.sort().filter(fieldName => Object.keys(data).indexOf(fieldName) >= 0)); linz.api.model.list(req, modelName, function (err, list) { if (err) { return cb(err); } if (!Object.keys(list.filters).length) { return cb(null); } var model = linz.api.model.get(modelName), dataKeys = Object.keys(data), filters = {}; async.each(fieldNames, function (fieldName, filtersDone) { if (!dataKeys.includes(fieldName)) { return filtersDone(null); } // call the filter renderer and update the content with the result list.filters[fieldName].filter.filter(fieldName, data, function (filterErr, result) { if (filterErr) { return filtersDone(filterErr); } filters = model.addSearchFilter(filters, result); return filtersDone(null); }); }, function (filterErr) { if (filterErr) { return cb(filterErr); } // consolidate filters into query filters = model.setFiltersAsQuery(filters); return cb(filterErr, filters); }); }); }
javascript
function renderSearchFilters(req, fieldNames, data, modelName, cb) { if (!req) { throw new Error('req is required.'); } if (!Array.isArray(fieldNames) || !fieldNames.length) { throw new Error('fieldNames is required and must be of type Array and cannot be empty.'); } if (typeof modelName !== 'string' || !modelName.length) { throw new Error('modelName is required and must be of type String and cannot be empty.'); } if (!(!Object.is(data, null) && !Array.isArray(data) && data === Object(data))) { throw new Error('data is required and must be of type Object.'); } // Sort fieldNames (to make MongoDB queries more predictable, and therefore easier to create indexes for), remove duplicates, and remove anything that doesn't have associated data. fieldNames = dedupe(fieldNames.sort().filter(fieldName => Object.keys(data).indexOf(fieldName) >= 0)); linz.api.model.list(req, modelName, function (err, list) { if (err) { return cb(err); } if (!Object.keys(list.filters).length) { return cb(null); } var model = linz.api.model.get(modelName), dataKeys = Object.keys(data), filters = {}; async.each(fieldNames, function (fieldName, filtersDone) { if (!dataKeys.includes(fieldName)) { return filtersDone(null); } // call the filter renderer and update the content with the result list.filters[fieldName].filter.filter(fieldName, data, function (filterErr, result) { if (filterErr) { return filtersDone(filterErr); } filters = model.addSearchFilter(filters, result); return filtersDone(null); }); }, function (filterErr) { if (filterErr) { return cb(filterErr); } // consolidate filters into query filters = model.setFiltersAsQuery(filters); return cb(filterErr, filters); }); }); }
[ "function", "renderSearchFilters", "(", "req", ",", "fieldNames", ",", "data", ",", "modelName", ",", "cb", ")", "{", "if", "(", "!", "req", ")", "{", "throw", "new", "Error", "(", "'req is required.'", ")", ";", "}", "if", "(", "!", "Array", ".", "isArray", "(", "fieldNames", ")", "||", "!", "fieldNames", ".", "length", ")", "{", "throw", "new", "Error", "(", "'fieldNames is required and must be of type Array and cannot be empty.'", ")", ";", "}", "if", "(", "typeof", "modelName", "!==", "'string'", "||", "!", "modelName", ".", "length", ")", "{", "throw", "new", "Error", "(", "'modelName is required and must be of type String and cannot be empty.'", ")", ";", "}", "if", "(", "!", "(", "!", "Object", ".", "is", "(", "data", ",", "null", ")", "&&", "!", "Array", ".", "isArray", "(", "data", ")", "&&", "data", "===", "Object", "(", "data", ")", ")", ")", "{", "throw", "new", "Error", "(", "'data is required and must be of type Object.'", ")", ";", "}", "// Sort fieldNames (to make MongoDB queries more predictable, and therefore easier to create indexes for), remove duplicates, and remove anything that doesn't have associated data.", "fieldNames", "=", "dedupe", "(", "fieldNames", ".", "sort", "(", ")", ".", "filter", "(", "fieldName", "=>", "Object", ".", "keys", "(", "data", ")", ".", "indexOf", "(", "fieldName", ")", ">=", "0", ")", ")", ";", "linz", ".", "api", ".", "model", ".", "list", "(", "req", ",", "modelName", ",", "function", "(", "err", ",", "list", ")", "{", "if", "(", "err", ")", "{", "return", "cb", "(", "err", ")", ";", "}", "if", "(", "!", "Object", ".", "keys", "(", "list", ".", "filters", ")", ".", "length", ")", "{", "return", "cb", "(", "null", ")", ";", "}", "var", "model", "=", "linz", ".", "api", ".", "model", ".", "get", "(", "modelName", ")", ",", "dataKeys", "=", "Object", ".", "keys", "(", "data", ")", ",", "filters", "=", "{", "}", ";", "async", ".", "each", "(", "fieldNames", ",", "function", "(", "fieldName", ",", "filtersDone", ")", "{", "if", "(", "!", "dataKeys", ".", "includes", "(", "fieldName", ")", ")", "{", "return", "filtersDone", "(", "null", ")", ";", "}", "// call the filter renderer and update the content with the result", "list", ".", "filters", "[", "fieldName", "]", ".", "filter", ".", "filter", "(", "fieldName", ",", "data", ",", "function", "(", "filterErr", ",", "result", ")", "{", "if", "(", "filterErr", ")", "{", "return", "filtersDone", "(", "filterErr", ")", ";", "}", "filters", "=", "model", ".", "addSearchFilter", "(", "filters", ",", "result", ")", ";", "return", "filtersDone", "(", "null", ")", ";", "}", ")", ";", "}", ",", "function", "(", "filterErr", ")", "{", "if", "(", "filterErr", ")", "{", "return", "cb", "(", "filterErr", ")", ";", "}", "// consolidate filters into query", "filters", "=", "model", ".", "setFiltersAsQuery", "(", "filters", ")", ";", "return", "cb", "(", "filterErr", ",", "filters", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Get search filters as a mongodb query @param {Array} fieldNames Field names @param {Object} data Form data @param {String} modelName Name of model @param {Function} cb Callback function @return {Object} or undefined @api public
[ "Get", "search", "filters", "as", "a", "mongodb", "query" ]
0ac03e722747406d29f9e1eed7e96b6be04456e8
https://github.com/linzjs/linz/blob/0ac03e722747406d29f9e1eed7e96b6be04456e8/lib/api/formtools/list.js#L118-L186
train