id
int32
0
58k
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
list
docstring
stringlengths
4
11.8k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
86
226
24,300
exonum/exonum-client
src/blockchain/merkle.js
calcHeight
function calcHeight (count) { let i = 0 while (bigInt(2).pow(i).lt(count)) { i++ } return i }
javascript
function calcHeight (count) { let i = 0 while (bigInt(2).pow(i).lt(count)) { i++ } return i }
[ "function", "calcHeight", "(", "count", ")", "{", "let", "i", "=", "0", "while", "(", "bigInt", "(", "2", ")", ".", "pow", "(", "i", ")", ".", "lt", "(", "count", ")", ")", "{", "i", "++", "}", "return", "i", "}" ]
Calculate height of merkle tree @param {bigInt} count @return {number}
[ "Calculate", "height", "of", "merkle", "tree" ]
edb77abe6479b7e13c667b2f00aa2dca97d4c401
https://github.com/exonum/exonum-client/blob/edb77abe6479b7e13c667b2f00aa2dca97d4c401/src/blockchain/merkle.js#L13-L19
24,301
exonum/exonum-client
src/blockchain/merkle.js
getHash
function getHash (data, depth, index) { let element let elementsHash if (depth !== 0 && (depth + 1) !== height) { throw new Error('Value node is on wrong height in tree.') } if (start.gt(index) || end.lt(index)) { throw new Error('Wrong index of value node.') } if (start.plus(elements.length).neq(index)) { throw new Error('Value node is on wrong position in tree.') } if (typeof data === 'string') { if (!validateHexadecimal(data)) { throw new TypeError('Tree element of wrong type is passed. Hexadecimal expected.') } element = data elementsHash = element } else { if (Array.isArray(data)) { if (!validateBytesArray(data)) { throw new TypeError('Tree element of wrong type is passed. Bytes array expected.') } element = data.slice(0) // clone array of 8-bit integers elementsHash = hash(element) } else { if (!isObject(data)) { throw new TypeError('Invalid value of data parameter.') } if (!isType(type)) { throw new TypeError('Invalid type of type parameter.') } element = data elementsHash = hash(element, type) } } elements.push(element) return elementsHash }
javascript
function getHash (data, depth, index) { let element let elementsHash if (depth !== 0 && (depth + 1) !== height) { throw new Error('Value node is on wrong height in tree.') } if (start.gt(index) || end.lt(index)) { throw new Error('Wrong index of value node.') } if (start.plus(elements.length).neq(index)) { throw new Error('Value node is on wrong position in tree.') } if (typeof data === 'string') { if (!validateHexadecimal(data)) { throw new TypeError('Tree element of wrong type is passed. Hexadecimal expected.') } element = data elementsHash = element } else { if (Array.isArray(data)) { if (!validateBytesArray(data)) { throw new TypeError('Tree element of wrong type is passed. Bytes array expected.') } element = data.slice(0) // clone array of 8-bit integers elementsHash = hash(element) } else { if (!isObject(data)) { throw new TypeError('Invalid value of data parameter.') } if (!isType(type)) { throw new TypeError('Invalid type of type parameter.') } element = data elementsHash = hash(element, type) } } elements.push(element) return elementsHash }
[ "function", "getHash", "(", "data", ",", "depth", ",", "index", ")", "{", "let", "element", "let", "elementsHash", "if", "(", "depth", "!==", "0", "&&", "(", "depth", "+", "1", ")", "!==", "height", ")", "{", "throw", "new", "Error", "(", "'Value node is on wrong height in tree.'", ")", "}", "if", "(", "start", ".", "gt", "(", "index", ")", "||", "end", ".", "lt", "(", "index", ")", ")", "{", "throw", "new", "Error", "(", "'Wrong index of value node.'", ")", "}", "if", "(", "start", ".", "plus", "(", "elements", ".", "length", ")", ".", "neq", "(", "index", ")", ")", "{", "throw", "new", "Error", "(", "'Value node is on wrong position in tree.'", ")", "}", "if", "(", "typeof", "data", "===", "'string'", ")", "{", "if", "(", "!", "validateHexadecimal", "(", "data", ")", ")", "{", "throw", "new", "TypeError", "(", "'Tree element of wrong type is passed. Hexadecimal expected.'", ")", "}", "element", "=", "data", "elementsHash", "=", "element", "}", "else", "{", "if", "(", "Array", ".", "isArray", "(", "data", ")", ")", "{", "if", "(", "!", "validateBytesArray", "(", "data", ")", ")", "{", "throw", "new", "TypeError", "(", "'Tree element of wrong type is passed. Bytes array expected.'", ")", "}", "element", "=", "data", ".", "slice", "(", "0", ")", "// clone array of 8-bit integers", "elementsHash", "=", "hash", "(", "element", ")", "}", "else", "{", "if", "(", "!", "isObject", "(", "data", ")", ")", "{", "throw", "new", "TypeError", "(", "'Invalid value of data parameter.'", ")", "}", "if", "(", "!", "isType", "(", "type", ")", ")", "{", "throw", "new", "TypeError", "(", "'Invalid type of type parameter.'", ")", "}", "element", "=", "data", "elementsHash", "=", "hash", "(", "element", ",", "type", ")", "}", "}", "elements", ".", "push", "(", "element", ")", "return", "elementsHash", "}" ]
Get value from node, insert into elements array and return its hash @param data @param {number} depth @param {number} index @returns {string}
[ "Get", "value", "from", "node", "insert", "into", "elements", "array", "and", "return", "its", "hash" ]
edb77abe6479b7e13c667b2f00aa2dca97d4c401
https://github.com/exonum/exonum-client/blob/edb77abe6479b7e13c667b2f00aa2dca97d4c401/src/blockchain/merkle.js#L41-L84
24,302
exonum/exonum-client
src/blockchain/merkle.js
recursive
function recursive (node, depth, index) { let hashLeft let hashRight let summingBuffer // case with single node in tree if (depth === 0 && node.val !== undefined) { return getHash(node.val, depth, index * 2) } if (node.left === undefined) { throw new Error('Left node is missed.') } if (typeof node.left === 'string') { if (!validateHexadecimal(node.left)) { throw new TypeError('Tree element of wrong type is passed. Hexadecimal expected.') } hashLeft = node.left } else { if (!isObject(node.left)) { throw new TypeError('Invalid type of left node.') } if (node.left.val !== undefined) { hashLeft = getHash(node.left.val, depth, index * 2) } else { hashLeft = recursive(node.left, depth + 1, index * 2) } } if (depth === 0) { rootBranch = 'right' } if (node.right !== undefined) { if (typeof node.right === 'string') { if (!validateHexadecimal(node.right)) { throw new TypeError('Tree element of wrong type is passed. Hexadecimal expected.') } hashRight = node.right } else { if (!isObject(node.right)) { throw new TypeError('Invalid type of right node.') } if (node.right.val !== undefined) { hashRight = getHash(node.right.val, depth, index * 2 + 1) } else { hashRight = recursive(node.right, depth + 1, index * 2 + 1) } } summingBuffer = new Uint8Array(64) summingBuffer.set(hexadecimalToUint8Array(hashLeft)) summingBuffer.set(hexadecimalToUint8Array(hashRight), 32) return hash(summingBuffer) } if (depth === 0 || rootBranch === 'left') { throw new Error('Right leaf is missed in left branch of tree.') } summingBuffer = hexadecimalToUint8Array(hashLeft) return hash(summingBuffer) }
javascript
function recursive (node, depth, index) { let hashLeft let hashRight let summingBuffer // case with single node in tree if (depth === 0 && node.val !== undefined) { return getHash(node.val, depth, index * 2) } if (node.left === undefined) { throw new Error('Left node is missed.') } if (typeof node.left === 'string') { if (!validateHexadecimal(node.left)) { throw new TypeError('Tree element of wrong type is passed. Hexadecimal expected.') } hashLeft = node.left } else { if (!isObject(node.left)) { throw new TypeError('Invalid type of left node.') } if (node.left.val !== undefined) { hashLeft = getHash(node.left.val, depth, index * 2) } else { hashLeft = recursive(node.left, depth + 1, index * 2) } } if (depth === 0) { rootBranch = 'right' } if (node.right !== undefined) { if (typeof node.right === 'string') { if (!validateHexadecimal(node.right)) { throw new TypeError('Tree element of wrong type is passed. Hexadecimal expected.') } hashRight = node.right } else { if (!isObject(node.right)) { throw new TypeError('Invalid type of right node.') } if (node.right.val !== undefined) { hashRight = getHash(node.right.val, depth, index * 2 + 1) } else { hashRight = recursive(node.right, depth + 1, index * 2 + 1) } } summingBuffer = new Uint8Array(64) summingBuffer.set(hexadecimalToUint8Array(hashLeft)) summingBuffer.set(hexadecimalToUint8Array(hashRight), 32) return hash(summingBuffer) } if (depth === 0 || rootBranch === 'left') { throw new Error('Right leaf is missed in left branch of tree.') } summingBuffer = hexadecimalToUint8Array(hashLeft) return hash(summingBuffer) }
[ "function", "recursive", "(", "node", ",", "depth", ",", "index", ")", "{", "let", "hashLeft", "let", "hashRight", "let", "summingBuffer", "// case with single node in tree", "if", "(", "depth", "===", "0", "&&", "node", ".", "val", "!==", "undefined", ")", "{", "return", "getHash", "(", "node", ".", "val", ",", "depth", ",", "index", "*", "2", ")", "}", "if", "(", "node", ".", "left", "===", "undefined", ")", "{", "throw", "new", "Error", "(", "'Left node is missed.'", ")", "}", "if", "(", "typeof", "node", ".", "left", "===", "'string'", ")", "{", "if", "(", "!", "validateHexadecimal", "(", "node", ".", "left", ")", ")", "{", "throw", "new", "TypeError", "(", "'Tree element of wrong type is passed. Hexadecimal expected.'", ")", "}", "hashLeft", "=", "node", ".", "left", "}", "else", "{", "if", "(", "!", "isObject", "(", "node", ".", "left", ")", ")", "{", "throw", "new", "TypeError", "(", "'Invalid type of left node.'", ")", "}", "if", "(", "node", ".", "left", ".", "val", "!==", "undefined", ")", "{", "hashLeft", "=", "getHash", "(", "node", ".", "left", ".", "val", ",", "depth", ",", "index", "*", "2", ")", "}", "else", "{", "hashLeft", "=", "recursive", "(", "node", ".", "left", ",", "depth", "+", "1", ",", "index", "*", "2", ")", "}", "}", "if", "(", "depth", "===", "0", ")", "{", "rootBranch", "=", "'right'", "}", "if", "(", "node", ".", "right", "!==", "undefined", ")", "{", "if", "(", "typeof", "node", ".", "right", "===", "'string'", ")", "{", "if", "(", "!", "validateHexadecimal", "(", "node", ".", "right", ")", ")", "{", "throw", "new", "TypeError", "(", "'Tree element of wrong type is passed. Hexadecimal expected.'", ")", "}", "hashRight", "=", "node", ".", "right", "}", "else", "{", "if", "(", "!", "isObject", "(", "node", ".", "right", ")", ")", "{", "throw", "new", "TypeError", "(", "'Invalid type of right node.'", ")", "}", "if", "(", "node", ".", "right", ".", "val", "!==", "undefined", ")", "{", "hashRight", "=", "getHash", "(", "node", ".", "right", ".", "val", ",", "depth", ",", "index", "*", "2", "+", "1", ")", "}", "else", "{", "hashRight", "=", "recursive", "(", "node", ".", "right", ",", "depth", "+", "1", ",", "index", "*", "2", "+", "1", ")", "}", "}", "summingBuffer", "=", "new", "Uint8Array", "(", "64", ")", "summingBuffer", ".", "set", "(", "hexadecimalToUint8Array", "(", "hashLeft", ")", ")", "summingBuffer", ".", "set", "(", "hexadecimalToUint8Array", "(", "hashRight", ")", ",", "32", ")", "return", "hash", "(", "summingBuffer", ")", "}", "if", "(", "depth", "===", "0", "||", "rootBranch", "===", "'left'", ")", "{", "throw", "new", "Error", "(", "'Right leaf is missed in left branch of tree.'", ")", "}", "summingBuffer", "=", "hexadecimalToUint8Array", "(", "hashLeft", ")", "return", "hash", "(", "summingBuffer", ")", "}" ]
Recursive tree traversal function @param {Object} node @param {number} depth @param {number} index @returns {string}
[ "Recursive", "tree", "traversal", "function" ]
edb77abe6479b7e13c667b2f00aa2dca97d4c401
https://github.com/exonum/exonum-client/blob/edb77abe6479b7e13c667b2f00aa2dca97d4c401/src/blockchain/merkle.js#L93-L155
24,303
exonum/exonum-client
src/blockchain/ProofPath.js
setBit
function setBit (buffer, pos, bit) { const byte = Math.floor(pos / 8) const bitPos = pos % 8 if (bit === 0) { const mask = 255 - (1 << bitPos) buffer[byte] &= mask } else { const mask = (1 << bitPos) buffer[byte] |= mask } }
javascript
function setBit (buffer, pos, bit) { const byte = Math.floor(pos / 8) const bitPos = pos % 8 if (bit === 0) { const mask = 255 - (1 << bitPos) buffer[byte] &= mask } else { const mask = (1 << bitPos) buffer[byte] |= mask } }
[ "function", "setBit", "(", "buffer", ",", "pos", ",", "bit", ")", "{", "const", "byte", "=", "Math", ".", "floor", "(", "pos", "/", "8", ")", "const", "bitPos", "=", "pos", "%", "8", "if", "(", "bit", "===", "0", ")", "{", "const", "mask", "=", "255", "-", "(", "1", "<<", "bitPos", ")", "buffer", "[", "byte", "]", "&=", "mask", "}", "else", "{", "const", "mask", "=", "(", "1", "<<", "bitPos", ")", "buffer", "[", "byte", "]", "|=", "mask", "}", "}" ]
Sets a specified bit in the byte buffer. @param {Uint8Array} buffer @param {number} pos 0-based position in the buffer to set @param {0 | 1} bit
[ "Sets", "a", "specified", "bit", "in", "the", "byte", "buffer", "." ]
edb77abe6479b7e13c667b2f00aa2dca97d4c401
https://github.com/exonum/exonum-client/blob/edb77abe6479b7e13c667b2f00aa2dca97d4c401/src/blockchain/ProofPath.js#L167-L178
24,304
exonum/exonum-client
src/blockchain/table.js
serializeKey
function serializeKey (serviceId, tableIndex) { let buffer = [] Uint16.serialize(serviceId, buffer, buffer.length) Uint16.serialize(tableIndex, buffer, buffer.length) return buffer }
javascript
function serializeKey (serviceId, tableIndex) { let buffer = [] Uint16.serialize(serviceId, buffer, buffer.length) Uint16.serialize(tableIndex, buffer, buffer.length) return buffer }
[ "function", "serializeKey", "(", "serviceId", ",", "tableIndex", ")", "{", "let", "buffer", "=", "[", "]", "Uint16", ".", "serialize", "(", "serviceId", ",", "buffer", ",", "buffer", ".", "length", ")", "Uint16", ".", "serialize", "(", "tableIndex", ",", "buffer", ",", "buffer", ".", "length", ")", "return", "buffer", "}" ]
Serialization table key @param {number} serviceId @param {number} tableIndex @returns {Array}
[ "Serialization", "table", "key" ]
edb77abe6479b7e13c667b2f00aa2dca97d4c401
https://github.com/exonum/exonum-client/blob/edb77abe6479b7e13c667b2f00aa2dca97d4c401/src/blockchain/table.js#L12-L17
24,305
mercadolibre/chico
dist/ui/chico.js
setAsyncContent
function setAsyncContent(event) { that._content.innerHTML = event.response; /** * Event emitted when the content change. * @event ch.Content#contentchange * @private */ that.emit('_contentchange'); /** * Event emitted if the content is loaded successfully. * @event ch.Content#contentdone * @ignore */ /** * Event emitted when the content is loading. * @event ch.Content#contentwaiting * @example * // Subscribe to "contentwaiting" event. * component.on('contentwaiting', function (event) { * // Some code here! * }); */ /** * Event emitted if the content isn't loaded successfully. * @event ch.Content#contenterror * @example * // Subscribe to "contenterror" event. * component.on('contenterror', function (event) { * // Some code here! * }); */ that.emit('content' + event.status, event); }
javascript
function setAsyncContent(event) { that._content.innerHTML = event.response; /** * Event emitted when the content change. * @event ch.Content#contentchange * @private */ that.emit('_contentchange'); /** * Event emitted if the content is loaded successfully. * @event ch.Content#contentdone * @ignore */ /** * Event emitted when the content is loading. * @event ch.Content#contentwaiting * @example * // Subscribe to "contentwaiting" event. * component.on('contentwaiting', function (event) { * // Some code here! * }); */ /** * Event emitted if the content isn't loaded successfully. * @event ch.Content#contenterror * @example * // Subscribe to "contenterror" event. * component.on('contenterror', function (event) { * // Some code here! * }); */ that.emit('content' + event.status, event); }
[ "function", "setAsyncContent", "(", "event", ")", "{", "that", ".", "_content", ".", "innerHTML", "=", "event", ".", "response", ";", "/**\n * Event emitted when the content change.\n * @event ch.Content#contentchange\n * @private\n */", "that", ".", "emit", "(", "'_contentchange'", ")", ";", "/**\n * Event emitted if the content is loaded successfully.\n * @event ch.Content#contentdone\n * @ignore\n */", "/**\n * Event emitted when the content is loading.\n * @event ch.Content#contentwaiting\n * @example\n * // Subscribe to \"contentwaiting\" event.\n * component.on('contentwaiting', function (event) {\n * // Some code here!\n * });\n */", "/**\n * Event emitted if the content isn't loaded successfully.\n * @event ch.Content#contenterror\n * @example\n * // Subscribe to \"contenterror\" event.\n * component.on('contenterror', function (event) {\n * // Some code here!\n * });\n */", "that", ".", "emit", "(", "'content'", "+", "event", ".", "status", ",", "event", ")", ";", "}" ]
Set async content into component's container and emits the current event. @private
[ "Set", "async", "content", "into", "component", "s", "container", "and", "emits", "the", "current", "event", "." ]
97fe3013b12281728d479c1eb63ea5b8f65dc39b
https://github.com/mercadolibre/chico/blob/97fe3013b12281728d479c1eb63ea5b8f65dc39b/dist/ui/chico.js#L181-L219
24,306
mercadolibre/chico
dist/ui/chico.js
setContent
function setContent(content) { if (content.nodeType !== undefined) { that._content.innerHTML = ''; that._content.appendChild(content); } else { that._content.innerHTML = content; } that._options.cache = true; /** * Event emitted when the content change. * @event ch.Content#contentchange * @private */ that.emit('_contentchange'); /** * Event emitted if the content is loaded successfully. * @event ch.Content#contentdone * @example * // Subscribe to "contentdone" event. * component.on('contentdone', function (event) { * // Some code here! * }); */ that.emit('contentdone'); }
javascript
function setContent(content) { if (content.nodeType !== undefined) { that._content.innerHTML = ''; that._content.appendChild(content); } else { that._content.innerHTML = content; } that._options.cache = true; /** * Event emitted when the content change. * @event ch.Content#contentchange * @private */ that.emit('_contentchange'); /** * Event emitted if the content is loaded successfully. * @event ch.Content#contentdone * @example * // Subscribe to "contentdone" event. * component.on('contentdone', function (event) { * // Some code here! * }); */ that.emit('contentdone'); }
[ "function", "setContent", "(", "content", ")", "{", "if", "(", "content", ".", "nodeType", "!==", "undefined", ")", "{", "that", ".", "_content", ".", "innerHTML", "=", "''", ";", "that", ".", "_content", ".", "appendChild", "(", "content", ")", ";", "}", "else", "{", "that", ".", "_content", ".", "innerHTML", "=", "content", ";", "}", "that", ".", "_options", ".", "cache", "=", "true", ";", "/**\n * Event emitted when the content change.\n * @event ch.Content#contentchange\n * @private\n */", "that", ".", "emit", "(", "'_contentchange'", ")", ";", "/**\n * Event emitted if the content is loaded successfully.\n * @event ch.Content#contentdone\n * @example\n * // Subscribe to \"contentdone\" event.\n * component.on('contentdone', function (event) {\n * // Some code here!\n * });\n */", "that", ".", "emit", "(", "'contentdone'", ")", ";", "}" ]
Set content into component's container and emits the contentdone event. @private
[ "Set", "content", "into", "component", "s", "container", "and", "emits", "the", "contentdone", "event", "." ]
97fe3013b12281728d479c1eb63ea5b8f65dc39b
https://github.com/mercadolibre/chico/blob/97fe3013b12281728d479c1eb63ea5b8f65dc39b/dist/ui/chico.js#L225-L254
24,307
mercadolibre/chico
dist/ui/chico.js
getAsyncContent
function getAsyncContent(url, options) { var requestCfg; // Initial options to be merged with the user's options options = tiny.extend({ 'method': 'GET', 'params': '', 'waiting': '<div class="ch-loading-large"></div>' }, defaults, options); // Set loading setAsyncContent({ 'status': 'waiting', 'response': options.waiting }); requestCfg = { method: options.method, success: function(resp) { setAsyncContent({ 'status': 'done', 'response': resp }); }, error: function(err) { setAsyncContent({ 'status': 'error', 'response': '<p>Error on ajax call.</p>', 'data': err.message || JSON.stringify(err) }); } }; if (options.cache !== undefined) { that._options.cache = options.cache; } if (options.cache === false && ['GET', 'HEAD'].indexOf(options.method.toUpperCase()) !== -1) { requestCfg.cache = false; } if (options.params) { if (['GET', 'HEAD'].indexOf(options.method.toUpperCase()) !== -1) { url += (url.indexOf('?') !== -1 || options.params[0] === '?' ? '' : '?') + options.params; } else { requestCfg.data = options.params; } } // Make a request tiny.ajax(url, requestCfg); }
javascript
function getAsyncContent(url, options) { var requestCfg; // Initial options to be merged with the user's options options = tiny.extend({ 'method': 'GET', 'params': '', 'waiting': '<div class="ch-loading-large"></div>' }, defaults, options); // Set loading setAsyncContent({ 'status': 'waiting', 'response': options.waiting }); requestCfg = { method: options.method, success: function(resp) { setAsyncContent({ 'status': 'done', 'response': resp }); }, error: function(err) { setAsyncContent({ 'status': 'error', 'response': '<p>Error on ajax call.</p>', 'data': err.message || JSON.stringify(err) }); } }; if (options.cache !== undefined) { that._options.cache = options.cache; } if (options.cache === false && ['GET', 'HEAD'].indexOf(options.method.toUpperCase()) !== -1) { requestCfg.cache = false; } if (options.params) { if (['GET', 'HEAD'].indexOf(options.method.toUpperCase()) !== -1) { url += (url.indexOf('?') !== -1 || options.params[0] === '?' ? '' : '?') + options.params; } else { requestCfg.data = options.params; } } // Make a request tiny.ajax(url, requestCfg); }
[ "function", "getAsyncContent", "(", "url", ",", "options", ")", "{", "var", "requestCfg", ";", "// Initial options to be merged with the user's options", "options", "=", "tiny", ".", "extend", "(", "{", "'method'", ":", "'GET'", ",", "'params'", ":", "''", ",", "'waiting'", ":", "'<div class=\"ch-loading-large\"></div>'", "}", ",", "defaults", ",", "options", ")", ";", "// Set loading", "setAsyncContent", "(", "{", "'status'", ":", "'waiting'", ",", "'response'", ":", "options", ".", "waiting", "}", ")", ";", "requestCfg", "=", "{", "method", ":", "options", ".", "method", ",", "success", ":", "function", "(", "resp", ")", "{", "setAsyncContent", "(", "{", "'status'", ":", "'done'", ",", "'response'", ":", "resp", "}", ")", ";", "}", ",", "error", ":", "function", "(", "err", ")", "{", "setAsyncContent", "(", "{", "'status'", ":", "'error'", ",", "'response'", ":", "'<p>Error on ajax call.</p>'", ",", "'data'", ":", "err", ".", "message", "||", "JSON", ".", "stringify", "(", "err", ")", "}", ")", ";", "}", "}", ";", "if", "(", "options", ".", "cache", "!==", "undefined", ")", "{", "that", ".", "_options", ".", "cache", "=", "options", ".", "cache", ";", "}", "if", "(", "options", ".", "cache", "===", "false", "&&", "[", "'GET'", ",", "'HEAD'", "]", ".", "indexOf", "(", "options", ".", "method", ".", "toUpperCase", "(", ")", ")", "!==", "-", "1", ")", "{", "requestCfg", ".", "cache", "=", "false", ";", "}", "if", "(", "options", ".", "params", ")", "{", "if", "(", "[", "'GET'", ",", "'HEAD'", "]", ".", "indexOf", "(", "options", ".", "method", ".", "toUpperCase", "(", ")", ")", "!==", "-", "1", ")", "{", "url", "+=", "(", "url", ".", "indexOf", "(", "'?'", ")", "!==", "-", "1", "||", "options", ".", "params", "[", "0", "]", "===", "'?'", "?", "''", ":", "'?'", ")", "+", "options", ".", "params", ";", "}", "else", "{", "requestCfg", ".", "data", "=", "options", ".", "params", ";", "}", "}", "// Make a request", "tiny", ".", "ajax", "(", "url", ",", "requestCfg", ")", ";", "}" ]
Get async content with given URL. @private
[ "Get", "async", "content", "with", "given", "URL", "." ]
97fe3013b12281728d479c1eb63ea5b8f65dc39b
https://github.com/mercadolibre/chico/blob/97fe3013b12281728d479c1eb63ea5b8f65dc39b/dist/ui/chico.js#L260-L310
24,308
mercadolibre/chico
dist/ui/chico.js
Positioner
function Positioner(options) { if (options === undefined) { throw new window.Error('ch.Positioner: Expected options defined.'); } // Creates its private options this._options = tiny.clone(this._defaults); // Init this._configure(options); }
javascript
function Positioner(options) { if (options === undefined) { throw new window.Error('ch.Positioner: Expected options defined.'); } // Creates its private options this._options = tiny.clone(this._defaults); // Init this._configure(options); }
[ "function", "Positioner", "(", "options", ")", "{", "if", "(", "options", "===", "undefined", ")", "{", "throw", "new", "window", ".", "Error", "(", "'ch.Positioner: Expected options defined.'", ")", ";", "}", "// Creates its private options", "this", ".", "_options", "=", "tiny", ".", "clone", "(", "this", ".", "_defaults", ")", ";", "// Init", "this", ".", "_configure", "(", "options", ")", ";", "}" ]
The Positioner lets you position elements on the screen and changes its positions. @memberof ch @constructor @param {Object} options Configuration object. @param {String} options.target A HTMLElement that reference to the element to be positioned. @param {String} [options.reference] A HTMLElement that it's a reference to position and size of element that will be considered to carry out the position. If it isn't defined through configuration, it will be the ch.viewport. @param {String} [options.side] The side option where the target element will be positioned. You must use: "left", "right", "top", "bottom" or "center". Default: "center". @param {String} [options.align] The align options where the target element will be positioned. You must use: "left", "right", "top", "bottom" or "center". Default: "center". @param {Number} [options.offsetX] Distance to displace the target horizontally. Default: 0. @param {Number} [options.offsetY] Distance to displace the target vertically. Default: 0. @param {String} [options.position] Thethe type of positioning used. You must use: "absolute" or "fixed". Default: "fixed". @requires ch.Viewport @returns {positioner} Returns a new instance of Positioner. @example // Instance the Positioner It requires a little configuration. // The default behavior place an element center into the Viewport. var positioned = new ch.Positioner({ 'target': document.querySelector('.target'), 'reference': document.querySelector('.reference'), 'side': 'top', 'align': 'left', 'offsetX': 20, 'offsetY': 10 }); @example // offsetX: The Positioner could be configurated with an offsetX. // This example show an element displaced horizontally by 10px of defined position. var positioned = new ch.Positioner({ 'target': document.querySelector('.target'), 'reference': document.querySelector('.reference'), 'side': 'top', 'align': 'left', 'offsetX': 10 }); @example // offsetY: The Positioner could be configurated with an offsetY. // This example show an element displaced vertically by 10px of defined position. var positioned = new ch.Positioner({ 'target': document.querySelector('.target'), 'reference': document.querySelector('.reference'), 'side': 'top', 'align': 'left', 'offsetY': 10 }); @example // positioned: The positioner could be configured to work with fixed or absolute position value. var positioned = new ch.Positioner({ 'target': document.querySelector('.target'), 'reference': document.querySelector('.reference'), 'position': 'fixed' });
[ "The", "Positioner", "lets", "you", "position", "elements", "on", "the", "screen", "and", "changes", "its", "positions", "." ]
97fe3013b12281728d479c1eb63ea5b8f65dc39b
https://github.com/mercadolibre/chico/blob/97fe3013b12281728d479c1eb63ea5b8f65dc39b/dist/ui/chico.js#L1030-L1041
24,309
mercadolibre/chico
dist/ui/chico.js
function (shortcut, name, callback) { if (this._collection[name] === undefined) { this._collection[name] = {}; } if (this._collection[name][shortcut] === undefined) { this._collection[name][shortcut] = []; } this._collection[name][shortcut].push(callback); return this; }
javascript
function (shortcut, name, callback) { if (this._collection[name] === undefined) { this._collection[name] = {}; } if (this._collection[name][shortcut] === undefined) { this._collection[name][shortcut] = []; } this._collection[name][shortcut].push(callback); return this; }
[ "function", "(", "shortcut", ",", "name", ",", "callback", ")", "{", "if", "(", "this", ".", "_collection", "[", "name", "]", "===", "undefined", ")", "{", "this", ".", "_collection", "[", "name", "]", "=", "{", "}", ";", "}", "if", "(", "this", ".", "_collection", "[", "name", "]", "[", "shortcut", "]", "===", "undefined", ")", "{", "this", ".", "_collection", "[", "name", "]", "[", "shortcut", "]", "=", "[", "]", ";", "}", "this", ".", "_collection", "[", "name", "]", "[", "shortcut", "]", ".", "push", "(", "callback", ")", ";", "return", "this", ";", "}" ]
Add a callback to a shortcut with given name. @param {(ch.onkeybackspace | ch.onkeytab | ch.onkeyenter | ch.onkeyesc | ch.onkeyleftarrow | ch.onkeyuparrow | ch.onkeyrightarrow | ch.onkeydownarrow)} shortcut Shortcut to subscribe. @param {String} name A name to add in the collection. @param {Function} callback A given function. @returns {Object} Retuns the ch.shortcuts. @example // Add a callback to ESC key with "component" name. ch.shortcuts.add(ch.onkeyesc, 'component', component.hide);
[ "Add", "a", "callback", "to", "a", "shortcut", "with", "given", "name", "." ]
97fe3013b12281728d479c1eb63ea5b8f65dc39b
https://github.com/mercadolibre/chico/blob/97fe3013b12281728d479c1eb63ea5b8f65dc39b/dist/ui/chico.js#L1308-L1322
24,310
mercadolibre/chico
dist/ui/chico.js
function (name, shortcut, callback) { var evt, evtCollection, evtCollectionLenght; if (name === undefined) { throw new Error('Shortcuts - "remove(name, shortcut, callback)": "name" parameter must be defined.'); } if (shortcut === undefined) { delete this._collection[name]; return this; } if (callback === undefined) { delete this._collection[name][shortcut]; return this; } evtCollection = this._collection[name][shortcut]; evtCollectionLenght = evtCollection.length; for (evt = 0; evt < evtCollectionLenght; evt += 1) { if (evtCollection[evt] === callback) { evtCollection.splice(evt, 1); } } return this; }
javascript
function (name, shortcut, callback) { var evt, evtCollection, evtCollectionLenght; if (name === undefined) { throw new Error('Shortcuts - "remove(name, shortcut, callback)": "name" parameter must be defined.'); } if (shortcut === undefined) { delete this._collection[name]; return this; } if (callback === undefined) { delete this._collection[name][shortcut]; return this; } evtCollection = this._collection[name][shortcut]; evtCollectionLenght = evtCollection.length; for (evt = 0; evt < evtCollectionLenght; evt += 1) { if (evtCollection[evt] === callback) { evtCollection.splice(evt, 1); } } return this; }
[ "function", "(", "name", ",", "shortcut", ",", "callback", ")", "{", "var", "evt", ",", "evtCollection", ",", "evtCollectionLenght", ";", "if", "(", "name", "===", "undefined", ")", "{", "throw", "new", "Error", "(", "'Shortcuts - \"remove(name, shortcut, callback)\": \"name\" parameter must be defined.'", ")", ";", "}", "if", "(", "shortcut", "===", "undefined", ")", "{", "delete", "this", ".", "_collection", "[", "name", "]", ";", "return", "this", ";", "}", "if", "(", "callback", "===", "undefined", ")", "{", "delete", "this", ".", "_collection", "[", "name", "]", "[", "shortcut", "]", ";", "return", "this", ";", "}", "evtCollection", "=", "this", ".", "_collection", "[", "name", "]", "[", "shortcut", "]", ";", "evtCollectionLenght", "=", "evtCollection", ".", "length", ";", "for", "(", "evt", "=", "0", ";", "evt", "<", "evtCollectionLenght", ";", "evt", "+=", "1", ")", "{", "if", "(", "evtCollection", "[", "evt", "]", "===", "callback", ")", "{", "evtCollection", ".", "splice", "(", "evt", ",", "1", ")", ";", "}", "}", "return", "this", ";", "}" ]
Removes a callback from a shortcut with given name. @param {String} name A name to remove from the collection. @param {(ch.onkeybackspace | ch.onkeytab | ch.onkeyenter | ch.onkeyesc | ch.onkeyleftarrow | ch.onkeyuparrow | ch.onkeyrightarrow | ch.onkeydownarrow)} [shortcut] Shortcut to unsubscribe. @param {Function} callback A given function. @returns {Object} Retuns the ch.shortcuts. @example // Remove a callback from ESC key with "component" name. ch.shortcuts.remove(ch.onkeyesc, 'component', component.hide);
[ "Removes", "a", "callback", "from", "a", "shortcut", "with", "given", "name", "." ]
97fe3013b12281728d479c1eb63ea5b8f65dc39b
https://github.com/mercadolibre/chico/blob/97fe3013b12281728d479c1eb63ea5b8f65dc39b/dist/ui/chico.js#L1334-L1366
24,311
mercadolibre/chico
dist/ui/chico.js
Tooltip
function Tooltip(el, options) { // TODO: Review what's going on here with options /* if (options === undefined && el !== undefined && el.nodeType !== undefined) { options = el; el = undefined; } */ options = tiny.extend(tiny.clone(this._defaults), options); return new ch.Layer(el, options); }
javascript
function Tooltip(el, options) { // TODO: Review what's going on here with options /* if (options === undefined && el !== undefined && el.nodeType !== undefined) { options = el; el = undefined; } */ options = tiny.extend(tiny.clone(this._defaults), options); return new ch.Layer(el, options); }
[ "function", "Tooltip", "(", "el", ",", "options", ")", "{", "// TODO: Review what's going on here with options", "/*\n if (options === undefined && el !== undefined && el.nodeType !== undefined) {\n options = el;\n el = undefined;\n }\n */", "options", "=", "tiny", ".", "extend", "(", "tiny", ".", "clone", "(", "this", ".", "_defaults", ")", ",", "options", ")", ";", "return", "new", "ch", ".", "Layer", "(", "el", ",", "options", ")", ";", "}" ]
Improves the native tooltips. @memberof ch @constructor @augments ch.Popover @param {HTMLElement} el A HTMLElement to create an instance of ch.Tooltip. @param {Object} [options] Options to customize an instance. @param {String} [options.addClass] CSS class names that will be added to the container on the component initialization. @param {String} [options.fx] Enable or disable UI effects. You must use: "slideDown", "fadeIn" or "none". Default: "fadeIn". @param {String} [options.width] Set a width for the container. Default: "auto". @param {String} [options.height] Set a height for the container. Default: "auto". @param {String} [options.shownby] Determines how to interact with the trigger to show the container. You must use: "pointertap", "pointerenter" or "none". Default: "pointerenter". @param {String} [options.hiddenby] Determines how to hide the component. You must use: "button", "pointers", "pointerleave", "all" or "none". Default: "pointerleave". @param {HTMLElement} [options.reference] It's a reference to position and size of element that will be considered to carry out the position. Default: the trigger element. @param {String} [options.side] The side option where the target element will be positioned. Its value can be: "left", "right", "top", "bottom" or "center". Default: "bottom". @param {String} [options.align] The align options where the target element will be positioned. Its value can be: "left", "right", "top", "bottom" or "center". Default: "left". @param {Number} [options.offsetX] Distance to displace the target horizontally. Default: 0. @param {Number} [options.offsetY] Distance to displace the target vertically. Default: 10. @param {String} [options.position] The type of positioning used. Its value must be "absolute" or "fixed". Default: "absolute". @param {String} [options.method] The type of request ("POST" or "GET") to load content by ajax. Default: "GET". @param {String} [options.params] Params like query string to be sent to the server. @param {Boolean} [options.cache] Force to cache the request by the browser. Default: true. @param {Boolean} [options.async] Force to sent request asynchronously. Default: true. @param {(String | HTMLElement)} [options.waiting] Temporary content to use while the ajax request is loading. Default: '&lt;div class="ch-loading ch-loading-centered"&gt;&lt;/div&gt;'. @param {(String | HTMLElement)} [options.content] The content to be shown into the Tooltip container. @returns {tooltip} Returns a new instance of Tooltip. @example // Create a new Tooltip. var tooltip = new ch.Tooltip(document.querySelector('.trigger'), [options]); @example // Create a new Tooltip using the shorthand way (content as parameter). var tooltip = new ch.Tooltip(document.querySelector('.trigger'), {'content': 'http://ui.ml.com:3040/ajax'});
[ "Improves", "the", "native", "tooltips", "." ]
97fe3013b12281728d479c1eb63ea5b8f65dc39b
https://github.com/mercadolibre/chico/blob/97fe3013b12281728d479c1eb63ea5b8f65dc39b/dist/ui/chico.js#L4562-L4575
24,312
mercadolibre/chico
dist/ui/chico.js
Transition
function Transition(el, options) { if (el === undefined || options === undefined) { options = {}; } options.content = (function () { var dummyElement = document.createElement('div'), content = options.waiting || ''; // TODO: options.content could be a HTMLElement dummyElement.innerHTML = '<div class="ch-loading-large"></div><p>' + content + '</p>'; return dummyElement.firstChild; }()); // el is not defined if (el === undefined) { el = tiny.extend(tiny.clone(this._defaults), options); // el is present as a object configuration } else if (el.nodeType === undefined && typeof el === 'object') { el = tiny.extend(tiny.clone(this._defaults), el); } else if (options !== undefined) { options = tiny.extend(tiny.clone(this._defaults), options); } return new ch.Modal(el, options); }
javascript
function Transition(el, options) { if (el === undefined || options === undefined) { options = {}; } options.content = (function () { var dummyElement = document.createElement('div'), content = options.waiting || ''; // TODO: options.content could be a HTMLElement dummyElement.innerHTML = '<div class="ch-loading-large"></div><p>' + content + '</p>'; return dummyElement.firstChild; }()); // el is not defined if (el === undefined) { el = tiny.extend(tiny.clone(this._defaults), options); // el is present as a object configuration } else if (el.nodeType === undefined && typeof el === 'object') { el = tiny.extend(tiny.clone(this._defaults), el); } else if (options !== undefined) { options = tiny.extend(tiny.clone(this._defaults), options); } return new ch.Modal(el, options); }
[ "function", "Transition", "(", "el", ",", "options", ")", "{", "if", "(", "el", "===", "undefined", "||", "options", "===", "undefined", ")", "{", "options", "=", "{", "}", ";", "}", "options", ".", "content", "=", "(", "function", "(", ")", "{", "var", "dummyElement", "=", "document", ".", "createElement", "(", "'div'", ")", ",", "content", "=", "options", ".", "waiting", "||", "''", ";", "// TODO: options.content could be a HTMLElement", "dummyElement", ".", "innerHTML", "=", "'<div class=\"ch-loading-large\"></div><p>'", "+", "content", "+", "'</p>'", ";", "return", "dummyElement", ".", "firstChild", ";", "}", "(", ")", ")", ";", "// el is not defined", "if", "(", "el", "===", "undefined", ")", "{", "el", "=", "tiny", ".", "extend", "(", "tiny", ".", "clone", "(", "this", ".", "_defaults", ")", ",", "options", ")", ";", "// el is present as a object configuration", "}", "else", "if", "(", "el", ".", "nodeType", "===", "undefined", "&&", "typeof", "el", "===", "'object'", ")", "{", "el", "=", "tiny", ".", "extend", "(", "tiny", ".", "clone", "(", "this", ".", "_defaults", ")", ",", "el", ")", ";", "}", "else", "if", "(", "options", "!==", "undefined", ")", "{", "options", "=", "tiny", ".", "extend", "(", "tiny", ".", "clone", "(", "this", ".", "_defaults", ")", ",", "options", ")", ";", "}", "return", "new", "ch", ".", "Modal", "(", "el", ",", "options", ")", ";", "}" ]
Transition lets you give feedback to the users when their have to wait for an action. @memberof ch @constructor @augments ch.Popover @param {HTMLElement} [el] A HTMLElement to create an instance of ch.Transition. @param {Object} [options] Options to customize an instance. @param {String} [options.addClass] CSS class names that will be added to the container on the component initialization. @param {String} [options.fx] Enable or disable UI effects. You must use: "slideDown", "fadeIn" or "none". Default: "fadeIn". @param {String} [options.width] Set a width for the container. Default: "50%". @param {String} [options.height] Set a height for the container. Default: "auto". @param {String} [options.shownby] Determines how to interact with the trigger to show the container. You must use: "pointertap", "pointerenter" or "none". Default: "pointertap". @param {String} [options.hiddenby] Determines how to hide the component. You must use: "button", "pointers", "pointerleave", "all" or "none". Default: "none". @param {String} [options.reference] It's a reference to position and size of element that will be considered to carry out the position. Default: ch.viewport. @param {String} [options.side] The side option where the target element will be positioned. Its value can be: "left", "right", "top", "bottom" or "center". Default: "center". @param {String} [options.align] The align options where the target element will be positioned. Its value can be: "left", "right", "top", "bottom" or "center". Default: "center". @param {Number} [options.offsetX] Distance to displace the target horizontally. Default: 0. @param {Number} [options.offsetY] Distance to displace the target vertically. Default: 0. @param {String} [options.position] The type of positioning used. Its value must be "absolute" or "fixed". Default: "fixed". @param {String} [options.method] The type of request ("POST" or "GET") to load content by ajax. Default: "GET". @param {String} [options.params] Params like query string to be sent to the server. @param {Boolean} [options.cache] Force to cache the request by the browser. Default: true. @param {Boolean} [options.async] Force to sent request asynchronously. Default: true. @param {(HTMLElement | String)} [options.waiting] Temporary content to use while the ajax request is loading. Default: '&lt;div class="ch-loading-large ch-loading-centered"&gt;&lt;/div&gt;'. @param {(HTMLElement | String)} [options.content] The content to be shown into the Transition container. Default: "Please wait..." @returns {transition} Returns a new instance of Transition. @example // Create a new Transition. var transition = new ch.Transition([el], [options]); @example // Create a new Transition with disabled effects. var transition = new ch.Transition({ 'fx': 'none' }); @example // Create a new Transition using the shorthand way (content as parameter). var transition = new ch.Transition('http://ui.ml.com:3040/ajax');
[ "Transition", "lets", "you", "give", "feedback", "to", "the", "users", "when", "their", "have", "to", "wait", "for", "an", "action", "." ]
97fe3013b12281728d479c1eb63ea5b8f65dc39b
https://github.com/mercadolibre/chico/blob/97fe3013b12281728d479c1eb63ea5b8f65dc39b/dist/ui/chico.js#L5038-L5065
24,313
mercadolibre/chico
dist/ui/chico.js
Countdown
function Countdown(el, options) { /** * Reference to context of an instance. * @type {Object} * @private */ var that = this; this._init(el, options); if (this.initialize !== undefined) { /** * If you define an initialize method, it will be executed when a new Countdown is created. * @memberof! ch.Countdown.prototype * @function */ this.initialize(); } /** * Event emitted when the component is ready to use. * @event ch.Countdown#ready * @example * // Subscribe to "ready" event. * countdown.on('ready', function () { * // Some code here! * }); */ window.setTimeout(function () { that.emit('ready'); }, 50); }
javascript
function Countdown(el, options) { /** * Reference to context of an instance. * @type {Object} * @private */ var that = this; this._init(el, options); if (this.initialize !== undefined) { /** * If you define an initialize method, it will be executed when a new Countdown is created. * @memberof! ch.Countdown.prototype * @function */ this.initialize(); } /** * Event emitted when the component is ready to use. * @event ch.Countdown#ready * @example * // Subscribe to "ready" event. * countdown.on('ready', function () { * // Some code here! * }); */ window.setTimeout(function () { that.emit('ready'); }, 50); }
[ "function", "Countdown", "(", "el", ",", "options", ")", "{", "/**\n * Reference to context of an instance.\n * @type {Object}\n * @private\n */", "var", "that", "=", "this", ";", "this", ".", "_init", "(", "el", ",", "options", ")", ";", "if", "(", "this", ".", "initialize", "!==", "undefined", ")", "{", "/**\n * If you define an initialize method, it will be executed when a new Countdown is created.\n * @memberof! ch.Countdown.prototype\n * @function\n */", "this", ".", "initialize", "(", ")", ";", "}", "/**\n * Event emitted when the component is ready to use.\n * @event ch.Countdown#ready\n * @example\n * // Subscribe to \"ready\" event.\n * countdown.on('ready', function () {\n * // Some code here!\n * });\n */", "window", ".", "setTimeout", "(", "function", "(", ")", "{", "that", ".", "emit", "(", "'ready'", ")", ";", "}", ",", "50", ")", ";", "}" ]
Countdown counts the maximum of characters that user can enter in a form control. Countdown could limit the possibility to continue inserting charset. @memberof ch @constructor @augments ch.Component @param {HTMLElement} el A HTMLElement to create an instance of ch.Countdown. @param {Object} [options] Options to customize an instance. @param {Number} [options.max] Number of the maximum amount of characters user can input in form control. Default: 500. @param {String} [options.plural] Message of remaining amount of characters, when it's different to 1. The variable that represents the number to be replaced, should be a hash. Default: "# characters left.". @param {String} [options.singular] Message of remaining amount of characters, when it's only 1. The variable that represents the number to be replaced, should be a hash. Default: "# character left.". @returns {countdown} Returns a new instance of Countdown. @example // Create a new Countdown. var countdown = new ch.Countdown([el], [options]); @example // Create a new Countdown with custom options. var countdown = new ch.Countdown({ 'max': 250, 'plural': 'Left: # characters.', 'singular': 'Left: # character.' }); @example // Create a new Countdown using the shorthand way (max as parameter). var countdown = new ch.Countdown({'max': 500});
[ "Countdown", "counts", "the", "maximum", "of", "characters", "that", "user", "can", "enter", "in", "a", "form", "control", ".", "Countdown", "could", "limit", "the", "possibility", "to", "continue", "inserting", "charset", "." ]
97fe3013b12281728d479c1eb63ea5b8f65dc39b
https://github.com/mercadolibre/chico/blob/97fe3013b12281728d479c1eb63ea5b8f65dc39b/dist/ui/chico.js#L8405-L8435
24,314
mercadolibre/chico
dist/mobile/chico.js
cancelPointerOnScroll
function cancelPointerOnScroll() { function blockPointer() { ch.pointerCanceled = true; function unblockPointer() { ch.pointerCanceled = false; } tiny.once(document, 'touchend', unblockPointer); } tiny.on(document, 'touchmove', blockPointer); }
javascript
function cancelPointerOnScroll() { function blockPointer() { ch.pointerCanceled = true; function unblockPointer() { ch.pointerCanceled = false; } tiny.once(document, 'touchend', unblockPointer); } tiny.on(document, 'touchmove', blockPointer); }
[ "function", "cancelPointerOnScroll", "(", ")", "{", "function", "blockPointer", "(", ")", "{", "ch", ".", "pointerCanceled", "=", "true", ";", "function", "unblockPointer", "(", ")", "{", "ch", ".", "pointerCanceled", "=", "false", ";", "}", "tiny", ".", "once", "(", "document", ",", "'touchend'", ",", "unblockPointer", ")", ";", "}", "tiny", ".", "on", "(", "document", ",", "'touchmove'", ",", "blockPointer", ")", ";", "}" ]
Cancel pointers if the user scroll. @name cancelPointerOnScroll
[ "Cancel", "pointers", "if", "the", "user", "scroll", "." ]
97fe3013b12281728d479c1eb63ea5b8f65dc39b
https://github.com/mercadolibre/chico/blob/97fe3013b12281728d479c1eb63ea5b8f65dc39b/dist/mobile/chico.js#L130-L143
24,315
stefanocudini/bootstrap-list-filter
bootstrap-list-filter.src.js
tmpl
function tmpl(str, data) { return str.replace(/\{ *([\w_]+) *\}/g, function (str, key) { return data[key] || ''; }); }
javascript
function tmpl(str, data) { return str.replace(/\{ *([\w_]+) *\}/g, function (str, key) { return data[key] || ''; }); }
[ "function", "tmpl", "(", "str", ",", "data", ")", "{", "return", "str", ".", "replace", "(", "/", "\\{ *([\\w_]+) *\\}", "/", "g", ",", "function", "(", "str", ",", "key", ")", "{", "return", "data", "[", "key", "]", "||", "''", ";", "}", ")", ";", "}" ]
last callData execution
[ "last", "callData", "execution" ]
2df9986d71bfbd252b10f6d5384e4bdf9c12f803
https://github.com/stefanocudini/bootstrap-list-filter/blob/2df9986d71bfbd252b10f6d5384e4bdf9c12f803/bootstrap-list-filter.src.js#L30-L34
24,316
jaredhanson/passport-oauth1
lib/strategy.js
OAuthStrategy
function OAuthStrategy(options, verify) { if (typeof options == 'function') { verify = options; options = undefined; } options = options || {}; if (!verify) { throw new TypeError('OAuthStrategy requires a verify callback'); } if (!options.requestTokenURL) { throw new TypeError('OAuthStrategy requires a requestTokenURL option'); } if (!options.accessTokenURL) { throw new TypeError('OAuthStrategy requires a accessTokenURL option'); } if (!options.userAuthorizationURL) { throw new TypeError('OAuthStrategy requires a userAuthorizationURL option'); } if (!options.consumerKey) { throw new TypeError('OAuthStrategy requires a consumerKey option'); } if (options.consumerSecret === undefined) { throw new TypeError('OAuthStrategy requires a consumerSecret option'); } passport.Strategy.call(this); this.name = 'oauth'; this._verify = verify; // NOTE: The _oauth property is considered "protected". Subclasses are // allowed to use it when making protected resource requests to retrieve // the user profile. this._oauth = new OAuth(options.requestTokenURL, options.accessTokenURL, options.consumerKey, options.consumerSecret, '1.0', null, options.signatureMethod || 'HMAC-SHA1', null, options.customHeaders); this._userAuthorizationURL = options.userAuthorizationURL; this._callbackURL = options.callbackURL; this._key = options.sessionKey || 'oauth'; this._requestTokenStore = options.requestTokenStore || new SessionRequestTokenStore({ key: this._key }); this._trustProxy = options.proxy; this._passReqToCallback = options.passReqToCallback; this._skipUserProfile = (options.skipUserProfile === undefined) ? false : options.skipUserProfile; }
javascript
function OAuthStrategy(options, verify) { if (typeof options == 'function') { verify = options; options = undefined; } options = options || {}; if (!verify) { throw new TypeError('OAuthStrategy requires a verify callback'); } if (!options.requestTokenURL) { throw new TypeError('OAuthStrategy requires a requestTokenURL option'); } if (!options.accessTokenURL) { throw new TypeError('OAuthStrategy requires a accessTokenURL option'); } if (!options.userAuthorizationURL) { throw new TypeError('OAuthStrategy requires a userAuthorizationURL option'); } if (!options.consumerKey) { throw new TypeError('OAuthStrategy requires a consumerKey option'); } if (options.consumerSecret === undefined) { throw new TypeError('OAuthStrategy requires a consumerSecret option'); } passport.Strategy.call(this); this.name = 'oauth'; this._verify = verify; // NOTE: The _oauth property is considered "protected". Subclasses are // allowed to use it when making protected resource requests to retrieve // the user profile. this._oauth = new OAuth(options.requestTokenURL, options.accessTokenURL, options.consumerKey, options.consumerSecret, '1.0', null, options.signatureMethod || 'HMAC-SHA1', null, options.customHeaders); this._userAuthorizationURL = options.userAuthorizationURL; this._callbackURL = options.callbackURL; this._key = options.sessionKey || 'oauth'; this._requestTokenStore = options.requestTokenStore || new SessionRequestTokenStore({ key: this._key }); this._trustProxy = options.proxy; this._passReqToCallback = options.passReqToCallback; this._skipUserProfile = (options.skipUserProfile === undefined) ? false : options.skipUserProfile; }
[ "function", "OAuthStrategy", "(", "options", ",", "verify", ")", "{", "if", "(", "typeof", "options", "==", "'function'", ")", "{", "verify", "=", "options", ";", "options", "=", "undefined", ";", "}", "options", "=", "options", "||", "{", "}", ";", "if", "(", "!", "verify", ")", "{", "throw", "new", "TypeError", "(", "'OAuthStrategy requires a verify callback'", ")", ";", "}", "if", "(", "!", "options", ".", "requestTokenURL", ")", "{", "throw", "new", "TypeError", "(", "'OAuthStrategy requires a requestTokenURL option'", ")", ";", "}", "if", "(", "!", "options", ".", "accessTokenURL", ")", "{", "throw", "new", "TypeError", "(", "'OAuthStrategy requires a accessTokenURL option'", ")", ";", "}", "if", "(", "!", "options", ".", "userAuthorizationURL", ")", "{", "throw", "new", "TypeError", "(", "'OAuthStrategy requires a userAuthorizationURL option'", ")", ";", "}", "if", "(", "!", "options", ".", "consumerKey", ")", "{", "throw", "new", "TypeError", "(", "'OAuthStrategy requires a consumerKey option'", ")", ";", "}", "if", "(", "options", ".", "consumerSecret", "===", "undefined", ")", "{", "throw", "new", "TypeError", "(", "'OAuthStrategy requires a consumerSecret option'", ")", ";", "}", "passport", ".", "Strategy", ".", "call", "(", "this", ")", ";", "this", ".", "name", "=", "'oauth'", ";", "this", ".", "_verify", "=", "verify", ";", "// NOTE: The _oauth property is considered \"protected\". Subclasses are", "// allowed to use it when making protected resource requests to retrieve", "// the user profile.", "this", ".", "_oauth", "=", "new", "OAuth", "(", "options", ".", "requestTokenURL", ",", "options", ".", "accessTokenURL", ",", "options", ".", "consumerKey", ",", "options", ".", "consumerSecret", ",", "'1.0'", ",", "null", ",", "options", ".", "signatureMethod", "||", "'HMAC-SHA1'", ",", "null", ",", "options", ".", "customHeaders", ")", ";", "this", ".", "_userAuthorizationURL", "=", "options", ".", "userAuthorizationURL", ";", "this", ".", "_callbackURL", "=", "options", ".", "callbackURL", ";", "this", ".", "_key", "=", "options", ".", "sessionKey", "||", "'oauth'", ";", "this", ".", "_requestTokenStore", "=", "options", ".", "requestTokenStore", "||", "new", "SessionRequestTokenStore", "(", "{", "key", ":", "this", ".", "_key", "}", ")", ";", "this", ".", "_trustProxy", "=", "options", ".", "proxy", ";", "this", ".", "_passReqToCallback", "=", "options", ".", "passReqToCallback", ";", "this", ".", "_skipUserProfile", "=", "(", "options", ".", "skipUserProfile", "===", "undefined", ")", "?", "false", ":", "options", ".", "skipUserProfile", ";", "}" ]
Creates an instance of `OAuthStrategy`. The OAuth authentication strategy authenticates requests using the OAuth protocol. OAuth provides a facility for delegated authentication, whereby users can authenticate using a third-party service such as Twitter. Delegating in this manner involves a sequence of events, including redirecting the user to the third-party service for authorization. Once authorization has been obtained, the user is redirected back to the application and a token can be used to obtain credentials. Applications must supply a `verify` callback, for which the function signature is: function(token, tokenSecret, profile, cb) { ... } The verify callback is responsible for finding or creating the user, and invoking `cb` with the following arguments: done(err, user, info); `user` should be set to `false` to indicate an authentication failure. Additional `info` can optionally be passed as a third argument, typically used to display informational messages. If an exception occured, `err` should be set. Options: - `requestTokenURL` URL used to obtain an unauthorized request token - `accessTokenURL` URL used to exchange a user-authorized request token for an access token - `userAuthorizationURL` URL used to obtain user authorization - `consumerKey` identifies client to service provider - `consumerSecret` secret used to establish ownership of the consumer key - 'signatureMethod' signature method used to sign the request (default: 'HMAC-SHA1') - `callbackURL` URL to which the service provider will redirect the user after obtaining authorization - `passReqToCallback` when `true`, `req` is the first argument to the verify callback (default: `false`) Examples: passport.use(new OAuthStrategy({ requestTokenURL: 'https://www.example.com/oauth/request_token', accessTokenURL: 'https://www.example.com/oauth/access_token', userAuthorizationURL: 'https://www.example.com/oauth/authorize', consumerKey: '123-456-789', consumerSecret: 'shhh-its-a-secret' callbackURL: 'https://www.example.net/auth/example/callback' }, function(token, tokenSecret, profile, cb) { User.findOrCreate(..., function (err, user) { cb(err, user); }); } )); @constructor @param {Object} options @param {Function} verify @api public
[ "Creates", "an", "instance", "of", "OAuthStrategy", "." ]
6e54eb376863bb7369722275cac10cff72684f0e
https://github.com/jaredhanson/passport-oauth1/blob/6e54eb376863bb7369722275cac10cff72684f0e/lib/strategy.js#L72-L105
24,317
adrai/node-cqrs-saga
lib/definitions/saga.js
function (sagaStore) { if (!sagaStore || !_.isObject(sagaStore)) { var err = new Error('Please pass a valid sagaStore!'); debug(err); throw err; } this.sagaStore = sagaStore; }
javascript
function (sagaStore) { if (!sagaStore || !_.isObject(sagaStore)) { var err = new Error('Please pass a valid sagaStore!'); debug(err); throw err; } this.sagaStore = sagaStore; }
[ "function", "(", "sagaStore", ")", "{", "if", "(", "!", "sagaStore", "||", "!", "_", ".", "isObject", "(", "sagaStore", ")", ")", "{", "var", "err", "=", "new", "Error", "(", "'Please pass a valid sagaStore!'", ")", ";", "debug", "(", "err", ")", ";", "throw", "err", ";", "}", "this", ".", "sagaStore", "=", "sagaStore", ";", "}" ]
Injects the needed sagaStore. @param {Object} sagaStore The sagaStore object to inject.
[ "Injects", "the", "needed", "sagaStore", "." ]
9770440df0e50b5a3897607a07e0252315b25edf
https://github.com/adrai/node-cqrs-saga/blob/9770440df0e50b5a3897607a07e0252315b25edf/lib/definitions/saga.js#L104-L111
24,318
adrai/node-cqrs-saga
lib/definitions/saga.js
function (cmds, callback) { if (!cmds || cmds.length === 0) { return callback(null); } var self = this; async.each(cmds, function (cmd, fn) { if (dotty.exists(cmd, self.definitions.command.id)) { return fn(null); } self.getNewId(function (err, id) { if (err) { debug(err); return fn(err); } dotty.put(cmd, self.definitions.command.id, id); fn(null); }); }, callback); }
javascript
function (cmds, callback) { if (!cmds || cmds.length === 0) { return callback(null); } var self = this; async.each(cmds, function (cmd, fn) { if (dotty.exists(cmd, self.definitions.command.id)) { return fn(null); } self.getNewId(function (err, id) { if (err) { debug(err); return fn(err); } dotty.put(cmd, self.definitions.command.id, id); fn(null); }); }, callback); }
[ "function", "(", "cmds", ",", "callback", ")", "{", "if", "(", "!", "cmds", "||", "cmds", ".", "length", "===", "0", ")", "{", "return", "callback", "(", "null", ")", ";", "}", "var", "self", "=", "this", ";", "async", ".", "each", "(", "cmds", ",", "function", "(", "cmd", ",", "fn", ")", "{", "if", "(", "dotty", ".", "exists", "(", "cmd", ",", "self", ".", "definitions", ".", "command", ".", "id", ")", ")", "{", "return", "fn", "(", "null", ")", ";", "}", "self", ".", "getNewId", "(", "function", "(", "err", ",", "id", ")", "{", "if", "(", "err", ")", "{", "debug", "(", "err", ")", ";", "return", "fn", "(", "err", ")", ";", "}", "dotty", ".", "put", "(", "cmd", ",", "self", ".", "definitions", ".", "command", ".", "id", ",", "id", ")", ";", "fn", "(", "null", ")", ";", "}", ")", ";", "}", ",", "callback", ")", ";", "}" ]
Checks if the passed commands have a command id. If not it will generate a new one and extend the command with it. @param {Array} cmds The passed commands array. @param {Function} callback The function, that will be called when this action is completed. `function(err){}`
[ "Checks", "if", "the", "passed", "commands", "have", "a", "command", "id", ".", "If", "not", "it", "will", "generate", "a", "new", "one", "and", "extend", "the", "command", "with", "it", "." ]
9770440df0e50b5a3897607a07e0252315b25edf
https://github.com/adrai/node-cqrs-saga/blob/9770440df0e50b5a3897607a07e0252315b25edf/lib/definitions/saga.js#L131-L151
24,319
adrai/node-cqrs-saga
lib/definitions/saga.js
function (evt) { for (var i = 0, len = this.containingProperties.length; i < len; i++) { var prop = this.containingProperties[i]; if (!dotty.exists(evt, prop)) { return false; } } return true; }
javascript
function (evt) { for (var i = 0, len = this.containingProperties.length; i < len; i++) { var prop = this.containingProperties[i]; if (!dotty.exists(evt, prop)) { return false; } } return true; }
[ "function", "(", "evt", ")", "{", "for", "(", "var", "i", "=", "0", ",", "len", "=", "this", ".", "containingProperties", ".", "length", ";", "i", "<", "len", ";", "i", "++", ")", "{", "var", "prop", "=", "this", ".", "containingProperties", "[", "i", "]", ";", "if", "(", "!", "dotty", ".", "exists", "(", "evt", ",", "prop", ")", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
Returns true if the passed event contains all requested properties. @param {Object} evt The passed event. @returns {boolean}
[ "Returns", "true", "if", "the", "passed", "event", "contains", "all", "requested", "properties", "." ]
9770440df0e50b5a3897607a07e0252315b25edf
https://github.com/adrai/node-cqrs-saga/blob/9770440df0e50b5a3897607a07e0252315b25edf/lib/definitions/saga.js#L158-L166
24,320
adrai/node-cqrs-saga
lib/definitions/saga.js
function (fn) { if (!fn || !_.isFunction(fn)) { var err = new Error('Please pass a valid function!'); debug(err); throw err; } if (fn.length === 3) { this.shouldHandle = fn; return this; } this.shouldHandle = function (evt, saga, callback) { callback(null, fn(evt, saga)); }; var unwrappedShouldHandle = this.shouldHandle; this.shouldHandle = function (evt, saga, clb) { var wrappedCallback = function () { try { clb.apply(this, _.toArray(arguments)); } catch (e) { debug(e); process.emit('uncaughtException', e); } }; try { unwrappedShouldHandle.call(this, evt, saga, wrappedCallback); } catch (e) { debug(e); process.emit('uncaughtException', e); } }; return this; }
javascript
function (fn) { if (!fn || !_.isFunction(fn)) { var err = new Error('Please pass a valid function!'); debug(err); throw err; } if (fn.length === 3) { this.shouldHandle = fn; return this; } this.shouldHandle = function (evt, saga, callback) { callback(null, fn(evt, saga)); }; var unwrappedShouldHandle = this.shouldHandle; this.shouldHandle = function (evt, saga, clb) { var wrappedCallback = function () { try { clb.apply(this, _.toArray(arguments)); } catch (e) { debug(e); process.emit('uncaughtException', e); } }; try { unwrappedShouldHandle.call(this, evt, saga, wrappedCallback); } catch (e) { debug(e); process.emit('uncaughtException', e); } }; return this; }
[ "function", "(", "fn", ")", "{", "if", "(", "!", "fn", "||", "!", "_", ".", "isFunction", "(", "fn", ")", ")", "{", "var", "err", "=", "new", "Error", "(", "'Please pass a valid function!'", ")", ";", "debug", "(", "err", ")", ";", "throw", "err", ";", "}", "if", "(", "fn", ".", "length", "===", "3", ")", "{", "this", ".", "shouldHandle", "=", "fn", ";", "return", "this", ";", "}", "this", ".", "shouldHandle", "=", "function", "(", "evt", ",", "saga", ",", "callback", ")", "{", "callback", "(", "null", ",", "fn", "(", "evt", ",", "saga", ")", ")", ";", "}", ";", "var", "unwrappedShouldHandle", "=", "this", ".", "shouldHandle", ";", "this", ".", "shouldHandle", "=", "function", "(", "evt", ",", "saga", ",", "clb", ")", "{", "var", "wrappedCallback", "=", "function", "(", ")", "{", "try", "{", "clb", ".", "apply", "(", "this", ",", "_", ".", "toArray", "(", "arguments", ")", ")", ";", "}", "catch", "(", "e", ")", "{", "debug", "(", "e", ")", ";", "process", ".", "emit", "(", "'uncaughtException'", ",", "e", ")", ";", "}", "}", ";", "try", "{", "unwrappedShouldHandle", ".", "call", "(", "this", ",", "evt", ",", "saga", ",", "wrappedCallback", ")", ";", "}", "catch", "(", "e", ")", "{", "debug", "(", "e", ")", ";", "process", ".", "emit", "(", "'uncaughtException'", ",", "e", ")", ";", "}", "}", ";", "return", "this", ";", "}" ]
Inject shouldHandle function. @param {Function} fn The function to be injected. @returns {Saga} to be able to chain...
[ "Inject", "shouldHandle", "function", "." ]
9770440df0e50b5a3897607a07e0252315b25edf
https://github.com/adrai/node-cqrs-saga/blob/9770440df0e50b5a3897607a07e0252315b25edf/lib/definitions/saga.js#L416-L453
24,321
adrai/node-cqrs-saga
lib/revisionGuard.js
function (evt, revInStore, callback) { var evtId = dotty.get(evt, this.definition.id); var revInEvt = dotty.get(evt, this.definition.revision); var self = this; var concatenatedId = this.getConcatenatedId(evt); this.store.set(concatenatedId, revInEvt + 1, revInStore, function (err) { if (err) { debug(err); if (err instanceof ConcurrencyError) { var retryIn = randomBetween(0, self.options.retryOnConcurrencyTimeout || 800); debug('retry in ' + retryIn + 'ms for [concatenatedId]=' + concatenatedId + ', [revInStore]=' + (revInStore || 'null') + ', [revInEvt]=' + revInEvt); setTimeout(function() { self.guard(evt, callback); }, retryIn); return; } return callback(err); } self.store.saveLastEvent(evt, function (err) { if (err) { debug('error while saving last event'); debug(err); } }); self.queue.remove(concatenatedId, evtId); callback(null); var pendingEvents = self.queue.get(concatenatedId); if (!pendingEvents || pendingEvents.length === 0) return debug('no other pending event found [concatenatedId]=' + concatenatedId + ', [revInStore]=' + (revInStore || 'null') + ', [revInEvt]=' + revInEvt); var nextEvent = _.find(pendingEvents, function (e) { var revInNextEvt = dotty.get(e.payload, self.definition.revision); return revInNextEvt === revInEvt + 1; }); if (!nextEvent) return debug('no next pending event found [concatenatedId]=' + concatenatedId + ', [revInStore]=' + (revInStore || 'null') + ', [revInEvt]=' + revInEvt); debug('found next pending event => guard [concatenatedId]=' + concatenatedId + ', [revInStore]=' + (revInStore || 'null') + ', [revInEvt]=' + revInEvt); self.guard(nextEvent.payload, nextEvent.callback); }); }
javascript
function (evt, revInStore, callback) { var evtId = dotty.get(evt, this.definition.id); var revInEvt = dotty.get(evt, this.definition.revision); var self = this; var concatenatedId = this.getConcatenatedId(evt); this.store.set(concatenatedId, revInEvt + 1, revInStore, function (err) { if (err) { debug(err); if (err instanceof ConcurrencyError) { var retryIn = randomBetween(0, self.options.retryOnConcurrencyTimeout || 800); debug('retry in ' + retryIn + 'ms for [concatenatedId]=' + concatenatedId + ', [revInStore]=' + (revInStore || 'null') + ', [revInEvt]=' + revInEvt); setTimeout(function() { self.guard(evt, callback); }, retryIn); return; } return callback(err); } self.store.saveLastEvent(evt, function (err) { if (err) { debug('error while saving last event'); debug(err); } }); self.queue.remove(concatenatedId, evtId); callback(null); var pendingEvents = self.queue.get(concatenatedId); if (!pendingEvents || pendingEvents.length === 0) return debug('no other pending event found [concatenatedId]=' + concatenatedId + ', [revInStore]=' + (revInStore || 'null') + ', [revInEvt]=' + revInEvt); var nextEvent = _.find(pendingEvents, function (e) { var revInNextEvt = dotty.get(e.payload, self.definition.revision); return revInNextEvt === revInEvt + 1; }); if (!nextEvent) return debug('no next pending event found [concatenatedId]=' + concatenatedId + ', [revInStore]=' + (revInStore || 'null') + ', [revInEvt]=' + revInEvt); debug('found next pending event => guard [concatenatedId]=' + concatenatedId + ', [revInStore]=' + (revInStore || 'null') + ', [revInEvt]=' + revInEvt); self.guard(nextEvent.payload, nextEvent.callback); }); }
[ "function", "(", "evt", ",", "revInStore", ",", "callback", ")", "{", "var", "evtId", "=", "dotty", ".", "get", "(", "evt", ",", "this", ".", "definition", ".", "id", ")", ";", "var", "revInEvt", "=", "dotty", ".", "get", "(", "evt", ",", "this", ".", "definition", ".", "revision", ")", ";", "var", "self", "=", "this", ";", "var", "concatenatedId", "=", "this", ".", "getConcatenatedId", "(", "evt", ")", ";", "this", ".", "store", ".", "set", "(", "concatenatedId", ",", "revInEvt", "+", "1", ",", "revInStore", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "debug", "(", "err", ")", ";", "if", "(", "err", "instanceof", "ConcurrencyError", ")", "{", "var", "retryIn", "=", "randomBetween", "(", "0", ",", "self", ".", "options", ".", "retryOnConcurrencyTimeout", "||", "800", ")", ";", "debug", "(", "'retry in '", "+", "retryIn", "+", "'ms for [concatenatedId]='", "+", "concatenatedId", "+", "', [revInStore]='", "+", "(", "revInStore", "||", "'null'", ")", "+", "', [revInEvt]='", "+", "revInEvt", ")", ";", "setTimeout", "(", "function", "(", ")", "{", "self", ".", "guard", "(", "evt", ",", "callback", ")", ";", "}", ",", "retryIn", ")", ";", "return", ";", "}", "return", "callback", "(", "err", ")", ";", "}", "self", ".", "store", ".", "saveLastEvent", "(", "evt", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "debug", "(", "'error while saving last event'", ")", ";", "debug", "(", "err", ")", ";", "}", "}", ")", ";", "self", ".", "queue", ".", "remove", "(", "concatenatedId", ",", "evtId", ")", ";", "callback", "(", "null", ")", ";", "var", "pendingEvents", "=", "self", ".", "queue", ".", "get", "(", "concatenatedId", ")", ";", "if", "(", "!", "pendingEvents", "||", "pendingEvents", ".", "length", "===", "0", ")", "return", "debug", "(", "'no other pending event found [concatenatedId]='", "+", "concatenatedId", "+", "', [revInStore]='", "+", "(", "revInStore", "||", "'null'", ")", "+", "', [revInEvt]='", "+", "revInEvt", ")", ";", "var", "nextEvent", "=", "_", ".", "find", "(", "pendingEvents", ",", "function", "(", "e", ")", "{", "var", "revInNextEvt", "=", "dotty", ".", "get", "(", "e", ".", "payload", ",", "self", ".", "definition", ".", "revision", ")", ";", "return", "revInNextEvt", "===", "revInEvt", "+", "1", ";", "}", ")", ";", "if", "(", "!", "nextEvent", ")", "return", "debug", "(", "'no next pending event found [concatenatedId]='", "+", "concatenatedId", "+", "', [revInStore]='", "+", "(", "revInStore", "||", "'null'", ")", "+", "', [revInEvt]='", "+", "revInEvt", ")", ";", "debug", "(", "'found next pending event => guard [concatenatedId]='", "+", "concatenatedId", "+", "', [revInStore]='", "+", "(", "revInStore", "||", "'null'", ")", "+", "', [revInEvt]='", "+", "revInEvt", ")", ";", "self", ".", "guard", "(", "nextEvent", ".", "payload", ",", "nextEvent", ".", "callback", ")", ";", "}", ")", ";", "}" ]
Finishes the guard stuff and save the new revision to store. @param {Object} evt The event object. @param {Number} revInStore The actual revision number in store. @param {Function} callback The function, that will be called when this action is completed. `function(err){}`
[ "Finishes", "the", "guard", "stuff", "and", "save", "the", "new", "revision", "to", "store", "." ]
9770440df0e50b5a3897607a07e0252315b25edf
https://github.com/adrai/node-cqrs-saga/blob/9770440df0e50b5a3897607a07e0252315b25edf/lib/revisionGuard.js#L185-L231
24,322
adrai/node-cqrs-saga
lib/orderQueue.js
function (id, objId, object, clb, fn) { this.queue[id] = this.queue[id] || []; var alreadyInQueue = _.find(this.queue[id], function (o) { return o.id === objId; }); if (alreadyInQueue) { debug('event already handling [concatenatedId]=' + id + ', [evtId]=' + objId); clb(new AlreadyHandlingError('Event: [id]=' + objId + ', [evtId]=' + objId + ' already handling!'), function (done) { done(null); }); return; } this.queue[id].push({ id: objId, payload: object, callback: clb }); this.retries[id] = this.retries[id] || {}; this.retries[id][objId] = this.retries[id][objId] || 0; if (fn) { var self = this; (function wait () { debug('wait called [concatenatedId]=' + id + ', [evtId]=' + objId); setTimeout(function () { var found = _.find(self.queue[id], function (o) { return o.id === objId; }); if (found) { var loopCount = self.retries[id][objId]++; fn(loopCount, wait); } }, self.options.queueTimeout); })(); } }
javascript
function (id, objId, object, clb, fn) { this.queue[id] = this.queue[id] || []; var alreadyInQueue = _.find(this.queue[id], function (o) { return o.id === objId; }); if (alreadyInQueue) { debug('event already handling [concatenatedId]=' + id + ', [evtId]=' + objId); clb(new AlreadyHandlingError('Event: [id]=' + objId + ', [evtId]=' + objId + ' already handling!'), function (done) { done(null); }); return; } this.queue[id].push({ id: objId, payload: object, callback: clb }); this.retries[id] = this.retries[id] || {}; this.retries[id][objId] = this.retries[id][objId] || 0; if (fn) { var self = this; (function wait () { debug('wait called [concatenatedId]=' + id + ', [evtId]=' + objId); setTimeout(function () { var found = _.find(self.queue[id], function (o) { return o.id === objId; }); if (found) { var loopCount = self.retries[id][objId]++; fn(loopCount, wait); } }, self.options.queueTimeout); })(); } }
[ "function", "(", "id", ",", "objId", ",", "object", ",", "clb", ",", "fn", ")", "{", "this", ".", "queue", "[", "id", "]", "=", "this", ".", "queue", "[", "id", "]", "||", "[", "]", ";", "var", "alreadyInQueue", "=", "_", ".", "find", "(", "this", ".", "queue", "[", "id", "]", ",", "function", "(", "o", ")", "{", "return", "o", ".", "id", "===", "objId", ";", "}", ")", ";", "if", "(", "alreadyInQueue", ")", "{", "debug", "(", "'event already handling [concatenatedId]='", "+", "id", "+", "', [evtId]='", "+", "objId", ")", ";", "clb", "(", "new", "AlreadyHandlingError", "(", "'Event: [id]='", "+", "objId", "+", "', [evtId]='", "+", "objId", "+", "' already handling!'", ")", ",", "function", "(", "done", ")", "{", "done", "(", "null", ")", ";", "}", ")", ";", "return", ";", "}", "this", ".", "queue", "[", "id", "]", ".", "push", "(", "{", "id", ":", "objId", ",", "payload", ":", "object", ",", "callback", ":", "clb", "}", ")", ";", "this", ".", "retries", "[", "id", "]", "=", "this", ".", "retries", "[", "id", "]", "||", "{", "}", ";", "this", ".", "retries", "[", "id", "]", "[", "objId", "]", "=", "this", ".", "retries", "[", "id", "]", "[", "objId", "]", "||", "0", ";", "if", "(", "fn", ")", "{", "var", "self", "=", "this", ";", "(", "function", "wait", "(", ")", "{", "debug", "(", "'wait called [concatenatedId]='", "+", "id", "+", "', [evtId]='", "+", "objId", ")", ";", "setTimeout", "(", "function", "(", ")", "{", "var", "found", "=", "_", ".", "find", "(", "self", ".", "queue", "[", "id", "]", ",", "function", "(", "o", ")", "{", "return", "o", ".", "id", "===", "objId", ";", "}", ")", ";", "if", "(", "found", ")", "{", "var", "loopCount", "=", "self", ".", "retries", "[", "id", "]", "[", "objId", "]", "++", ";", "fn", "(", "loopCount", ",", "wait", ")", ";", "}", "}", ",", "self", ".", "options", ".", "queueTimeout", ")", ";", "}", ")", "(", ")", ";", "}", "}" ]
Pushes a new item in the queue. @param {String} id The aggregate id. @param {String} objId The event id. @param {Object} object The event. @param {Function} clb The callback function for the event handle. @param {Function} fn The timeout function handle.
[ "Pushes", "a", "new", "item", "in", "the", "queue", "." ]
9770440df0e50b5a3897607a07e0252315b25edf
https://github.com/adrai/node-cqrs-saga/blob/9770440df0e50b5a3897607a07e0252315b25edf/lib/orderQueue.js#L26-L62
24,323
adrai/node-cqrs-saga
lib/orderQueue.js
function (id, objId) { if (this.queue[id]) { _.remove(this.queue[id], function (o) { return o.id === objId; }); } if (objId && this.retries[id] && this.retries[id][objId]) { this.retries[id][objId] = 0; } }
javascript
function (id, objId) { if (this.queue[id]) { _.remove(this.queue[id], function (o) { return o.id === objId; }); } if (objId && this.retries[id] && this.retries[id][objId]) { this.retries[id][objId] = 0; } }
[ "function", "(", "id", ",", "objId", ")", "{", "if", "(", "this", ".", "queue", "[", "id", "]", ")", "{", "_", ".", "remove", "(", "this", ".", "queue", "[", "id", "]", ",", "function", "(", "o", ")", "{", "return", "o", ".", "id", "===", "objId", ";", "}", ")", ";", "}", "if", "(", "objId", "&&", "this", ".", "retries", "[", "id", "]", "&&", "this", ".", "retries", "[", "id", "]", "[", "objId", "]", ")", "{", "this", ".", "retries", "[", "id", "]", "[", "objId", "]", "=", "0", ";", "}", "}" ]
Removes an event from the queue. @param {String} id The aggregate id. @param {String} objId The event id.
[ "Removes", "an", "event", "from", "the", "queue", "." ]
9770440df0e50b5a3897607a07e0252315b25edf
https://github.com/adrai/node-cqrs-saga/blob/9770440df0e50b5a3897607a07e0252315b25edf/lib/orderQueue.js#L81-L91
24,324
adrai/node-cqrs-saga
lib/pm.js
function (fn) { if (!fn || !_.isFunction(fn)) { var err = new Error('Please pass a valid function!'); debug(err); throw err; } this.onEventMissingHandle = fn; return this; }
javascript
function (fn) { if (!fn || !_.isFunction(fn)) { var err = new Error('Please pass a valid function!'); debug(err); throw err; } this.onEventMissingHandle = fn; return this; }
[ "function", "(", "fn", ")", "{", "if", "(", "!", "fn", "||", "!", "_", ".", "isFunction", "(", "fn", ")", ")", "{", "var", "err", "=", "new", "Error", "(", "'Please pass a valid function!'", ")", ";", "debug", "(", "err", ")", ";", "throw", "err", ";", "}", "this", ".", "onEventMissingHandle", "=", "fn", ";", "return", "this", ";", "}" ]
Inject function for event missing handle. @param {Function} fn the function to be injected @returns {ProcessManager} to be able to chain...
[ "Inject", "function", "for", "event", "missing", "handle", "." ]
9770440df0e50b5a3897607a07e0252315b25edf
https://github.com/adrai/node-cqrs-saga/blob/9770440df0e50b5a3897607a07e0252315b25edf/lib/pm.js#L200-L210
24,325
adrai/node-cqrs-saga
lib/pm.js
function (callback) { var self = this; var warnings = null; async.series([ // load saga files... function (callback) { if (self.options.sagaPath === '') { self.sagas = {}; debug('empty sagaPath defined so no sagas will be loaded...'); return callback(null); } debug('load saga files...'); self.structureLoader(self.options.sagaPath, function (err, sagas, warns) { if (err) { return callback(err); } warnings = warns; self.sagas = attachLookupFunctions(sagas); callback(null); }); }, // prepare infrastructure... function (callback) { debug('prepare infrastructure...'); async.parallel([ // prepare sagaStore... function (callback) { debug('prepare sagaStore...'); self.sagaStore.on('connect', function () { self.emit('connect'); }); self.sagaStore.on('disconnect', function () { self.emit('disconnect'); }); self.sagaStore.connect(callback); }, // prepare revisionGuard... function (callback) { debug('prepare revisionGuard...'); if (!self.revisionGuardStore) { return callback(null); } self.revisionGuardStore.on('connect', function () { self.emit('connect'); }); self.revisionGuardStore.on('disconnect', function () { self.emit('disconnect'); }); self.revisionGuardStore.connect(callback); } ], callback); }, // inject all needed dependencies... function (callback) { debug('inject all needed dependencies...'); if (self.revisionGuardStore) { self.revisionGuard = new RevisionGuard(self.revisionGuardStore, self.options.revisionGuard); self.revisionGuard.onEventMissing(function (info, evt) { self.onEventMissingHandle(info, evt); }); } if (self.options.sagaPath !== '') { self.eventDispatcher = new EventDispatcher(self.sagas, self.definitions.event); self.sagas.defineOptions({}) // options??? .defineCommand(self.definitions.command) .defineEvent(self.definitions.event) .idGenerator(self.getNewId) .useSagaStore(self.sagaStore); } if (self.revisionGuardStore) { self.revisionGuard.defineEvent(self.definitions.event); } callback(null); } ], function (err) { if (err) { debug(err); } if (callback) { callback(err, warnings); } }); }
javascript
function (callback) { var self = this; var warnings = null; async.series([ // load saga files... function (callback) { if (self.options.sagaPath === '') { self.sagas = {}; debug('empty sagaPath defined so no sagas will be loaded...'); return callback(null); } debug('load saga files...'); self.structureLoader(self.options.sagaPath, function (err, sagas, warns) { if (err) { return callback(err); } warnings = warns; self.sagas = attachLookupFunctions(sagas); callback(null); }); }, // prepare infrastructure... function (callback) { debug('prepare infrastructure...'); async.parallel([ // prepare sagaStore... function (callback) { debug('prepare sagaStore...'); self.sagaStore.on('connect', function () { self.emit('connect'); }); self.sagaStore.on('disconnect', function () { self.emit('disconnect'); }); self.sagaStore.connect(callback); }, // prepare revisionGuard... function (callback) { debug('prepare revisionGuard...'); if (!self.revisionGuardStore) { return callback(null); } self.revisionGuardStore.on('connect', function () { self.emit('connect'); }); self.revisionGuardStore.on('disconnect', function () { self.emit('disconnect'); }); self.revisionGuardStore.connect(callback); } ], callback); }, // inject all needed dependencies... function (callback) { debug('inject all needed dependencies...'); if (self.revisionGuardStore) { self.revisionGuard = new RevisionGuard(self.revisionGuardStore, self.options.revisionGuard); self.revisionGuard.onEventMissing(function (info, evt) { self.onEventMissingHandle(info, evt); }); } if (self.options.sagaPath !== '') { self.eventDispatcher = new EventDispatcher(self.sagas, self.definitions.event); self.sagas.defineOptions({}) // options??? .defineCommand(self.definitions.command) .defineEvent(self.definitions.event) .idGenerator(self.getNewId) .useSagaStore(self.sagaStore); } if (self.revisionGuardStore) { self.revisionGuard.defineEvent(self.definitions.event); } callback(null); } ], function (err) { if (err) { debug(err); } if (callback) { callback(err, warnings); } }); }
[ "function", "(", "callback", ")", "{", "var", "self", "=", "this", ";", "var", "warnings", "=", "null", ";", "async", ".", "series", "(", "[", "// load saga files...", "function", "(", "callback", ")", "{", "if", "(", "self", ".", "options", ".", "sagaPath", "===", "''", ")", "{", "self", ".", "sagas", "=", "{", "}", ";", "debug", "(", "'empty sagaPath defined so no sagas will be loaded...'", ")", ";", "return", "callback", "(", "null", ")", ";", "}", "debug", "(", "'load saga files...'", ")", ";", "self", ".", "structureLoader", "(", "self", ".", "options", ".", "sagaPath", ",", "function", "(", "err", ",", "sagas", ",", "warns", ")", "{", "if", "(", "err", ")", "{", "return", "callback", "(", "err", ")", ";", "}", "warnings", "=", "warns", ";", "self", ".", "sagas", "=", "attachLookupFunctions", "(", "sagas", ")", ";", "callback", "(", "null", ")", ";", "}", ")", ";", "}", ",", "// prepare infrastructure...", "function", "(", "callback", ")", "{", "debug", "(", "'prepare infrastructure...'", ")", ";", "async", ".", "parallel", "(", "[", "// prepare sagaStore...", "function", "(", "callback", ")", "{", "debug", "(", "'prepare sagaStore...'", ")", ";", "self", ".", "sagaStore", ".", "on", "(", "'connect'", ",", "function", "(", ")", "{", "self", ".", "emit", "(", "'connect'", ")", ";", "}", ")", ";", "self", ".", "sagaStore", ".", "on", "(", "'disconnect'", ",", "function", "(", ")", "{", "self", ".", "emit", "(", "'disconnect'", ")", ";", "}", ")", ";", "self", ".", "sagaStore", ".", "connect", "(", "callback", ")", ";", "}", ",", "// prepare revisionGuard...", "function", "(", "callback", ")", "{", "debug", "(", "'prepare revisionGuard...'", ")", ";", "if", "(", "!", "self", ".", "revisionGuardStore", ")", "{", "return", "callback", "(", "null", ")", ";", "}", "self", ".", "revisionGuardStore", ".", "on", "(", "'connect'", ",", "function", "(", ")", "{", "self", ".", "emit", "(", "'connect'", ")", ";", "}", ")", ";", "self", ".", "revisionGuardStore", ".", "on", "(", "'disconnect'", ",", "function", "(", ")", "{", "self", ".", "emit", "(", "'disconnect'", ")", ";", "}", ")", ";", "self", ".", "revisionGuardStore", ".", "connect", "(", "callback", ")", ";", "}", "]", ",", "callback", ")", ";", "}", ",", "// inject all needed dependencies...", "function", "(", "callback", ")", "{", "debug", "(", "'inject all needed dependencies...'", ")", ";", "if", "(", "self", ".", "revisionGuardStore", ")", "{", "self", ".", "revisionGuard", "=", "new", "RevisionGuard", "(", "self", ".", "revisionGuardStore", ",", "self", ".", "options", ".", "revisionGuard", ")", ";", "self", ".", "revisionGuard", ".", "onEventMissing", "(", "function", "(", "info", ",", "evt", ")", "{", "self", ".", "onEventMissingHandle", "(", "info", ",", "evt", ")", ";", "}", ")", ";", "}", "if", "(", "self", ".", "options", ".", "sagaPath", "!==", "''", ")", "{", "self", ".", "eventDispatcher", "=", "new", "EventDispatcher", "(", "self", ".", "sagas", ",", "self", ".", "definitions", ".", "event", ")", ";", "self", ".", "sagas", ".", "defineOptions", "(", "{", "}", ")", "// options???", ".", "defineCommand", "(", "self", ".", "definitions", ".", "command", ")", ".", "defineEvent", "(", "self", ".", "definitions", ".", "event", ")", ".", "idGenerator", "(", "self", ".", "getNewId", ")", ".", "useSagaStore", "(", "self", ".", "sagaStore", ")", ";", "}", "if", "(", "self", ".", "revisionGuardStore", ")", "{", "self", ".", "revisionGuard", ".", "defineEvent", "(", "self", ".", "definitions", ".", "event", ")", ";", "}", "callback", "(", "null", ")", ";", "}", "]", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "debug", "(", "err", ")", ";", "}", "if", "(", "callback", ")", "{", "callback", "(", "err", ",", "warnings", ")", ";", "}", "}", ")", ";", "}" ]
Call this function to initialize the saga. @param {Function} callback the function that will be called when this action has finished [optional] `function(err){}`
[ "Call", "this", "function", "to", "initialize", "the", "saga", "." ]
9770440df0e50b5a3897607a07e0252315b25edf
https://github.com/adrai/node-cqrs-saga/blob/9770440df0e50b5a3897607a07e0252315b25edf/lib/pm.js#L217-L314
24,326
adrai/node-cqrs-saga
lib/pm.js
function (callback) { if (self.options.sagaPath === '') { self.sagas = {}; debug('empty sagaPath defined so no sagas will be loaded...'); return callback(null); } debug('load saga files...'); self.structureLoader(self.options.sagaPath, function (err, sagas, warns) { if (err) { return callback(err); } warnings = warns; self.sagas = attachLookupFunctions(sagas); callback(null); }); }
javascript
function (callback) { if (self.options.sagaPath === '') { self.sagas = {}; debug('empty sagaPath defined so no sagas will be loaded...'); return callback(null); } debug('load saga files...'); self.structureLoader(self.options.sagaPath, function (err, sagas, warns) { if (err) { return callback(err); } warnings = warns; self.sagas = attachLookupFunctions(sagas); callback(null); }); }
[ "function", "(", "callback", ")", "{", "if", "(", "self", ".", "options", ".", "sagaPath", "===", "''", ")", "{", "self", ".", "sagas", "=", "{", "}", ";", "debug", "(", "'empty sagaPath defined so no sagas will be loaded...'", ")", ";", "return", "callback", "(", "null", ")", ";", "}", "debug", "(", "'load saga files...'", ")", ";", "self", ".", "structureLoader", "(", "self", ".", "options", ".", "sagaPath", ",", "function", "(", "err", ",", "sagas", ",", "warns", ")", "{", "if", "(", "err", ")", "{", "return", "callback", "(", "err", ")", ";", "}", "warnings", "=", "warns", ";", "self", ".", "sagas", "=", "attachLookupFunctions", "(", "sagas", ")", ";", "callback", "(", "null", ")", ";", "}", ")", ";", "}" ]
load saga files...
[ "load", "saga", "files", "..." ]
9770440df0e50b5a3897607a07e0252315b25edf
https://github.com/adrai/node-cqrs-saga/blob/9770440df0e50b5a3897607a07e0252315b25edf/lib/pm.js#L225-L240
24,327
adrai/node-cqrs-saga
lib/pm.js
function (callback) { debug('prepare sagaStore...'); self.sagaStore.on('connect', function () { self.emit('connect'); }); self.sagaStore.on('disconnect', function () { self.emit('disconnect'); }); self.sagaStore.connect(callback); }
javascript
function (callback) { debug('prepare sagaStore...'); self.sagaStore.on('connect', function () { self.emit('connect'); }); self.sagaStore.on('disconnect', function () { self.emit('disconnect'); }); self.sagaStore.connect(callback); }
[ "function", "(", "callback", ")", "{", "debug", "(", "'prepare sagaStore...'", ")", ";", "self", ".", "sagaStore", ".", "on", "(", "'connect'", ",", "function", "(", ")", "{", "self", ".", "emit", "(", "'connect'", ")", ";", "}", ")", ";", "self", ".", "sagaStore", ".", "on", "(", "'disconnect'", ",", "function", "(", ")", "{", "self", ".", "emit", "(", "'disconnect'", ")", ";", "}", ")", ";", "self", ".", "sagaStore", ".", "connect", "(", "callback", ")", ";", "}" ]
prepare sagaStore...
[ "prepare", "sagaStore", "..." ]
9770440df0e50b5a3897607a07e0252315b25edf
https://github.com/adrai/node-cqrs-saga/blob/9770440df0e50b5a3897607a07e0252315b25edf/lib/pm.js#L248-L260
24,328
adrai/node-cqrs-saga
lib/pm.js
function (evt, callback) { var self = this; this.eventDispatcher.dispatch(evt, function (errs, sagaModels) { var cmds = []; if (!sagaModels || sagaModels.length === 0) { if (callback) { callback(errs, cmds, []); } return; } async.each(sagaModels, function (sagaModel, callback) { var cmdsToSend = sagaModel.getUndispatchedCommands(); function setCommandToDispatched (c, clb) { debug('set command to dispatched'); self.setCommandToDispatched(dotty.get(c, self.definitions.command.id), sagaModel.id, function (err) { if (err) { return clb(err); } cmds.push(c); sagaModel.removeUnsentCommand(c); clb(null); }); } async.each(cmdsToSend, function (cmd, callback) { if (self.onCommandHandle) { debug('publish a command'); self.onCommandHandle(cmd, function (err) { if (err) { debug(err); return callback(err); } setCommandToDispatched(cmd, callback); }); } else { setCommandToDispatched(cmd, callback); } }, callback); }, function (err) { if (err) { if (!errs) { errs = [err]; } else if (_.isArray(errs)) { errs.unshift(err); } debug(err); } if (callback) { try { callback(errs, cmds, sagaModels); } catch (e) { debug(e); console.log(e.stack); process.emit('uncaughtException', e); } } }); }); }
javascript
function (evt, callback) { var self = this; this.eventDispatcher.dispatch(evt, function (errs, sagaModels) { var cmds = []; if (!sagaModels || sagaModels.length === 0) { if (callback) { callback(errs, cmds, []); } return; } async.each(sagaModels, function (sagaModel, callback) { var cmdsToSend = sagaModel.getUndispatchedCommands(); function setCommandToDispatched (c, clb) { debug('set command to dispatched'); self.setCommandToDispatched(dotty.get(c, self.definitions.command.id), sagaModel.id, function (err) { if (err) { return clb(err); } cmds.push(c); sagaModel.removeUnsentCommand(c); clb(null); }); } async.each(cmdsToSend, function (cmd, callback) { if (self.onCommandHandle) { debug('publish a command'); self.onCommandHandle(cmd, function (err) { if (err) { debug(err); return callback(err); } setCommandToDispatched(cmd, callback); }); } else { setCommandToDispatched(cmd, callback); } }, callback); }, function (err) { if (err) { if (!errs) { errs = [err]; } else if (_.isArray(errs)) { errs.unshift(err); } debug(err); } if (callback) { try { callback(errs, cmds, sagaModels); } catch (e) { debug(e); console.log(e.stack); process.emit('uncaughtException', e); } } }); }); }
[ "function", "(", "evt", ",", "callback", ")", "{", "var", "self", "=", "this", ";", "this", ".", "eventDispatcher", ".", "dispatch", "(", "evt", ",", "function", "(", "errs", ",", "sagaModels", ")", "{", "var", "cmds", "=", "[", "]", ";", "if", "(", "!", "sagaModels", "||", "sagaModels", ".", "length", "===", "0", ")", "{", "if", "(", "callback", ")", "{", "callback", "(", "errs", ",", "cmds", ",", "[", "]", ")", ";", "}", "return", ";", "}", "async", ".", "each", "(", "sagaModels", ",", "function", "(", "sagaModel", ",", "callback", ")", "{", "var", "cmdsToSend", "=", "sagaModel", ".", "getUndispatchedCommands", "(", ")", ";", "function", "setCommandToDispatched", "(", "c", ",", "clb", ")", "{", "debug", "(", "'set command to dispatched'", ")", ";", "self", ".", "setCommandToDispatched", "(", "dotty", ".", "get", "(", "c", ",", "self", ".", "definitions", ".", "command", ".", "id", ")", ",", "sagaModel", ".", "id", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "return", "clb", "(", "err", ")", ";", "}", "cmds", ".", "push", "(", "c", ")", ";", "sagaModel", ".", "removeUnsentCommand", "(", "c", ")", ";", "clb", "(", "null", ")", ";", "}", ")", ";", "}", "async", ".", "each", "(", "cmdsToSend", ",", "function", "(", "cmd", ",", "callback", ")", "{", "if", "(", "self", ".", "onCommandHandle", ")", "{", "debug", "(", "'publish a command'", ")", ";", "self", ".", "onCommandHandle", "(", "cmd", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "debug", "(", "err", ")", ";", "return", "callback", "(", "err", ")", ";", "}", "setCommandToDispatched", "(", "cmd", ",", "callback", ")", ";", "}", ")", ";", "}", "else", "{", "setCommandToDispatched", "(", "cmd", ",", "callback", ")", ";", "}", "}", ",", "callback", ")", ";", "}", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "if", "(", "!", "errs", ")", "{", "errs", "=", "[", "err", "]", ";", "}", "else", "if", "(", "_", ".", "isArray", "(", "errs", ")", ")", "{", "errs", ".", "unshift", "(", "err", ")", ";", "}", "debug", "(", "err", ")", ";", "}", "if", "(", "callback", ")", "{", "try", "{", "callback", "(", "errs", ",", "cmds", ",", "sagaModels", ")", ";", "}", "catch", "(", "e", ")", "{", "debug", "(", "e", ")", ";", "console", ".", "log", "(", "e", ".", "stack", ")", ";", "process", ".", "emit", "(", "'uncaughtException'", ",", "e", ")", ";", "}", "}", "}", ")", ";", "}", ")", ";", "}" ]
Call this function to forward it to the dispatcher. @param {Object} evt The event object @param {Function} callback The function that will be called when this action has finished [optional] `function(errs, evt, notifications){}` notifications is of type Array
[ "Call", "this", "function", "to", "forward", "it", "to", "the", "dispatcher", "." ]
9770440df0e50b5a3897607a07e0252315b25edf
https://github.com/adrai/node-cqrs-saga/blob/9770440df0e50b5a3897607a07e0252315b25edf/lib/pm.js#L336-L403
24,329
adrai/node-cqrs-saga
lib/pm.js
function (evt, callback) { if (!evt || !_.isObject(evt)) { var err = new Error('Please pass a valid event!'); debug(err); throw err; } var self = this; var workWithRevisionGuard = false; if ( this.revisionGuard && !!this.definitions.event.revision && dotty.exists(evt, this.definitions.event.revision) && !!this.definitions.event.aggregateId && dotty.exists(evt, this.definitions.event.aggregateId) ) { workWithRevisionGuard = true; } if (dotty.get(evt, this.definitions.event.name) === this.options.commandRejectedEventName) { workWithRevisionGuard = false; } if (!workWithRevisionGuard) { return this.dispatch(evt, callback); } this.revisionGuard.guard(evt, function (err, done) { if (err) { debug(err); if (callback) { callback([err]); } return; } self.dispatch(evt, function (errs, cmds, sagaModels) { if (errs) { debug(errs); if (callback) { callback(errs, cmds, sagaModels); } return; } done(function (err) { if (err) { if (!errs) { errs = [err]; } else if (_.isArray(errs)) { errs.unshift(err); } debug(err); } if (callback) { callback(errs, cmds, sagaModels); } }); }); }); }
javascript
function (evt, callback) { if (!evt || !_.isObject(evt)) { var err = new Error('Please pass a valid event!'); debug(err); throw err; } var self = this; var workWithRevisionGuard = false; if ( this.revisionGuard && !!this.definitions.event.revision && dotty.exists(evt, this.definitions.event.revision) && !!this.definitions.event.aggregateId && dotty.exists(evt, this.definitions.event.aggregateId) ) { workWithRevisionGuard = true; } if (dotty.get(evt, this.definitions.event.name) === this.options.commandRejectedEventName) { workWithRevisionGuard = false; } if (!workWithRevisionGuard) { return this.dispatch(evt, callback); } this.revisionGuard.guard(evt, function (err, done) { if (err) { debug(err); if (callback) { callback([err]); } return; } self.dispatch(evt, function (errs, cmds, sagaModels) { if (errs) { debug(errs); if (callback) { callback(errs, cmds, sagaModels); } return; } done(function (err) { if (err) { if (!errs) { errs = [err]; } else if (_.isArray(errs)) { errs.unshift(err); } debug(err); } if (callback) { callback(errs, cmds, sagaModels); } }); }); }); }
[ "function", "(", "evt", ",", "callback", ")", "{", "if", "(", "!", "evt", "||", "!", "_", ".", "isObject", "(", "evt", ")", ")", "{", "var", "err", "=", "new", "Error", "(", "'Please pass a valid event!'", ")", ";", "debug", "(", "err", ")", ";", "throw", "err", ";", "}", "var", "self", "=", "this", ";", "var", "workWithRevisionGuard", "=", "false", ";", "if", "(", "this", ".", "revisionGuard", "&&", "!", "!", "this", ".", "definitions", ".", "event", ".", "revision", "&&", "dotty", ".", "exists", "(", "evt", ",", "this", ".", "definitions", ".", "event", ".", "revision", ")", "&&", "!", "!", "this", ".", "definitions", ".", "event", ".", "aggregateId", "&&", "dotty", ".", "exists", "(", "evt", ",", "this", ".", "definitions", ".", "event", ".", "aggregateId", ")", ")", "{", "workWithRevisionGuard", "=", "true", ";", "}", "if", "(", "dotty", ".", "get", "(", "evt", ",", "this", ".", "definitions", ".", "event", ".", "name", ")", "===", "this", ".", "options", ".", "commandRejectedEventName", ")", "{", "workWithRevisionGuard", "=", "false", ";", "}", "if", "(", "!", "workWithRevisionGuard", ")", "{", "return", "this", ".", "dispatch", "(", "evt", ",", "callback", ")", ";", "}", "this", ".", "revisionGuard", ".", "guard", "(", "evt", ",", "function", "(", "err", ",", "done", ")", "{", "if", "(", "err", ")", "{", "debug", "(", "err", ")", ";", "if", "(", "callback", ")", "{", "callback", "(", "[", "err", "]", ")", ";", "}", "return", ";", "}", "self", ".", "dispatch", "(", "evt", ",", "function", "(", "errs", ",", "cmds", ",", "sagaModels", ")", "{", "if", "(", "errs", ")", "{", "debug", "(", "errs", ")", ";", "if", "(", "callback", ")", "{", "callback", "(", "errs", ",", "cmds", ",", "sagaModels", ")", ";", "}", "return", ";", "}", "done", "(", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "if", "(", "!", "errs", ")", "{", "errs", "=", "[", "err", "]", ";", "}", "else", "if", "(", "_", ".", "isArray", "(", "errs", ")", ")", "{", "errs", ".", "unshift", "(", "err", ")", ";", "}", "debug", "(", "err", ")", ";", "}", "if", "(", "callback", ")", "{", "callback", "(", "errs", ",", "cmds", ",", "sagaModels", ")", ";", "}", "}", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Call this function to let the saga handle it. @param {Object} evt The event object @param {Function} callback The function that will be called when this action has finished [optional] `function(err, cmds, sagaModels){}` cmds and sagaModels are of type Array
[ "Call", "this", "function", "to", "let", "the", "saga", "handle", "it", "." ]
9770440df0e50b5a3897607a07e0252315b25edf
https://github.com/adrai/node-cqrs-saga/blob/9770440df0e50b5a3897607a07e0252315b25edf/lib/pm.js#L411-L473
24,330
adrai/node-cqrs-saga
lib/pm.js
function (date, callback) { var self = this; this.sagaStore.getOlderSagas(date, function (err, sagas) { if (err) { debug(err); return callback(err); } var sagaModels = []; sagas.forEach(function (s) { var sagaModel = new SagaModel(s.id); sagaModel.set(s); sagaModel.actionOnCommit = 'update'; var calledRemoveTimeout = false; var orgRemoveTimeout = sagaModel.removeTimeout; sagaModel.removeTimeout = function () { calledRemoveTimeout = true; orgRemoveTimeout.bind(sagaModel)(); }; sagaModel.commit = function (clb) { if (sagaModel.isDestroyed()) { self.removeSaga(sagaModel, clb); } else if (calledRemoveTimeout) { sagaModel.setCommitStamp(new Date()); self.sagaStore.save(sagaModel.toJSON(), [], clb); } else { var err = new Error('Use commit only to remove a saga!'); debug(err); if (clb) { return clb(err); } throw err; } }; sagaModels.push(sagaModel); }); callback(null, sagaModels); }); }
javascript
function (date, callback) { var self = this; this.sagaStore.getOlderSagas(date, function (err, sagas) { if (err) { debug(err); return callback(err); } var sagaModels = []; sagas.forEach(function (s) { var sagaModel = new SagaModel(s.id); sagaModel.set(s); sagaModel.actionOnCommit = 'update'; var calledRemoveTimeout = false; var orgRemoveTimeout = sagaModel.removeTimeout; sagaModel.removeTimeout = function () { calledRemoveTimeout = true; orgRemoveTimeout.bind(sagaModel)(); }; sagaModel.commit = function (clb) { if (sagaModel.isDestroyed()) { self.removeSaga(sagaModel, clb); } else if (calledRemoveTimeout) { sagaModel.setCommitStamp(new Date()); self.sagaStore.save(sagaModel.toJSON(), [], clb); } else { var err = new Error('Use commit only to remove a saga!'); debug(err); if (clb) { return clb(err); } throw err; } }; sagaModels.push(sagaModel); }); callback(null, sagaModels); }); }
[ "function", "(", "date", ",", "callback", ")", "{", "var", "self", "=", "this", ";", "this", ".", "sagaStore", ".", "getOlderSagas", "(", "date", ",", "function", "(", "err", ",", "sagas", ")", "{", "if", "(", "err", ")", "{", "debug", "(", "err", ")", ";", "return", "callback", "(", "err", ")", ";", "}", "var", "sagaModels", "=", "[", "]", ";", "sagas", ".", "forEach", "(", "function", "(", "s", ")", "{", "var", "sagaModel", "=", "new", "SagaModel", "(", "s", ".", "id", ")", ";", "sagaModel", ".", "set", "(", "s", ")", ";", "sagaModel", ".", "actionOnCommit", "=", "'update'", ";", "var", "calledRemoveTimeout", "=", "false", ";", "var", "orgRemoveTimeout", "=", "sagaModel", ".", "removeTimeout", ";", "sagaModel", ".", "removeTimeout", "=", "function", "(", ")", "{", "calledRemoveTimeout", "=", "true", ";", "orgRemoveTimeout", ".", "bind", "(", "sagaModel", ")", "(", ")", ";", "}", ";", "sagaModel", ".", "commit", "=", "function", "(", "clb", ")", "{", "if", "(", "sagaModel", ".", "isDestroyed", "(", ")", ")", "{", "self", ".", "removeSaga", "(", "sagaModel", ",", "clb", ")", ";", "}", "else", "if", "(", "calledRemoveTimeout", ")", "{", "sagaModel", ".", "setCommitStamp", "(", "new", "Date", "(", ")", ")", ";", "self", ".", "sagaStore", ".", "save", "(", "sagaModel", ".", "toJSON", "(", ")", ",", "[", "]", ",", "clb", ")", ";", "}", "else", "{", "var", "err", "=", "new", "Error", "(", "'Use commit only to remove a saga!'", ")", ";", "debug", "(", "err", ")", ";", "if", "(", "clb", ")", "{", "return", "clb", "(", "err", ")", ";", "}", "throw", "err", ";", "}", "}", ";", "sagaModels", ".", "push", "(", "sagaModel", ")", ";", "}", ")", ";", "callback", "(", "null", ",", "sagaModels", ")", ";", "}", ")", ";", "}" ]
Use this function to get all sagas that are older then the passed date. @param {Date} date The date @param {Function} callback The function, that will be called when this action is completed. `function(err, sagas){}` saga is of type Array.
[ "Use", "this", "function", "to", "get", "all", "sagas", "that", "are", "older", "then", "the", "passed", "date", "." ]
9770440df0e50b5a3897607a07e0252315b25edf
https://github.com/adrai/node-cqrs-saga/blob/9770440df0e50b5a3897607a07e0252315b25edf/lib/pm.js#L593-L630
24,331
adrai/node-cqrs-saga
lib/pm.js
function (options, callback) { if (!callback) { callback = options; options = {}; } this.sagaStore.getUndispatchedCommands(options, callback); }
javascript
function (options, callback) { if (!callback) { callback = options; options = {}; } this.sagaStore.getUndispatchedCommands(options, callback); }
[ "function", "(", "options", ",", "callback", ")", "{", "if", "(", "!", "callback", ")", "{", "callback", "=", "options", ";", "options", "=", "{", "}", ";", "}", "this", ".", "sagaStore", ".", "getUndispatchedCommands", "(", "options", ",", "callback", ")", ";", "}" ]
Use this function to get all undispatched commands. @param {Function} callback The function, that will be called when this action is completed. `function(err, cmdsSagaMap){}` cmdsSagaMap is of type Array.
[ "Use", "this", "function", "to", "get", "all", "undispatched", "commands", "." ]
9770440df0e50b5a3897607a07e0252315b25edf
https://github.com/adrai/node-cqrs-saga/blob/9770440df0e50b5a3897607a07e0252315b25edf/lib/pm.js#L637-L643
24,332
adrai/node-cqrs-saga
lib/pm.js
function (saga, callback) { var sagaId = saga.id || saga; this.sagaStore.remove(sagaId, callback); }
javascript
function (saga, callback) { var sagaId = saga.id || saga; this.sagaStore.remove(sagaId, callback); }
[ "function", "(", "saga", ",", "callback", ")", "{", "var", "sagaId", "=", "saga", ".", "id", "||", "saga", ";", "this", ".", "sagaStore", ".", "remove", "(", "sagaId", ",", "callback", ")", ";", "}" ]
Use this function to remove the matched saga. @param {String} saga The id of the saga or the saga itself @param {Function} callback The function, that will be called when this action is completed. [optional] `function(err){}`
[ "Use", "this", "function", "to", "remove", "the", "matched", "saga", "." ]
9770440df0e50b5a3897607a07e0252315b25edf
https://github.com/adrai/node-cqrs-saga/blob/9770440df0e50b5a3897607a07e0252315b25edf/lib/pm.js#L662-L665
24,333
apis-is/apis
endpoints/declension/index.js
getDeclensions
function getDeclensions(callback, providedParams) { const params = Object.assign({}, providedParams) request.get(params, (err, res, body) => { if (err || res.statusCode !== 200) { return res.status(500).json({ error: 'A request to dev.phpbin.ja.is resulted in a error', }) } let $ const sanitisedBody = body.replace(/<!--[\s\S]*?-->/g, '') try { $ = cheerio.load(sanitisedBody) } catch (error) { return res.status(500).json({ error: 'Parsing the data from dev.phpbin.ja.is resulted in a error', moreinfo: error, }) } // Links mean results! const result = $('a') // more than 1 result from request (ex: 'hús') if (result.length > 1) { // call recursively again with new url const id = result[0].attribs.on_click.match(/\d+/)[0] baseUrl.query = { id } params.url = url.format(baseUrl) return getDeclensions(callback, params) } // else just call func to return data return callback($) }) }
javascript
function getDeclensions(callback, providedParams) { const params = Object.assign({}, providedParams) request.get(params, (err, res, body) => { if (err || res.statusCode !== 200) { return res.status(500).json({ error: 'A request to dev.phpbin.ja.is resulted in a error', }) } let $ const sanitisedBody = body.replace(/<!--[\s\S]*?-->/g, '') try { $ = cheerio.load(sanitisedBody) } catch (error) { return res.status(500).json({ error: 'Parsing the data from dev.phpbin.ja.is resulted in a error', moreinfo: error, }) } // Links mean results! const result = $('a') // more than 1 result from request (ex: 'hús') if (result.length > 1) { // call recursively again with new url const id = result[0].attribs.on_click.match(/\d+/)[0] baseUrl.query = { id } params.url = url.format(baseUrl) return getDeclensions(callback, params) } // else just call func to return data return callback($) }) }
[ "function", "getDeclensions", "(", "callback", ",", "providedParams", ")", "{", "const", "params", "=", "Object", ".", "assign", "(", "{", "}", ",", "providedParams", ")", "request", ".", "get", "(", "params", ",", "(", "err", ",", "res", ",", "body", ")", "=>", "{", "if", "(", "err", "||", "res", ".", "statusCode", "!==", "200", ")", "{", "return", "res", ".", "status", "(", "500", ")", ".", "json", "(", "{", "error", ":", "'A request to dev.phpbin.ja.is resulted in a error'", ",", "}", ")", "}", "let", "$", "const", "sanitisedBody", "=", "body", ".", "replace", "(", "/", "<!--[\\s\\S]*?-->", "/", "g", ",", "''", ")", "try", "{", "$", "=", "cheerio", ".", "load", "(", "sanitisedBody", ")", "}", "catch", "(", "error", ")", "{", "return", "res", ".", "status", "(", "500", ")", ".", "json", "(", "{", "error", ":", "'Parsing the data from dev.phpbin.ja.is resulted in a error'", ",", "moreinfo", ":", "error", ",", "}", ")", "}", "// Links mean results!", "const", "result", "=", "$", "(", "'a'", ")", "// more than 1 result from request (ex: 'hús')", "if", "(", "result", ".", "length", ">", "1", ")", "{", "// call recursively again with new url", "const", "id", "=", "result", "[", "0", "]", ".", "attribs", ".", "on_click", ".", "match", "(", "/", "\\d+", "/", ")", "[", "0", "]", "baseUrl", ".", "query", "=", "{", "id", "}", "params", ".", "url", "=", "url", ".", "format", "(", "baseUrl", ")", "return", "getDeclensions", "(", "callback", ",", "params", ")", "}", "// else just call func to return data", "return", "callback", "(", "$", ")", "}", ")", "}" ]
return permutation of a given word
[ "return", "permutation", "of", "a", "given", "word" ]
96a23ab30d5b498a0805da06cf87e84d61422c27
https://github.com/apis-is/apis/blob/96a23ab30d5b498a0805da06cf87e84d61422c27/endpoints/declension/index.js#L14-L50
24,334
ibm-developer/generator-ibm-core-node-express
app/templates/idt.js
runIDT
function runIDT(args) { const cmd = 'bx dev ' + args.join(' '); console.log(chalk.blue('Running:'), cmd); cp.execSync(cmd, {stdio: 'inherit'}); }
javascript
function runIDT(args) { const cmd = 'bx dev ' + args.join(' '); console.log(chalk.blue('Running:'), cmd); cp.execSync(cmd, {stdio: 'inherit'}); }
[ "function", "runIDT", "(", "args", ")", "{", "const", "cmd", "=", "'bx dev '", "+", "args", ".", "join", "(", "' '", ")", ";", "console", ".", "log", "(", "chalk", ".", "blue", "(", "'Running:'", ")", ",", "cmd", ")", ";", "cp", ".", "execSync", "(", "cmd", ",", "{", "stdio", ":", "'inherit'", "}", ")", ";", "}" ]
Run IDT with whatever args we were given.
[ "Run", "IDT", "with", "whatever", "args", "we", "were", "given", "." ]
ae55bb3fafc949b7d786cd45a10e10d30d9457a6
https://github.com/ibm-developer/generator-ibm-core-node-express/blob/ae55bb3fafc949b7d786cd45a10e10d30d9457a6/app/templates/idt.js#L55-L59
24,335
ibm-developer/generator-ibm-core-node-express
app/templates/public/swagger-ui/swagger-ui.js
function(resource) { var resource = Docs.escapeResourceName(resource); if (resource == '') { $('.resource ul.endpoints').slideUp(); return; } $('li#resource_' + resource).removeClass('active'); var elem = $('li#resource_' + resource + ' ul.endpoints'); elem.slideUp(); }
javascript
function(resource) { var resource = Docs.escapeResourceName(resource); if (resource == '') { $('.resource ul.endpoints').slideUp(); return; } $('li#resource_' + resource).removeClass('active'); var elem = $('li#resource_' + resource + ' ul.endpoints'); elem.slideUp(); }
[ "function", "(", "resource", ")", "{", "var", "resource", "=", "Docs", ".", "escapeResourceName", "(", "resource", ")", ";", "if", "(", "resource", "==", "''", ")", "{", "$", "(", "'.resource ul.endpoints'", ")", ".", "slideUp", "(", ")", ";", "return", ";", "}", "$", "(", "'li#resource_'", "+", "resource", ")", ".", "removeClass", "(", "'active'", ")", ";", "var", "elem", "=", "$", "(", "'li#resource_'", "+", "resource", "+", "' ul.endpoints'", ")", ";", "elem", ".", "slideUp", "(", ")", ";", "}" ]
Collapse resource and mark as explicitly closed
[ "Collapse", "resource", "and", "mark", "as", "explicitly", "closed" ]
ae55bb3fafc949b7d786cd45a10e10d30d9457a6
https://github.com/ibm-developer/generator-ibm-core-node-express/blob/ae55bb3fafc949b7d786cd45a10e10d30d9457a6/app/templates/public/swagger-ui/swagger-ui.js#L949-L960
24,336
ibm-developer/generator-ibm-core-node-express
app/templates/public/swagger-ui/swagger-ui.js
runSingle
function runSingle(task, domain) { try { task(); } catch (e) { if (isNodeJS) { // In node, uncaught exceptions are considered fatal errors. // Re-throw them synchronously to interrupt flushing! // Ensure continuation if the uncaught exception is suppressed // listening "uncaughtException" events (as domains does). // Continue in next event to avoid tick recursion. if (domain) { domain.exit(); } setTimeout(flush, 0); if (domain) { domain.enter(); } throw e; } else { // In browsers, uncaught exceptions are not fatal. // Re-throw them asynchronously to avoid slow-downs. setTimeout(function () { throw e; }, 0); } } if (domain) { domain.exit(); } }
javascript
function runSingle(task, domain) { try { task(); } catch (e) { if (isNodeJS) { // In node, uncaught exceptions are considered fatal errors. // Re-throw them synchronously to interrupt flushing! // Ensure continuation if the uncaught exception is suppressed // listening "uncaughtException" events (as domains does). // Continue in next event to avoid tick recursion. if (domain) { domain.exit(); } setTimeout(flush, 0); if (domain) { domain.enter(); } throw e; } else { // In browsers, uncaught exceptions are not fatal. // Re-throw them asynchronously to avoid slow-downs. setTimeout(function () { throw e; }, 0); } } if (domain) { domain.exit(); } }
[ "function", "runSingle", "(", "task", ",", "domain", ")", "{", "try", "{", "task", "(", ")", ";", "}", "catch", "(", "e", ")", "{", "if", "(", "isNodeJS", ")", "{", "// In node, uncaught exceptions are considered fatal errors.", "// Re-throw them synchronously to interrupt flushing!", "// Ensure continuation if the uncaught exception is suppressed", "// listening \"uncaughtException\" events (as domains does).", "// Continue in next event to avoid tick recursion.", "if", "(", "domain", ")", "{", "domain", ".", "exit", "(", ")", ";", "}", "setTimeout", "(", "flush", ",", "0", ")", ";", "if", "(", "domain", ")", "{", "domain", ".", "enter", "(", ")", ";", "}", "throw", "e", ";", "}", "else", "{", "// In browsers, uncaught exceptions are not fatal.", "// Re-throw them asynchronously to avoid slow-downs.", "setTimeout", "(", "function", "(", ")", "{", "throw", "e", ";", "}", ",", "0", ")", ";", "}", "}", "if", "(", "domain", ")", "{", "domain", ".", "exit", "(", ")", ";", "}", "}" ]
runs a single function in the async queue
[ "runs", "a", "single", "function", "in", "the", "async", "queue" ]
ae55bb3fafc949b7d786cd45a10e10d30d9457a6
https://github.com/ibm-developer/generator-ibm-core-node-express/blob/ae55bb3fafc949b7d786cd45a10e10d30d9457a6/app/templates/public/swagger-ui/swagger-ui.js#L18279-L18313
24,337
ibm-developer/generator-ibm-core-node-express
app/templates/public/swagger-ui/swagger-ui.js
captureLine
function captureLine() { if (!hasStacks) { return; } try { throw new Error(); } catch (e) { var lines = e.stack.split("\n"); var firstLine = lines[0].indexOf("@") > 0 ? lines[1] : lines[2]; var fileNameAndLineNumber = getFileNameAndLineNumber(firstLine); if (!fileNameAndLineNumber) { return; } qFileName = fileNameAndLineNumber[0]; return fileNameAndLineNumber[1]; } }
javascript
function captureLine() { if (!hasStacks) { return; } try { throw new Error(); } catch (e) { var lines = e.stack.split("\n"); var firstLine = lines[0].indexOf("@") > 0 ? lines[1] : lines[2]; var fileNameAndLineNumber = getFileNameAndLineNumber(firstLine); if (!fileNameAndLineNumber) { return; } qFileName = fileNameAndLineNumber[0]; return fileNameAndLineNumber[1]; } }
[ "function", "captureLine", "(", ")", "{", "if", "(", "!", "hasStacks", ")", "{", "return", ";", "}", "try", "{", "throw", "new", "Error", "(", ")", ";", "}", "catch", "(", "e", ")", "{", "var", "lines", "=", "e", ".", "stack", ".", "split", "(", "\"\\n\"", ")", ";", "var", "firstLine", "=", "lines", "[", "0", "]", ".", "indexOf", "(", "\"@\"", ")", ">", "0", "?", "lines", "[", "1", "]", ":", "lines", "[", "2", "]", ";", "var", "fileNameAndLineNumber", "=", "getFileNameAndLineNumber", "(", "firstLine", ")", ";", "if", "(", "!", "fileNameAndLineNumber", ")", "{", "return", ";", "}", "qFileName", "=", "fileNameAndLineNumber", "[", "0", "]", ";", "return", "fileNameAndLineNumber", "[", "1", "]", ";", "}", "}" ]
discover own file name and line number range for filtering stack traces
[ "discover", "own", "file", "name", "and", "line", "number", "range", "for", "filtering", "stack", "traces" ]
ae55bb3fafc949b7d786cd45a10e10d30d9457a6
https://github.com/ibm-developer/generator-ibm-core-node-express/blob/ae55bb3fafc949b7d786cd45a10e10d30d9457a6/app/templates/public/swagger-ui/swagger-ui.js#L18596-L18614
24,338
ibm-developer/generator-ibm-core-node-express
app/templates/public/swagger-ui/swagger-ui.js
Q
function Q(value) { // If the object is already a Promise, return it directly. This enables // the resolve function to both be used to created references from objects, // but to tolerably coerce non-promises to promises. if (value instanceof Promise) { return value; } // assimilate thenables if (isPromiseAlike(value)) { return coerce(value); } else { return fulfill(value); } }
javascript
function Q(value) { // If the object is already a Promise, return it directly. This enables // the resolve function to both be used to created references from objects, // but to tolerably coerce non-promises to promises. if (value instanceof Promise) { return value; } // assimilate thenables if (isPromiseAlike(value)) { return coerce(value); } else { return fulfill(value); } }
[ "function", "Q", "(", "value", ")", "{", "// If the object is already a Promise, return it directly. This enables", "// the resolve function to both be used to created references from objects,", "// but to tolerably coerce non-promises to promises.", "if", "(", "value", "instanceof", "Promise", ")", "{", "return", "value", ";", "}", "// assimilate thenables", "if", "(", "isPromiseAlike", "(", "value", ")", ")", "{", "return", "coerce", "(", "value", ")", ";", "}", "else", "{", "return", "fulfill", "(", "value", ")", ";", "}", "}" ]
end of shims beginning of real work Constructs a promise for an immediate reference, passes promises through, or coerces promises from different systems. @param value immediate reference or promise
[ "end", "of", "shims", "beginning", "of", "real", "work", "Constructs", "a", "promise", "for", "an", "immediate", "reference", "passes", "promises", "through", "or", "coerces", "promises", "from", "different", "systems", "." ]
ae55bb3fafc949b7d786cd45a10e10d30d9457a6
https://github.com/ibm-developer/generator-ibm-core-node-express/blob/ae55bb3fafc949b7d786cd45a10e10d30d9457a6/app/templates/public/swagger-ui/swagger-ui.js#L18635-L18649
24,339
ibm-developer/generator-ibm-core-node-express
app/templates/public/swagger-ui/swagger-ui.js
continuer
function continuer(verb, arg) { var result; // Until V8 3.19 / Chromium 29 is released, SpiderMonkey is the only // engine that has a deployed base of browsers that support generators. // However, SM's generators use the Python-inspired semantics of // outdated ES6 drafts. We would like to support ES6, but we'd also // like to make it possible to use generators in deployed browsers, so // we also support Python-style generators. At some point we can remove // this block. if (typeof StopIteration === "undefined") { // ES6 Generators try { result = generator[verb](arg); } catch (exception) { return reject(exception); } if (result.done) { return Q(result.value); } else { return when(result.value, callback, errback); } } else { // SpiderMonkey Generators // FIXME: Remove this case when SM does ES6 generators. try { result = generator[verb](arg); } catch (exception) { if (isStopIteration(exception)) { return Q(exception.value); } else { return reject(exception); } } return when(result, callback, errback); } }
javascript
function continuer(verb, arg) { var result; // Until V8 3.19 / Chromium 29 is released, SpiderMonkey is the only // engine that has a deployed base of browsers that support generators. // However, SM's generators use the Python-inspired semantics of // outdated ES6 drafts. We would like to support ES6, but we'd also // like to make it possible to use generators in deployed browsers, so // we also support Python-style generators. At some point we can remove // this block. if (typeof StopIteration === "undefined") { // ES6 Generators try { result = generator[verb](arg); } catch (exception) { return reject(exception); } if (result.done) { return Q(result.value); } else { return when(result.value, callback, errback); } } else { // SpiderMonkey Generators // FIXME: Remove this case when SM does ES6 generators. try { result = generator[verb](arg); } catch (exception) { if (isStopIteration(exception)) { return Q(exception.value); } else { return reject(exception); } } return when(result, callback, errback); } }
[ "function", "continuer", "(", "verb", ",", "arg", ")", "{", "var", "result", ";", "// Until V8 3.19 / Chromium 29 is released, SpiderMonkey is the only", "// engine that has a deployed base of browsers that support generators.", "// However, SM's generators use the Python-inspired semantics of", "// outdated ES6 drafts. We would like to support ES6, but we'd also", "// like to make it possible to use generators in deployed browsers, so", "// we also support Python-style generators. At some point we can remove", "// this block.", "if", "(", "typeof", "StopIteration", "===", "\"undefined\"", ")", "{", "// ES6 Generators", "try", "{", "result", "=", "generator", "[", "verb", "]", "(", "arg", ")", ";", "}", "catch", "(", "exception", ")", "{", "return", "reject", "(", "exception", ")", ";", "}", "if", "(", "result", ".", "done", ")", "{", "return", "Q", "(", "result", ".", "value", ")", ";", "}", "else", "{", "return", "when", "(", "result", ".", "value", ",", "callback", ",", "errback", ")", ";", "}", "}", "else", "{", "// SpiderMonkey Generators", "// FIXME: Remove this case when SM does ES6 generators.", "try", "{", "result", "=", "generator", "[", "verb", "]", "(", "arg", ")", ";", "}", "catch", "(", "exception", ")", "{", "if", "(", "isStopIteration", "(", "exception", ")", ")", "{", "return", "Q", "(", "exception", ".", "value", ")", ";", "}", "else", "{", "return", "reject", "(", "exception", ")", ";", "}", "}", "return", "when", "(", "result", ",", "callback", ",", "errback", ")", ";", "}", "}" ]
when verb is "send", arg is a value when verb is "throw", arg is an exception
[ "when", "verb", "is", "send", "arg", "is", "a", "value", "when", "verb", "is", "throw", "arg", "is", "an", "exception" ]
ae55bb3fafc949b7d786cd45a10e10d30d9457a6
https://github.com/ibm-developer/generator-ibm-core-node-express/blob/ae55bb3fafc949b7d786cd45a10e10d30d9457a6/app/templates/public/swagger-ui/swagger-ui.js#L19408-L19445
24,340
ibm-developer/generator-ibm-core-node-express
app/templates/public/swagger-ui/swagger-ui.js
function(data){ if (data === undefined) { data = ''; } var $msgbar = $('#message-bar'); $msgbar.removeClass('message-fail'); $msgbar.addClass('message-success'); $msgbar.text(data); if(window.SwaggerTranslator) { window.SwaggerTranslator.translate($msgbar); } }
javascript
function(data){ if (data === undefined) { data = ''; } var $msgbar = $('#message-bar'); $msgbar.removeClass('message-fail'); $msgbar.addClass('message-success'); $msgbar.text(data); if(window.SwaggerTranslator) { window.SwaggerTranslator.translate($msgbar); } }
[ "function", "(", "data", ")", "{", "if", "(", "data", "===", "undefined", ")", "{", "data", "=", "''", ";", "}", "var", "$msgbar", "=", "$", "(", "'#message-bar'", ")", ";", "$msgbar", ".", "removeClass", "(", "'message-fail'", ")", ";", "$msgbar", ".", "addClass", "(", "'message-success'", ")", ";", "$msgbar", ".", "text", "(", "data", ")", ";", "if", "(", "window", ".", "SwaggerTranslator", ")", "{", "window", ".", "SwaggerTranslator", ".", "translate", "(", "$msgbar", ")", ";", "}", "}" ]
Shows message on topbar of the ui
[ "Shows", "message", "on", "topbar", "of", "the", "ui" ]
ae55bb3fafc949b7d786cd45a10e10d30d9457a6
https://github.com/ibm-developer/generator-ibm-core-node-express/blob/ae55bb3fafc949b7d786cd45a10e10d30d9457a6/app/templates/public/swagger-ui/swagger-ui.js#L21945-L21956
24,341
ibm-developer/generator-ibm-core-node-express
app/templates/public/swagger-ui/swagger-ui.js
function(data) { var h, headerArray, headers, i, l, len, o; headers = {}; headerArray = data.getAllResponseHeaders().split('\r'); for (l = 0, len = headerArray.length; l < len; l++) { i = headerArray[l]; h = i.match(/^([^:]*?):(.*)$/); if (!h) { h = []; } h.shift(); if (h[0] !== void 0 && h[1] !== void 0) { headers[h[0].trim()] = h[1].trim(); } } o = {}; o.content = {}; o.content.data = data.responseText; o.headers = headers; o.request = {}; o.request.url = this.invocationUrl; o.status = data.status; return o; }
javascript
function(data) { var h, headerArray, headers, i, l, len, o; headers = {}; headerArray = data.getAllResponseHeaders().split('\r'); for (l = 0, len = headerArray.length; l < len; l++) { i = headerArray[l]; h = i.match(/^([^:]*?):(.*)$/); if (!h) { h = []; } h.shift(); if (h[0] !== void 0 && h[1] !== void 0) { headers[h[0].trim()] = h[1].trim(); } } o = {}; o.content = {}; o.content.data = data.responseText; o.headers = headers; o.request = {}; o.request.url = this.invocationUrl; o.status = data.status; return o; }
[ "function", "(", "data", ")", "{", "var", "h", ",", "headerArray", ",", "headers", ",", "i", ",", "l", ",", "len", ",", "o", ";", "headers", "=", "{", "}", ";", "headerArray", "=", "data", ".", "getAllResponseHeaders", "(", ")", ".", "split", "(", "'\\r'", ")", ";", "for", "(", "l", "=", "0", ",", "len", "=", "headerArray", ".", "length", ";", "l", "<", "len", ";", "l", "++", ")", "{", "i", "=", "headerArray", "[", "l", "]", ";", "h", "=", "i", ".", "match", "(", "/", "^([^:]*?):(.*)$", "/", ")", ";", "if", "(", "!", "h", ")", "{", "h", "=", "[", "]", ";", "}", "h", ".", "shift", "(", ")", ";", "if", "(", "h", "[", "0", "]", "!==", "void", "0", "&&", "h", "[", "1", "]", "!==", "void", "0", ")", "{", "headers", "[", "h", "[", "0", "]", ".", "trim", "(", ")", "]", "=", "h", "[", "1", "]", ".", "trim", "(", ")", ";", "}", "}", "o", "=", "{", "}", ";", "o", ".", "content", "=", "{", "}", ";", "o", ".", "content", ".", "data", "=", "data", ".", "responseText", ";", "o", ".", "headers", "=", "headers", ";", "o", ".", "request", "=", "{", "}", ";", "o", ".", "request", ".", "url", "=", "this", ".", "invocationUrl", ";", "o", ".", "status", "=", "data", ".", "status", ";", "return", "o", ";", "}" ]
wraps a jquery response as a shred response
[ "wraps", "a", "jquery", "response", "as", "a", "shred", "response" ]
ae55bb3fafc949b7d786cd45a10e10d30d9457a6
https://github.com/ibm-developer/generator-ibm-core-node-express/blob/ae55bb3fafc949b7d786cd45a10e10d30d9457a6/app/templates/public/swagger-ui/swagger-ui.js#L23582-L23605
24,342
ibm-developer/generator-ibm-core-node-express
app/templates/public/swagger-ui/swagger-ui.js
function(response) { var prettyJson = JSON.stringify(response, null, '\t').replace(/\n/g, '<br>'); $('.response_body', $(this.el)).html(_.escape(prettyJson)); }
javascript
function(response) { var prettyJson = JSON.stringify(response, null, '\t').replace(/\n/g, '<br>'); $('.response_body', $(this.el)).html(_.escape(prettyJson)); }
[ "function", "(", "response", ")", "{", "var", "prettyJson", "=", "JSON", ".", "stringify", "(", "response", ",", "null", ",", "'\\t'", ")", ".", "replace", "(", "/", "\\n", "/", "g", ",", "'<br>'", ")", ";", "$", "(", "'.response_body'", ",", "$", "(", "this", ".", "el", ")", ")", ".", "html", "(", "_", ".", "escape", "(", "prettyJson", ")", ")", ";", "}" ]
Show response from server
[ "Show", "response", "from", "server" ]
ae55bb3fafc949b7d786cd45a10e10d30d9457a6
https://github.com/ibm-developer/generator-ibm-core-node-express/blob/ae55bb3fafc949b7d786cd45a10e10d30d9457a6/app/templates/public/swagger-ui/swagger-ui.js#L23634-L23637
24,343
magalhas/backbone-react-component
examples/blog/public/components/blog.js
function (event) { var target = event.target; var key = target.getAttribute('name'); var nextState = {}; nextState[key] = target.value; this.setState(nextState); }
javascript
function (event) { var target = event.target; var key = target.getAttribute('name'); var nextState = {}; nextState[key] = target.value; this.setState(nextState); }
[ "function", "(", "event", ")", "{", "var", "target", "=", "event", ".", "target", ";", "var", "key", "=", "target", ".", "getAttribute", "(", "'name'", ")", ";", "var", "nextState", "=", "{", "}", ";", "nextState", "[", "key", "]", "=", "target", ".", "value", ";", "this", ".", "setState", "(", "nextState", ")", ";", "}" ]
Whenever an input changes, set it into this.state
[ "Whenever", "an", "input", "changes", "set", "it", "into", "this", ".", "state" ]
5525a9576912461936f48d97e533bde0b793b327
https://github.com/magalhas/backbone-react-component/blob/5525a9576912461936f48d97e533bde0b793b327/examples/blog/public/components/blog.js#L47-L53
24,344
magalhas/backbone-react-component
examples/blog/public/components/blog.js
function (event) { var id = event.target.parentNode.getAttribute('data-id'); // By getting collection through this.state you get an hash of the collection this.setState(_.findWhere(this.state.collection, {id: id})); }
javascript
function (event) { var id = event.target.parentNode.getAttribute('data-id'); // By getting collection through this.state you get an hash of the collection this.setState(_.findWhere(this.state.collection, {id: id})); }
[ "function", "(", "event", ")", "{", "var", "id", "=", "event", ".", "target", ".", "parentNode", ".", "getAttribute", "(", "'data-id'", ")", ";", "// By getting collection through this.state you get an hash of the collection", "this", ".", "setState", "(", "_", ".", "findWhere", "(", "this", ".", "state", ".", "collection", ",", "{", "id", ":", "id", "}", ")", ")", ";", "}" ]
Getting the id of the post that triggered the edit button and passing the respective model into this.state.
[ "Getting", "the", "id", "of", "the", "post", "that", "triggered", "the", "edit", "button", "and", "passing", "the", "respective", "model", "into", "this", ".", "state", "." ]
5525a9576912461936f48d97e533bde0b793b327
https://github.com/magalhas/backbone-react-component/blob/5525a9576912461936f48d97e533bde0b793b327/examples/blog/public/components/blog.js#L56-L60
24,345
magalhas/backbone-react-component
examples/blog/public/components/blog.js
function (event) { event.preventDefault(); var collection = this.getCollection(); var id = this.state.id; var model; if (id) { // Update existing model model = collection.get(id); model.save(this.state, {wait: true}); } else { // Create a new one collection.create(this.state, {wait: true}); } // Set initial state this.replaceState(this.getInitialState()); }
javascript
function (event) { event.preventDefault(); var collection = this.getCollection(); var id = this.state.id; var model; if (id) { // Update existing model model = collection.get(id); model.save(this.state, {wait: true}); } else { // Create a new one collection.create(this.state, {wait: true}); } // Set initial state this.replaceState(this.getInitialState()); }
[ "function", "(", "event", ")", "{", "event", ".", "preventDefault", "(", ")", ";", "var", "collection", "=", "this", ".", "getCollection", "(", ")", ";", "var", "id", "=", "this", ".", "state", ".", "id", ";", "var", "model", ";", "if", "(", "id", ")", "{", "// Update existing model", "model", "=", "collection", ".", "get", "(", "id", ")", ";", "model", ".", "save", "(", "this", ".", "state", ",", "{", "wait", ":", "true", "}", ")", ";", "}", "else", "{", "// Create a new one", "collection", ".", "create", "(", "this", ".", "state", ",", "{", "wait", ":", "true", "}", ")", ";", "}", "// Set initial state", "this", ".", "replaceState", "(", "this", ".", "getInitialState", "(", ")", ")", ";", "}" ]
Save the new or existing post to the services
[ "Save", "the", "new", "or", "existing", "post", "to", "the", "services" ]
5525a9576912461936f48d97e533bde0b793b327
https://github.com/magalhas/backbone-react-component/blob/5525a9576912461936f48d97e533bde0b793b327/examples/blog/public/components/blog.js#L70-L85
24,346
magalhas/backbone-react-component
examples/blog/public/components/blog.js
function () { return ( React.DOM.div(null, this.state.collection && this.state.collection.map(this.createPost), this.createForm() ) ); }
javascript
function () { return ( React.DOM.div(null, this.state.collection && this.state.collection.map(this.createPost), this.createForm() ) ); }
[ "function", "(", ")", "{", "return", "(", "React", ".", "DOM", ".", "div", "(", "null", ",", "this", ".", "state", ".", "collection", "&&", "this", ".", "state", ".", "collection", ".", "map", "(", "this", ".", "createPost", ")", ",", "this", ".", "createForm", "(", ")", ")", ")", ";", "}" ]
Go go react
[ "Go", "go", "react" ]
5525a9576912461936f48d97e533bde0b793b327
https://github.com/magalhas/backbone-react-component/blob/5525a9576912461936f48d97e533bde0b793b327/examples/blog/public/components/blog.js#L87-L94
24,347
clay/amphora
lib/services/attachRoutes.js
validPath
function validPath(path, site) { let reservedRoute; if (path[0] !== '/') { log('warn', `Cannot attach route '${path}' for site ${site.slug}. Path must begin with a slash.`); return false; } reservedRoute = _.find(reservedRoutes, (route) => path.indexOf(route) === 1); if (reservedRoute) { log('warn', `Cannot attach route '${path}' for site ${site.slug}. Route prefix /${reservedRoute} is reserved by Amphora.`); return false; } return true; }
javascript
function validPath(path, site) { let reservedRoute; if (path[0] !== '/') { log('warn', `Cannot attach route '${path}' for site ${site.slug}. Path must begin with a slash.`); return false; } reservedRoute = _.find(reservedRoutes, (route) => path.indexOf(route) === 1); if (reservedRoute) { log('warn', `Cannot attach route '${path}' for site ${site.slug}. Route prefix /${reservedRoute} is reserved by Amphora.`); return false; } return true; }
[ "function", "validPath", "(", "path", ",", "site", ")", "{", "let", "reservedRoute", ";", "if", "(", "path", "[", "0", "]", "!==", "'/'", ")", "{", "log", "(", "'warn'", ",", "`", "${", "path", "}", "${", "site", ".", "slug", "}", "`", ")", ";", "return", "false", ";", "}", "reservedRoute", "=", "_", ".", "find", "(", "reservedRoutes", ",", "(", "route", ")", "=>", "path", ".", "indexOf", "(", "route", ")", "===", "1", ")", ";", "if", "(", "reservedRoute", ")", "{", "log", "(", "'warn'", ",", "`", "${", "path", "}", "${", "site", ".", "slug", "}", "${", "reservedRoute", "}", "`", ")", ";", "return", "false", ";", "}", "return", "true", ";", "}" ]
Checks for validity of a route to be attached @param {String} path @param {Object} site @returns {Boolean}
[ "Checks", "for", "validity", "of", "a", "route", "to", "be", "attached" ]
b883a94cbc38c1891ce568addb6cb280aa1d5353
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/services/attachRoutes.js#L16-L32
24,348
clay/amphora
lib/services/attachRoutes.js
normalizeRedirectPath
function normalizeRedirectPath(redirect, site) { return site.path && !redirect.includes(site.path) ? `${site.path}${redirect}` : redirect; }
javascript
function normalizeRedirectPath(redirect, site) { return site.path && !redirect.includes(site.path) ? `${site.path}${redirect}` : redirect; }
[ "function", "normalizeRedirectPath", "(", "redirect", ",", "site", ")", "{", "return", "site", ".", "path", "&&", "!", "redirect", ".", "includes", "(", "site", ".", "path", ")", "?", "`", "${", "site", ".", "path", "}", "${", "redirect", "}", "`", ":", "redirect", ";", "}" ]
Normalizes redirects path appending site's path to it on sub-sites' redirects. @param {String} redirect @param {Object} site @return {String}
[ "Normalizes", "redirects", "path", "appending", "site", "s", "path", "to", "it", "on", "sub", "-", "sites", "redirects", "." ]
b883a94cbc38c1891ce568addb6cb280aa1d5353
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/services/attachRoutes.js#L40-L42
24,349
clay/amphora
lib/services/attachRoutes.js
attachRedirect
function attachRedirect(router, { path, redirect }, site) { redirect = normalizeRedirectPath(redirect, site); return router.get(path, (req, res) => { res.redirect(301, redirect); }); }
javascript
function attachRedirect(router, { path, redirect }, site) { redirect = normalizeRedirectPath(redirect, site); return router.get(path, (req, res) => { res.redirect(301, redirect); }); }
[ "function", "attachRedirect", "(", "router", ",", "{", "path", ",", "redirect", "}", ",", "site", ")", "{", "redirect", "=", "normalizeRedirectPath", "(", "redirect", ",", "site", ")", ";", "return", "router", ".", "get", "(", "path", ",", "(", "req", ",", "res", ")", "=>", "{", "res", ".", "redirect", "(", "301", ",", "redirect", ")", ";", "}", ")", ";", "}" ]
Attaches a route with redirect to the router. @param {Router} router @param {Object} route @param {String} route.path @param {String} route.redirect @param {Object} site @return {Router}
[ "Attaches", "a", "route", "with", "redirect", "to", "the", "router", "." ]
b883a94cbc38c1891ce568addb6cb280aa1d5353
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/services/attachRoutes.js#L64-L70
24,350
clay/amphora
lib/services/attachRoutes.js
attachDynamicRoute
function attachDynamicRoute(router, { path, dynamicPage }) { return router.get(path, render.renderDynamicRoute(dynamicPage)); }
javascript
function attachDynamicRoute(router, { path, dynamicPage }) { return router.get(path, render.renderDynamicRoute(dynamicPage)); }
[ "function", "attachDynamicRoute", "(", "router", ",", "{", "path", ",", "dynamicPage", "}", ")", "{", "return", "router", ".", "get", "(", "path", ",", "render", ".", "renderDynamicRoute", "(", "dynamicPage", ")", ")", ";", "}" ]
Attaches a dynamic route to the router. @param {Router} router @param {Object} route @param {String} route.path @param {String} route.dynamicPage @return {Router}
[ "Attaches", "a", "dynamic", "route", "to", "the", "router", "." ]
b883a94cbc38c1891ce568addb6cb280aa1d5353
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/services/attachRoutes.js#L80-L82
24,351
clay/amphora
lib/services/attachRoutes.js
parseHandler
function parseHandler(router, routeObj, site) { const { redirect, dynamicPage, path, middleware } = routeObj; if (!validPath(path, site)) { return; } if (middleware) { router.use(path, middleware); } if (redirect) { return attachRedirect(router, routeObj, site); } else if (dynamicPage) { return attachDynamicRoute(router, routeObj); // Pass in the page ID } else { return attachPlainRoute(router, routeObj); } }
javascript
function parseHandler(router, routeObj, site) { const { redirect, dynamicPage, path, middleware } = routeObj; if (!validPath(path, site)) { return; } if (middleware) { router.use(path, middleware); } if (redirect) { return attachRedirect(router, routeObj, site); } else if (dynamicPage) { return attachDynamicRoute(router, routeObj); // Pass in the page ID } else { return attachPlainRoute(router, routeObj); } }
[ "function", "parseHandler", "(", "router", ",", "routeObj", ",", "site", ")", "{", "const", "{", "redirect", ",", "dynamicPage", ",", "path", ",", "middleware", "}", "=", "routeObj", ";", "if", "(", "!", "validPath", "(", "path", ",", "site", ")", ")", "{", "return", ";", "}", "if", "(", "middleware", ")", "{", "router", ".", "use", "(", "path", ",", "middleware", ")", ";", "}", "if", "(", "redirect", ")", "{", "return", "attachRedirect", "(", "router", ",", "routeObj", ",", "site", ")", ";", "}", "else", "if", "(", "dynamicPage", ")", "{", "return", "attachDynamicRoute", "(", "router", ",", "routeObj", ")", ";", "// Pass in the page ID", "}", "else", "{", "return", "attachPlainRoute", "(", "router", ",", "routeObj", ")", ";", "}", "}" ]
Parses site route config object. @param {Router} router @param {Object} routeObj - Route config @param {Object} site @return {Router}
[ "Parses", "site", "route", "config", "object", "." ]
b883a94cbc38c1891ce568addb6cb280aa1d5353
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/services/attachRoutes.js#L91-L109
24,352
clay/amphora
lib/services/attachRoutes.js
attachRoutes
function attachRoutes(router, routes = [], site) { routes.forEach((route) => { parseHandler(router, route, site); }); return router; }
javascript
function attachRoutes(router, routes = [], site) { routes.forEach((route) => { parseHandler(router, route, site); }); return router; }
[ "function", "attachRoutes", "(", "router", ",", "routes", "=", "[", "]", ",", "site", ")", "{", "routes", ".", "forEach", "(", "(", "route", ")", "=>", "{", "parseHandler", "(", "router", ",", "route", ",", "site", ")", ";", "}", ")", ";", "return", "router", ";", "}" ]
Parses and attach all routes to the router. @param {Router} router @param {Object[]} routes @param {Object} site @param {Array} reservedRoutes @return {Router}
[ "Parses", "and", "attach", "all", "routes", "to", "the", "router", "." ]
b883a94cbc38c1891ce568addb6cb280aa1d5353
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/services/attachRoutes.js#L119-L125
24,353
clay/amphora
lib/services/composer.js
resolveComponentReferences
function resolveComponentReferences(data, locals, filter = referenceProperty) { const referenceObjects = references.listDeepObjects(data, filter); return bluebird.all(referenceObjects).each(referenceObject => { return components.get(referenceObject[referenceProperty], locals) .then(obj => { // the thing we got back might have its own references return resolveComponentReferences(obj, locals, filter).finally(() => { _.assign(referenceObject, _.omit(obj, referenceProperty)); }).catch(function (error) { const logObj = { stack: error.stack, cmpt: referenceObject[referenceProperty] }; if (error.status) { logObj.status = error.status; } log('error', `${error.message}`, logObj); return bluebird.reject(error); }); }); }).then(() => data); }
javascript
function resolveComponentReferences(data, locals, filter = referenceProperty) { const referenceObjects = references.listDeepObjects(data, filter); return bluebird.all(referenceObjects).each(referenceObject => { return components.get(referenceObject[referenceProperty], locals) .then(obj => { // the thing we got back might have its own references return resolveComponentReferences(obj, locals, filter).finally(() => { _.assign(referenceObject, _.omit(obj, referenceProperty)); }).catch(function (error) { const logObj = { stack: error.stack, cmpt: referenceObject[referenceProperty] }; if (error.status) { logObj.status = error.status; } log('error', `${error.message}`, logObj); return bluebird.reject(error); }); }); }).then(() => data); }
[ "function", "resolveComponentReferences", "(", "data", ",", "locals", ",", "filter", "=", "referenceProperty", ")", "{", "const", "referenceObjects", "=", "references", ".", "listDeepObjects", "(", "data", ",", "filter", ")", ";", "return", "bluebird", ".", "all", "(", "referenceObjects", ")", ".", "each", "(", "referenceObject", "=>", "{", "return", "components", ".", "get", "(", "referenceObject", "[", "referenceProperty", "]", ",", "locals", ")", ".", "then", "(", "obj", "=>", "{", "// the thing we got back might have its own references", "return", "resolveComponentReferences", "(", "obj", ",", "locals", ",", "filter", ")", ".", "finally", "(", "(", ")", "=>", "{", "_", ".", "assign", "(", "referenceObject", ",", "_", ".", "omit", "(", "obj", ",", "referenceProperty", ")", ")", ";", "}", ")", ".", "catch", "(", "function", "(", "error", ")", "{", "const", "logObj", "=", "{", "stack", ":", "error", ".", "stack", ",", "cmpt", ":", "referenceObject", "[", "referenceProperty", "]", "}", ";", "if", "(", "error", ".", "status", ")", "{", "logObj", ".", "status", "=", "error", ".", "status", ";", "}", "log", "(", "'error'", ",", "`", "${", "error", ".", "message", "}", "`", ",", "logObj", ")", ";", "return", "bluebird", ".", "reject", "(", "error", ")", ";", "}", ")", ";", "}", ")", ";", "}", ")", ".", "then", "(", "(", ")", "=>", "data", ")", ";", "}" ]
Compose a component, recursively filling in all component references with instance data. @param {object} data @param {object} locals Extra data that some GETs use @param {function|string} [filter='_ref'] @returns {Promise} - Resolves with composed component data
[ "Compose", "a", "component", "recursively", "filling", "in", "all", "component", "references", "with", "instance", "data", "." ]
b883a94cbc38c1891ce568addb6cb280aa1d5353
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/services/composer.js#L19-L44
24,354
clay/amphora
lib/services/composer.js
composePage
function composePage(pageData, locals) { const layoutReference = pageData.layout, pageDataNoConf = references.omitPageConfiguration(pageData); return components.get(layoutReference) .then(layoutData => mapLayoutToPageData(pageDataNoConf, layoutData)) .then(fullData => resolveComponentReferences(fullData, locals)); }
javascript
function composePage(pageData, locals) { const layoutReference = pageData.layout, pageDataNoConf = references.omitPageConfiguration(pageData); return components.get(layoutReference) .then(layoutData => mapLayoutToPageData(pageDataNoConf, layoutData)) .then(fullData => resolveComponentReferences(fullData, locals)); }
[ "function", "composePage", "(", "pageData", ",", "locals", ")", "{", "const", "layoutReference", "=", "pageData", ".", "layout", ",", "pageDataNoConf", "=", "references", ".", "omitPageConfiguration", "(", "pageData", ")", ";", "return", "components", ".", "get", "(", "layoutReference", ")", ".", "then", "(", "layoutData", "=>", "mapLayoutToPageData", "(", "pageDataNoConf", ",", "layoutData", ")", ")", ".", "then", "(", "fullData", "=>", "resolveComponentReferences", "(", "fullData", ",", "locals", ")", ")", ";", "}" ]
Compose a page, recursively filling in all component references with instance data. @param {object} pageData @param {object} locals @return {Promise} - Resolves with composed page data
[ "Compose", "a", "page", "recursively", "filling", "in", "all", "component", "references", "with", "instance", "data", "." ]
b883a94cbc38c1891ce568addb6cb280aa1d5353
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/services/composer.js#L53-L60
24,355
clay/amphora
lib/utils/layout-to-page-data.js
mapLayoutToPageData
function mapLayoutToPageData(pageData, layoutData) { // quickly (and shallowly) go through the layout's properties, // finding strings that map to page properties _.each(layoutData, function (list, key) { if (_.isString(list)) { if (_.isArray(pageData[key])) { // if you find a match and the data exists, // replace the property in the layout data layoutData[key] = _.map(pageData[key], refToObj); } else { // otherwise replace it with an empty list // as all layout properties are component lists layoutData[key] = []; } } }); return layoutData; }
javascript
function mapLayoutToPageData(pageData, layoutData) { // quickly (and shallowly) go through the layout's properties, // finding strings that map to page properties _.each(layoutData, function (list, key) { if (_.isString(list)) { if (_.isArray(pageData[key])) { // if you find a match and the data exists, // replace the property in the layout data layoutData[key] = _.map(pageData[key], refToObj); } else { // otherwise replace it with an empty list // as all layout properties are component lists layoutData[key] = []; } } }); return layoutData; }
[ "function", "mapLayoutToPageData", "(", "pageData", ",", "layoutData", ")", "{", "// quickly (and shallowly) go through the layout's properties,", "// finding strings that map to page properties", "_", ".", "each", "(", "layoutData", ",", "function", "(", "list", ",", "key", ")", "{", "if", "(", "_", ".", "isString", "(", "list", ")", ")", "{", "if", "(", "_", ".", "isArray", "(", "pageData", "[", "key", "]", ")", ")", "{", "// if you find a match and the data exists,", "// replace the property in the layout data", "layoutData", "[", "key", "]", "=", "_", ".", "map", "(", "pageData", "[", "key", "]", ",", "refToObj", ")", ";", "}", "else", "{", "// otherwise replace it with an empty list", "// as all layout properties are component lists", "layoutData", "[", "key", "]", "=", "[", "]", ";", "}", "}", "}", ")", ";", "return", "layoutData", ";", "}" ]
Maps strings in arrays of layoutData into the properties of pageData @param {object} pageData @param {object} layoutData @returns {*}
[ "Maps", "strings", "in", "arrays", "of", "layoutData", "into", "the", "properties", "of", "pageData" ]
b883a94cbc38c1891ce568addb6cb280aa1d5353
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/utils/layout-to-page-data.js#L21-L39
24,356
clay/amphora
lib/services/uris.js
del
function del(uri, user, locals) { const callHooks = _.get(locals, 'hooks') !== 'false'; return db.get(uri).then(oldPageUri => { return db.del(uri).then(() => { const prefix = getPrefix(uri), site = siteService.getSiteFromPrefix(prefix), pageUrl = buf.decode(uri.split('/').pop()); if (!callHooks) { return Promise.resolve(oldPageUri); } bus.publish('unpublishPage', { uri: oldPageUri, url: pageUrl, user }); notifications.notify(site, 'unpublished', { url: pageUrl, uri: oldPageUri }); return meta.unpublishPage(oldPageUri, user) .then(() => oldPageUri); }); }); }
javascript
function del(uri, user, locals) { const callHooks = _.get(locals, 'hooks') !== 'false'; return db.get(uri).then(oldPageUri => { return db.del(uri).then(() => { const prefix = getPrefix(uri), site = siteService.getSiteFromPrefix(prefix), pageUrl = buf.decode(uri.split('/').pop()); if (!callHooks) { return Promise.resolve(oldPageUri); } bus.publish('unpublishPage', { uri: oldPageUri, url: pageUrl, user }); notifications.notify(site, 'unpublished', { url: pageUrl, uri: oldPageUri }); return meta.unpublishPage(oldPageUri, user) .then(() => oldPageUri); }); }); }
[ "function", "del", "(", "uri", ",", "user", ",", "locals", ")", "{", "const", "callHooks", "=", "_", ".", "get", "(", "locals", ",", "'hooks'", ")", "!==", "'false'", ";", "return", "db", ".", "get", "(", "uri", ")", ".", "then", "(", "oldPageUri", "=>", "{", "return", "db", ".", "del", "(", "uri", ")", ".", "then", "(", "(", ")", "=>", "{", "const", "prefix", "=", "getPrefix", "(", "uri", ")", ",", "site", "=", "siteService", ".", "getSiteFromPrefix", "(", "prefix", ")", ",", "pageUrl", "=", "buf", ".", "decode", "(", "uri", ".", "split", "(", "'/'", ")", ".", "pop", "(", ")", ")", ";", "if", "(", "!", "callHooks", ")", "{", "return", "Promise", ".", "resolve", "(", "oldPageUri", ")", ";", "}", "bus", ".", "publish", "(", "'unpublishPage'", ",", "{", "uri", ":", "oldPageUri", ",", "url", ":", "pageUrl", ",", "user", "}", ")", ";", "notifications", ".", "notify", "(", "site", ",", "'unpublished'", ",", "{", "url", ":", "pageUrl", ",", "uri", ":", "oldPageUri", "}", ")", ";", "return", "meta", ".", "unpublishPage", "(", "oldPageUri", ",", "user", ")", ".", "then", "(", "(", ")", "=>", "oldPageUri", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Deletes a URI NOTE: Return the data it used to contain. This is often used to create queues or messaging on the client-side, because clients can guarantee that only one client was allowed to be the last one to fetch a particular item. @param {string} uri @param {object} user @param {object} locals @returns {Promise}
[ "Deletes", "a", "URI" ]
b883a94cbc38c1891ce568addb6cb280aa1d5353
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/services/uris.js#L45-L64
24,357
clay/amphora
lib/services/upgrade.js
aggregateTransforms
function aggregateTransforms(schemaVersion, currentVersion, upgradeFile) { var transformVersions = generateVersionArray(upgradeFile), applicableVersions = []; for (let i = 0; i < transformVersions.length; i++) { let version = transformVersions[i]; if (!currentVersion && schemaVersion || schemaVersion >= version && version > currentVersion) { applicableVersions.push(transformVersions[i]); } } return applicableVersions; }
javascript
function aggregateTransforms(schemaVersion, currentVersion, upgradeFile) { var transformVersions = generateVersionArray(upgradeFile), applicableVersions = []; for (let i = 0; i < transformVersions.length; i++) { let version = transformVersions[i]; if (!currentVersion && schemaVersion || schemaVersion >= version && version > currentVersion) { applicableVersions.push(transformVersions[i]); } } return applicableVersions; }
[ "function", "aggregateTransforms", "(", "schemaVersion", ",", "currentVersion", ",", "upgradeFile", ")", "{", "var", "transformVersions", "=", "generateVersionArray", "(", "upgradeFile", ")", ",", "applicableVersions", "=", "[", "]", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "transformVersions", ".", "length", ";", "i", "++", ")", "{", "let", "version", "=", "transformVersions", "[", "i", "]", ";", "if", "(", "!", "currentVersion", "&&", "schemaVersion", "||", "schemaVersion", ">=", "version", "&&", "version", ">", "currentVersion", ")", "{", "applicableVersions", ".", "push", "(", "transformVersions", "[", "i", "]", ")", ";", "}", "}", "return", "applicableVersions", ";", "}" ]
Iterate through the array of version transforms provided and determine which versions are valid to be run. - If the data has no current version but the schema declares one, then run it - If the current schema version is greater than the current version AND the tranform version is greater than the current version, run it. @param {Number} schemaVersion @param {Number} currentVersion @param {Object} upgradeFile @return {Array}
[ "Iterate", "through", "the", "array", "of", "version", "transforms", "provided", "and", "determine", "which", "versions", "are", "valid", "to", "be", "run", "." ]
b883a94cbc38c1891ce568addb6cb280aa1d5353
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/services/upgrade.js#L56-L69
24,358
clay/amphora
lib/services/upgrade.js
runTransforms
function runTransforms(transforms, upgradeFile, ref, data, locals) { log('debug', `Running ${transforms.length} transforms`); return bluebird.reduce(transforms, function (acc, val) { var key = val.toString(); // Parsefloat strips decimals with `.0` leaving just the int, // let's add them back in if (!_.includes(key, '.')) { key += '.0'; } return bluebird.try(upgradeFile[key].bind(null, ref, acc, locals)) .catch(e => { log('error', `Error upgrading ${ref} to version ${key}: ${e.message}`, { errStack: e.stack, cmptData: JSON.stringify(acc) }); return bluebird.reject(e); }); }, data) .then(function (resp) { // Assign the version number automatically resp._version = transforms[transforms.length - 1]; return resp; }); }
javascript
function runTransforms(transforms, upgradeFile, ref, data, locals) { log('debug', `Running ${transforms.length} transforms`); return bluebird.reduce(transforms, function (acc, val) { var key = val.toString(); // Parsefloat strips decimals with `.0` leaving just the int, // let's add them back in if (!_.includes(key, '.')) { key += '.0'; } return bluebird.try(upgradeFile[key].bind(null, ref, acc, locals)) .catch(e => { log('error', `Error upgrading ${ref} to version ${key}: ${e.message}`, { errStack: e.stack, cmptData: JSON.stringify(acc) }); return bluebird.reject(e); }); }, data) .then(function (resp) { // Assign the version number automatically resp._version = transforms[transforms.length - 1]; return resp; }); }
[ "function", "runTransforms", "(", "transforms", ",", "upgradeFile", ",", "ref", ",", "data", ",", "locals", ")", "{", "log", "(", "'debug'", ",", "`", "${", "transforms", ".", "length", "}", "`", ")", ";", "return", "bluebird", ".", "reduce", "(", "transforms", ",", "function", "(", "acc", ",", "val", ")", "{", "var", "key", "=", "val", ".", "toString", "(", ")", ";", "// Parsefloat strips decimals with `.0` leaving just the int,", "// let's add them back in", "if", "(", "!", "_", ".", "includes", "(", "key", ",", "'.'", ")", ")", "{", "key", "+=", "'.0'", ";", "}", "return", "bluebird", ".", "try", "(", "upgradeFile", "[", "key", "]", ".", "bind", "(", "null", ",", "ref", ",", "acc", ",", "locals", ")", ")", ".", "catch", "(", "e", "=>", "{", "log", "(", "'error'", ",", "`", "${", "ref", "}", "${", "key", "}", "${", "e", ".", "message", "}", "`", ",", "{", "errStack", ":", "e", ".", "stack", ",", "cmptData", ":", "JSON", ".", "stringify", "(", "acc", ")", "}", ")", ";", "return", "bluebird", ".", "reject", "(", "e", ")", ";", "}", ")", ";", "}", ",", "data", ")", ".", "then", "(", "function", "(", "resp", ")", "{", "// Assign the version number automatically", "resp", ".", "_version", "=", "transforms", "[", "transforms", ".", "length", "-", "1", "]", ";", "return", "resp", ";", "}", ")", ";", "}" ]
We have a the transforms we need to perform, so let's reduce them into the final data object. @param {Array} transforms @param {Object} upgradeFile @param {String} ref @param {Object} data @param {Object} locals @return {Promise}
[ "We", "have", "a", "the", "transforms", "we", "need", "to", "perform", "so", "let", "s", "reduce", "them", "into", "the", "final", "data", "object", "." ]
b883a94cbc38c1891ce568addb6cb280aa1d5353
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/services/upgrade.js#L82-L107
24,359
clay/amphora
lib/services/upgrade.js
saveTransformedData
function saveTransformedData(uri) { return function (data) { return db.put(uri, JSON.stringify(data)) .then(function () { // If the Promise resolves it means we saved, // so let's return the data return data; }); }; }
javascript
function saveTransformedData(uri) { return function (data) { return db.put(uri, JSON.stringify(data)) .then(function () { // If the Promise resolves it means we saved, // so let's return the data return data; }); }; }
[ "function", "saveTransformedData", "(", "uri", ")", "{", "return", "function", "(", "data", ")", "{", "return", "db", ".", "put", "(", "uri", ",", "JSON", ".", "stringify", "(", "data", ")", ")", ".", "then", "(", "function", "(", ")", "{", "// If the Promise resolves it means we saved,", "// so let's return the data", "return", "data", ";", "}", ")", ";", "}", ";", "}" ]
The data that was upgraded needs to be saved so that we never need to upgrade again. Send it to the DB before returning that data. @param {String} uri @return {Function}
[ "The", "data", "that", "was", "upgraded", "needs", "to", "be", "saved", "so", "that", "we", "never", "need", "to", "upgrade", "again", ".", "Send", "it", "to", "the", "DB", "before", "returning", "that", "data", "." ]
b883a94cbc38c1891ce568addb6cb280aa1d5353
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/services/upgrade.js#L117-L126
24,360
clay/amphora
lib/services/upgrade.js
upgradeData
function upgradeData(schemaVersion, dataVersion, ref, data, locals) { const name = isComponent(ref) ? getComponentName(ref) : getLayoutName(ref), dir = isComponent(ref) ? files.getComponentPath(name) : files.getLayoutPath(name), // Get the component directory upgradeFile = files.tryRequire(path.resolve(dir, 'upgrade')); // Grab the the upgrade.js file var transforms = []; log('debug', `Running upgrade for ${name}: ${ref}`); // If no upgrade file exists, exit early if (!upgradeFile) { log('debug', `No upgrade file found for component: ${name}`); return bluebird.resolve(data); } // find all the transforms that have to be performed (object.keys) transforms = aggregateTransforms(schemaVersion, dataVersion, upgradeFile); // If no transforms need to be run, exit early if (!transforms.length) { log('debug', `Upgrade tried to run, but no upgrade function was found for ${name}`, { component: name, currentVersion: dataVersion, schemaVersion }); return bluebird.resolve(data); } // pass through the transform return runTransforms(transforms, upgradeFile, ref, data, locals) .then(saveTransformedData(ref)) .catch(e => { throw e; }); }
javascript
function upgradeData(schemaVersion, dataVersion, ref, data, locals) { const name = isComponent(ref) ? getComponentName(ref) : getLayoutName(ref), dir = isComponent(ref) ? files.getComponentPath(name) : files.getLayoutPath(name), // Get the component directory upgradeFile = files.tryRequire(path.resolve(dir, 'upgrade')); // Grab the the upgrade.js file var transforms = []; log('debug', `Running upgrade for ${name}: ${ref}`); // If no upgrade file exists, exit early if (!upgradeFile) { log('debug', `No upgrade file found for component: ${name}`); return bluebird.resolve(data); } // find all the transforms that have to be performed (object.keys) transforms = aggregateTransforms(schemaVersion, dataVersion, upgradeFile); // If no transforms need to be run, exit early if (!transforms.length) { log('debug', `Upgrade tried to run, but no upgrade function was found for ${name}`, { component: name, currentVersion: dataVersion, schemaVersion }); return bluebird.resolve(data); } // pass through the transform return runTransforms(transforms, upgradeFile, ref, data, locals) .then(saveTransformedData(ref)) .catch(e => { throw e; }); }
[ "function", "upgradeData", "(", "schemaVersion", ",", "dataVersion", ",", "ref", ",", "data", ",", "locals", ")", "{", "const", "name", "=", "isComponent", "(", "ref", ")", "?", "getComponentName", "(", "ref", ")", ":", "getLayoutName", "(", "ref", ")", ",", "dir", "=", "isComponent", "(", "ref", ")", "?", "files", ".", "getComponentPath", "(", "name", ")", ":", "files", ".", "getLayoutPath", "(", "name", ")", ",", "// Get the component directory", "upgradeFile", "=", "files", ".", "tryRequire", "(", "path", ".", "resolve", "(", "dir", ",", "'upgrade'", ")", ")", ";", "// Grab the the upgrade.js file", "var", "transforms", "=", "[", "]", ";", "log", "(", "'debug'", ",", "`", "${", "name", "}", "${", "ref", "}", "`", ")", ";", "// If no upgrade file exists, exit early", "if", "(", "!", "upgradeFile", ")", "{", "log", "(", "'debug'", ",", "`", "${", "name", "}", "`", ")", ";", "return", "bluebird", ".", "resolve", "(", "data", ")", ";", "}", "// find all the transforms that have to be performed (object.keys)", "transforms", "=", "aggregateTransforms", "(", "schemaVersion", ",", "dataVersion", ",", "upgradeFile", ")", ";", "// If no transforms need to be run, exit early", "if", "(", "!", "transforms", ".", "length", ")", "{", "log", "(", "'debug'", ",", "`", "${", "name", "}", "`", ",", "{", "component", ":", "name", ",", "currentVersion", ":", "dataVersion", ",", "schemaVersion", "}", ")", ";", "return", "bluebird", ".", "resolve", "(", "data", ")", ";", "}", "// pass through the transform", "return", "runTransforms", "(", "transforms", ",", "upgradeFile", ",", "ref", ",", "data", ",", "locals", ")", ".", "then", "(", "saveTransformedData", "(", "ref", ")", ")", ".", "catch", "(", "e", "=>", "{", "throw", "e", ";", "}", ")", ";", "}" ]
We know a upgrade needs to happen, so let's kick it off. If there is no upgrade file, return early cause we can't do anything. If it exists though, we need to find which transforms to perform, make them happen, save that new data and then send it back @param {Number} schemaVersion @param {Number} dataVersion @param {String} ref @param {Object} data @param {Object} locals @return {Promise}
[ "We", "know", "a", "upgrade", "needs", "to", "happen", "so", "let", "s", "kick", "it", "off", ".", "If", "there", "is", "no", "upgrade", "file", "return", "early", "cause", "we", "can", "t", "do", "anything", "." ]
b883a94cbc38c1891ce568addb6cb280aa1d5353
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/services/upgrade.js#L144-L178
24,361
clay/amphora
lib/services/upgrade.js
checkForUpgrade
function checkForUpgrade(ref, data, locals) { return utils.getSchema(ref) .then(schema => { // If version does not match what's in the data if (schema && schema._version && schema._version !== data._version) { return module.exports.upgradeData(schema._version, data._version, ref, data, locals); } return bluebird.resolve(data); }); }
javascript
function checkForUpgrade(ref, data, locals) { return utils.getSchema(ref) .then(schema => { // If version does not match what's in the data if (schema && schema._version && schema._version !== data._version) { return module.exports.upgradeData(schema._version, data._version, ref, data, locals); } return bluebird.resolve(data); }); }
[ "function", "checkForUpgrade", "(", "ref", ",", "data", ",", "locals", ")", "{", "return", "utils", ".", "getSchema", "(", "ref", ")", ".", "then", "(", "schema", "=>", "{", "// If version does not match what's in the data", "if", "(", "schema", "&&", "schema", ".", "_version", "&&", "schema", ".", "_version", "!==", "data", ".", "_version", ")", "{", "return", "module", ".", "exports", ".", "upgradeData", "(", "schema", ".", "_version", ",", "data", ".", "_version", ",", "ref", ",", "data", ",", "locals", ")", ";", "}", "return", "bluebird", ".", "resolve", "(", "data", ")", ";", "}", ")", ";", "}" ]
Grab the schema for the component and check if the schema and data versions do not match. If they do we don't need to do anything, otherwise the upgrade process needs to be kicked off. @param {String} ref @param {Object} data @param {Object} locals @return {Promise}
[ "Grab", "the", "schema", "for", "the", "component", "and", "check", "if", "the", "schema", "and", "data", "versions", "do", "not", "match", ".", "If", "they", "do", "we", "don", "t", "need", "to", "do", "anything", "otherwise", "the", "upgrade", "process", "needs", "to", "be", "kicked", "off", "." ]
b883a94cbc38c1891ce568addb6cb280aa1d5353
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/services/upgrade.js#L191-L201
24,362
clay/amphora
lib/services/db.js
defer
function defer() { const def = promiseDefer(); def.apply = function (err, result) { if (err) { def.reject(err); } else { def.resolve(result); } }; return def; }
javascript
function defer() { const def = promiseDefer(); def.apply = function (err, result) { if (err) { def.reject(err); } else { def.resolve(result); } }; return def; }
[ "function", "defer", "(", ")", "{", "const", "def", "=", "promiseDefer", "(", ")", ";", "def", ".", "apply", "=", "function", "(", "err", ",", "result", ")", "{", "if", "(", "err", ")", "{", "def", ".", "reject", "(", "err", ")", ";", "}", "else", "{", "def", ".", "resolve", "(", "result", ")", ";", "}", "}", ";", "return", "def", ";", "}" ]
Use ES6 promises @returns {{apply: function}}
[ "Use", "ES6", "promises" ]
b883a94cbc38c1891ce568addb6cb280aa1d5353
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/services/db.js#L12-L24
24,363
clay/amphora
lib/services/db.js
list
function list(options = {}) { options = _.defaults(options, { limit: -1, keys: true, values: true, fillCache: false, json: true }); // The prefix option is a shortcut for a greaterThan and lessThan range. if (options.prefix) { // \x00 is the first possible alphanumeric character, and \xFF is the last options.gte = options.prefix + '\x00'; options.lte = options.prefix + '\xff'; } let readStream, transformOptions = { objectMode: options.values, isArray: options.isArray }; // if keys but no values, or values but no keys, always return as array. if (options.keys && !options.values || !options.keys && options.values) { transformOptions.isArray = true; } readStream = module.exports.createReadStream(options); if (_.isFunction(options.transforms)) { options.transforms = options.transforms(); } // apply all transforms if (options.transforms) { readStream = _.reduce(options.transforms, function (readStream, transform) { return readStream.pipe(transform); }, readStream); } if (options.json) { readStream = readStream.pipe(jsonTransform(transformOptions)); } return readStream; }
javascript
function list(options = {}) { options = _.defaults(options, { limit: -1, keys: true, values: true, fillCache: false, json: true }); // The prefix option is a shortcut for a greaterThan and lessThan range. if (options.prefix) { // \x00 is the first possible alphanumeric character, and \xFF is the last options.gte = options.prefix + '\x00'; options.lte = options.prefix + '\xff'; } let readStream, transformOptions = { objectMode: options.values, isArray: options.isArray }; // if keys but no values, or values but no keys, always return as array. if (options.keys && !options.values || !options.keys && options.values) { transformOptions.isArray = true; } readStream = module.exports.createReadStream(options); if (_.isFunction(options.transforms)) { options.transforms = options.transforms(); } // apply all transforms if (options.transforms) { readStream = _.reduce(options.transforms, function (readStream, transform) { return readStream.pipe(transform); }, readStream); } if (options.json) { readStream = readStream.pipe(jsonTransform(transformOptions)); } return readStream; }
[ "function", "list", "(", "options", "=", "{", "}", ")", "{", "options", "=", "_", ".", "defaults", "(", "options", ",", "{", "limit", ":", "-", "1", ",", "keys", ":", "true", ",", "values", ":", "true", ",", "fillCache", ":", "false", ",", "json", ":", "true", "}", ")", ";", "// The prefix option is a shortcut for a greaterThan and lessThan range.", "if", "(", "options", ".", "prefix", ")", "{", "// \\x00 is the first possible alphanumeric character, and \\xFF is the last", "options", ".", "gte", "=", "options", ".", "prefix", "+", "'\\x00'", ";", "options", ".", "lte", "=", "options", ".", "prefix", "+", "'\\xff'", ";", "}", "let", "readStream", ",", "transformOptions", "=", "{", "objectMode", ":", "options", ".", "values", ",", "isArray", ":", "options", ".", "isArray", "}", ";", "// if keys but no values, or values but no keys, always return as array.", "if", "(", "options", ".", "keys", "&&", "!", "options", ".", "values", "||", "!", "options", ".", "keys", "&&", "options", ".", "values", ")", "{", "transformOptions", ".", "isArray", "=", "true", ";", "}", "readStream", "=", "module", ".", "exports", ".", "createReadStream", "(", "options", ")", ";", "if", "(", "_", ".", "isFunction", "(", "options", ".", "transforms", ")", ")", "{", "options", ".", "transforms", "=", "options", ".", "transforms", "(", ")", ";", "}", "// apply all transforms", "if", "(", "options", ".", "transforms", ")", "{", "readStream", "=", "_", ".", "reduce", "(", "options", ".", "transforms", ",", "function", "(", "readStream", ",", "transform", ")", "{", "return", "readStream", ".", "pipe", "(", "transform", ")", ";", "}", ",", "readStream", ")", ";", "}", "if", "(", "options", ".", "json", ")", "{", "readStream", "=", "readStream", ".", "pipe", "(", "jsonTransform", "(", "transformOptions", ")", ")", ";", "}", "return", "readStream", ";", "}" ]
Get a read stream of all the keys. @example db.list({prefix: '/_components/hey'}) WARNING: Try to always end with the same character (like a /) or be completely consistent with your prefixing because the '/' character is right in the middle of the sorting range of characters. You will get weird results if you're not careful with your ending character. For example, `/_components/text` will also return the entries of `/_components/text-box`, so the search should really be `/_components/text/`. @param {object} [options] @returns {ReadStream} /* eslint-disable complexity
[ "Get", "a", "read", "stream", "of", "all", "the", "keys", "." ]
b883a94cbc38c1891ce568addb6cb280aa1d5353
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/services/db.js#L56-L101
24,364
clay/amphora
lib/services/publish.js
_checkForUrlProperty
function _checkForUrlProperty(uri, { url, customUrl }) { if (!url && !customUrl) { return bluebird.reject(new Error('Page does not have a `url` or `customUrl` property set')); } return bluebird.resolve(url || customUrl); }
javascript
function _checkForUrlProperty(uri, { url, customUrl }) { if (!url && !customUrl) { return bluebird.reject(new Error('Page does not have a `url` or `customUrl` property set')); } return bluebird.resolve(url || customUrl); }
[ "function", "_checkForUrlProperty", "(", "uri", ",", "{", "url", ",", "customUrl", "}", ")", "{", "if", "(", "!", "url", "&&", "!", "customUrl", ")", "{", "return", "bluebird", ".", "reject", "(", "new", "Error", "(", "'Page does not have a `url` or `customUrl` property set'", ")", ")", ";", "}", "return", "bluebird", ".", "resolve", "(", "url", "||", "customUrl", ")", ";", "}" ]
Return the url for a page based on own url. This occurs when a page falls outside of all publishing rules supplied by the implementation BUT there is a `url` property already set on the page data. @param {String} uri @param {Object} pageData @param {String} pageData.url @param {String} pageData.customUrl @returns {Promise}
[ "Return", "the", "url", "for", "a", "page", "based", "on", "own", "url", ".", "This", "occurs", "when", "a", "page", "falls", "outside", "of", "all", "publishing", "rules", "supplied", "by", "the", "implementation", "BUT", "there", "is", "a", "url", "property", "already", "set", "on", "the", "page", "data", "." ]
b883a94cbc38c1891ce568addb6cb280aa1d5353
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/services/publish.js#L84-L90
24,365
clay/amphora
lib/services/publish.js
_checkForDynamicPage
function _checkForDynamicPage(uri, { _dynamic }) { if (!_dynamic || typeof _dynamic !== 'boolean') { return bluebird.reject(new Error('Page is not dynamic and requires a url')); } return bluebird.resolve(_dynamic); }
javascript
function _checkForDynamicPage(uri, { _dynamic }) { if (!_dynamic || typeof _dynamic !== 'boolean') { return bluebird.reject(new Error('Page is not dynamic and requires a url')); } return bluebird.resolve(_dynamic); }
[ "function", "_checkForDynamicPage", "(", "uri", ",", "{", "_dynamic", "}", ")", "{", "if", "(", "!", "_dynamic", "||", "typeof", "_dynamic", "!==", "'boolean'", ")", "{", "return", "bluebird", ".", "reject", "(", "new", "Error", "(", "'Page is not dynamic and requires a url'", ")", ")", ";", "}", "return", "bluebird", ".", "resolve", "(", "_dynamic", ")", ";", "}" ]
Allow a page to be published if it is dynamic. This allows the page to be published, but the pages service has the logic to not create a _uri to point to the page @param {String} uri @param {Boolean|Undefined} _dynamic @return {Promise}
[ "Allow", "a", "page", "to", "be", "published", "if", "it", "is", "dynamic", ".", "This", "allows", "the", "page", "to", "be", "published", "but", "the", "pages", "service", "has", "the", "logic", "to", "not", "create", "a", "_uri", "to", "point", "to", "the", "page" ]
b883a94cbc38c1891ce568addb6cb280aa1d5353
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/services/publish.js#L101-L107
24,366
clay/amphora
lib/services/publish.js
_checkForArchived
function _checkForArchived(uri) { return db.getMeta(replaceVersion(uri)) .then(meta => meta.archived) .then(archived => archived ? bluebird.reject({ val: '', errors: { _checkForArchived: 'The page is archived and cannot be published' } }) : bluebird.resolve({ val: '', errors: {} }) ); }
javascript
function _checkForArchived(uri) { return db.getMeta(replaceVersion(uri)) .then(meta => meta.archived) .then(archived => archived ? bluebird.reject({ val: '', errors: { _checkForArchived: 'The page is archived and cannot be published' } }) : bluebird.resolve({ val: '', errors: {} }) ); }
[ "function", "_checkForArchived", "(", "uri", ")", "{", "return", "db", ".", "getMeta", "(", "replaceVersion", "(", "uri", ")", ")", ".", "then", "(", "meta", "=>", "meta", ".", "archived", ")", ".", "then", "(", "archived", "=>", "archived", "?", "bluebird", ".", "reject", "(", "{", "val", ":", "''", ",", "errors", ":", "{", "_checkForArchived", ":", "'The page is archived and cannot be published'", "}", "}", ")", ":", "bluebird", ".", "resolve", "(", "{", "val", ":", "''", ",", "errors", ":", "{", "}", "}", ")", ")", ";", "}" ]
Checks the archive property on a page's meta object, to determine whether it can be published. Archived pages should not be published. Otherwise, an initial object is passed to the processing chain in processPublishRules. @param {String} uri @returns {Promise}
[ "Checks", "the", "archive", "property", "on", "a", "page", "s", "meta", "object", "to", "determine", "whether", "it", "can", "be", "published", ".", "Archived", "pages", "should", "not", "be", "published", ".", "Otherwise", "an", "initial", "object", "is", "passed", "to", "the", "processing", "chain", "in", "processPublishRules", "." ]
b883a94cbc38c1891ce568addb6cb280aa1d5353
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/services/publish.js#L117-L124
24,367
clay/amphora
lib/services/publish.js
addToMeta
function addToMeta(meta, modifiers = [], uri, data) { if (!modifiers.length) return meta; return bluebird.reduce(modifiers, (acc, modify) => { return bluebird.try(modify.bind(null, uri, data, acc)) .then(resp => Object.assign(acc, resp)); }, {}).then(acc => Object.assign(acc, meta)); }
javascript
function addToMeta(meta, modifiers = [], uri, data) { if (!modifiers.length) return meta; return bluebird.reduce(modifiers, (acc, modify) => { return bluebird.try(modify.bind(null, uri, data, acc)) .then(resp => Object.assign(acc, resp)); }, {}).then(acc => Object.assign(acc, meta)); }
[ "function", "addToMeta", "(", "meta", ",", "modifiers", "=", "[", "]", ",", "uri", ",", "data", ")", "{", "if", "(", "!", "modifiers", ".", "length", ")", "return", "meta", ";", "return", "bluebird", ".", "reduce", "(", "modifiers", ",", "(", "acc", ",", "modify", ")", "=>", "{", "return", "bluebird", ".", "try", "(", "modify", ".", "bind", "(", "null", ",", "uri", ",", "data", ",", "acc", ")", ")", ".", "then", "(", "resp", "=>", "Object", ".", "assign", "(", "acc", ",", "resp", ")", ")", ";", "}", ",", "{", "}", ")", ".", "then", "(", "acc", "=>", "Object", ".", "assign", "(", "acc", ",", "meta", ")", ")", ";", "}" ]
Allow functions to add data to the meta object. Functions are defined on the site controller and can be synchronous or async. @param {Object} meta @param {Array} modifiers @param {String} uri @param {Object} data @returns {Promise}
[ "Allow", "functions", "to", "add", "data", "to", "the", "meta", "object", ".", "Functions", "are", "defined", "on", "the", "site", "controller", "and", "can", "be", "synchronous", "or", "async", "." ]
b883a94cbc38c1891ce568addb6cb280aa1d5353
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/services/publish.js#L137-L144
24,368
clay/amphora
lib/services/publish.js
publishPageAtUrl
function publishPageAtUrl(url, uri, data, locals, site) { // eslint-disable-line if (data._dynamic) { locals.isDynamicPublishUrl = true; return data; } // set the publishUrl for component's model.js files that // may want to know about the URL of the page locals.publishUrl = url; return bluebird.resolve({ url }) .then(metaObj => storeUrlHistory(metaObj, uri, url)) .then(metaObj => addRedirects(metaObj, uri)) .then(metaObj => addToMeta(metaObj, site.assignToMetaOnPublish, uri, data)); }
javascript
function publishPageAtUrl(url, uri, data, locals, site) { // eslint-disable-line if (data._dynamic) { locals.isDynamicPublishUrl = true; return data; } // set the publishUrl for component's model.js files that // may want to know about the URL of the page locals.publishUrl = url; return bluebird.resolve({ url }) .then(metaObj => storeUrlHistory(metaObj, uri, url)) .then(metaObj => addRedirects(metaObj, uri)) .then(metaObj => addToMeta(metaObj, site.assignToMetaOnPublish, uri, data)); }
[ "function", "publishPageAtUrl", "(", "url", ",", "uri", ",", "data", ",", "locals", ",", "site", ")", "{", "// eslint-disable-line", "if", "(", "data", ".", "_dynamic", ")", "{", "locals", ".", "isDynamicPublishUrl", "=", "true", ";", "return", "data", ";", "}", "// set the publishUrl for component's model.js files that", "// may want to know about the URL of the page", "locals", ".", "publishUrl", "=", "url", ";", "return", "bluebird", ".", "resolve", "(", "{", "url", "}", ")", ".", "then", "(", "metaObj", "=>", "storeUrlHistory", "(", "metaObj", ",", "uri", ",", "url", ")", ")", ".", "then", "(", "metaObj", "=>", "addRedirects", "(", "metaObj", ",", "uri", ")", ")", ".", "then", "(", "metaObj", "=>", "addToMeta", "(", "metaObj", ",", "site", ".", "assignToMetaOnPublish", ",", "uri", ",", "data", ")", ")", ";", "}" ]
Always do these actions when publishing a page @param {String} url @param {String} uri @param {Object} data @param {Object} locals @param {Object} site @return {Promise}
[ "Always", "do", "these", "actions", "when", "publishing", "a", "page" ]
b883a94cbc38c1891ce568addb6cb280aa1d5353
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/services/publish.js#L156-L170
24,369
clay/amphora
lib/services/publish.js
processPublishRules
function processPublishRules(publishingChain, uri, pageData, locals) { // check whether page is archived, then run the rest of the publishing chain return _checkForArchived(uri) .then(initialObj => { return bluebird.reduce(publishingChain, (acc, fn, index) => { if (!acc.val) { return bluebird.try(() => fn(uri, pageData, locals)) .then(val => { acc.val = val; return acc; }) .catch(e => { acc.errors[fn.name || index] = e.message; return bluebird.resolve(acc); }); } return acc; }, initialObj); }) .catch(err => bluebird.resolve(err)); // err object constructed in _checkForArchived function above }
javascript
function processPublishRules(publishingChain, uri, pageData, locals) { // check whether page is archived, then run the rest of the publishing chain return _checkForArchived(uri) .then(initialObj => { return bluebird.reduce(publishingChain, (acc, fn, index) => { if (!acc.val) { return bluebird.try(() => fn(uri, pageData, locals)) .then(val => { acc.val = val; return acc; }) .catch(e => { acc.errors[fn.name || index] = e.message; return bluebird.resolve(acc); }); } return acc; }, initialObj); }) .catch(err => bluebird.resolve(err)); // err object constructed in _checkForArchived function above }
[ "function", "processPublishRules", "(", "publishingChain", ",", "uri", ",", "pageData", ",", "locals", ")", "{", "// check whether page is archived, then run the rest of the publishing chain", "return", "_checkForArchived", "(", "uri", ")", ".", "then", "(", "initialObj", "=>", "{", "return", "bluebird", ".", "reduce", "(", "publishingChain", ",", "(", "acc", ",", "fn", ",", "index", ")", "=>", "{", "if", "(", "!", "acc", ".", "val", ")", "{", "return", "bluebird", ".", "try", "(", "(", ")", "=>", "fn", "(", "uri", ",", "pageData", ",", "locals", ")", ")", ".", "then", "(", "val", "=>", "{", "acc", ".", "val", "=", "val", ";", "return", "acc", ";", "}", ")", ".", "catch", "(", "e", "=>", "{", "acc", ".", "errors", "[", "fn", ".", "name", "||", "index", "]", "=", "e", ".", "message", ";", "return", "bluebird", ".", "resolve", "(", "acc", ")", ";", "}", ")", ";", "}", "return", "acc", ";", "}", ",", "initialObj", ")", ";", "}", ")", ".", "catch", "(", "err", "=>", "bluebird", ".", "resolve", "(", "err", ")", ")", ";", "// err object constructed in _checkForArchived function above", "}" ]
Reduce through the publishing rules supplied by the site and aggregate the error messages until a valid url is retrieved. Once retrieved, skip the rest of the rules quickly and return the result. @param {Array} publishingChain @param {String} uri @param {Object} pageData @param {Object} locals @returns {Promise}
[ "Reduce", "through", "the", "publishing", "rules", "supplied", "by", "the", "site", "and", "aggregate", "the", "error", "messages", "until", "a", "valid", "url", "is", "retrieved", ".", "Once", "retrieved", "skip", "the", "rest", "of", "the", "rules", "quickly", "and", "return", "the", "result", "." ]
b883a94cbc38c1891ce568addb6cb280aa1d5353
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/services/publish.js#L185-L206
24,370
clay/amphora
lib/services/publish.js
validatePublishRules
function validatePublishRules(uri, { val, errors }) { let err, errMsg; if (!val) { errMsg = `Error publishing page: ${replaceVersion(uri)}`; log('error', errMsg, { publishRuleErrors: errors }); err = new Error(errMsg); err.status = 400; return bluebird.reject(err); } return val; }
javascript
function validatePublishRules(uri, { val, errors }) { let err, errMsg; if (!val) { errMsg = `Error publishing page: ${replaceVersion(uri)}`; log('error', errMsg, { publishRuleErrors: errors }); err = new Error(errMsg); err.status = 400; return bluebird.reject(err); } return val; }
[ "function", "validatePublishRules", "(", "uri", ",", "{", "val", ",", "errors", "}", ")", "{", "let", "err", ",", "errMsg", ";", "if", "(", "!", "val", ")", "{", "errMsg", "=", "`", "${", "replaceVersion", "(", "uri", ")", "}", "`", ";", "log", "(", "'error'", ",", "errMsg", ",", "{", "publishRuleErrors", ":", "errors", "}", ")", ";", "err", "=", "new", "Error", "(", "errMsg", ")", ";", "err", ".", "status", "=", "400", ";", "return", "bluebird", ".", "reject", "(", "err", ")", ";", "}", "return", "val", ";", "}" ]
Given the response from the processing of the publish rules, determine if we need to log errors or if we're good to proceed. @param {String} uri @param {String} val @param {Object} errors @returns {String|Promise<Error>}
[ "Given", "the", "response", "from", "the", "processing", "of", "the", "publish", "rules", "determine", "if", "we", "need", "to", "log", "errors", "or", "if", "we", "re", "good", "to", "proceed", "." ]
b883a94cbc38c1891ce568addb6cb280aa1d5353
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/services/publish.js#L218-L230
24,371
clay/amphora
lib/responses.js
removePrefix
function removePrefix(str, prefixToken) { const index = str.indexOf(prefixToken); if (index > -1) { str = str.substr(index + prefixToken.length).trim(); } return str; }
javascript
function removePrefix(str, prefixToken) { const index = str.indexOf(prefixToken); if (index > -1) { str = str.substr(index + prefixToken.length).trim(); } return str; }
[ "function", "removePrefix", "(", "str", ",", "prefixToken", ")", "{", "const", "index", "=", "str", ".", "indexOf", "(", "prefixToken", ")", ";", "if", "(", "index", ">", "-", "1", ")", "{", "str", "=", "str", ".", "substr", "(", "index", "+", "prefixToken", ".", "length", ")", ".", "trim", "(", ")", ";", "}", "return", "str", ";", "}" ]
Finds prefixToken, and removes it and anything before it. @param {string} str @param {string} prefixToken @returns {string}
[ "Finds", "prefixToken", "and", "removes", "it", "and", "anything", "before", "it", "." ]
b883a94cbc38c1891ce568addb6cb280aa1d5353
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/responses.js#L19-L26
24,372
clay/amphora
lib/responses.js
notFound
function notFound(err, res) { if (!(err instanceof Error) && err) { res = err; } const message = 'Not Found', code = 404; // hide error from user of api. sendDefaultResponseForCode(code, message, res); }
javascript
function notFound(err, res) { if (!(err instanceof Error) && err) { res = err; } const message = 'Not Found', code = 404; // hide error from user of api. sendDefaultResponseForCode(code, message, res); }
[ "function", "notFound", "(", "err", ",", "res", ")", "{", "if", "(", "!", "(", "err", "instanceof", "Error", ")", "&&", "err", ")", "{", "res", "=", "err", ";", "}", "const", "message", "=", "'Not Found'", ",", "code", "=", "404", ";", "// hide error from user of api.", "sendDefaultResponseForCode", "(", "code", ",", "message", ",", "res", ")", ";", "}" ]
All "Not Found" errors are routed like this. @param {Error} [err] @param {object} res
[ "All", "Not", "Found", "errors", "are", "routed", "like", "this", "." ]
b883a94cbc38c1891ce568addb6cb280aa1d5353
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/responses.js#L266-L276
24,373
clay/amphora
lib/responses.js
serverError
function serverError(err, res) { // error is required to be logged log('error', err.message, { stack: err.stack }); const message = err.message || 'Server Error', // completely hide these messages from outside code = 500; sendDefaultResponseForCode(code, message, res); }
javascript
function serverError(err, res) { // error is required to be logged log('error', err.message, { stack: err.stack }); const message = err.message || 'Server Error', // completely hide these messages from outside code = 500; sendDefaultResponseForCode(code, message, res); }
[ "function", "serverError", "(", "err", ",", "res", ")", "{", "// error is required to be logged", "log", "(", "'error'", ",", "err", ".", "message", ",", "{", "stack", ":", "err", ".", "stack", "}", ")", ";", "const", "message", "=", "err", ".", "message", "||", "'Server Error'", ",", "// completely hide these messages from outside", "code", "=", "500", ";", "sendDefaultResponseForCode", "(", "code", ",", "message", ",", "res", ")", ";", "}" ]
All server errors should look like this. In general, 500s represent a _developer mistake_. We should try to replace them with more descriptive errors. @param {Error} err @param {object} res
[ "All", "server", "errors", "should", "look", "like", "this", "." ]
b883a94cbc38c1891ce568addb6cb280aa1d5353
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/responses.js#L285-L293
24,374
clay/amphora
lib/responses.js
expectText
function expectText(fn, res) { bluebird.try(fn).then(result => { res.set('Content-Type', 'text/plain'); res.send(result); }).catch(handleError(res)); }
javascript
function expectText(fn, res) { bluebird.try(fn).then(result => { res.set('Content-Type', 'text/plain'); res.send(result); }).catch(handleError(res)); }
[ "function", "expectText", "(", "fn", ",", "res", ")", "{", "bluebird", ".", "try", "(", "fn", ")", ".", "then", "(", "result", "=>", "{", "res", ".", "set", "(", "'Content-Type'", ",", "'text/plain'", ")", ";", "res", ".", "send", "(", "result", ")", ";", "}", ")", ".", "catch", "(", "handleError", "(", "res", ")", ")", ";", "}" ]
Reusable code to return Text data, both for good results AND errors. Captures and hides appropriate errors. @param {function} fn @param {object} res
[ "Reusable", "code", "to", "return", "Text", "data", "both", "for", "good", "results", "AND", "errors", "." ]
b883a94cbc38c1891ce568addb6cb280aa1d5353
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/responses.js#L368-L373
24,375
clay/amphora
lib/responses.js
checkArchivedToPublish
function checkArchivedToPublish(req, res, next) { if (req.body.archived) { return metaController.checkProps(req.uri, 'published') .then(resp => { if (resp === true) { throw new Error('Client error, cannot modify archive while page is published'); // archived true, published true } else next(); }) .catch(err => handleError(res)(err)); } else next(); }
javascript
function checkArchivedToPublish(req, res, next) { if (req.body.archived) { return metaController.checkProps(req.uri, 'published') .then(resp => { if (resp === true) { throw new Error('Client error, cannot modify archive while page is published'); // archived true, published true } else next(); }) .catch(err => handleError(res)(err)); } else next(); }
[ "function", "checkArchivedToPublish", "(", "req", ",", "res", ",", "next", ")", "{", "if", "(", "req", ".", "body", ".", "archived", ")", "{", "return", "metaController", ".", "checkProps", "(", "req", ".", "uri", ",", "'published'", ")", ".", "then", "(", "resp", "=>", "{", "if", "(", "resp", "===", "true", ")", "{", "throw", "new", "Error", "(", "'Client error, cannot modify archive while page is published'", ")", ";", "// archived true, published true", "}", "else", "next", "(", ")", ";", "}", ")", ".", "catch", "(", "err", "=>", "handleError", "(", "res", ")", "(", "err", ")", ")", ";", "}", "else", "next", "(", ")", ";", "}" ]
Checks the archived property on the request object to determine if the request is attempting to archive the page. If true, checks the published property on the meta object of the page, by calling checkProps. @param {object} req @param {object} res @param {function} next @returns {Promise | void}
[ "Checks", "the", "archived", "property", "on", "the", "request", "object", "to", "determine", "if", "the", "request", "is", "attempting", "to", "archive", "the", "page", ".", "If", "true", "checks", "the", "published", "property", "on", "the", "meta", "object", "of", "the", "page", "by", "calling", "checkProps", "." ]
b883a94cbc38c1891ce568addb6cb280aa1d5353
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/responses.js#L384-L394
24,376
clay/amphora
lib/responses.js
expectJSON
function expectJSON(fn, res) { bluebird.try(fn).then(function (result) { res.json(result); }).catch(handleError(res)); }
javascript
function expectJSON(fn, res) { bluebird.try(fn).then(function (result) { res.json(result); }).catch(handleError(res)); }
[ "function", "expectJSON", "(", "fn", ",", "res", ")", "{", "bluebird", ".", "try", "(", "fn", ")", ".", "then", "(", "function", "(", "result", ")", "{", "res", ".", "json", "(", "result", ")", ";", "}", ")", ".", "catch", "(", "handleError", "(", "res", ")", ")", ";", "}" ]
Reusable code to return JSON data, both for good results AND errors. Captures and hides appropriate errors. These return JSON always, because these endpoints are JSON-only. @param {function} fn @param {object} res
[ "Reusable", "code", "to", "return", "JSON", "data", "both", "for", "good", "results", "AND", "errors", "." ]
b883a94cbc38c1891ce568addb6cb280aa1d5353
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/responses.js#L405-L409
24,377
clay/amphora
lib/responses.js
list
function list(options) { return function (req, res) { let list, listOptions = _.assign({ prefix: req.uri, values: false }, options); list = db.list(listOptions); res.set('Content-Type', 'application/json'); list.pipe(res); }; }
javascript
function list(options) { return function (req, res) { let list, listOptions = _.assign({ prefix: req.uri, values: false }, options); list = db.list(listOptions); res.set('Content-Type', 'application/json'); list.pipe(res); }; }
[ "function", "list", "(", "options", ")", "{", "return", "function", "(", "req", ",", "res", ")", "{", "let", "list", ",", "listOptions", "=", "_", ".", "assign", "(", "{", "prefix", ":", "req", ".", "uri", ",", "values", ":", "false", "}", ",", "options", ")", ";", "list", "=", "db", ".", "list", "(", "listOptions", ")", ";", "res", ".", "set", "(", "'Content-Type'", ",", "'application/json'", ")", ";", "list", ".", "pipe", "(", "res", ")", ";", "}", ";", "}" ]
List all things in the db @param {object} [options] @param {string} [options.prefix] @param {boolean} [options.values] @param {function|array} [options.transforms] @returns {function}
[ "List", "all", "things", "in", "the", "db" ]
b883a94cbc38c1891ce568addb6cb280aa1d5353
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/responses.js#L419-L432
24,378
clay/amphora
lib/responses.js
listWithoutVersions
function listWithoutVersions() { const options = { transforms() { return [filter({wantStrings: true}, function (str) { return str.indexOf('@') === -1; })]; } }; return list(options); }
javascript
function listWithoutVersions() { const options = { transforms() { return [filter({wantStrings: true}, function (str) { return str.indexOf('@') === -1; })]; } }; return list(options); }
[ "function", "listWithoutVersions", "(", ")", "{", "const", "options", "=", "{", "transforms", "(", ")", "{", "return", "[", "filter", "(", "{", "wantStrings", ":", "true", "}", ",", "function", "(", "str", ")", "{", "return", "str", ".", "indexOf", "(", "'@'", ")", "===", "-", "1", ";", "}", ")", "]", ";", "}", "}", ";", "return", "list", "(", "options", ")", ";", "}" ]
List all things in the db that start with this prefix @returns {function}
[ "List", "all", "things", "in", "the", "db", "that", "start", "with", "this", "prefix" ]
b883a94cbc38c1891ce568addb6cb280aa1d5353
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/responses.js#L438-L448
24,379
clay/amphora
lib/responses.js
listWithPublishedVersions
function listWithPublishedVersions(req, res) { const publishedString = '@published', options = { transforms() { return [filter({ wantStrings: true }, function (str) { return str.indexOf(publishedString) !== -1; })]; } }; // Trim the URI to `../pages` for the query to work req.uri = req.uri.replace(`/${publishedString}`, ''); return list(options)(req, res); }
javascript
function listWithPublishedVersions(req, res) { const publishedString = '@published', options = { transforms() { return [filter({ wantStrings: true }, function (str) { return str.indexOf(publishedString) !== -1; })]; } }; // Trim the URI to `../pages` for the query to work req.uri = req.uri.replace(`/${publishedString}`, ''); return list(options)(req, res); }
[ "function", "listWithPublishedVersions", "(", "req", ",", "res", ")", "{", "const", "publishedString", "=", "'@published'", ",", "options", "=", "{", "transforms", "(", ")", "{", "return", "[", "filter", "(", "{", "wantStrings", ":", "true", "}", ",", "function", "(", "str", ")", "{", "return", "str", ".", "indexOf", "(", "publishedString", ")", "!==", "-", "1", ";", "}", ")", "]", ";", "}", "}", ";", "// Trim the URI to `../pages` for the query to work", "req", ".", "uri", "=", "req", ".", "uri", ".", "replace", "(", "`", "${", "publishedString", "}", "`", ",", "''", ")", ";", "return", "list", "(", "options", ")", "(", "req", ",", "res", ")", ";", "}" ]
List all things in the db that start with this prefix _and_ are published @param {Object} req @param {Object} res @returns {Function}
[ "List", "all", "things", "in", "the", "db", "that", "start", "with", "this", "prefix", "_and_", "are", "published" ]
b883a94cbc38c1891ce568addb6cb280aa1d5353
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/responses.js#L458-L471
24,380
clay/amphora
lib/responses.js
putRouteFromDB
function putRouteFromDB(req, res) { expectJSON(function () { return db.put(req.uri, JSON.stringify(req.body)).then(() => req.body); }, res); }
javascript
function putRouteFromDB(req, res) { expectJSON(function () { return db.put(req.uri, JSON.stringify(req.body)).then(() => req.body); }, res); }
[ "function", "putRouteFromDB", "(", "req", ",", "res", ")", "{", "expectJSON", "(", "function", "(", ")", "{", "return", "db", ".", "put", "(", "req", ".", "uri", ",", "JSON", ".", "stringify", "(", "req", ".", "body", ")", ")", ".", "then", "(", "(", ")", "=>", "req", ".", "body", ")", ";", "}", ",", "res", ")", ";", "}" ]
This route puts straight to the db. Assumptions: - that there is no extension if they're putting data. @param {object} req @param {object} res
[ "This", "route", "puts", "straight", "to", "the", "db", "." ]
b883a94cbc38c1891ce568addb6cb280aa1d5353
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/responses.js#L490-L494
24,381
clay/amphora
lib/responses.js
deleteRouteFromDB
function deleteRouteFromDB(req, res) { expectJSON(() => { return db.get(req.uri) .then(oldData => db.del(req.uri).then(() => oldData)); }, res); }
javascript
function deleteRouteFromDB(req, res) { expectJSON(() => { return db.get(req.uri) .then(oldData => db.del(req.uri).then(() => oldData)); }, res); }
[ "function", "deleteRouteFromDB", "(", "req", ",", "res", ")", "{", "expectJSON", "(", "(", ")", "=>", "{", "return", "db", ".", "get", "(", "req", ".", "uri", ")", ".", "then", "(", "oldData", "=>", "db", ".", "del", "(", "req", ".", "uri", ")", ".", "then", "(", "(", ")", "=>", "oldData", ")", ")", ";", "}", ",", "res", ")", ";", "}" ]
This route deletes from the db, and returns what used to be there. Assumptions: - that there is no extension if they're deleting data. NOTE: Return the data it used to contain. This is often used to create queues or messaging on the client-side, because clients can guarantee that only one client was allowed to be the last one to fetch a particular item. @param {object} req @param {object} res
[ "This", "route", "deletes", "from", "the", "db", "and", "returns", "what", "used", "to", "be", "there", "." ]
b883a94cbc38c1891ce568addb6cb280aa1d5353
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/responses.js#L508-L513
24,382
clay/amphora
lib/responses.js
forceEditableInstance
function forceEditableInstance(code = 303) { return (req, res) => { res.redirect(code, `${res.locals.site.protocol}://${req.uri.replace('@published', '')}`); }; }
javascript
function forceEditableInstance(code = 303) { return (req, res) => { res.redirect(code, `${res.locals.site.protocol}://${req.uri.replace('@published', '')}`); }; }
[ "function", "forceEditableInstance", "(", "code", "=", "303", ")", "{", "return", "(", "req", ",", "res", ")", "=>", "{", "res", ".", "redirect", "(", "code", ",", "`", "${", "res", ".", "locals", ".", "site", ".", "protocol", "}", "${", "req", ".", "uri", ".", "replace", "(", "'@published'", ",", "''", ")", "}", "`", ")", ";", "}", ";", "}" ]
Forces a redirect back to the non-published version of a uri @param {Number} code @returns {Function}
[ "Forces", "a", "redirect", "back", "to", "the", "non", "-", "published", "version", "of", "a", "uri" ]
b883a94cbc38c1891ce568addb6cb280aa1d5353
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/responses.js#L522-L526
24,383
clay/amphora
lib/services/sites.js
normalizePath
function normalizePath(urlPath) { if (!urlPath) { return ''; // make sure path starts with a / } else if (_.head(urlPath) !== '/') { urlPath = '/' + urlPath; } // make sure path does not end with a / return _.trimEnd(urlPath, '/'); }
javascript
function normalizePath(urlPath) { if (!urlPath) { return ''; // make sure path starts with a / } else if (_.head(urlPath) !== '/') { urlPath = '/' + urlPath; } // make sure path does not end with a / return _.trimEnd(urlPath, '/'); }
[ "function", "normalizePath", "(", "urlPath", ")", "{", "if", "(", "!", "urlPath", ")", "{", "return", "''", ";", "// make sure path starts with a /", "}", "else", "if", "(", "_", ".", "head", "(", "urlPath", ")", "!==", "'/'", ")", "{", "urlPath", "=", "'/'", "+", "urlPath", ";", "}", "// make sure path does not end with a /", "return", "_", ".", "trimEnd", "(", "urlPath", ",", "'/'", ")", ";", "}" ]
Normalize path to never end with a slash. @param {string} urlPath @returns {string}
[ "Normalize", "path", "to", "never", "end", "with", "a", "slash", "." ]
b883a94cbc38c1891ce568addb6cb280aa1d5353
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/services/sites.js#L16-L25
24,384
clay/amphora
lib/services/sites.js
normalizeDirectory
function normalizeDirectory(dir) { if (!dir || dir === path.sep) { dir = '.'; } else if (_.head(dir) === path.sep) { dir = dir.substr(1); } if (dir.length > 1 && _.last(dir) === path.sep) { dir = dir.substring(0, dir.length - 1); } return dir; }
javascript
function normalizeDirectory(dir) { if (!dir || dir === path.sep) { dir = '.'; } else if (_.head(dir) === path.sep) { dir = dir.substr(1); } if (dir.length > 1 && _.last(dir) === path.sep) { dir = dir.substring(0, dir.length - 1); } return dir; }
[ "function", "normalizeDirectory", "(", "dir", ")", "{", "if", "(", "!", "dir", "||", "dir", "===", "path", ".", "sep", ")", "{", "dir", "=", "'.'", ";", "}", "else", "if", "(", "_", ".", "head", "(", "dir", ")", "===", "path", ".", "sep", ")", "{", "dir", "=", "dir", ".", "substr", "(", "1", ")", ";", "}", "if", "(", "dir", ".", "length", ">", "1", "&&", "_", ".", "last", "(", "dir", ")", "===", "path", ".", "sep", ")", "{", "dir", "=", "dir", ".", "substring", "(", "0", ",", "dir", ".", "length", "-", "1", ")", ";", "}", "return", "dir", ";", "}" ]
Normalize directory to never start with slash, never end with slash, and always exist @param {string} dir @returns {string}
[ "Normalize", "directory", "to", "never", "start", "with", "slash", "never", "end", "with", "slash", "and", "always", "exist" ]
b883a94cbc38c1891ce568addb6cb280aa1d5353
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/services/sites.js#L32-L44
24,385
clay/amphora
lib/services/sites.js
getSite
function getSite(host, path) { // note: uses the memoized version return _.find(module.exports.sites(), function (site) { return site.host === host && site.path === path; }); }
javascript
function getSite(host, path) { // note: uses the memoized version return _.find(module.exports.sites(), function (site) { return site.host === host && site.path === path; }); }
[ "function", "getSite", "(", "host", ",", "path", ")", "{", "// note: uses the memoized version", "return", "_", ".", "find", "(", "module", ".", "exports", ".", "sites", "(", ")", ",", "function", "(", "site", ")", "{", "return", "site", ".", "host", "===", "host", "&&", "site", ".", "path", "===", "path", ";", "}", ")", ";", "}" ]
get site config that matches a specific host + path @param {string} host @param {string} path (make sure it starts with a slash!) @returns {object}
[ "get", "site", "config", "that", "matches", "a", "specific", "host", "+", "path" ]
b883a94cbc38c1891ce568addb6cb280aa1d5353
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/services/sites.js#L100-L105
24,386
clay/amphora
lib/services/sites.js
getSiteFromPrefix
function getSiteFromPrefix(prefix) { var split = prefix.split('/'), // Split the url/uri by `/` host = split.shift(), // The first value should be the host ('http://' is not included) optPath = split.shift(), // The next value is the first part of the site's path OR the whole part path = optPath ? `/${optPath}` : '', length = split.length + 1, // We always need at least one pass through the for loop site; // Initialize the return value to `undefined` for (let i = 0; i < length; i++) { site = getSite(host, path); // Try to get the site based on the host and path if (site) { // If a site was found, break out of the loop break; } else { path += `/${split.shift()}`; // Grab the next value and append it to the `path` value } } return site; // Return the site }
javascript
function getSiteFromPrefix(prefix) { var split = prefix.split('/'), // Split the url/uri by `/` host = split.shift(), // The first value should be the host ('http://' is not included) optPath = split.shift(), // The next value is the first part of the site's path OR the whole part path = optPath ? `/${optPath}` : '', length = split.length + 1, // We always need at least one pass through the for loop site; // Initialize the return value to `undefined` for (let i = 0; i < length; i++) { site = getSite(host, path); // Try to get the site based on the host and path if (site) { // If a site was found, break out of the loop break; } else { path += `/${split.shift()}`; // Grab the next value and append it to the `path` value } } return site; // Return the site }
[ "function", "getSiteFromPrefix", "(", "prefix", ")", "{", "var", "split", "=", "prefix", ".", "split", "(", "'/'", ")", ",", "// Split the url/uri by `/`", "host", "=", "split", ".", "shift", "(", ")", ",", "// The first value should be the host ('http://' is not included)", "optPath", "=", "split", ".", "shift", "(", ")", ",", "// The next value is the first part of the site's path OR the whole part", "path", "=", "optPath", "?", "`", "${", "optPath", "}", "`", ":", "''", ",", "length", "=", "split", ".", "length", "+", "1", ",", "// We always need at least one pass through the for loop", "site", ";", "// Initialize the return value to `undefined`", "for", "(", "let", "i", "=", "0", ";", "i", "<", "length", ";", "i", "++", ")", "{", "site", "=", "getSite", "(", "host", ",", "path", ")", ";", "// Try to get the site based on the host and path", "if", "(", "site", ")", "{", "// If a site was found, break out of the loop", "break", ";", "}", "else", "{", "path", "+=", "`", "${", "split", ".", "shift", "(", ")", "}", "`", ";", "// Grab the next value and append it to the `path` value", "}", "}", "return", "site", ";", "// Return the site", "}" ]
Get the site a URI belongs to @param {string} prefix @returns {object}
[ "Get", "the", "site", "a", "URI", "belongs", "to" ]
b883a94cbc38c1891ce568addb6cb280aa1d5353
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/services/sites.js#L113-L132
24,387
clay/amphora
lib/services/metadata.js
userOrRobot
function userOrRobot(user) { if (user && _.get(user, 'username') && _.get(user, 'provider')) { return user; } else { // no actual user, this was an api key return { username: 'robot', provider: 'clay', imageUrl: 'clay-avatar', // kiln will supply a clay avatar name: 'Clay', auth: 'admin' }; } }
javascript
function userOrRobot(user) { if (user && _.get(user, 'username') && _.get(user, 'provider')) { return user; } else { // no actual user, this was an api key return { username: 'robot', provider: 'clay', imageUrl: 'clay-avatar', // kiln will supply a clay avatar name: 'Clay', auth: 'admin' }; } }
[ "function", "userOrRobot", "(", "user", ")", "{", "if", "(", "user", "&&", "_", ".", "get", "(", "user", ",", "'username'", ")", "&&", "_", ".", "get", "(", "user", ",", "'provider'", ")", ")", "{", "return", "user", ";", "}", "else", "{", "// no actual user, this was an api key", "return", "{", "username", ":", "'robot'", ",", "provider", ":", "'clay'", ",", "imageUrl", ":", "'clay-avatar'", ",", "// kiln will supply a clay avatar", "name", ":", "'Clay'", ",", "auth", ":", "'admin'", "}", ";", "}", "}" ]
Either return the user object or the system for a specific action @param {Object} user @returns {Object}
[ "Either", "return", "the", "user", "object", "or", "the", "system", "for", "a", "specific", "action" ]
b883a94cbc38c1891ce568addb6cb280aa1d5353
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/services/metadata.js#L16-L29
24,388
clay/amphora
lib/services/metadata.js
publishPage
function publishPage(uri, publishMeta, user) { const NOW = new Date().toISOString(), update = { published: true, publishTime: NOW, history: [{ action: 'publish', timestamp: NOW, users: [userOrRobot(user)] }] }; return changeMetaState(uri, Object.assign(publishMeta, update)); }
javascript
function publishPage(uri, publishMeta, user) { const NOW = new Date().toISOString(), update = { published: true, publishTime: NOW, history: [{ action: 'publish', timestamp: NOW, users: [userOrRobot(user)] }] }; return changeMetaState(uri, Object.assign(publishMeta, update)); }
[ "function", "publishPage", "(", "uri", ",", "publishMeta", ",", "user", ")", "{", "const", "NOW", "=", "new", "Date", "(", ")", ".", "toISOString", "(", ")", ",", "update", "=", "{", "published", ":", "true", ",", "publishTime", ":", "NOW", ",", "history", ":", "[", "{", "action", ":", "'publish'", ",", "timestamp", ":", "NOW", ",", "users", ":", "[", "userOrRobot", "(", "user", ")", "]", "}", "]", "}", ";", "return", "changeMetaState", "(", "uri", ",", "Object", ".", "assign", "(", "publishMeta", ",", "update", ")", ")", ";", "}" ]
On publish of a page, update the metadara for the page @param {String} uri @param {Object} publishMeta @param {Object|Undefined} user @returns {Promise}
[ "On", "publish", "of", "a", "page", "update", "the", "metadara", "for", "the", "page" ]
b883a94cbc38c1891ce568addb6cb280aa1d5353
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/services/metadata.js#L40-L49
24,389
clay/amphora
lib/services/metadata.js
createPage
function createPage(ref, user) { const NOW = new Date().toISOString(), users = [userOrRobot(user)], meta = { createdAt: NOW, archived: false, published: false, publishTime: null, updateTime: null, urlHistory: [], firstPublishTime: null, url: '', title: '', authors: [], users, history: [{action: 'create', timestamp: NOW, users }], siteSlug: sitesService.getSiteFromPrefix(ref.substring(0, ref.indexOf('/_pages'))).slug }; return putMeta(ref, meta); }
javascript
function createPage(ref, user) { const NOW = new Date().toISOString(), users = [userOrRobot(user)], meta = { createdAt: NOW, archived: false, published: false, publishTime: null, updateTime: null, urlHistory: [], firstPublishTime: null, url: '', title: '', authors: [], users, history: [{action: 'create', timestamp: NOW, users }], siteSlug: sitesService.getSiteFromPrefix(ref.substring(0, ref.indexOf('/_pages'))).slug }; return putMeta(ref, meta); }
[ "function", "createPage", "(", "ref", ",", "user", ")", "{", "const", "NOW", "=", "new", "Date", "(", ")", ".", "toISOString", "(", ")", ",", "users", "=", "[", "userOrRobot", "(", "user", ")", "]", ",", "meta", "=", "{", "createdAt", ":", "NOW", ",", "archived", ":", "false", ",", "published", ":", "false", ",", "publishTime", ":", "null", ",", "updateTime", ":", "null", ",", "urlHistory", ":", "[", "]", ",", "firstPublishTime", ":", "null", ",", "url", ":", "''", ",", "title", ":", "''", ",", "authors", ":", "[", "]", ",", "users", ",", "history", ":", "[", "{", "action", ":", "'create'", ",", "timestamp", ":", "NOW", ",", "users", "}", "]", ",", "siteSlug", ":", "sitesService", ".", "getSiteFromPrefix", "(", "ref", ".", "substring", "(", "0", ",", "ref", ".", "indexOf", "(", "'/_pages'", ")", ")", ")", ".", "slug", "}", ";", "return", "putMeta", "(", "ref", ",", "meta", ")", ";", "}" ]
Create the initial meta object for the page @param {String} ref @param {Object|Underfined} user @returns {Promise}
[ "Create", "the", "initial", "meta", "object", "for", "the", "page" ]
b883a94cbc38c1891ce568addb6cb280aa1d5353
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/services/metadata.js#L59-L79
24,390
clay/amphora
lib/services/metadata.js
publishLayout
function publishLayout(uri, user) { const NOW = new Date().toISOString(), users = [userOrRobot(user)], update = { published: true, publishTime: NOW, history: [{ action: 'publish', timestamp: NOW, users }] }; return changeMetaState(uri, update); }
javascript
function publishLayout(uri, user) { const NOW = new Date().toISOString(), users = [userOrRobot(user)], update = { published: true, publishTime: NOW, history: [{ action: 'publish', timestamp: NOW, users }] }; return changeMetaState(uri, update); }
[ "function", "publishLayout", "(", "uri", ",", "user", ")", "{", "const", "NOW", "=", "new", "Date", "(", ")", ".", "toISOString", "(", ")", ",", "users", "=", "[", "userOrRobot", "(", "user", ")", "]", ",", "update", "=", "{", "published", ":", "true", ",", "publishTime", ":", "NOW", ",", "history", ":", "[", "{", "action", ":", "'publish'", ",", "timestamp", ":", "NOW", ",", "users", "}", "]", "}", ";", "return", "changeMetaState", "(", "uri", ",", "update", ")", ";", "}" ]
Update the layouts meta object on publish @param {String} uri @param {Object} user @returns {Promise}
[ "Update", "the", "layouts", "meta", "object", "on", "publish" ]
b883a94cbc38c1891ce568addb6cb280aa1d5353
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/services/metadata.js#L106-L116
24,391
clay/amphora
lib/services/metadata.js
unpublishPage
function unpublishPage(uri, user) { const update = { published: false, publishTime: null, url: '', history: [{ action: 'unpublish', timestamp: new Date().toISOString(), users: [userOrRobot(user)] }] }; return changeMetaState(uri, update); }
javascript
function unpublishPage(uri, user) { const update = { published: false, publishTime: null, url: '', history: [{ action: 'unpublish', timestamp: new Date().toISOString(), users: [userOrRobot(user)] }] }; return changeMetaState(uri, update); }
[ "function", "unpublishPage", "(", "uri", ",", "user", ")", "{", "const", "update", "=", "{", "published", ":", "false", ",", "publishTime", ":", "null", ",", "url", ":", "''", ",", "history", ":", "[", "{", "action", ":", "'unpublish'", ",", "timestamp", ":", "new", "Date", "(", ")", ".", "toISOString", "(", ")", ",", "users", ":", "[", "userOrRobot", "(", "user", ")", "]", "}", "]", "}", ";", "return", "changeMetaState", "(", "uri", ",", "update", ")", ";", "}" ]
Update the page meta on unpublish @param {String} uri @param {Object} user @returns {Promise}
[ "Update", "the", "page", "meta", "on", "unpublish" ]
b883a94cbc38c1891ce568addb6cb280aa1d5353
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/services/metadata.js#L125-L134
24,392
clay/amphora
lib/services/metadata.js
changeMetaState
function changeMetaState(uri, update) { return getMeta(uri) .then(old => mergeNewAndOldMeta(old, update)) .then(updatedMeta => putMeta(uri, updatedMeta)); }
javascript
function changeMetaState(uri, update) { return getMeta(uri) .then(old => mergeNewAndOldMeta(old, update)) .then(updatedMeta => putMeta(uri, updatedMeta)); }
[ "function", "changeMetaState", "(", "uri", ",", "update", ")", "{", "return", "getMeta", "(", "uri", ")", ".", "then", "(", "old", "=>", "mergeNewAndOldMeta", "(", "old", ",", "update", ")", ")", ".", "then", "(", "updatedMeta", "=>", "putMeta", "(", "uri", ",", "updatedMeta", ")", ")", ";", "}" ]
Given a uri and an object that is an update, retreive the old meta, merge the new and old and then put the merge to the db. @param {String} uri @param {Object} update @returns {Promise}
[ "Given", "a", "uri", "and", "an", "object", "that", "is", "an", "update", "retreive", "the", "old", "meta", "merge", "the", "new", "and", "old", "and", "then", "put", "the", "merge", "to", "the", "db", "." ]
b883a94cbc38c1891ce568addb6cb280aa1d5353
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/services/metadata.js#L160-L164
24,393
clay/amphora
lib/services/metadata.js
putMeta
function putMeta(uri, data) { const id = replaceVersion(uri.replace('/meta', '')); return db.putMeta(id, data) .then(pubToBus(id)); }
javascript
function putMeta(uri, data) { const id = replaceVersion(uri.replace('/meta', '')); return db.putMeta(id, data) .then(pubToBus(id)); }
[ "function", "putMeta", "(", "uri", ",", "data", ")", "{", "const", "id", "=", "replaceVersion", "(", "uri", ".", "replace", "(", "'/meta'", ",", "''", ")", ")", ";", "return", "db", ".", "putMeta", "(", "id", ",", "data", ")", ".", "then", "(", "pubToBus", "(", "id", ")", ")", ";", "}" ]
Write the page's meta object to the DB @param {String} uri @param {Object} data @returns {Promise}
[ "Write", "the", "page", "s", "meta", "object", "to", "the", "DB" ]
b883a94cbc38c1891ce568addb6cb280aa1d5353
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/services/metadata.js#L214-L219
24,394
clay/amphora
lib/services/metadata.js
patchMeta
function patchMeta(uri, data) { const id = replaceVersion(uri.replace('/meta', '')); return db.patchMeta(id, data) .then(() => getMeta(uri)) .then(pubToBus(id)); }
javascript
function patchMeta(uri, data) { const id = replaceVersion(uri.replace('/meta', '')); return db.patchMeta(id, data) .then(() => getMeta(uri)) .then(pubToBus(id)); }
[ "function", "patchMeta", "(", "uri", ",", "data", ")", "{", "const", "id", "=", "replaceVersion", "(", "uri", ".", "replace", "(", "'/meta'", ",", "''", ")", ")", ";", "return", "db", ".", "patchMeta", "(", "id", ",", "data", ")", ".", "then", "(", "(", ")", "=>", "getMeta", "(", "uri", ")", ")", ".", "then", "(", "pubToBus", "(", "id", ")", ")", ";", "}" ]
Update a subset of properties on a metadata object @param {String} uri @param {Object} data @returns {Promise}
[ "Update", "a", "subset", "of", "properties", "on", "a", "metadata", "object" ]
b883a94cbc38c1891ce568addb6cb280aa1d5353
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/services/metadata.js#L229-L235
24,395
clay/amphora
lib/services/metadata.js
checkProps
function checkProps(uri, props) { const id = replaceVersion(uri.replace('/meta', '')); return db.getMeta(id) .then(meta => { return Array.isArray(props) ? props.every(prop => meta[prop]) : meta[props] && true; }) .catch(err => { throw new Error(err); }); }
javascript
function checkProps(uri, props) { const id = replaceVersion(uri.replace('/meta', '')); return db.getMeta(id) .then(meta => { return Array.isArray(props) ? props.every(prop => meta[prop]) : meta[props] && true; }) .catch(err => { throw new Error(err); }); }
[ "function", "checkProps", "(", "uri", ",", "props", ")", "{", "const", "id", "=", "replaceVersion", "(", "uri", ".", "replace", "(", "'/meta'", ",", "''", ")", ")", ";", "return", "db", ".", "getMeta", "(", "id", ")", ".", "then", "(", "meta", "=>", "{", "return", "Array", ".", "isArray", "(", "props", ")", "?", "props", ".", "every", "(", "prop", "=>", "meta", "[", "prop", "]", ")", ":", "meta", "[", "props", "]", "&&", "true", ";", "}", ")", ".", "catch", "(", "err", "=>", "{", "throw", "new", "Error", "(", "err", ")", ";", "}", ")", ";", "}" ]
Check metadata property or properties for truthy values. Returns true if all properties have truthy values. @param {String} uri @param {String | Array} props @returns {Boolean | Object}
[ "Check", "metadata", "property", "or", "properties", "for", "truthy", "values", ".", "Returns", "true", "if", "all", "properties", "have", "truthy", "values", "." ]
b883a94cbc38c1891ce568addb6cb280aa1d5353
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/services/metadata.js#L244-L256
24,396
clay/amphora
lib/services/models.js
put
function put(model, uri, data, locals) { const startTime = process.hrtime(), timeoutLimit = TIMEOUT_CONSTANT * TIMEOUT_PUT_COEFFICIENT; return bluebird.try(() => { return bluebird.resolve(model.save(uri, data, locals)) .then(resolvedData => { if (!_.isObject(resolvedData)) { throw new Error(`Unable to save ${uri}: Data from model.save must be an object!`); } return { key: uri, type: 'put', value: JSON.stringify(resolvedData) }; }); }).tap(() => { const ms = timer.getMillisecondsSince(startTime); if (ms > timeoutLimit * 0.5) { log('warn', `slow put ${uri} ${ms}ms`); } }).timeout(timeoutLimit, `Module PUT exceeded ${timeoutLimit}ms: ${uri}`); }
javascript
function put(model, uri, data, locals) { const startTime = process.hrtime(), timeoutLimit = TIMEOUT_CONSTANT * TIMEOUT_PUT_COEFFICIENT; return bluebird.try(() => { return bluebird.resolve(model.save(uri, data, locals)) .then(resolvedData => { if (!_.isObject(resolvedData)) { throw new Error(`Unable to save ${uri}: Data from model.save must be an object!`); } return { key: uri, type: 'put', value: JSON.stringify(resolvedData) }; }); }).tap(() => { const ms = timer.getMillisecondsSince(startTime); if (ms > timeoutLimit * 0.5) { log('warn', `slow put ${uri} ${ms}ms`); } }).timeout(timeoutLimit, `Module PUT exceeded ${timeoutLimit}ms: ${uri}`); }
[ "function", "put", "(", "model", ",", "uri", ",", "data", ",", "locals", ")", "{", "const", "startTime", "=", "process", ".", "hrtime", "(", ")", ",", "timeoutLimit", "=", "TIMEOUT_CONSTANT", "*", "TIMEOUT_PUT_COEFFICIENT", ";", "return", "bluebird", ".", "try", "(", "(", ")", "=>", "{", "return", "bluebird", ".", "resolve", "(", "model", ".", "save", "(", "uri", ",", "data", ",", "locals", ")", ")", ".", "then", "(", "resolvedData", "=>", "{", "if", "(", "!", "_", ".", "isObject", "(", "resolvedData", ")", ")", "{", "throw", "new", "Error", "(", "`", "${", "uri", "}", "`", ")", ";", "}", "return", "{", "key", ":", "uri", ",", "type", ":", "'put'", ",", "value", ":", "JSON", ".", "stringify", "(", "resolvedData", ")", "}", ";", "}", ")", ";", "}", ")", ".", "tap", "(", "(", ")", "=>", "{", "const", "ms", "=", "timer", ".", "getMillisecondsSince", "(", "startTime", ")", ";", "if", "(", "ms", ">", "timeoutLimit", "*", "0.5", ")", "{", "log", "(", "'warn'", ",", "`", "${", "uri", "}", "${", "ms", "}", "`", ")", ";", "}", "}", ")", ".", "timeout", "(", "timeoutLimit", ",", "`", "${", "timeoutLimit", "}", "${", "uri", "}", "`", ")", ";", "}" ]
Execute the save function of a model.js file for either a component or a layout @param {Object} model @param {String} uri @param {Object} data @param {Object} locals @returns {Object}
[ "Execute", "the", "save", "function", "of", "a", "model", ".", "js", "file", "for", "either", "a", "component", "or", "a", "layout" ]
b883a94cbc38c1891ce568addb6cb280aa1d5353
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/services/models.js#L23-L47
24,397
clay/amphora
lib/services/models.js
get
function get(model, renderModel, executeRender, uri, locals) { /* eslint max-params: ["error", 5] */ var promise; if (executeRender) { const startTime = process.hrtime(), timeoutLimit = TIMEOUT_CONSTANT * TIMEOUT_GET_COEFFICIENT; promise = bluebird.try(() => { return db.get(uri) .then(upgrade.init(uri, locals)) // Run an upgrade! .then(data => model.render(uri, data, locals)); }).tap(result => { const ms = timer.getMillisecondsSince(startTime); if (!_.isObject(result)) { throw new Error(`Component model must return object, not ${typeof result}: ${uri}`); } if (ms > timeoutLimit * 0.5) { log('warn', `slow get ${uri} ${ms}ms`); } }).timeout(timeoutLimit, `Model GET exceeded ${timeoutLimit}ms: ${uri}`); } else { promise = db.get(uri).then(upgrade.init(uri, locals)); // Run an upgrade! } if (renderModel && _.isFunction(renderModel)) { promise = promise.then(data => renderModel(uri, data, locals)); } return promise.then(data => { if (!_.isObject(data)) { throw new Error(`Client: Invalid data type for component at ${uri} of ${typeof data}`); } return data; }); }
javascript
function get(model, renderModel, executeRender, uri, locals) { /* eslint max-params: ["error", 5] */ var promise; if (executeRender) { const startTime = process.hrtime(), timeoutLimit = TIMEOUT_CONSTANT * TIMEOUT_GET_COEFFICIENT; promise = bluebird.try(() => { return db.get(uri) .then(upgrade.init(uri, locals)) // Run an upgrade! .then(data => model.render(uri, data, locals)); }).tap(result => { const ms = timer.getMillisecondsSince(startTime); if (!_.isObject(result)) { throw new Error(`Component model must return object, not ${typeof result}: ${uri}`); } if (ms > timeoutLimit * 0.5) { log('warn', `slow get ${uri} ${ms}ms`); } }).timeout(timeoutLimit, `Model GET exceeded ${timeoutLimit}ms: ${uri}`); } else { promise = db.get(uri).then(upgrade.init(uri, locals)); // Run an upgrade! } if (renderModel && _.isFunction(renderModel)) { promise = promise.then(data => renderModel(uri, data, locals)); } return promise.then(data => { if (!_.isObject(data)) { throw new Error(`Client: Invalid data type for component at ${uri} of ${typeof data}`); } return data; }); }
[ "function", "get", "(", "model", ",", "renderModel", ",", "executeRender", ",", "uri", ",", "locals", ")", "{", "/* eslint max-params: [\"error\", 5] */", "var", "promise", ";", "if", "(", "executeRender", ")", "{", "const", "startTime", "=", "process", ".", "hrtime", "(", ")", ",", "timeoutLimit", "=", "TIMEOUT_CONSTANT", "*", "TIMEOUT_GET_COEFFICIENT", ";", "promise", "=", "bluebird", ".", "try", "(", "(", ")", "=>", "{", "return", "db", ".", "get", "(", "uri", ")", ".", "then", "(", "upgrade", ".", "init", "(", "uri", ",", "locals", ")", ")", "// Run an upgrade!", ".", "then", "(", "data", "=>", "model", ".", "render", "(", "uri", ",", "data", ",", "locals", ")", ")", ";", "}", ")", ".", "tap", "(", "result", "=>", "{", "const", "ms", "=", "timer", ".", "getMillisecondsSince", "(", "startTime", ")", ";", "if", "(", "!", "_", ".", "isObject", "(", "result", ")", ")", "{", "throw", "new", "Error", "(", "`", "${", "typeof", "result", "}", "${", "uri", "}", "`", ")", ";", "}", "if", "(", "ms", ">", "timeoutLimit", "*", "0.5", ")", "{", "log", "(", "'warn'", ",", "`", "${", "uri", "}", "${", "ms", "}", "`", ")", ";", "}", "}", ")", ".", "timeout", "(", "timeoutLimit", ",", "`", "${", "timeoutLimit", "}", "${", "uri", "}", "`", ")", ";", "}", "else", "{", "promise", "=", "db", ".", "get", "(", "uri", ")", ".", "then", "(", "upgrade", ".", "init", "(", "uri", ",", "locals", ")", ")", ";", "// Run an upgrade!", "}", "if", "(", "renderModel", "&&", "_", ".", "isFunction", "(", "renderModel", ")", ")", "{", "promise", "=", "promise", ".", "then", "(", "data", "=>", "renderModel", "(", "uri", ",", "data", ",", "locals", ")", ")", ";", "}", "return", "promise", ".", "then", "(", "data", "=>", "{", "if", "(", "!", "_", ".", "isObject", "(", "data", ")", ")", "{", "throw", "new", "Error", "(", "`", "${", "uri", "}", "${", "typeof", "data", "}", "`", ")", ";", "}", "return", "data", ";", "}", ")", ";", "}" ]
Execute the get function of a model.js file for either a component or a layout @param {Object} model @param {Object} renderModel @param {Boolean} executeRender @param {String} uri @param {Object} locals @returns {Promise}
[ "Execute", "the", "get", "function", "of", "a", "model", ".", "js", "file", "for", "either", "a", "component", "or", "a", "layout" ]
b883a94cbc38c1891ce568addb6cb280aa1d5353
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/services/models.js#L60-L98
24,398
clay/amphora
lib/services/pages.js
renameReferenceUniquely
function renameReferenceUniquely(uri) { const prefix = uri.substr(0, uri.indexOf('/_components/')); return `${prefix}/_components/${getComponentName(uri)}/instances/${uid.get()}`; }
javascript
function renameReferenceUniquely(uri) { const prefix = uri.substr(0, uri.indexOf('/_components/')); return `${prefix}/_components/${getComponentName(uri)}/instances/${uid.get()}`; }
[ "function", "renameReferenceUniquely", "(", "uri", ")", "{", "const", "prefix", "=", "uri", ".", "substr", "(", "0", ",", "uri", ".", "indexOf", "(", "'/_components/'", ")", ")", ";", "return", "`", "${", "prefix", "}", "${", "getComponentName", "(", "uri", ")", "}", "${", "uid", ".", "get", "(", ")", "}", "`", ";", "}" ]
Get a reference that is unique, but of the same component type as original. @param {string} uri @returns {string}
[ "Get", "a", "reference", "that", "is", "unique", "but", "of", "the", "same", "component", "type", "as", "original", "." ]
b883a94cbc38c1891ce568addb6cb280aa1d5353
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/services/pages.js#L56-L60
24,399
clay/amphora
lib/services/pages.js
getPageClonePutOperations
function getPageClonePutOperations(pageData, locals) { return bluebird.all(_.reduce(pageData, (promises, pageValue, pageKey) => { if (typeof pageValue === 'string' && getComponentName(pageValue)) { // for all strings that are component references promises.push(components.get(pageValue, locals) // only follow the paths of instance references. Don't clone default components .then(refData => composer.resolveComponentReferences(refData, locals, isInstanceReferenceObject)) .then(resolvedData => { // for each instance reference within resolved data _.each(references.listDeepObjects(resolvedData, isInstanceReferenceObject), obj => { obj._ref = renameReferenceUniquely(obj._ref); }); // rename reference in pageData const ref = renameReferenceUniquely(pageValue); pageData[pageKey] = ref; // put new data using cascading PUT at place that page now points return dbOps.getPutOperations(components.cmptPut, ref, resolvedData, locals); })); } else { // for all object-like things (i.e., objects and arrays) promises = promises.concat(getPageClonePutOperations(pageValue, locals)); } return promises; }, [])).then(_.flatten); // only one level of flattening needed }
javascript
function getPageClonePutOperations(pageData, locals) { return bluebird.all(_.reduce(pageData, (promises, pageValue, pageKey) => { if (typeof pageValue === 'string' && getComponentName(pageValue)) { // for all strings that are component references promises.push(components.get(pageValue, locals) // only follow the paths of instance references. Don't clone default components .then(refData => composer.resolveComponentReferences(refData, locals, isInstanceReferenceObject)) .then(resolvedData => { // for each instance reference within resolved data _.each(references.listDeepObjects(resolvedData, isInstanceReferenceObject), obj => { obj._ref = renameReferenceUniquely(obj._ref); }); // rename reference in pageData const ref = renameReferenceUniquely(pageValue); pageData[pageKey] = ref; // put new data using cascading PUT at place that page now points return dbOps.getPutOperations(components.cmptPut, ref, resolvedData, locals); })); } else { // for all object-like things (i.e., objects and arrays) promises = promises.concat(getPageClonePutOperations(pageValue, locals)); } return promises; }, [])).then(_.flatten); // only one level of flattening needed }
[ "function", "getPageClonePutOperations", "(", "pageData", ",", "locals", ")", "{", "return", "bluebird", ".", "all", "(", "_", ".", "reduce", "(", "pageData", ",", "(", "promises", ",", "pageValue", ",", "pageKey", ")", "=>", "{", "if", "(", "typeof", "pageValue", "===", "'string'", "&&", "getComponentName", "(", "pageValue", ")", ")", "{", "// for all strings that are component references", "promises", ".", "push", "(", "components", ".", "get", "(", "pageValue", ",", "locals", ")", "// only follow the paths of instance references. Don't clone default components", ".", "then", "(", "refData", "=>", "composer", ".", "resolveComponentReferences", "(", "refData", ",", "locals", ",", "isInstanceReferenceObject", ")", ")", ".", "then", "(", "resolvedData", "=>", "{", "// for each instance reference within resolved data", "_", ".", "each", "(", "references", ".", "listDeepObjects", "(", "resolvedData", ",", "isInstanceReferenceObject", ")", ",", "obj", "=>", "{", "obj", ".", "_ref", "=", "renameReferenceUniquely", "(", "obj", ".", "_ref", ")", ";", "}", ")", ";", "// rename reference in pageData", "const", "ref", "=", "renameReferenceUniquely", "(", "pageValue", ")", ";", "pageData", "[", "pageKey", "]", "=", "ref", ";", "// put new data using cascading PUT at place that page now points", "return", "dbOps", ".", "getPutOperations", "(", "components", ".", "cmptPut", ",", "ref", ",", "resolvedData", ",", "locals", ")", ";", "}", ")", ")", ";", "}", "else", "{", "// for all object-like things (i.e., objects and arrays)", "promises", "=", "promises", ".", "concat", "(", "getPageClonePutOperations", "(", "pageValue", ",", "locals", ")", ")", ";", "}", "return", "promises", ";", "}", ",", "[", "]", ")", ")", ".", "then", "(", "_", ".", "flatten", ")", ";", "// only one level of flattening needed", "}" ]
Clone all instance components that are referenced by this page data, and maintain the data's object structure. @param {object} pageData @param {object} locals @returns {Promise}
[ "Clone", "all", "instance", "components", "that", "are", "referenced", "by", "this", "page", "data", "and", "maintain", "the", "data", "s", "object", "structure", "." ]
b883a94cbc38c1891ce568addb6cb280aa1d5353
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/services/pages.js#L69-L96