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
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
signalfx/signalfx-nodejs
|
lib/proto/signal_fx_protocol_buffers_pb2.js
|
EventUploadMessage
|
function EventUploadMessage(properties) {
this.events = [];
if (properties)
for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
if (properties[keys[i]] != null)
this[keys[i]] = properties[keys[i]];
}
|
javascript
|
function EventUploadMessage(properties) {
this.events = [];
if (properties)
for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
if (properties[keys[i]] != null)
this[keys[i]] = properties[keys[i]];
}
|
[
"function",
"EventUploadMessage",
"(",
"properties",
")",
"{",
"this",
".",
"events",
"=",
"[",
"]",
";",
"if",
"(",
"properties",
")",
"for",
"(",
"var",
"keys",
"=",
"Object",
".",
"keys",
"(",
"properties",
")",
",",
"i",
"=",
"0",
";",
"i",
"<",
"keys",
".",
"length",
";",
"++",
"i",
")",
"if",
"(",
"properties",
"[",
"keys",
"[",
"i",
"]",
"]",
"!=",
"null",
")",
"this",
"[",
"keys",
"[",
"i",
"]",
"]",
"=",
"properties",
"[",
"keys",
"[",
"i",
"]",
"]",
";",
"}"
] |
Properties of an EventUploadMessage.
@memberof com.signalfx.metrics.protobuf
@interface IEventUploadMessage
@property {Array.<com.signalfx.metrics.protobuf.IEvent>|null} [events] EventUploadMessage events
Constructs a new EventUploadMessage.
@memberof com.signalfx.metrics.protobuf
@classdesc Represents an EventUploadMessage.
@implements IEventUploadMessage
@constructor
@param {com.signalfx.metrics.protobuf.IEventUploadMessage=} [properties] Properties to set
|
[
"Properties",
"of",
"an",
"EventUploadMessage",
"."
] |
88f14af02c9af8de54e3ff273b5c9d3ab32030de
|
https://github.com/signalfx/signalfx-nodejs/blob/88f14af02c9af8de54e3ff273b5c9d3ab32030de/lib/proto/signal_fx_protocol_buffers_pb2.js#L2218-L2224
|
train
|
signalfx/signalfx-nodejs
|
lib/client/signalflow/message_router.js
|
getRoutedMessageHandler
|
function getRoutedMessageHandler(params, onMessage, onError, isRetryPatchMode) {
var expectedBatchMessageCount = 0;
var numBatchesDetermined = false;
var messageBatchBuffer = [];
var lastSeenDataTime = 0;
var lastSeenDataBatchTime = 0;
function composeDataBatches(dataArray) {
if (dataArray.length === 0) {
if (messageBatchBuffer.length > 0) {
console.error('Composed an empty data batch despite having data in the buffer!');
}
return null;
}
var errorOccurred = false;
var basisData = dataArray[0];
var expectedTimeStamp = basisData.logicalTimestampMs;
lastSeenDataBatchTime = expectedTimeStamp;
dataArray.slice(1).forEach(function (batch) {
if (batch.logicalTimestampMs !== expectedTimeStamp) {
errorOccurred = true;
} else {
basisData.data = basisData.data.concat(batch.data);
}
});
if (errorOccurred) {
console.error('Bad timestamp pairs when flushing data batches! Inconsistent data!');
return null;
}
return basisData;
}
function flushBuffer() {
if (numBatchesDetermined && messageBatchBuffer.length === expectedBatchMessageCount && messageBatchBuffer.length > 0) {
onMessage(composeDataBatches(messageBatchBuffer));
messageBatchBuffer = [];
}
}
return {
getLatestBatchTimeStamp: function () {
return lastSeenDataBatchTime;
},
onMessage: function messageReceived(msg) {
if (!msg.type && msg.hasOwnProperty('error')) {
onMessage(msg);
return;
}
switch (msg.type) {
case 'data':
if (lastSeenDataTime && lastSeenDataTime !== msg.logicalTimestampMs) {
// if zero time series are encountered, then no metadata arrives, but data batches arrive with differing
// timestamp as the only evidence of a stream block
numBatchesDetermined = true;
}
lastSeenDataTime = msg.logicalTimestampMs;
messageBatchBuffer.push(msg);
if (!numBatchesDetermined) {
expectedBatchMessageCount++;
} else if (messageBatchBuffer.length === expectedBatchMessageCount) {
flushBuffer();
}
break;
case 'message':
if (msg.message && msg.message.messageCode === 'JOB_RUNNING_RESOLUTION') {
numBatchesDetermined = true;
flushBuffer();
}
onMessage(msg);
break;
case 'metadata':
case 'event':
onMessage(msg);
break;
case 'control-message':
if (isRetryPatchMode && !numBatchesDetermined) {
break;
}
onMessage(msg);
break;
case 'error':
if (onError) {
onError(msg);
}
break;
default:
console.log('Unrecognized message type.');
break;
}
flushBuffer();
}
};
}
|
javascript
|
function getRoutedMessageHandler(params, onMessage, onError, isRetryPatchMode) {
var expectedBatchMessageCount = 0;
var numBatchesDetermined = false;
var messageBatchBuffer = [];
var lastSeenDataTime = 0;
var lastSeenDataBatchTime = 0;
function composeDataBatches(dataArray) {
if (dataArray.length === 0) {
if (messageBatchBuffer.length > 0) {
console.error('Composed an empty data batch despite having data in the buffer!');
}
return null;
}
var errorOccurred = false;
var basisData = dataArray[0];
var expectedTimeStamp = basisData.logicalTimestampMs;
lastSeenDataBatchTime = expectedTimeStamp;
dataArray.slice(1).forEach(function (batch) {
if (batch.logicalTimestampMs !== expectedTimeStamp) {
errorOccurred = true;
} else {
basisData.data = basisData.data.concat(batch.data);
}
});
if (errorOccurred) {
console.error('Bad timestamp pairs when flushing data batches! Inconsistent data!');
return null;
}
return basisData;
}
function flushBuffer() {
if (numBatchesDetermined && messageBatchBuffer.length === expectedBatchMessageCount && messageBatchBuffer.length > 0) {
onMessage(composeDataBatches(messageBatchBuffer));
messageBatchBuffer = [];
}
}
return {
getLatestBatchTimeStamp: function () {
return lastSeenDataBatchTime;
},
onMessage: function messageReceived(msg) {
if (!msg.type && msg.hasOwnProperty('error')) {
onMessage(msg);
return;
}
switch (msg.type) {
case 'data':
if (lastSeenDataTime && lastSeenDataTime !== msg.logicalTimestampMs) {
// if zero time series are encountered, then no metadata arrives, but data batches arrive with differing
// timestamp as the only evidence of a stream block
numBatchesDetermined = true;
}
lastSeenDataTime = msg.logicalTimestampMs;
messageBatchBuffer.push(msg);
if (!numBatchesDetermined) {
expectedBatchMessageCount++;
} else if (messageBatchBuffer.length === expectedBatchMessageCount) {
flushBuffer();
}
break;
case 'message':
if (msg.message && msg.message.messageCode === 'JOB_RUNNING_RESOLUTION') {
numBatchesDetermined = true;
flushBuffer();
}
onMessage(msg);
break;
case 'metadata':
case 'event':
onMessage(msg);
break;
case 'control-message':
if (isRetryPatchMode && !numBatchesDetermined) {
break;
}
onMessage(msg);
break;
case 'error':
if (onError) {
onError(msg);
}
break;
default:
console.log('Unrecognized message type.');
break;
}
flushBuffer();
}
};
}
|
[
"function",
"getRoutedMessageHandler",
"(",
"params",
",",
"onMessage",
",",
"onError",
",",
"isRetryPatchMode",
")",
"{",
"var",
"expectedBatchMessageCount",
"=",
"0",
";",
"var",
"numBatchesDetermined",
"=",
"false",
";",
"var",
"messageBatchBuffer",
"=",
"[",
"]",
";",
"var",
"lastSeenDataTime",
"=",
"0",
";",
"var",
"lastSeenDataBatchTime",
"=",
"0",
";",
"function",
"composeDataBatches",
"(",
"dataArray",
")",
"{",
"if",
"(",
"dataArray",
".",
"length",
"===",
"0",
")",
"{",
"if",
"(",
"messageBatchBuffer",
".",
"length",
">",
"0",
")",
"{",
"console",
".",
"error",
"(",
"'Composed an empty data batch despite having data in the buffer!'",
")",
";",
"}",
"return",
"null",
";",
"}",
"var",
"errorOccurred",
"=",
"false",
";",
"var",
"basisData",
"=",
"dataArray",
"[",
"0",
"]",
";",
"var",
"expectedTimeStamp",
"=",
"basisData",
".",
"logicalTimestampMs",
";",
"lastSeenDataBatchTime",
"=",
"expectedTimeStamp",
";",
"dataArray",
".",
"slice",
"(",
"1",
")",
".",
"forEach",
"(",
"function",
"(",
"batch",
")",
"{",
"if",
"(",
"batch",
".",
"logicalTimestampMs",
"!==",
"expectedTimeStamp",
")",
"{",
"errorOccurred",
"=",
"true",
";",
"}",
"else",
"{",
"basisData",
".",
"data",
"=",
"basisData",
".",
"data",
".",
"concat",
"(",
"batch",
".",
"data",
")",
";",
"}",
"}",
")",
";",
"if",
"(",
"errorOccurred",
")",
"{",
"console",
".",
"error",
"(",
"'Bad timestamp pairs when flushing data batches! Inconsistent data!'",
")",
";",
"return",
"null",
";",
"}",
"return",
"basisData",
";",
"}",
"function",
"flushBuffer",
"(",
")",
"{",
"if",
"(",
"numBatchesDetermined",
"&&",
"messageBatchBuffer",
".",
"length",
"===",
"expectedBatchMessageCount",
"&&",
"messageBatchBuffer",
".",
"length",
">",
"0",
")",
"{",
"onMessage",
"(",
"composeDataBatches",
"(",
"messageBatchBuffer",
")",
")",
";",
"messageBatchBuffer",
"=",
"[",
"]",
";",
"}",
"}",
"return",
"{",
"getLatestBatchTimeStamp",
":",
"function",
"(",
")",
"{",
"return",
"lastSeenDataBatchTime",
";",
"}",
",",
"onMessage",
":",
"function",
"messageReceived",
"(",
"msg",
")",
"{",
"if",
"(",
"!",
"msg",
".",
"type",
"&&",
"msg",
".",
"hasOwnProperty",
"(",
"'error'",
")",
")",
"{",
"onMessage",
"(",
"msg",
")",
";",
"return",
";",
"}",
"switch",
"(",
"msg",
".",
"type",
")",
"{",
"case",
"'data'",
":",
"if",
"(",
"lastSeenDataTime",
"&&",
"lastSeenDataTime",
"!==",
"msg",
".",
"logicalTimestampMs",
")",
"{",
"numBatchesDetermined",
"=",
"true",
";",
"}",
"lastSeenDataTime",
"=",
"msg",
".",
"logicalTimestampMs",
";",
"messageBatchBuffer",
".",
"push",
"(",
"msg",
")",
";",
"if",
"(",
"!",
"numBatchesDetermined",
")",
"{",
"expectedBatchMessageCount",
"++",
";",
"}",
"else",
"if",
"(",
"messageBatchBuffer",
".",
"length",
"===",
"expectedBatchMessageCount",
")",
"{",
"flushBuffer",
"(",
")",
";",
"}",
"break",
";",
"case",
"'message'",
":",
"if",
"(",
"msg",
".",
"message",
"&&",
"msg",
".",
"message",
".",
"messageCode",
"===",
"'JOB_RUNNING_RESOLUTION'",
")",
"{",
"numBatchesDetermined",
"=",
"true",
";",
"flushBuffer",
"(",
")",
";",
"}",
"onMessage",
"(",
"msg",
")",
";",
"break",
";",
"case",
"'metadata'",
":",
"case",
"'event'",
":",
"onMessage",
"(",
"msg",
")",
";",
"break",
";",
"case",
"'control-message'",
":",
"if",
"(",
"isRetryPatchMode",
"&&",
"!",
"numBatchesDetermined",
")",
"{",
"break",
";",
"}",
"onMessage",
"(",
"msg",
")",
";",
"break",
";",
"case",
"'error'",
":",
"if",
"(",
"onError",
")",
"{",
"onError",
"(",
"msg",
")",
";",
"}",
"break",
";",
"default",
":",
"console",
".",
"log",
"(",
"'Unrecognized message type.'",
")",
";",
"break",
";",
"}",
"flushBuffer",
"(",
")",
";",
"}",
"}",
";",
"}"
] |
a routed message handler deals with all messages within a particular channel scope it is responsible for massaging messages and flushing batches of data messages.
|
[
"a",
"routed",
"message",
"handler",
"deals",
"with",
"all",
"messages",
"within",
"a",
"particular",
"channel",
"scope",
"it",
"is",
"responsible",
"for",
"massaging",
"messages",
"and",
"flushing",
"batches",
"of",
"data",
"messages",
"."
] |
88f14af02c9af8de54e3ff273b5c9d3ab32030de
|
https://github.com/signalfx/signalfx-nodejs/blob/88f14af02c9af8de54e3ff273b5c9d3ab32030de/lib/client/signalflow/message_router.js#L8-L102
|
train
|
defunctzombie/node-browser-resolve
|
index.js
|
load_shims_sync
|
function load_shims_sync(paths, browser) {
// identify if our file should be replaced per the browser field
// original filename|id -> replacement
var shims = Object.create(null);
var cur_path;
while (cur_path = paths.shift()) {
var pkg_path = path.join(cur_path, 'package.json');
try {
var data = fs.readFileSync(pkg_path, 'utf8');
find_shims_in_package(data, cur_path, shims, browser);
return shims;
}
catch (err) {
// ignore paths we can't open
// avoids an exists check
if (err.code === 'ENOENT') {
continue;
}
throw err;
}
}
return shims;
}
|
javascript
|
function load_shims_sync(paths, browser) {
// identify if our file should be replaced per the browser field
// original filename|id -> replacement
var shims = Object.create(null);
var cur_path;
while (cur_path = paths.shift()) {
var pkg_path = path.join(cur_path, 'package.json');
try {
var data = fs.readFileSync(pkg_path, 'utf8');
find_shims_in_package(data, cur_path, shims, browser);
return shims;
}
catch (err) {
// ignore paths we can't open
// avoids an exists check
if (err.code === 'ENOENT') {
continue;
}
throw err;
}
}
return shims;
}
|
[
"function",
"load_shims_sync",
"(",
"paths",
",",
"browser",
")",
"{",
"var",
"shims",
"=",
"Object",
".",
"create",
"(",
"null",
")",
";",
"var",
"cur_path",
";",
"while",
"(",
"cur_path",
"=",
"paths",
".",
"shift",
"(",
")",
")",
"{",
"var",
"pkg_path",
"=",
"path",
".",
"join",
"(",
"cur_path",
",",
"'package.json'",
")",
";",
"try",
"{",
"var",
"data",
"=",
"fs",
".",
"readFileSync",
"(",
"pkg_path",
",",
"'utf8'",
")",
";",
"find_shims_in_package",
"(",
"data",
",",
"cur_path",
",",
"shims",
",",
"browser",
")",
";",
"return",
"shims",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"if",
"(",
"err",
".",
"code",
"===",
"'ENOENT'",
")",
"{",
"continue",
";",
"}",
"throw",
"err",
";",
"}",
"}",
"return",
"shims",
";",
"}"
] |
paths is mutated synchronously load shims from first package.json file found
|
[
"paths",
"is",
"mutated",
"synchronously",
"load",
"shims",
"from",
"first",
"package",
".",
"json",
"file",
"found"
] |
427bb886cc22cc773651d3f2a51d4c5ea455870e
|
https://github.com/defunctzombie/node-browser-resolve/blob/427bb886cc22cc773651d3f2a51d4c5ea455870e/index.js#L121-L146
|
train
|
exonum/exonum-client
|
src/types/hexadecimal.js
|
hexTypeFactory
|
function hexTypeFactory (serizalizer, size, name) {
return Object.defineProperties({}, {
size: {
get: () => () => size,
enumerable: true
},
name: {
get: () => name,
enumerable: true
},
serialize: {
get: () => serizalizer
}
})
}
|
javascript
|
function hexTypeFactory (serizalizer, size, name) {
return Object.defineProperties({}, {
size: {
get: () => () => size,
enumerable: true
},
name: {
get: () => name,
enumerable: true
},
serialize: {
get: () => serizalizer
}
})
}
|
[
"function",
"hexTypeFactory",
"(",
"serizalizer",
",",
"size",
",",
"name",
")",
"{",
"return",
"Object",
".",
"defineProperties",
"(",
"{",
"}",
",",
"{",
"size",
":",
"{",
"get",
":",
"(",
")",
"=>",
"(",
")",
"=>",
"size",
",",
"enumerable",
":",
"true",
"}",
",",
"name",
":",
"{",
"get",
":",
"(",
")",
"=>",
"name",
",",
"enumerable",
":",
"true",
"}",
",",
"serialize",
":",
"{",
"get",
":",
"(",
")",
"=>",
"serizalizer",
"}",
"}",
")",
"}"
] |
Factory for building Hex Types
@param {function(value, buffer, from)} serizalizer function accepting value, buffer, position and returns modified buffer
@param {number} size type size in bytes
@param {string} name type name to distinguish between types
@returns {Object} hex type
|
[
"Factory",
"for",
"building",
"Hex",
"Types"
] |
edb77abe6479b7e13c667b2f00aa2dca97d4c401
|
https://github.com/exonum/exonum-client/blob/edb77abe6479b7e13c667b2f00aa2dca97d4c401/src/types/hexadecimal.js#L49-L63
|
train
|
exonum/exonum-client
|
src/types/hexadecimal.js
|
Uuid
|
function Uuid (validator, serializer, factory) {
const size = 16
const name = 'Uuid'
function cleaner (value) {
return String(value).replace(/-/g, '')
}
validator = validator.bind(null, name, size)
serializer = serializer((value) => validator(cleaner(value)))
return factory(serializer, size, name)
}
|
javascript
|
function Uuid (validator, serializer, factory) {
const size = 16
const name = 'Uuid'
function cleaner (value) {
return String(value).replace(/-/g, '')
}
validator = validator.bind(null, name, size)
serializer = serializer((value) => validator(cleaner(value)))
return factory(serializer, size, name)
}
|
[
"function",
"Uuid",
"(",
"validator",
",",
"serializer",
",",
"factory",
")",
"{",
"const",
"size",
"=",
"16",
"const",
"name",
"=",
"'Uuid'",
"function",
"cleaner",
"(",
"value",
")",
"{",
"return",
"String",
"(",
"value",
")",
".",
"replace",
"(",
"/",
"-",
"/",
"g",
",",
"''",
")",
"}",
"validator",
"=",
"validator",
".",
"bind",
"(",
"null",
",",
"name",
",",
"size",
")",
"serializer",
"=",
"serializer",
"(",
"(",
"value",
")",
"=>",
"validator",
"(",
"cleaner",
"(",
"value",
")",
")",
")",
"return",
"factory",
"(",
"serializer",
",",
"size",
",",
"name",
")",
"}"
] |
Uuid type factory
@param {function(name, size, value)} validator hexadecimal validator
@param {function(validator, value, buffer, from)} encoder function accepting validator, value, buffer, position and returns modified buffer
@param {function(serizalizer, size, name)} factory type builder factory
@returns {Object} hex type
@private
|
[
"Uuid",
"type",
"factory"
] |
edb77abe6479b7e13c667b2f00aa2dca97d4c401
|
https://github.com/exonum/exonum-client/blob/edb77abe6479b7e13c667b2f00aa2dca97d4c401/src/types/hexadecimal.js#L87-L99
|
train
|
exonum/exonum-client
|
src/types/hexadecimal.js
|
Hash
|
function Hash (validator, serializer, factory) {
const size = HASH_LENGTH
const name = 'Hash'
validator = validator.bind(null, name, size)
serializer = serializer(validator)
const hasher = function (value) {
return validator(value) && value
}
return Object.defineProperty(factory(serializer, size, name),
'hash',
{
value: hasher
})
}
|
javascript
|
function Hash (validator, serializer, factory) {
const size = HASH_LENGTH
const name = 'Hash'
validator = validator.bind(null, name, size)
serializer = serializer(validator)
const hasher = function (value) {
return validator(value) && value
}
return Object.defineProperty(factory(serializer, size, name),
'hash',
{
value: hasher
})
}
|
[
"function",
"Hash",
"(",
"validator",
",",
"serializer",
",",
"factory",
")",
"{",
"const",
"size",
"=",
"HASH_LENGTH",
"const",
"name",
"=",
"'Hash'",
"validator",
"=",
"validator",
".",
"bind",
"(",
"null",
",",
"name",
",",
"size",
")",
"serializer",
"=",
"serializer",
"(",
"validator",
")",
"const",
"hasher",
"=",
"function",
"(",
"value",
")",
"{",
"return",
"validator",
"(",
"value",
")",
"&&",
"value",
"}",
"return",
"Object",
".",
"defineProperty",
"(",
"factory",
"(",
"serializer",
",",
"size",
",",
"name",
")",
",",
"'hash'",
",",
"{",
"value",
":",
"hasher",
"}",
")",
"}"
] |
Hash type factory
@param {function(name, size, value)} validator hexadecimal validator
@param {function(validator, value, buffer, from)} encoder function accepting validator, value, buffer, position and returns modified buffer
@param {function(serizalizer, size, name)} factory type builder factory
@returns {Object} hex type
@private
|
[
"Hash",
"type",
"factory"
] |
edb77abe6479b7e13c667b2f00aa2dca97d4c401
|
https://github.com/exonum/exonum-client/blob/edb77abe6479b7e13c667b2f00aa2dca97d4c401/src/types/hexadecimal.js#L110-L126
|
train
|
exonum/exonum-client
|
src/types/hexadecimal.js
|
Digest
|
function Digest (validator, serializer, factory) {
const size = 64
const name = 'Digest'
validator = validator.bind(null, name, size)
serializer = serializer(validator)
return factory(serializer, size, name)
}
|
javascript
|
function Digest (validator, serializer, factory) {
const size = 64
const name = 'Digest'
validator = validator.bind(null, name, size)
serializer = serializer(validator)
return factory(serializer, size, name)
}
|
[
"function",
"Digest",
"(",
"validator",
",",
"serializer",
",",
"factory",
")",
"{",
"const",
"size",
"=",
"64",
"const",
"name",
"=",
"'Digest'",
"validator",
"=",
"validator",
".",
"bind",
"(",
"null",
",",
"name",
",",
"size",
")",
"serializer",
"=",
"serializer",
"(",
"validator",
")",
"return",
"factory",
"(",
"serializer",
",",
"size",
",",
"name",
")",
"}"
] |
Digest type factory
@param {function(name, size, value)} validator hexadecimal validator
@param {function(validator, value, buffer, from)} encoder function accepting validator, value, buffer, position and returns modified buffer
@param {function(serizalizer, size, name)} factory type builder factory
@returns {Object} hex type
@private
|
[
"Digest",
"type",
"factory"
] |
edb77abe6479b7e13c667b2f00aa2dca97d4c401
|
https://github.com/exonum/exonum-client/blob/edb77abe6479b7e13c667b2f00aa2dca97d4c401/src/types/hexadecimal.js#L137-L145
|
train
|
exonum/exonum-client
|
src/types/hexadecimal.js
|
PublicKey
|
function PublicKey (validator, serializer, factory) {
const size = PUBLIC_KEY_LENGTH
const name = 'PublicKey'
validator = validator.bind(null, name, size)
serializer = serializer(validator)
return factory(serializer, size, name)
}
|
javascript
|
function PublicKey (validator, serializer, factory) {
const size = PUBLIC_KEY_LENGTH
const name = 'PublicKey'
validator = validator.bind(null, name, size)
serializer = serializer(validator)
return factory(serializer, size, name)
}
|
[
"function",
"PublicKey",
"(",
"validator",
",",
"serializer",
",",
"factory",
")",
"{",
"const",
"size",
"=",
"PUBLIC_KEY_LENGTH",
"const",
"name",
"=",
"'PublicKey'",
"validator",
"=",
"validator",
".",
"bind",
"(",
"null",
",",
"name",
",",
"size",
")",
"serializer",
"=",
"serializer",
"(",
"validator",
")",
"return",
"factory",
"(",
"serializer",
",",
"size",
",",
"name",
")",
"}"
] |
PublicKey type factory
@param {function(name, size, value)} validator hexadecimal validator
@param {function(validator, value, buffer, from)} encoder function accepting validator, value, buffer, position and returns modified buffer
@param {function(serizalizer, size, name)} factory type builder factory
@returns {Object} hex type
@private
|
[
"PublicKey",
"type",
"factory"
] |
edb77abe6479b7e13c667b2f00aa2dca97d4c401
|
https://github.com/exonum/exonum-client/blob/edb77abe6479b7e13c667b2f00aa2dca97d4c401/src/types/hexadecimal.js#L156-L164
|
train
|
exonum/exonum-client
|
src/types/primitive.js
|
insertIntegerToByteArray
|
function insertIntegerToByteArray (number, buffer, from, size) {
let value = bigInt(number) // convert a number-like object into a big integer
for (let pos = 0; pos < size; pos++) {
const divmod = value.divmod(256)
buffer[from + pos] = divmod.remainder.toJSNumber()
value = divmod.quotient
}
return buffer
}
|
javascript
|
function insertIntegerToByteArray (number, buffer, from, size) {
let value = bigInt(number) // convert a number-like object into a big integer
for (let pos = 0; pos < size; pos++) {
const divmod = value.divmod(256)
buffer[from + pos] = divmod.remainder.toJSNumber()
value = divmod.quotient
}
return buffer
}
|
[
"function",
"insertIntegerToByteArray",
"(",
"number",
",",
"buffer",
",",
"from",
",",
"size",
")",
"{",
"let",
"value",
"=",
"bigInt",
"(",
"number",
")",
"for",
"(",
"let",
"pos",
"=",
"0",
";",
"pos",
"<",
"size",
";",
"pos",
"++",
")",
"{",
"const",
"divmod",
"=",
"value",
".",
"divmod",
"(",
"256",
")",
"buffer",
"[",
"from",
"+",
"pos",
"]",
"=",
"divmod",
".",
"remainder",
".",
"toJSNumber",
"(",
")",
"value",
"=",
"divmod",
".",
"quotient",
"}",
"return",
"buffer",
"}"
] |
Insert number into array as as little-endian
@param {number|bigInt} number
@param {Array} buffer
@param {number} from
@param {number} size
@returns {boolean}
|
[
"Insert",
"number",
"into",
"array",
"as",
"as",
"little",
"-",
"endian"
] |
edb77abe6479b7e13c667b2f00aa2dca97d4c401
|
https://github.com/exonum/exonum-client/blob/edb77abe6479b7e13c667b2f00aa2dca97d4c401/src/types/primitive.js#L15-L25
|
train
|
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
|
train
|
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",
")",
"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
|
train
|
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",
"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
|
train
|
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
|
train
|
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
|
train
|
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",
";",
"that",
".",
"emit",
"(",
"'_contentchange'",
")",
";",
"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
|
train
|
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",
";",
"that",
".",
"emit",
"(",
"'_contentchange'",
")",
";",
"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
|
train
|
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",
";",
"options",
"=",
"tiny",
".",
"extend",
"(",
"{",
"'method'",
":",
"'GET'",
",",
"'params'",
":",
"''",
",",
"'waiting'",
":",
"'<div class=\"ch-loading-large\"></div>'",
"}",
",",
"defaults",
",",
"options",
")",
";",
"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",
";",
"}",
"}",
"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
|
train
|
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.'",
")",
";",
"}",
"this",
".",
"_options",
"=",
"tiny",
".",
"clone",
"(",
"this",
".",
"_defaults",
")",
";",
"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
|
train
|
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
|
train
|
|
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
|
train
|
|
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",
")",
"{",
"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: '<div class="ch-loading ch-loading-centered"></div>'.
@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
|
train
|
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",
"||",
"''",
";",
"dummyElement",
".",
"innerHTML",
"=",
"'<div class=\"ch-loading-large\"></div><p>'",
"+",
"content",
"+",
"'</p>'",
";",
"return",
"dummyElement",
".",
"firstChild",
";",
"}",
"(",
")",
")",
";",
"if",
"(",
"el",
"===",
"undefined",
")",
"{",
"el",
"=",
"tiny",
".",
"extend",
"(",
"tiny",
".",
"clone",
"(",
"this",
".",
"_defaults",
")",
",",
"options",
")",
";",
"}",
"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: '<div class="ch-loading-large ch-loading-centered"></div>'.
@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
|
train
|
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",
")",
"{",
"var",
"that",
"=",
"this",
";",
"this",
".",
"_init",
"(",
"el",
",",
"options",
")",
";",
"if",
"(",
"this",
".",
"initialize",
"!==",
"undefined",
")",
"{",
"this",
".",
"initialize",
"(",
")",
";",
"}",
"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
|
train
|
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
|
train
|
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
|
train
|
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",
";",
"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
|
train
|
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
|
train
|
|
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
|
train
|
|
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
|
train
|
|
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
|
train
|
|
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
|
train
|
|
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
|
train
|
|
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
|
train
|
|
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
|
train
|
|
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",
"(",
"[",
"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",
")",
"{",
"debug",
"(",
"'prepare infrastructure...'",
")",
";",
"async",
".",
"parallel",
"(",
"[",
"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 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",
")",
";",
"}",
",",
"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",
"(",
"{",
"}",
")",
".",
"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
|
train
|
|
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
|
train
|
|
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
|
train
|
|
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
|
train
|
|
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
|
train
|
|
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
|
train
|
|
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
|
train
|
|
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
|
train
|
|
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",
",",
"}",
")",
"}",
"const",
"result",
"=",
"$",
"(",
"'a'",
")",
"if",
"(",
"result",
".",
"length",
">",
"1",
")",
"{",
"const",
"id",
"=",
"result",
"[",
"0",
"]",
".",
"attribs",
".",
"on_click",
".",
"match",
"(",
"/",
"\\d+",
"/",
")",
"[",
"0",
"]",
"baseUrl",
".",
"query",
"=",
"{",
"id",
"}",
"params",
".",
"url",
"=",
"url",
".",
"format",
"(",
"baseUrl",
")",
"return",
"getDeclensions",
"(",
"callback",
",",
"params",
")",
"}",
"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
|
train
|
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
|
train
|
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
|
train
|
|
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",
")",
"{",
"if",
"(",
"domain",
")",
"{",
"domain",
".",
"exit",
"(",
")",
";",
"}",
"setTimeout",
"(",
"flush",
",",
"0",
")",
";",
"if",
"(",
"domain",
")",
"{",
"domain",
".",
"enter",
"(",
")",
";",
"}",
"throw",
"e",
";",
"}",
"else",
"{",
"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
|
train
|
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\"",
")",
";",
"\\n",
"var",
"firstLine",
"=",
"lines",
"[",
"0",
"]",
".",
"indexOf",
"(",
"\"@\"",
")",
">",
"0",
"?",
"lines",
"[",
"1",
"]",
":",
"lines",
"[",
"2",
"]",
";",
"var",
"fileNameAndLineNumber",
"=",
"getFileNameAndLineNumber",
"(",
"firstLine",
")",
";",
"if",
"(",
"!",
"fileNameAndLineNumber",
")",
"{",
"return",
";",
"}",
"qFileName",
"=",
"fileNameAndLineNumber",
"[",
"0",
"]",
";",
"}",
"}"
] |
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
|
train
|
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",
"(",
"value",
"instanceof",
"Promise",
")",
"{",
"return",
"value",
";",
"}",
"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
|
train
|
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",
";",
"if",
"(",
"typeof",
"StopIteration",
"===",
"\"undefined\"",
")",
"{",
"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",
"{",
"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
|
train
|
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
|
train
|
|
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'",
")",
";",
"\\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",
";",
"}"
] |
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
|
train
|
|
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'",
")",
".",
"\\t",
"replace",
";",
"(",
"/",
"\\n",
"/",
"g",
",",
"'<br>'",
")",
"}"
] |
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
|
train
|
|
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
|
train
|
|
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'",
")",
";",
"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
|
train
|
|
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",
")",
"{",
"model",
"=",
"collection",
".",
"get",
"(",
"id",
")",
";",
"model",
".",
"save",
"(",
"this",
".",
"state",
",",
"{",
"wait",
":",
"true",
"}",
")",
";",
"}",
"else",
"{",
"collection",
".",
"create",
"(",
"this",
".",
"state",
",",
"{",
"wait",
":",
"true",
"}",
")",
";",
"}",
"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
|
train
|
|
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
|
train
|
|
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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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",
")",
";",
"}",
"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
|
train
|
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
|
train
|
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",
"=>",
"{",
"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
|
train
|
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
|
train
|
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",
")",
"{",
"_",
".",
"each",
"(",
"layoutData",
",",
"function",
"(",
"list",
",",
"key",
")",
"{",
"if",
"(",
"_",
".",
"isString",
"(",
"list",
")",
")",
"{",
"if",
"(",
"_",
".",
"isArray",
"(",
"pageData",
"[",
"key",
"]",
")",
")",
"{",
"layoutData",
"[",
"key",
"]",
"=",
"_",
".",
"map",
"(",
"pageData",
"[",
"key",
"]",
",",
"refToObj",
")",
";",
"}",
"else",
"{",
"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
|
train
|
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
|
train
|
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
|
train
|
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",
"(",
")",
";",
"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",
")",
"{",
"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
|
train
|
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",
"(",
")",
"{",
"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
|
train
|
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",
")",
",",
"upgradeFile",
"=",
"files",
".",
"tryRequire",
"(",
"path",
".",
"resolve",
"(",
"dir",
",",
"'upgrade'",
")",
")",
";",
"var",
"transforms",
"=",
"[",
"]",
";",
"log",
"(",
"'debug'",
",",
"`",
"${",
"name",
"}",
"${",
"ref",
"}",
"`",
")",
";",
"if",
"(",
"!",
"upgradeFile",
")",
"{",
"log",
"(",
"'debug'",
",",
"`",
"${",
"name",
"}",
"`",
")",
";",
"return",
"bluebird",
".",
"resolve",
"(",
"data",
")",
";",
"}",
"transforms",
"=",
"aggregateTransforms",
"(",
"schemaVersion",
",",
"dataVersion",
",",
"upgradeFile",
")",
";",
"if",
"(",
"!",
"transforms",
".",
"length",
")",
"{",
"log",
"(",
"'debug'",
",",
"`",
"${",
"name",
"}",
"`",
",",
"{",
"component",
":",
"name",
",",
"currentVersion",
":",
"dataVersion",
",",
"schemaVersion",
"}",
")",
";",
"return",
"bluebird",
".",
"resolve",
"(",
"data",
")",
";",
"}",
"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
|
train
|
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",
"(",
"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
|
train
|
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
|
train
|
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",
"}",
")",
";",
"if",
"(",
"options",
".",
"prefix",
")",
"{",
"options",
".",
"gte",
"=",
"options",
".",
"prefix",
"+",
"'\\x00'",
";",
"\\x00",
"}",
"options",
".",
"lte",
"=",
"options",
".",
"prefix",
"+",
"'\\xff'",
";",
"\\xff",
"let",
"readStream",
",",
"transformOptions",
"=",
"{",
"objectMode",
":",
"options",
".",
"values",
",",
"isArray",
":",
"options",
".",
"isArray",
"}",
";",
"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",
"(",
")",
";",
"}",
"if",
"(",
"options",
".",
"transforms",
")",
"{",
"readStream",
"=",
"_",
".",
"reduce",
"(",
"options",
".",
"transforms",
",",
"function",
"(",
"readStream",
",",
"transform",
")",
"{",
"return",
"readStream",
".",
"pipe",
"(",
"transform",
")",
";",
"}",
",",
"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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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",
")",
"{",
"if",
"(",
"data",
".",
"_dynamic",
")",
"{",
"locals",
".",
"isDynamicPublishUrl",
"=",
"true",
";",
"return",
"data",
";",
"}",
"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
|
train
|
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",
")",
"{",
"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",
")",
")",
";",
"}"
] |
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
|
train
|
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
|
train
|
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
|
train
|
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",
";",
"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
|
train
|
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",
")",
"{",
"log",
"(",
"'error'",
",",
"err",
".",
"message",
",",
"{",
"stack",
":",
"err",
".",
"stack",
"}",
")",
";",
"const",
"message",
"=",
"err",
".",
"message",
"||",
"'Server Error'",
",",
"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
|
train
|
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
|
train
|
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'",
")",
";",
"}",
"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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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",
";",
"}",
")",
"]",
";",
"}",
"}",
";",
"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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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",
"''",
";",
"}",
"else",
"if",
"(",
"_",
".",
"head",
"(",
"urlPath",
")",
"!==",
"'/'",
")",
"{",
"urlPath",
"=",
"'/'",
"+",
"urlPath",
";",
"}",
"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
|
train
|
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
|
train
|
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",
")",
"{",
"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
|
train
|
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",
"(",
"'/'",
")",
",",
"host",
"=",
"split",
".",
"shift",
"(",
")",
",",
"optPath",
"=",
"split",
".",
"shift",
"(",
")",
",",
"path",
"=",
"optPath",
"?",
"`",
"${",
"optPath",
"}",
"`",
":",
"''",
",",
"length",
"=",
"split",
".",
"length",
"+",
"1",
",",
"site",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"length",
";",
"i",
"++",
")",
"{",
"site",
"=",
"getSite",
"(",
"host",
",",
"path",
")",
";",
"if",
"(",
"site",
")",
"{",
"break",
";",
"}",
"else",
"{",
"path",
"+=",
"`",
"${",
"split",
".",
"shift",
"(",
")",
"}",
"`",
";",
"}",
"}",
"return",
"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
|
train
|
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",
"{",
"return",
"{",
"username",
":",
"'robot'",
",",
"provider",
":",
"'clay'",
",",
"imageUrl",
":",
"'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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.