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 |
---|---|---|---|---|---|---|---|---|---|---|---|
clay/amphora
|
lib/services/metadata.js
|
unpublishPage
|
function unpublishPage(uri, user) {
const update = {
published: false,
publishTime: null,
url: '',
history: [{ action: 'unpublish', timestamp: new Date().toISOString(), users: [userOrRobot(user)] }]
};
return changeMetaState(uri, update);
}
|
javascript
|
function unpublishPage(uri, user) {
const update = {
published: false,
publishTime: null,
url: '',
history: [{ action: 'unpublish', timestamp: new Date().toISOString(), users: [userOrRobot(user)] }]
};
return changeMetaState(uri, update);
}
|
[
"function",
"unpublishPage",
"(",
"uri",
",",
"user",
")",
"{",
"const",
"update",
"=",
"{",
"published",
":",
"false",
",",
"publishTime",
":",
"null",
",",
"url",
":",
"''",
",",
"history",
":",
"[",
"{",
"action",
":",
"'unpublish'",
",",
"timestamp",
":",
"new",
"Date",
"(",
")",
".",
"toISOString",
"(",
")",
",",
"users",
":",
"[",
"userOrRobot",
"(",
"user",
")",
"]",
"}",
"]",
"}",
";",
"return",
"changeMetaState",
"(",
"uri",
",",
"update",
")",
";",
"}"
] |
Update the page meta on unpublish
@param {String} uri
@param {Object} user
@returns {Promise}
|
[
"Update",
"the",
"page",
"meta",
"on",
"unpublish"
] |
b883a94cbc38c1891ce568addb6cb280aa1d5353
|
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/services/metadata.js#L125-L134
|
train
|
clay/amphora
|
lib/services/metadata.js
|
changeMetaState
|
function changeMetaState(uri, update) {
return getMeta(uri)
.then(old => mergeNewAndOldMeta(old, update))
.then(updatedMeta => putMeta(uri, updatedMeta));
}
|
javascript
|
function changeMetaState(uri, update) {
return getMeta(uri)
.then(old => mergeNewAndOldMeta(old, update))
.then(updatedMeta => putMeta(uri, updatedMeta));
}
|
[
"function",
"changeMetaState",
"(",
"uri",
",",
"update",
")",
"{",
"return",
"getMeta",
"(",
"uri",
")",
".",
"then",
"(",
"old",
"=>",
"mergeNewAndOldMeta",
"(",
"old",
",",
"update",
")",
")",
".",
"then",
"(",
"updatedMeta",
"=>",
"putMeta",
"(",
"uri",
",",
"updatedMeta",
")",
")",
";",
"}"
] |
Given a uri and an object that is an
update, retreive the old meta, merge
the new and old and then put the merge
to the db.
@param {String} uri
@param {Object} update
@returns {Promise}
|
[
"Given",
"a",
"uri",
"and",
"an",
"object",
"that",
"is",
"an",
"update",
"retreive",
"the",
"old",
"meta",
"merge",
"the",
"new",
"and",
"old",
"and",
"then",
"put",
"the",
"merge",
"to",
"the",
"db",
"."
] |
b883a94cbc38c1891ce568addb6cb280aa1d5353
|
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/services/metadata.js#L160-L164
|
train
|
clay/amphora
|
lib/services/metadata.js
|
putMeta
|
function putMeta(uri, data) {
const id = replaceVersion(uri.replace('/meta', ''));
return db.putMeta(id, data)
.then(pubToBus(id));
}
|
javascript
|
function putMeta(uri, data) {
const id = replaceVersion(uri.replace('/meta', ''));
return db.putMeta(id, data)
.then(pubToBus(id));
}
|
[
"function",
"putMeta",
"(",
"uri",
",",
"data",
")",
"{",
"const",
"id",
"=",
"replaceVersion",
"(",
"uri",
".",
"replace",
"(",
"'/meta'",
",",
"''",
")",
")",
";",
"return",
"db",
".",
"putMeta",
"(",
"id",
",",
"data",
")",
".",
"then",
"(",
"pubToBus",
"(",
"id",
")",
")",
";",
"}"
] |
Write the page's meta object to the DB
@param {String} uri
@param {Object} data
@returns {Promise}
|
[
"Write",
"the",
"page",
"s",
"meta",
"object",
"to",
"the",
"DB"
] |
b883a94cbc38c1891ce568addb6cb280aa1d5353
|
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/services/metadata.js#L214-L219
|
train
|
clay/amphora
|
lib/services/metadata.js
|
patchMeta
|
function patchMeta(uri, data) {
const id = replaceVersion(uri.replace('/meta', ''));
return db.patchMeta(id, data)
.then(() => getMeta(uri))
.then(pubToBus(id));
}
|
javascript
|
function patchMeta(uri, data) {
const id = replaceVersion(uri.replace('/meta', ''));
return db.patchMeta(id, data)
.then(() => getMeta(uri))
.then(pubToBus(id));
}
|
[
"function",
"patchMeta",
"(",
"uri",
",",
"data",
")",
"{",
"const",
"id",
"=",
"replaceVersion",
"(",
"uri",
".",
"replace",
"(",
"'/meta'",
",",
"''",
")",
")",
";",
"return",
"db",
".",
"patchMeta",
"(",
"id",
",",
"data",
")",
".",
"then",
"(",
"(",
")",
"=>",
"getMeta",
"(",
"uri",
")",
")",
".",
"then",
"(",
"pubToBus",
"(",
"id",
")",
")",
";",
"}"
] |
Update a subset of properties on
a metadata object
@param {String} uri
@param {Object} data
@returns {Promise}
|
[
"Update",
"a",
"subset",
"of",
"properties",
"on",
"a",
"metadata",
"object"
] |
b883a94cbc38c1891ce568addb6cb280aa1d5353
|
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/services/metadata.js#L229-L235
|
train
|
clay/amphora
|
lib/services/metadata.js
|
checkProps
|
function checkProps(uri, props) {
const id = replaceVersion(uri.replace('/meta', ''));
return db.getMeta(id)
.then(meta => {
return Array.isArray(props)
? props.every(prop => meta[prop])
: meta[props] && true;
})
.catch(err => {
throw new Error(err);
});
}
|
javascript
|
function checkProps(uri, props) {
const id = replaceVersion(uri.replace('/meta', ''));
return db.getMeta(id)
.then(meta => {
return Array.isArray(props)
? props.every(prop => meta[prop])
: meta[props] && true;
})
.catch(err => {
throw new Error(err);
});
}
|
[
"function",
"checkProps",
"(",
"uri",
",",
"props",
")",
"{",
"const",
"id",
"=",
"replaceVersion",
"(",
"uri",
".",
"replace",
"(",
"'/meta'",
",",
"''",
")",
")",
";",
"return",
"db",
".",
"getMeta",
"(",
"id",
")",
".",
"then",
"(",
"meta",
"=>",
"{",
"return",
"Array",
".",
"isArray",
"(",
"props",
")",
"?",
"props",
".",
"every",
"(",
"prop",
"=>",
"meta",
"[",
"prop",
"]",
")",
":",
"meta",
"[",
"props",
"]",
"&&",
"true",
";",
"}",
")",
".",
"catch",
"(",
"err",
"=>",
"{",
"throw",
"new",
"Error",
"(",
"err",
")",
";",
"}",
")",
";",
"}"
] |
Check metadata property or properties for truthy values.
Returns true if all properties have truthy values.
@param {String} uri
@param {String | Array} props
@returns {Boolean | Object}
|
[
"Check",
"metadata",
"property",
"or",
"properties",
"for",
"truthy",
"values",
".",
"Returns",
"true",
"if",
"all",
"properties",
"have",
"truthy",
"values",
"."
] |
b883a94cbc38c1891ce568addb6cb280aa1d5353
|
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/services/metadata.js#L244-L256
|
train
|
clay/amphora
|
lib/services/models.js
|
put
|
function put(model, uri, data, locals) {
const startTime = process.hrtime(),
timeoutLimit = TIMEOUT_CONSTANT * TIMEOUT_PUT_COEFFICIENT;
return bluebird.try(() => {
return bluebird.resolve(model.save(uri, data, locals))
.then(resolvedData => {
if (!_.isObject(resolvedData)) {
throw new Error(`Unable to save ${uri}: Data from model.save must be an object!`);
}
return {
key: uri,
type: 'put',
value: JSON.stringify(resolvedData)
};
});
}).tap(() => {
const ms = timer.getMillisecondsSince(startTime);
if (ms > timeoutLimit * 0.5) {
log('warn', `slow put ${uri} ${ms}ms`);
}
}).timeout(timeoutLimit, `Module PUT exceeded ${timeoutLimit}ms: ${uri}`);
}
|
javascript
|
function put(model, uri, data, locals) {
const startTime = process.hrtime(),
timeoutLimit = TIMEOUT_CONSTANT * TIMEOUT_PUT_COEFFICIENT;
return bluebird.try(() => {
return bluebird.resolve(model.save(uri, data, locals))
.then(resolvedData => {
if (!_.isObject(resolvedData)) {
throw new Error(`Unable to save ${uri}: Data from model.save must be an object!`);
}
return {
key: uri,
type: 'put',
value: JSON.stringify(resolvedData)
};
});
}).tap(() => {
const ms = timer.getMillisecondsSince(startTime);
if (ms > timeoutLimit * 0.5) {
log('warn', `slow put ${uri} ${ms}ms`);
}
}).timeout(timeoutLimit, `Module PUT exceeded ${timeoutLimit}ms: ${uri}`);
}
|
[
"function",
"put",
"(",
"model",
",",
"uri",
",",
"data",
",",
"locals",
")",
"{",
"const",
"startTime",
"=",
"process",
".",
"hrtime",
"(",
")",
",",
"timeoutLimit",
"=",
"TIMEOUT_CONSTANT",
"*",
"TIMEOUT_PUT_COEFFICIENT",
";",
"return",
"bluebird",
".",
"try",
"(",
"(",
")",
"=>",
"{",
"return",
"bluebird",
".",
"resolve",
"(",
"model",
".",
"save",
"(",
"uri",
",",
"data",
",",
"locals",
")",
")",
".",
"then",
"(",
"resolvedData",
"=>",
"{",
"if",
"(",
"!",
"_",
".",
"isObject",
"(",
"resolvedData",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"`",
"${",
"uri",
"}",
"`",
")",
";",
"}",
"return",
"{",
"key",
":",
"uri",
",",
"type",
":",
"'put'",
",",
"value",
":",
"JSON",
".",
"stringify",
"(",
"resolvedData",
")",
"}",
";",
"}",
")",
";",
"}",
")",
".",
"tap",
"(",
"(",
")",
"=>",
"{",
"const",
"ms",
"=",
"timer",
".",
"getMillisecondsSince",
"(",
"startTime",
")",
";",
"if",
"(",
"ms",
">",
"timeoutLimit",
"*",
"0.5",
")",
"{",
"log",
"(",
"'warn'",
",",
"`",
"${",
"uri",
"}",
"${",
"ms",
"}",
"`",
")",
";",
"}",
"}",
")",
".",
"timeout",
"(",
"timeoutLimit",
",",
"`",
"${",
"timeoutLimit",
"}",
"${",
"uri",
"}",
"`",
")",
";",
"}"
] |
Execute the save function of a model.js file
for either a component or a layout
@param {Object} model
@param {String} uri
@param {Object} data
@param {Object} locals
@returns {Object}
|
[
"Execute",
"the",
"save",
"function",
"of",
"a",
"model",
".",
"js",
"file",
"for",
"either",
"a",
"component",
"or",
"a",
"layout"
] |
b883a94cbc38c1891ce568addb6cb280aa1d5353
|
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/services/models.js#L23-L47
|
train
|
clay/amphora
|
lib/services/models.js
|
get
|
function get(model, renderModel, executeRender, uri, locals) { /* eslint max-params: ["error", 5] */
var promise;
if (executeRender) {
const startTime = process.hrtime(),
timeoutLimit = TIMEOUT_CONSTANT * TIMEOUT_GET_COEFFICIENT;
promise = bluebird.try(() => {
return db.get(uri)
.then(upgrade.init(uri, locals)) // Run an upgrade!
.then(data => model.render(uri, data, locals));
}).tap(result => {
const ms = timer.getMillisecondsSince(startTime);
if (!_.isObject(result)) {
throw new Error(`Component model must return object, not ${typeof result}: ${uri}`);
}
if (ms > timeoutLimit * 0.5) {
log('warn', `slow get ${uri} ${ms}ms`);
}
}).timeout(timeoutLimit, `Model GET exceeded ${timeoutLimit}ms: ${uri}`);
} else {
promise = db.get(uri).then(upgrade.init(uri, locals)); // Run an upgrade!
}
if (renderModel && _.isFunction(renderModel)) {
promise = promise.then(data => renderModel(uri, data, locals));
}
return promise.then(data => {
if (!_.isObject(data)) {
throw new Error(`Client: Invalid data type for component at ${uri} of ${typeof data}`);
}
return data;
});
}
|
javascript
|
function get(model, renderModel, executeRender, uri, locals) { /* eslint max-params: ["error", 5] */
var promise;
if (executeRender) {
const startTime = process.hrtime(),
timeoutLimit = TIMEOUT_CONSTANT * TIMEOUT_GET_COEFFICIENT;
promise = bluebird.try(() => {
return db.get(uri)
.then(upgrade.init(uri, locals)) // Run an upgrade!
.then(data => model.render(uri, data, locals));
}).tap(result => {
const ms = timer.getMillisecondsSince(startTime);
if (!_.isObject(result)) {
throw new Error(`Component model must return object, not ${typeof result}: ${uri}`);
}
if (ms > timeoutLimit * 0.5) {
log('warn', `slow get ${uri} ${ms}ms`);
}
}).timeout(timeoutLimit, `Model GET exceeded ${timeoutLimit}ms: ${uri}`);
} else {
promise = db.get(uri).then(upgrade.init(uri, locals)); // Run an upgrade!
}
if (renderModel && _.isFunction(renderModel)) {
promise = promise.then(data => renderModel(uri, data, locals));
}
return promise.then(data => {
if (!_.isObject(data)) {
throw new Error(`Client: Invalid data type for component at ${uri} of ${typeof data}`);
}
return data;
});
}
|
[
"function",
"get",
"(",
"model",
",",
"renderModel",
",",
"executeRender",
",",
"uri",
",",
"locals",
")",
"{",
"var",
"promise",
";",
"if",
"(",
"executeRender",
")",
"{",
"const",
"startTime",
"=",
"process",
".",
"hrtime",
"(",
")",
",",
"timeoutLimit",
"=",
"TIMEOUT_CONSTANT",
"*",
"TIMEOUT_GET_COEFFICIENT",
";",
"promise",
"=",
"bluebird",
".",
"try",
"(",
"(",
")",
"=>",
"{",
"return",
"db",
".",
"get",
"(",
"uri",
")",
".",
"then",
"(",
"upgrade",
".",
"init",
"(",
"uri",
",",
"locals",
")",
")",
".",
"then",
"(",
"data",
"=>",
"model",
".",
"render",
"(",
"uri",
",",
"data",
",",
"locals",
")",
")",
";",
"}",
")",
".",
"tap",
"(",
"result",
"=>",
"{",
"const",
"ms",
"=",
"timer",
".",
"getMillisecondsSince",
"(",
"startTime",
")",
";",
"if",
"(",
"!",
"_",
".",
"isObject",
"(",
"result",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"`",
"${",
"typeof",
"result",
"}",
"${",
"uri",
"}",
"`",
")",
";",
"}",
"if",
"(",
"ms",
">",
"timeoutLimit",
"*",
"0.5",
")",
"{",
"log",
"(",
"'warn'",
",",
"`",
"${",
"uri",
"}",
"${",
"ms",
"}",
"`",
")",
";",
"}",
"}",
")",
".",
"timeout",
"(",
"timeoutLimit",
",",
"`",
"${",
"timeoutLimit",
"}",
"${",
"uri",
"}",
"`",
")",
";",
"}",
"else",
"{",
"promise",
"=",
"db",
".",
"get",
"(",
"uri",
")",
".",
"then",
"(",
"upgrade",
".",
"init",
"(",
"uri",
",",
"locals",
")",
")",
";",
"}",
"if",
"(",
"renderModel",
"&&",
"_",
".",
"isFunction",
"(",
"renderModel",
")",
")",
"{",
"promise",
"=",
"promise",
".",
"then",
"(",
"data",
"=>",
"renderModel",
"(",
"uri",
",",
"data",
",",
"locals",
")",
")",
";",
"}",
"return",
"promise",
".",
"then",
"(",
"data",
"=>",
"{",
"if",
"(",
"!",
"_",
".",
"isObject",
"(",
"data",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"`",
"${",
"uri",
"}",
"${",
"typeof",
"data",
"}",
"`",
")",
";",
"}",
"return",
"data",
";",
"}",
")",
";",
"}"
] |
Execute the get function of a model.js file
for either a component or a layout
@param {Object} model
@param {Object} renderModel
@param {Boolean} executeRender
@param {String} uri
@param {Object} locals
@returns {Promise}
|
[
"Execute",
"the",
"get",
"function",
"of",
"a",
"model",
".",
"js",
"file",
"for",
"either",
"a",
"component",
"or",
"a",
"layout"
] |
b883a94cbc38c1891ce568addb6cb280aa1d5353
|
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/services/models.js#L60-L98
|
train
|
clay/amphora
|
lib/services/pages.js
|
renameReferenceUniquely
|
function renameReferenceUniquely(uri) {
const prefix = uri.substr(0, uri.indexOf('/_components/'));
return `${prefix}/_components/${getComponentName(uri)}/instances/${uid.get()}`;
}
|
javascript
|
function renameReferenceUniquely(uri) {
const prefix = uri.substr(0, uri.indexOf('/_components/'));
return `${prefix}/_components/${getComponentName(uri)}/instances/${uid.get()}`;
}
|
[
"function",
"renameReferenceUniquely",
"(",
"uri",
")",
"{",
"const",
"prefix",
"=",
"uri",
".",
"substr",
"(",
"0",
",",
"uri",
".",
"indexOf",
"(",
"'/_components/'",
")",
")",
";",
"return",
"`",
"${",
"prefix",
"}",
"${",
"getComponentName",
"(",
"uri",
")",
"}",
"${",
"uid",
".",
"get",
"(",
")",
"}",
"`",
";",
"}"
] |
Get a reference that is unique, but of the same component type as original.
@param {string} uri
@returns {string}
|
[
"Get",
"a",
"reference",
"that",
"is",
"unique",
"but",
"of",
"the",
"same",
"component",
"type",
"as",
"original",
"."
] |
b883a94cbc38c1891ce568addb6cb280aa1d5353
|
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/services/pages.js#L56-L60
|
train
|
clay/amphora
|
lib/services/pages.js
|
getPageClonePutOperations
|
function getPageClonePutOperations(pageData, locals) {
return bluebird.all(_.reduce(pageData, (promises, pageValue, pageKey) => {
if (typeof pageValue === 'string' && getComponentName(pageValue)) {
// for all strings that are component references
promises.push(components.get(pageValue, locals)
// only follow the paths of instance references. Don't clone default components
.then(refData => composer.resolveComponentReferences(refData, locals, isInstanceReferenceObject))
.then(resolvedData => {
// for each instance reference within resolved data
_.each(references.listDeepObjects(resolvedData, isInstanceReferenceObject), obj => {
obj._ref = renameReferenceUniquely(obj._ref);
});
// rename reference in pageData
const ref = renameReferenceUniquely(pageValue);
pageData[pageKey] = ref;
// put new data using cascading PUT at place that page now points
return dbOps.getPutOperations(components.cmptPut, ref, resolvedData, locals);
}));
} else {
// for all object-like things (i.e., objects and arrays)
promises = promises.concat(getPageClonePutOperations(pageValue, locals));
}
return promises;
}, [])).then(_.flatten); // only one level of flattening needed
}
|
javascript
|
function getPageClonePutOperations(pageData, locals) {
return bluebird.all(_.reduce(pageData, (promises, pageValue, pageKey) => {
if (typeof pageValue === 'string' && getComponentName(pageValue)) {
// for all strings that are component references
promises.push(components.get(pageValue, locals)
// only follow the paths of instance references. Don't clone default components
.then(refData => composer.resolveComponentReferences(refData, locals, isInstanceReferenceObject))
.then(resolvedData => {
// for each instance reference within resolved data
_.each(references.listDeepObjects(resolvedData, isInstanceReferenceObject), obj => {
obj._ref = renameReferenceUniquely(obj._ref);
});
// rename reference in pageData
const ref = renameReferenceUniquely(pageValue);
pageData[pageKey] = ref;
// put new data using cascading PUT at place that page now points
return dbOps.getPutOperations(components.cmptPut, ref, resolvedData, locals);
}));
} else {
// for all object-like things (i.e., objects and arrays)
promises = promises.concat(getPageClonePutOperations(pageValue, locals));
}
return promises;
}, [])).then(_.flatten); // only one level of flattening needed
}
|
[
"function",
"getPageClonePutOperations",
"(",
"pageData",
",",
"locals",
")",
"{",
"return",
"bluebird",
".",
"all",
"(",
"_",
".",
"reduce",
"(",
"pageData",
",",
"(",
"promises",
",",
"pageValue",
",",
"pageKey",
")",
"=>",
"{",
"if",
"(",
"typeof",
"pageValue",
"===",
"'string'",
"&&",
"getComponentName",
"(",
"pageValue",
")",
")",
"{",
"promises",
".",
"push",
"(",
"components",
".",
"get",
"(",
"pageValue",
",",
"locals",
")",
".",
"then",
"(",
"refData",
"=>",
"composer",
".",
"resolveComponentReferences",
"(",
"refData",
",",
"locals",
",",
"isInstanceReferenceObject",
")",
")",
".",
"then",
"(",
"resolvedData",
"=>",
"{",
"_",
".",
"each",
"(",
"references",
".",
"listDeepObjects",
"(",
"resolvedData",
",",
"isInstanceReferenceObject",
")",
",",
"obj",
"=>",
"{",
"obj",
".",
"_ref",
"=",
"renameReferenceUniquely",
"(",
"obj",
".",
"_ref",
")",
";",
"}",
")",
";",
"const",
"ref",
"=",
"renameReferenceUniquely",
"(",
"pageValue",
")",
";",
"pageData",
"[",
"pageKey",
"]",
"=",
"ref",
";",
"return",
"dbOps",
".",
"getPutOperations",
"(",
"components",
".",
"cmptPut",
",",
"ref",
",",
"resolvedData",
",",
"locals",
")",
";",
"}",
")",
")",
";",
"}",
"else",
"{",
"promises",
"=",
"promises",
".",
"concat",
"(",
"getPageClonePutOperations",
"(",
"pageValue",
",",
"locals",
")",
")",
";",
"}",
"return",
"promises",
";",
"}",
",",
"[",
"]",
")",
")",
".",
"then",
"(",
"_",
".",
"flatten",
")",
";",
"}"
] |
Clone all instance components that are referenced by this page data, and maintain the data's object structure.
@param {object} pageData
@param {object} locals
@returns {Promise}
|
[
"Clone",
"all",
"instance",
"components",
"that",
"are",
"referenced",
"by",
"this",
"page",
"data",
"and",
"maintain",
"the",
"data",
"s",
"object",
"structure",
"."
] |
b883a94cbc38c1891ce568addb6cb280aa1d5353
|
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/services/pages.js#L69-L96
|
train
|
clay/amphora
|
lib/services/pages.js
|
replacePageReferenceVersions
|
function replacePageReferenceVersions(data, version) {
const replace = _.partial(replaceVersion, _, version);
return _.mapValues(data, function (value, key) {
let result;
if (references.isUri(value)) {
result = replace(value);
} else if (_.isArray(value) && key !== 'urlHistory') {
// urlHistory is an array of old page urls. they're not component refs and shouldn't be versioned
result = _.map(value, replace);
} else {
result = value;
}
return result;
});
}
|
javascript
|
function replacePageReferenceVersions(data, version) {
const replace = _.partial(replaceVersion, _, version);
return _.mapValues(data, function (value, key) {
let result;
if (references.isUri(value)) {
result = replace(value);
} else if (_.isArray(value) && key !== 'urlHistory') {
// urlHistory is an array of old page urls. they're not component refs and shouldn't be versioned
result = _.map(value, replace);
} else {
result = value;
}
return result;
});
}
|
[
"function",
"replacePageReferenceVersions",
"(",
"data",
",",
"version",
")",
"{",
"const",
"replace",
"=",
"_",
".",
"partial",
"(",
"replaceVersion",
",",
"_",
",",
"version",
")",
";",
"return",
"_",
".",
"mapValues",
"(",
"data",
",",
"function",
"(",
"value",
",",
"key",
")",
"{",
"let",
"result",
";",
"if",
"(",
"references",
".",
"isUri",
"(",
"value",
")",
")",
"{",
"result",
"=",
"replace",
"(",
"value",
")",
";",
"}",
"else",
"if",
"(",
"_",
".",
"isArray",
"(",
"value",
")",
"&&",
"key",
"!==",
"'urlHistory'",
")",
"{",
"result",
"=",
"_",
".",
"map",
"(",
"value",
",",
"replace",
")",
";",
"}",
"else",
"{",
"result",
"=",
"value",
";",
"}",
"return",
"result",
";",
"}",
")",
";",
"}"
] |
Replace the referenced things in the page data with a different version
@param {object} data
@param {string} version
@returns {object}
|
[
"Replace",
"the",
"referenced",
"things",
"in",
"the",
"page",
"data",
"with",
"a",
"different",
"version"
] |
b883a94cbc38c1891ce568addb6cb280aa1d5353
|
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/services/pages.js#L120-L136
|
train
|
clay/amphora
|
lib/services/pages.js
|
getRecursivePublishedPutOperations
|
function getRecursivePublishedPutOperations(locals) {
return rootComponentRef => {
/**
* 1) Get reference (could be latest, could be other)
* 2) Get all references within reference
* 3) Replace all references with @published (including root reference)
* 4) Get list of put operations needed
*/
return components.get(rootComponentRef, locals)
.then(data => composer.resolveComponentReferences(data, locals))
.then(data => dbOps.getPutOperations(components.cmptPut, replaceVersion(rootComponentRef, 'published'), data, locals));
};
}
|
javascript
|
function getRecursivePublishedPutOperations(locals) {
return rootComponentRef => {
/**
* 1) Get reference (could be latest, could be other)
* 2) Get all references within reference
* 3) Replace all references with @published (including root reference)
* 4) Get list of put operations needed
*/
return components.get(rootComponentRef, locals)
.then(data => composer.resolveComponentReferences(data, locals))
.then(data => dbOps.getPutOperations(components.cmptPut, replaceVersion(rootComponentRef, 'published'), data, locals));
};
}
|
[
"function",
"getRecursivePublishedPutOperations",
"(",
"locals",
")",
"{",
"return",
"rootComponentRef",
"=>",
"{",
"return",
"components",
".",
"get",
"(",
"rootComponentRef",
",",
"locals",
")",
".",
"then",
"(",
"data",
"=>",
"composer",
".",
"resolveComponentReferences",
"(",
"data",
",",
"locals",
")",
")",
".",
"then",
"(",
"data",
"=>",
"dbOps",
".",
"getPutOperations",
"(",
"components",
".",
"cmptPut",
",",
"replaceVersion",
"(",
"rootComponentRef",
",",
"'published'",
")",
",",
"data",
",",
"locals",
")",
")",
";",
"}",
";",
"}"
] |
Get a list of all operations with all references converted to @published
@param {object} locals
@returns {function}
|
[
"Get",
"a",
"list",
"of",
"all",
"operations",
"with",
"all",
"references",
"converted",
"to"
] |
b883a94cbc38c1891ce568addb6cb280aa1d5353
|
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/services/pages.js#L143-L155
|
train
|
clay/amphora
|
lib/services/pages.js
|
getSite
|
function getSite(prefix, locals) {
const site = locals && locals.site;
return site || siteService.getSiteFromPrefix(prefix);
}
|
javascript
|
function getSite(prefix, locals) {
const site = locals && locals.site;
return site || siteService.getSiteFromPrefix(prefix);
}
|
[
"function",
"getSite",
"(",
"prefix",
",",
"locals",
")",
"{",
"const",
"site",
"=",
"locals",
"&&",
"locals",
".",
"site",
";",
"return",
"site",
"||",
"siteService",
".",
"getSiteFromPrefix",
"(",
"prefix",
")",
";",
"}"
] |
Given either locals or a string,
return the site we're working with
@param {String} prefix
@param {Object} locals
@returns {Object}
|
[
"Given",
"either",
"locals",
"or",
"a",
"string",
"return",
"the",
"site",
"we",
"re",
"working",
"with"
] |
b883a94cbc38c1891ce568addb6cb280aa1d5353
|
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/services/pages.js#L165-L169
|
train
|
clay/amphora
|
lib/services/pages.js
|
publish
|
function publish(uri, data, locals) {
const startTime = process.hrtime(),
prefix = getPrefix(uri),
site = getSite(prefix, locals),
timeoutLimit = timeoutConstant * timeoutPublishCoefficient,
user = locals && locals.user;
var publishedMeta; // We need to store some meta a little later
return getPublishData(uri, data)
.then(publishService.resolvePublishUrl(uri, locals, site))
.then(({ meta, data: pageData}) => {
const published = 'published',
dynamicPage = pageData._dynamic,
componentList = references.getPageReferences(pageData);
if (!references.isUrl(meta.url) && !dynamicPage) {
throw new Error('Client: Page must have valid url to publish.');
}
return bluebird.map(componentList, getRecursivePublishedPutOperations(locals))
.then(_.flatten) // only one level of flattening needed, because getPutOperations should have flattened its list already
.then(ops => {
// convert the data to all @published
pageData = replacePageReferenceVersions(pageData, published);
// Make public unless we're dealing with a `_dynamic` page
if (!dynamicPage) {
addOpToMakePublic(ops, prefix, meta.url, uri);
}
// Store the metadata if we're at this point
publishedMeta = meta;
// add page PUT operation last
return addOp(replaceVersion(uri, published), pageData, ops);
});
})
.then(applyBatch)
.tap(() => {
const ms = timer.getMillisecondsSince(startTime);
if (ms > timeoutLimit * 0.5) {
log('warn', `slow publish ${uri} ${ms}ms`);
} else {
log('info', `published ${replaceVersion(uri)} ${ms}ms`);
}
})
.timeout(timeoutLimit, `Page publish exceeded ${timeoutLimit}ms: ${uri}`)
.then(publishedData => {
return meta.publishPage(uri, publishedMeta, user).then(() => {
// Notify the bus
bus.publish('publishPage', { uri, data: publishedData, user});
notifications.notify(site, 'published', publishedData);
// Update the meta object
return publishedData;
});
});
}
|
javascript
|
function publish(uri, data, locals) {
const startTime = process.hrtime(),
prefix = getPrefix(uri),
site = getSite(prefix, locals),
timeoutLimit = timeoutConstant * timeoutPublishCoefficient,
user = locals && locals.user;
var publishedMeta; // We need to store some meta a little later
return getPublishData(uri, data)
.then(publishService.resolvePublishUrl(uri, locals, site))
.then(({ meta, data: pageData}) => {
const published = 'published',
dynamicPage = pageData._dynamic,
componentList = references.getPageReferences(pageData);
if (!references.isUrl(meta.url) && !dynamicPage) {
throw new Error('Client: Page must have valid url to publish.');
}
return bluebird.map(componentList, getRecursivePublishedPutOperations(locals))
.then(_.flatten) // only one level of flattening needed, because getPutOperations should have flattened its list already
.then(ops => {
// convert the data to all @published
pageData = replacePageReferenceVersions(pageData, published);
// Make public unless we're dealing with a `_dynamic` page
if (!dynamicPage) {
addOpToMakePublic(ops, prefix, meta.url, uri);
}
// Store the metadata if we're at this point
publishedMeta = meta;
// add page PUT operation last
return addOp(replaceVersion(uri, published), pageData, ops);
});
})
.then(applyBatch)
.tap(() => {
const ms = timer.getMillisecondsSince(startTime);
if (ms > timeoutLimit * 0.5) {
log('warn', `slow publish ${uri} ${ms}ms`);
} else {
log('info', `published ${replaceVersion(uri)} ${ms}ms`);
}
})
.timeout(timeoutLimit, `Page publish exceeded ${timeoutLimit}ms: ${uri}`)
.then(publishedData => {
return meta.publishPage(uri, publishedMeta, user).then(() => {
// Notify the bus
bus.publish('publishPage', { uri, data: publishedData, user});
notifications.notify(site, 'published', publishedData);
// Update the meta object
return publishedData;
});
});
}
|
[
"function",
"publish",
"(",
"uri",
",",
"data",
",",
"locals",
")",
"{",
"const",
"startTime",
"=",
"process",
".",
"hrtime",
"(",
")",
",",
"prefix",
"=",
"getPrefix",
"(",
"uri",
")",
",",
"site",
"=",
"getSite",
"(",
"prefix",
",",
"locals",
")",
",",
"timeoutLimit",
"=",
"timeoutConstant",
"*",
"timeoutPublishCoefficient",
",",
"user",
"=",
"locals",
"&&",
"locals",
".",
"user",
";",
"var",
"publishedMeta",
";",
"return",
"getPublishData",
"(",
"uri",
",",
"data",
")",
".",
"then",
"(",
"publishService",
".",
"resolvePublishUrl",
"(",
"uri",
",",
"locals",
",",
"site",
")",
")",
".",
"then",
"(",
"(",
"{",
"meta",
",",
"data",
":",
"pageData",
"}",
")",
"=>",
"{",
"const",
"published",
"=",
"'published'",
",",
"dynamicPage",
"=",
"pageData",
".",
"_dynamic",
",",
"componentList",
"=",
"references",
".",
"getPageReferences",
"(",
"pageData",
")",
";",
"if",
"(",
"!",
"references",
".",
"isUrl",
"(",
"meta",
".",
"url",
")",
"&&",
"!",
"dynamicPage",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Client: Page must have valid url to publish.'",
")",
";",
"}",
"return",
"bluebird",
".",
"map",
"(",
"componentList",
",",
"getRecursivePublishedPutOperations",
"(",
"locals",
")",
")",
".",
"then",
"(",
"_",
".",
"flatten",
")",
".",
"then",
"(",
"ops",
"=>",
"{",
"pageData",
"=",
"replacePageReferenceVersions",
"(",
"pageData",
",",
"published",
")",
";",
"if",
"(",
"!",
"dynamicPage",
")",
"{",
"addOpToMakePublic",
"(",
"ops",
",",
"prefix",
",",
"meta",
".",
"url",
",",
"uri",
")",
";",
"}",
"publishedMeta",
"=",
"meta",
";",
"return",
"addOp",
"(",
"replaceVersion",
"(",
"uri",
",",
"published",
")",
",",
"pageData",
",",
"ops",
")",
";",
"}",
")",
";",
"}",
")",
".",
"then",
"(",
"applyBatch",
")",
".",
"tap",
"(",
"(",
")",
"=>",
"{",
"const",
"ms",
"=",
"timer",
".",
"getMillisecondsSince",
"(",
"startTime",
")",
";",
"if",
"(",
"ms",
">",
"timeoutLimit",
"*",
"0.5",
")",
"{",
"log",
"(",
"'warn'",
",",
"`",
"${",
"uri",
"}",
"${",
"ms",
"}",
"`",
")",
";",
"}",
"else",
"{",
"log",
"(",
"'info'",
",",
"`",
"${",
"replaceVersion",
"(",
"uri",
")",
"}",
"${",
"ms",
"}",
"`",
")",
";",
"}",
"}",
")",
".",
"timeout",
"(",
"timeoutLimit",
",",
"`",
"${",
"timeoutLimit",
"}",
"${",
"uri",
"}",
"`",
")",
".",
"then",
"(",
"publishedData",
"=>",
"{",
"return",
"meta",
".",
"publishPage",
"(",
"uri",
",",
"publishedMeta",
",",
"user",
")",
".",
"then",
"(",
"(",
")",
"=>",
"{",
"bus",
".",
"publish",
"(",
"'publishPage'",
",",
"{",
"uri",
",",
"data",
":",
"publishedData",
",",
"user",
"}",
")",
";",
"notifications",
".",
"notify",
"(",
"site",
",",
"'published'",
",",
"publishedData",
")",
";",
"return",
"publishedData",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] |
Publish a uri
@param {string} uri
@param {object} [data]
@param {object} [locals]
@returns {Promise}
|
[
"Publish",
"a",
"uri"
] |
b883a94cbc38c1891ce568addb6cb280aa1d5353
|
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/services/pages.js#L226-L284
|
train
|
clay/amphora
|
lib/services/plugins.js
|
initPlugins
|
function initPlugins(router, site) {
return bluebird.all(module.exports.plugins.map(plugin => {
return bluebird.try(() => {
if (typeof plugin === 'function') {
return plugin(router, pluginDBAdapter, publish, sites, site);
} else {
log('warn', 'Plugin is not a function');
return bluebird.resolve();
}
});
}));
}
|
javascript
|
function initPlugins(router, site) {
return bluebird.all(module.exports.plugins.map(plugin => {
return bluebird.try(() => {
if (typeof plugin === 'function') {
return plugin(router, pluginDBAdapter, publish, sites, site);
} else {
log('warn', 'Plugin is not a function');
return bluebird.resolve();
}
});
}));
}
|
[
"function",
"initPlugins",
"(",
"router",
",",
"site",
")",
"{",
"return",
"bluebird",
".",
"all",
"(",
"module",
".",
"exports",
".",
"plugins",
".",
"map",
"(",
"plugin",
"=>",
"{",
"return",
"bluebird",
".",
"try",
"(",
"(",
")",
"=>",
"{",
"if",
"(",
"typeof",
"plugin",
"===",
"'function'",
")",
"{",
"return",
"plugin",
"(",
"router",
",",
"pluginDBAdapter",
",",
"publish",
",",
"sites",
",",
"site",
")",
";",
"}",
"else",
"{",
"log",
"(",
"'warn'",
",",
"'Plugin is not a function'",
")",
";",
"return",
"bluebird",
".",
"resolve",
"(",
")",
";",
"}",
"}",
")",
";",
"}",
")",
")",
";",
"}"
] |
Call each plugin and pass along the router,
a subset of the db service the publish method
of the bus service.
@param {Object} router
@param {Object} site
@returns {Promise}
|
[
"Call",
"each",
"plugin",
"and",
"pass",
"along",
"the",
"router",
"a",
"subset",
"of",
"the",
"db",
"service",
"the",
"publish",
"method",
"of",
"the",
"bus",
"service",
"."
] |
b883a94cbc38c1891ce568addb6cb280aa1d5353
|
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/services/plugins.js#L23-L34
|
train
|
clay/amphora
|
lib/services/plugins.js
|
createDBAdapter
|
function createDBAdapter() {
var returnObj = {
getMeta,
patchMeta
};
for (const key in db) {
/* istanbul ignore else */
if (db.hasOwnProperty(key) && key.indexOf('Meta') === -1) {
returnObj[key] = db[key];
}
}
return returnObj;
}
|
javascript
|
function createDBAdapter() {
var returnObj = {
getMeta,
patchMeta
};
for (const key in db) {
/* istanbul ignore else */
if (db.hasOwnProperty(key) && key.indexOf('Meta') === -1) {
returnObj[key] = db[key];
}
}
return returnObj;
}
|
[
"function",
"createDBAdapter",
"(",
")",
"{",
"var",
"returnObj",
"=",
"{",
"getMeta",
",",
"patchMeta",
"}",
";",
"for",
"(",
"const",
"key",
"in",
"db",
")",
"{",
"if",
"(",
"db",
".",
"hasOwnProperty",
"(",
"key",
")",
"&&",
"key",
".",
"indexOf",
"(",
"'Meta'",
")",
"===",
"-",
"1",
")",
"{",
"returnObj",
"[",
"key",
"]",
"=",
"db",
"[",
"key",
"]",
";",
"}",
"}",
"return",
"returnObj",
";",
"}"
] |
Builds the db object to pass to
the plugin. Needs to use the metadata
functions and not pass along `putMeta`
@returns {Object}
|
[
"Builds",
"the",
"db",
"object",
"to",
"pass",
"to",
"the",
"plugin",
".",
"Needs",
"to",
"use",
"the",
"metadata",
"functions",
"and",
"not",
"pass",
"along",
"putMeta"
] |
b883a94cbc38c1891ce568addb6cb280aa1d5353
|
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/services/plugins.js#L43-L57
|
train
|
clay/amphora
|
lib/services/bus.js
|
connect
|
function connect(busModule) {
if (busModule) {
module.exports.client = busModule.connect();
BUS_MODULE = true;
} else {
log('info', `Connecting to default Redis event bus at ${process.env.CLAY_BUS_HOST}`);
module.exports.client = new Redis(process.env.CLAY_BUS_HOST);
}
}
|
javascript
|
function connect(busModule) {
if (busModule) {
module.exports.client = busModule.connect();
BUS_MODULE = true;
} else {
log('info', `Connecting to default Redis event bus at ${process.env.CLAY_BUS_HOST}`);
module.exports.client = new Redis(process.env.CLAY_BUS_HOST);
}
}
|
[
"function",
"connect",
"(",
"busModule",
")",
"{",
"if",
"(",
"busModule",
")",
"{",
"module",
".",
"exports",
".",
"client",
"=",
"busModule",
".",
"connect",
"(",
")",
";",
"BUS_MODULE",
"=",
"true",
";",
"}",
"else",
"{",
"log",
"(",
"'info'",
",",
"`",
"${",
"process",
".",
"env",
".",
"CLAY_BUS_HOST",
"}",
"`",
")",
";",
"module",
".",
"exports",
".",
"client",
"=",
"new",
"Redis",
"(",
"process",
".",
"env",
".",
"CLAY_BUS_HOST",
")",
";",
"}",
"}"
] |
Connect to the bus Redis instance
@param {Object} busModule
|
[
"Connect",
"to",
"the",
"bus",
"Redis",
"instance"
] |
b883a94cbc38c1891ce568addb6cb280aa1d5353
|
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/services/bus.js#L13-L21
|
train
|
clay/amphora
|
lib/services/bus.js
|
publish
|
function publish(topic, msg) {
if (!topic || !msg || typeof topic !== 'string' || typeof msg !== 'object') {
throw new Error('A `topic` (string) and `msg` (object) property must be defined');
}
if (module.exports.client && BUS_MODULE) {
module.exports.client.publish(`${NAMESPACE}:${topic}`, msg);
} else if (module.exports.client) {
module.exports.client.publish(`${NAMESPACE}:${topic}`, JSON.stringify(msg));
}
}
|
javascript
|
function publish(topic, msg) {
if (!topic || !msg || typeof topic !== 'string' || typeof msg !== 'object') {
throw new Error('A `topic` (string) and `msg` (object) property must be defined');
}
if (module.exports.client && BUS_MODULE) {
module.exports.client.publish(`${NAMESPACE}:${topic}`, msg);
} else if (module.exports.client) {
module.exports.client.publish(`${NAMESPACE}:${topic}`, JSON.stringify(msg));
}
}
|
[
"function",
"publish",
"(",
"topic",
",",
"msg",
")",
"{",
"if",
"(",
"!",
"topic",
"||",
"!",
"msg",
"||",
"typeof",
"topic",
"!==",
"'string'",
"||",
"typeof",
"msg",
"!==",
"'object'",
")",
"{",
"throw",
"new",
"Error",
"(",
"'A `topic` (string) and `msg` (object) property must be defined'",
")",
";",
"}",
"if",
"(",
"module",
".",
"exports",
".",
"client",
"&&",
"BUS_MODULE",
")",
"{",
"module",
".",
"exports",
".",
"client",
".",
"publish",
"(",
"`",
"${",
"NAMESPACE",
"}",
"${",
"topic",
"}",
"`",
",",
"msg",
")",
";",
"}",
"else",
"if",
"(",
"module",
".",
"exports",
".",
"client",
")",
"{",
"module",
".",
"exports",
".",
"client",
".",
"publish",
"(",
"`",
"${",
"NAMESPACE",
"}",
"${",
"topic",
"}",
"`",
",",
"JSON",
".",
"stringify",
"(",
"msg",
")",
")",
";",
"}",
"}"
] |
Publish a message to the bus.
@param {String} topic
@param {String} msg
|
[
"Publish",
"a",
"message",
"to",
"the",
"bus",
"."
] |
b883a94cbc38c1891ce568addb6cb280aa1d5353
|
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/services/bus.js#L29-L39
|
train
|
clay/amphora
|
lib/locals.js
|
addSiteData
|
function addSiteData(site) {
return (req, res, next) => {
res.locals.url = uriToUrl(req.hostname + req.originalUrl, site.protocol, site.port);
res.locals.site = site;
next();
};
}
|
javascript
|
function addSiteData(site) {
return (req, res, next) => {
res.locals.url = uriToUrl(req.hostname + req.originalUrl, site.protocol, site.port);
res.locals.site = site;
next();
};
}
|
[
"function",
"addSiteData",
"(",
"site",
")",
"{",
"return",
"(",
"req",
",",
"res",
",",
"next",
")",
"=>",
"{",
"res",
".",
"locals",
".",
"url",
"=",
"uriToUrl",
"(",
"req",
".",
"hostname",
"+",
"req",
".",
"originalUrl",
",",
"site",
".",
"protocol",
",",
"site",
".",
"port",
")",
";",
"res",
".",
"locals",
".",
"site",
"=",
"site",
";",
"next",
"(",
")",
";",
"}",
";",
"}"
] |
Add site data to locals for each site
@param {Object} site
@returns {Function}
|
[
"Add",
"site",
"data",
"to",
"locals",
"for",
"each",
"site"
] |
b883a94cbc38c1891ce568addb6cb280aa1d5353
|
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/locals.js#L12-L19
|
train
|
clay/amphora
|
lib/locals.js
|
addQueryParams
|
function addQueryParams(req, res, next) {
_assign(res.locals, req.params, req.query);
next();
}
|
javascript
|
function addQueryParams(req, res, next) {
_assign(res.locals, req.params, req.query);
next();
}
|
[
"function",
"addQueryParams",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"_assign",
"(",
"res",
".",
"locals",
",",
"req",
".",
"params",
",",
"req",
".",
"query",
")",
";",
"next",
"(",
")",
";",
"}"
] |
Adds query params to locals
@param {Object} req
@param {Object} res
@param {Function} next
|
[
"Adds",
"query",
"params",
"to",
"locals"
] |
b883a94cbc38c1891ce568addb6cb280aa1d5353
|
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/locals.js#L27-L30
|
train
|
clay/amphora
|
lib/locals.js
|
addAvailableRoutes
|
function addAvailableRoutes(router) {
return (req, res, next) => {
const routes = router.stack
.filter((r) => r.route && r.route.path) // grab only the defined routes (not api stuff)
.map((r) => r.route.path); // pull out their paths
res.locals.routes = routes; // and add them to the locals
next();
};
}
|
javascript
|
function addAvailableRoutes(router) {
return (req, res, next) => {
const routes = router.stack
.filter((r) => r.route && r.route.path) // grab only the defined routes (not api stuff)
.map((r) => r.route.path); // pull out their paths
res.locals.routes = routes; // and add them to the locals
next();
};
}
|
[
"function",
"addAvailableRoutes",
"(",
"router",
")",
"{",
"return",
"(",
"req",
",",
"res",
",",
"next",
")",
"=>",
"{",
"const",
"routes",
"=",
"router",
".",
"stack",
".",
"filter",
"(",
"(",
"r",
")",
"=>",
"r",
".",
"route",
"&&",
"r",
".",
"route",
".",
"path",
")",
".",
"map",
"(",
"(",
"r",
")",
"=>",
"r",
".",
"route",
".",
"path",
")",
";",
"res",
".",
"locals",
".",
"routes",
"=",
"routes",
";",
"next",
"(",
")",
";",
"}",
";",
"}"
] |
Adds available site routes to locals
@param {express.Router} router
@returns {Function}
|
[
"Adds",
"available",
"site",
"routes",
"to",
"locals"
] |
b883a94cbc38c1891ce568addb6cb280aa1d5353
|
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/locals.js#L37-L46
|
train
|
clay/amphora
|
lib/locals.js
|
addAvailableComponents
|
function addAvailableComponents(req, res, next) {
res.locals.components = files.getComponents();
next();
}
|
javascript
|
function addAvailableComponents(req, res, next) {
res.locals.components = files.getComponents();
next();
}
|
[
"function",
"addAvailableComponents",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"res",
".",
"locals",
".",
"components",
"=",
"files",
".",
"getComponents",
"(",
")",
";",
"next",
"(",
")",
";",
"}"
] |
Adds available components to locals
@param {Object} req
@param {Object} res
@param {Function} next
|
[
"Adds",
"available",
"components",
"to",
"locals"
] |
b883a94cbc38c1891ce568addb6cb280aa1d5353
|
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/locals.js#L54-L57
|
train
|
clay/amphora
|
lib/locals.js
|
addUser
|
function addUser(req, res, next) {
res.locals.user = req.user;
next();
}
|
javascript
|
function addUser(req, res, next) {
res.locals.user = req.user;
next();
}
|
[
"function",
"addUser",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"res",
".",
"locals",
".",
"user",
"=",
"req",
".",
"user",
";",
"next",
"(",
")",
";",
"}"
] |
Adds current user to locals
@param {Object} req
@param {Object} res
@param {Function} next
|
[
"Adds",
"current",
"user",
"to",
"locals"
] |
b883a94cbc38c1891ce568addb6cb280aa1d5353
|
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/locals.js#L65-L68
|
train
|
clay/amphora
|
lib/services/references.js
|
isPropagatingVersion
|
function isPropagatingVersion(uri) {
const version = uri.split('@')[1];
return !!version && _.includes(propagatingVersions, version);
}
|
javascript
|
function isPropagatingVersion(uri) {
const version = uri.split('@')[1];
return !!version && _.includes(propagatingVersions, version);
}
|
[
"function",
"isPropagatingVersion",
"(",
"uri",
")",
"{",
"const",
"version",
"=",
"uri",
".",
"split",
"(",
"'@'",
")",
"[",
"1",
"]",
";",
"return",
"!",
"!",
"version",
"&&",
"_",
".",
"includes",
"(",
"propagatingVersions",
",",
"version",
")",
";",
"}"
] |
Some versions should propagate throughout the rest of the data.
@param {string} uri
@returns {boolean}
|
[
"Some",
"versions",
"should",
"propagate",
"throughout",
"the",
"rest",
"of",
"the",
"data",
"."
] |
b883a94cbc38c1891ce568addb6cb280aa1d5353
|
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/services/references.js#L60-L64
|
train
|
clay/amphora
|
lib/services/references.js
|
uriToUrl
|
function uriToUrl(uri, protocol, port) {
// just pretend to start with http; it's overwritten two lines down
const parts = urlParse.parse('http://' + uri);
parts.protocol = protocol || 'http';
parts.port = port || process.env.PORT;
delete parts.host;
if (parts.port &&
(parts.protocol === 'http' && parts.port.toString() === '80') ||
parts.protocol === 'https' && parts.port.toString() === '443'
) {
delete parts.port;
}
return parts.format();
}
|
javascript
|
function uriToUrl(uri, protocol, port) {
// just pretend to start with http; it's overwritten two lines down
const parts = urlParse.parse('http://' + uri);
parts.protocol = protocol || 'http';
parts.port = port || process.env.PORT;
delete parts.host;
if (parts.port &&
(parts.protocol === 'http' && parts.port.toString() === '80') ||
parts.protocol === 'https' && parts.port.toString() === '443'
) {
delete parts.port;
}
return parts.format();
}
|
[
"function",
"uriToUrl",
"(",
"uri",
",",
"protocol",
",",
"port",
")",
"{",
"const",
"parts",
"=",
"urlParse",
".",
"parse",
"(",
"'http://'",
"+",
"uri",
")",
";",
"parts",
".",
"protocol",
"=",
"protocol",
"||",
"'http'",
";",
"parts",
".",
"port",
"=",
"port",
"||",
"process",
".",
"env",
".",
"PORT",
";",
"delete",
"parts",
".",
"host",
";",
"if",
"(",
"parts",
".",
"port",
"&&",
"(",
"parts",
".",
"protocol",
"===",
"'http'",
"&&",
"parts",
".",
"port",
".",
"toString",
"(",
")",
"===",
"'80'",
")",
"||",
"parts",
".",
"protocol",
"===",
"'https'",
"&&",
"parts",
".",
"port",
".",
"toString",
"(",
")",
"===",
"'443'",
")",
"{",
"delete",
"parts",
".",
"port",
";",
"}",
"return",
"parts",
".",
"format",
"(",
")",
";",
"}"
] |
Take the protocol and port from a sourceUrl and apply them to some uri
@param {string} uri
@param {string} [protocol]
@param {string} [port]
@returns {string}
|
[
"Take",
"the",
"protocol",
"and",
"port",
"from",
"a",
"sourceUrl",
"and",
"apply",
"them",
"to",
"some",
"uri"
] |
b883a94cbc38c1891ce568addb6cb280aa1d5353
|
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/services/references.js#L92-L108
|
train
|
clay/amphora
|
lib/services/references.js
|
urlToUri
|
function urlToUri(url) {
let parts;
if (!isUrl(url)) {
throw new Error('Invalid url ' + url);
}
parts = urlParse.parse(url);
return `${parts.hostname}${decodeURIComponent(parts.path)}`;
}
|
javascript
|
function urlToUri(url) {
let parts;
if (!isUrl(url)) {
throw new Error('Invalid url ' + url);
}
parts = urlParse.parse(url);
return `${parts.hostname}${decodeURIComponent(parts.path)}`;
}
|
[
"function",
"urlToUri",
"(",
"url",
")",
"{",
"let",
"parts",
";",
"if",
"(",
"!",
"isUrl",
"(",
"url",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Invalid url '",
"+",
"url",
")",
";",
"}",
"parts",
"=",
"urlParse",
".",
"parse",
"(",
"url",
")",
";",
"return",
"`",
"${",
"parts",
".",
"hostname",
"}",
"${",
"decodeURIComponent",
"(",
"parts",
".",
"path",
")",
"}",
"`",
";",
"}"
] |
Remove protocol and port
@param {string} url
@returns {string}
|
[
"Remove",
"protocol",
"and",
"port"
] |
b883a94cbc38c1891ce568addb6cb280aa1d5353
|
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/services/references.js#L115-L124
|
train
|
clay/amphora
|
lib/services/components.js
|
put
|
function put(uri, data, locals) {
let model = files.getComponentModule(getComponentName(uri)),
callHooks = _.get(locals, 'hooks') !== 'false',
result;
if (model && _.isFunction(model.save) && callHooks) {
result = models.put(model, uri, data, locals);
} else {
result = dbOps.putDefaultBehavior(uri, data);
}
return result;
}
|
javascript
|
function put(uri, data, locals) {
let model = files.getComponentModule(getComponentName(uri)),
callHooks = _.get(locals, 'hooks') !== 'false',
result;
if (model && _.isFunction(model.save) && callHooks) {
result = models.put(model, uri, data, locals);
} else {
result = dbOps.putDefaultBehavior(uri, data);
}
return result;
}
|
[
"function",
"put",
"(",
"uri",
",",
"data",
",",
"locals",
")",
"{",
"let",
"model",
"=",
"files",
".",
"getComponentModule",
"(",
"getComponentName",
"(",
"uri",
")",
")",
",",
"callHooks",
"=",
"_",
".",
"get",
"(",
"locals",
",",
"'hooks'",
")",
"!==",
"'false'",
",",
"result",
";",
"if",
"(",
"model",
"&&",
"_",
".",
"isFunction",
"(",
"model",
".",
"save",
")",
"&&",
"callHooks",
")",
"{",
"result",
"=",
"models",
".",
"put",
"(",
"model",
",",
"uri",
",",
"data",
",",
"locals",
")",
";",
"}",
"else",
"{",
"result",
"=",
"dbOps",
".",
"putDefaultBehavior",
"(",
"uri",
",",
"data",
")",
";",
"}",
"return",
"result",
";",
"}"
] |
Given a component uri, its data and the locals
check if there exists a model.js file for the
component.
If yes, run the model.js. If not, turn the component
data into ops.
@param {String} uri
@param {String} data
@param {Object} [locals]
@returns {Promise}
|
[
"Given",
"a",
"component",
"uri",
"its",
"data",
"and",
"the",
"locals",
"check",
"if",
"there",
"exists",
"a",
"model",
".",
"js",
"file",
"for",
"the",
"component",
"."
] |
b883a94cbc38c1891ce568addb6cb280aa1d5353
|
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/services/components.js#L40-L52
|
train
|
clay/amphora
|
lib/render.js
|
getExtension
|
function getExtension(req) {
return _.get(req, 'params.ext', '') ? req.params.ext.toLowerCase() : renderers.default;
}
|
javascript
|
function getExtension(req) {
return _.get(req, 'params.ext', '') ? req.params.ext.toLowerCase() : renderers.default;
}
|
[
"function",
"getExtension",
"(",
"req",
")",
"{",
"return",
"_",
".",
"get",
"(",
"req",
",",
"'params.ext'",
",",
"''",
")",
"?",
"req",
".",
"params",
".",
"ext",
".",
"toLowerCase",
"(",
")",
":",
"renderers",
".",
"default",
";",
"}"
] |
Check the renderers for the request extension. If the
request does not have an extension, grab the default.
@param {Object} req
@return {String}
|
[
"Check",
"the",
"renderers",
"for",
"the",
"request",
"extension",
".",
"If",
"the",
"request",
"does",
"not",
"have",
"an",
"extension",
"grab",
"the",
"default",
"."
] |
b883a94cbc38c1891ce568addb6cb280aa1d5353
|
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/render.js#L26-L28
|
train
|
clay/amphora
|
lib/render.js
|
findRenderer
|
function findRenderer(extension) {
var renderer;
// Default to HTML if you don't have an extension
extension = extension || renderers.default;
// Get the renderer
renderer = _.get(renderers, `${extension}`, null);
if (renderer) {
return renderer;
} else {
return new Error(`Renderer not found for extension ${extension}`);
}
}
|
javascript
|
function findRenderer(extension) {
var renderer;
// Default to HTML if you don't have an extension
extension = extension || renderers.default;
// Get the renderer
renderer = _.get(renderers, `${extension}`, null);
if (renderer) {
return renderer;
} else {
return new Error(`Renderer not found for extension ${extension}`);
}
}
|
[
"function",
"findRenderer",
"(",
"extension",
")",
"{",
"var",
"renderer",
";",
"extension",
"=",
"extension",
"||",
"renderers",
".",
"default",
";",
"renderer",
"=",
"_",
".",
"get",
"(",
"renderers",
",",
"`",
"${",
"extension",
"}",
"`",
",",
"null",
")",
";",
"if",
"(",
"renderer",
")",
"{",
"return",
"renderer",
";",
"}",
"else",
"{",
"return",
"new",
"Error",
"(",
"`",
"${",
"extension",
"}",
"`",
")",
";",
"}",
"}"
] |
Find the renderer so to use for the request.
@param {String|Undefined} extension
@return {Object}
|
[
"Find",
"the",
"renderer",
"so",
"to",
"use",
"for",
"the",
"request",
"."
] |
b883a94cbc38c1891ce568addb6cb280aa1d5353
|
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/render.js#L47-L60
|
train
|
clay/amphora
|
lib/render.js
|
renderComponent
|
function renderComponent(req, res, hrStart) {
var extension = getExtension(req), // Get the extension for the request
renderer = findRenderer(extension), // Determine which renderer we are using
_ref = req.uri,
locals = res.locals,
options = options || {};
if (renderer instanceof Error) {
log('error', renderer);
return Promise.reject(renderer);
}
// Add request route params, request query params
// and the request extension to the locals object
locals.params = req.params;
locals.query = req.query;
locals.extension = extension;
return components.get(_ref, locals)
.then(cmptData => formDataForRenderer(cmptData, { _ref }, locals))
.tap(logTime(hrStart, _ref))
.then(({data, options}) => renderer.render(data, options, res))
.catch(err => log('error', err));
}
|
javascript
|
function renderComponent(req, res, hrStart) {
var extension = getExtension(req), // Get the extension for the request
renderer = findRenderer(extension), // Determine which renderer we are using
_ref = req.uri,
locals = res.locals,
options = options || {};
if (renderer instanceof Error) {
log('error', renderer);
return Promise.reject(renderer);
}
// Add request route params, request query params
// and the request extension to the locals object
locals.params = req.params;
locals.query = req.query;
locals.extension = extension;
return components.get(_ref, locals)
.then(cmptData => formDataForRenderer(cmptData, { _ref }, locals))
.tap(logTime(hrStart, _ref))
.then(({data, options}) => renderer.render(data, options, res))
.catch(err => log('error', err));
}
|
[
"function",
"renderComponent",
"(",
"req",
",",
"res",
",",
"hrStart",
")",
"{",
"var",
"extension",
"=",
"getExtension",
"(",
"req",
")",
",",
"renderer",
"=",
"findRenderer",
"(",
"extension",
")",
",",
"_ref",
"=",
"req",
".",
"uri",
",",
"locals",
"=",
"res",
".",
"locals",
",",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"if",
"(",
"renderer",
"instanceof",
"Error",
")",
"{",
"log",
"(",
"'error'",
",",
"renderer",
")",
";",
"return",
"Promise",
".",
"reject",
"(",
"renderer",
")",
";",
"}",
"locals",
".",
"params",
"=",
"req",
".",
"params",
";",
"locals",
".",
"query",
"=",
"req",
".",
"query",
";",
"locals",
".",
"extension",
"=",
"extension",
";",
"return",
"components",
".",
"get",
"(",
"_ref",
",",
"locals",
")",
".",
"then",
"(",
"cmptData",
"=>",
"formDataForRenderer",
"(",
"cmptData",
",",
"{",
"_ref",
"}",
",",
"locals",
")",
")",
".",
"tap",
"(",
"logTime",
"(",
"hrStart",
",",
"_ref",
")",
")",
".",
"then",
"(",
"(",
"{",
"data",
",",
"options",
"}",
")",
"=>",
"renderer",
".",
"render",
"(",
"data",
",",
"options",
",",
"res",
")",
")",
".",
"catch",
"(",
"err",
"=>",
"log",
"(",
"'error'",
",",
"err",
")",
")",
";",
"}"
] |
Render a component via whatever renderer should be used
@param {Object} req
@param {Object} res
@param {Object} hrStart
@return {Promise}
|
[
"Render",
"a",
"component",
"via",
"whatever",
"renderer",
"should",
"be",
"used"
] |
b883a94cbc38c1891ce568addb6cb280aa1d5353
|
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/render.js#L70-L92
|
train
|
clay/amphora
|
lib/render.js
|
renderPage
|
function renderPage(uri, req, res, hrStart) {
const locals = res.locals,
extension = getExtension(req),
renderer = findRenderer(extension);
// Add request route params, request query params
// and the request extension to the locals object
locals.params = req.params;
locals.query = req.query;
locals.extension = extension;
// look up page alias' component instance
return getDBObject(uri)
.then(formDataFromLayout(locals, uri))
.then(data => {
logTime(hrStart, uri);
return data;
})
.then(({ data, options }) => renderer.render(data, options, res))
.catch(responses.handleError(res));
}
|
javascript
|
function renderPage(uri, req, res, hrStart) {
const locals = res.locals,
extension = getExtension(req),
renderer = findRenderer(extension);
// Add request route params, request query params
// and the request extension to the locals object
locals.params = req.params;
locals.query = req.query;
locals.extension = extension;
// look up page alias' component instance
return getDBObject(uri)
.then(formDataFromLayout(locals, uri))
.then(data => {
logTime(hrStart, uri);
return data;
})
.then(({ data, options }) => renderer.render(data, options, res))
.catch(responses.handleError(res));
}
|
[
"function",
"renderPage",
"(",
"uri",
",",
"req",
",",
"res",
",",
"hrStart",
")",
"{",
"const",
"locals",
"=",
"res",
".",
"locals",
",",
"extension",
"=",
"getExtension",
"(",
"req",
")",
",",
"renderer",
"=",
"findRenderer",
"(",
"extension",
")",
";",
"locals",
".",
"params",
"=",
"req",
".",
"params",
";",
"locals",
".",
"query",
"=",
"req",
".",
"query",
";",
"locals",
".",
"extension",
"=",
"extension",
";",
"return",
"getDBObject",
"(",
"uri",
")",
".",
"then",
"(",
"formDataFromLayout",
"(",
"locals",
",",
"uri",
")",
")",
".",
"then",
"(",
"data",
"=>",
"{",
"logTime",
"(",
"hrStart",
",",
"uri",
")",
";",
"return",
"data",
";",
"}",
")",
".",
"then",
"(",
"(",
"{",
"data",
",",
"options",
"}",
")",
"=>",
"renderer",
".",
"render",
"(",
"data",
",",
"options",
",",
"res",
")",
")",
".",
"catch",
"(",
"responses",
".",
"handleError",
"(",
"res",
")",
")",
";",
"}"
] |
Render a page with the appropriate renderer
@param {String} uri
@param {Object} req
@param {Object} res
@param {Object} hrStart
@return {Promise}
|
[
"Render",
"a",
"page",
"with",
"the",
"appropriate",
"renderer"
] |
b883a94cbc38c1891ce568addb6cb280aa1d5353
|
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/render.js#L111-L131
|
train
|
clay/amphora
|
lib/render.js
|
renderDynamicRoute
|
function renderDynamicRoute(pageId) {
return (req, res) => {
const hrStart = process.hrtime(),
site = res.locals.site,
pageUri = `${getExpressRoutePrefix(site)}/_pages/${pageId}@published`;
return module.exports.renderPage(pageUri, req, res, hrStart);
};
}
|
javascript
|
function renderDynamicRoute(pageId) {
return (req, res) => {
const hrStart = process.hrtime(),
site = res.locals.site,
pageUri = `${getExpressRoutePrefix(site)}/_pages/${pageId}@published`;
return module.exports.renderPage(pageUri, req, res, hrStart);
};
}
|
[
"function",
"renderDynamicRoute",
"(",
"pageId",
")",
"{",
"return",
"(",
"req",
",",
"res",
")",
"=>",
"{",
"const",
"hrStart",
"=",
"process",
".",
"hrtime",
"(",
")",
",",
"site",
"=",
"res",
".",
"locals",
".",
"site",
",",
"pageUri",
"=",
"`",
"${",
"getExpressRoutePrefix",
"(",
"site",
")",
"}",
"${",
"pageId",
"}",
"`",
";",
"return",
"module",
".",
"exports",
".",
"renderPage",
"(",
"pageUri",
",",
"req",
",",
"res",
",",
"hrStart",
")",
";",
"}",
";",
"}"
] |
Given a pageId, render the page directly from a call
to an Express route without trying to match to a uri
directly
@param {String} pageId
@return {Function}
|
[
"Given",
"a",
"pageId",
"render",
"the",
"page",
"directly",
"from",
"a",
"call",
"to",
"an",
"Express",
"route",
"without",
"trying",
"to",
"match",
"to",
"a",
"uri",
"directly"
] |
b883a94cbc38c1891ce568addb6cb280aa1d5353
|
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/render.js#L141-L149
|
train
|
clay/amphora
|
lib/render.js
|
formDataFromLayout
|
function formDataFromLayout(locals, uri) {
return function (result) {
const _layoutRef = result.layout,
pageData = references.omitPageConfiguration(result);
return components.get(_layoutRef, locals)
.then(layout => mapLayoutToPageData(pageData, layout))
.then(mappedData => module.exports.formDataForRenderer(mappedData, { _layoutRef, _ref: uri }, locals));
};
}
|
javascript
|
function formDataFromLayout(locals, uri) {
return function (result) {
const _layoutRef = result.layout,
pageData = references.omitPageConfiguration(result);
return components.get(_layoutRef, locals)
.then(layout => mapLayoutToPageData(pageData, layout))
.then(mappedData => module.exports.formDataForRenderer(mappedData, { _layoutRef, _ref: uri }, locals));
};
}
|
[
"function",
"formDataFromLayout",
"(",
"locals",
",",
"uri",
")",
"{",
"return",
"function",
"(",
"result",
")",
"{",
"const",
"_layoutRef",
"=",
"result",
".",
"layout",
",",
"pageData",
"=",
"references",
".",
"omitPageConfiguration",
"(",
"result",
")",
";",
"return",
"components",
".",
"get",
"(",
"_layoutRef",
",",
"locals",
")",
".",
"then",
"(",
"layout",
"=>",
"mapLayoutToPageData",
"(",
"pageData",
",",
"layout",
")",
")",
".",
"then",
"(",
"mappedData",
"=>",
"module",
".",
"exports",
".",
"formDataForRenderer",
"(",
"mappedData",
",",
"{",
"_layoutRef",
",",
"_ref",
":",
"uri",
"}",
",",
"locals",
")",
")",
";",
"}",
";",
"}"
] |
Given a page uri, get it from the db, resolve the layout,
map page data to the page ares and then format all the
data for the renderer
@param {Object} locals
@param {String} uri
@return {Function<Promise>}
|
[
"Given",
"a",
"page",
"uri",
"get",
"it",
"from",
"the",
"db",
"resolve",
"the",
"layout",
"map",
"page",
"data",
"to",
"the",
"page",
"ares",
"and",
"then",
"format",
"all",
"the",
"data",
"for",
"the",
"renderer"
] |
b883a94cbc38c1891ce568addb6cb280aa1d5353
|
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/render.js#L160-L169
|
train
|
clay/amphora
|
lib/render.js
|
formDataForRenderer
|
function formDataForRenderer(unresolvedData, { _layoutRef, _ref }, locals) {
return composer.resolveComponentReferences(unresolvedData, locals)
.then((data) => ({
data,
options: { locals, _ref, _layoutRef }
}));
}
|
javascript
|
function formDataForRenderer(unresolvedData, { _layoutRef, _ref }, locals) {
return composer.resolveComponentReferences(unresolvedData, locals)
.then((data) => ({
data,
options: { locals, _ref, _layoutRef }
}));
}
|
[
"function",
"formDataForRenderer",
"(",
"unresolvedData",
",",
"{",
"_layoutRef",
",",
"_ref",
"}",
",",
"locals",
")",
"{",
"return",
"composer",
".",
"resolveComponentReferences",
"(",
"unresolvedData",
",",
"locals",
")",
".",
"then",
"(",
"(",
"data",
")",
"=>",
"(",
"{",
"data",
",",
"options",
":",
"{",
"locals",
",",
"_ref",
",",
"_layoutRef",
"}",
"}",
")",
")",
";",
"}"
] |
Resolve all references for nested objects and form the
data up in the expected object to send to a renderer
@param {Object} unresolvedData
@param {Object} options
@param {Object} locals
@return {Promise}
|
[
"Resolve",
"all",
"references",
"for",
"nested",
"objects",
"and",
"form",
"the",
"data",
"up",
"in",
"the",
"expected",
"object",
"to",
"send",
"to",
"a",
"renderer"
] |
b883a94cbc38c1891ce568addb6cb280aa1d5353
|
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/render.js#L179-L185
|
train
|
clay/amphora
|
lib/render.js
|
getExpressRoutePrefix
|
function getExpressRoutePrefix(site) {
let prefix = site.host;
if (site.path.length > 1) {
prefix += site.path;
}
return prefix;
}
|
javascript
|
function getExpressRoutePrefix(site) {
let prefix = site.host;
if (site.path.length > 1) {
prefix += site.path;
}
return prefix;
}
|
[
"function",
"getExpressRoutePrefix",
"(",
"site",
")",
"{",
"let",
"prefix",
"=",
"site",
".",
"host",
";",
"if",
"(",
"site",
".",
"path",
".",
"length",
">",
"1",
")",
"{",
"prefix",
"+=",
"site",
".",
"path",
";",
"}",
"return",
"prefix",
";",
"}"
] |
Get the prefix that normalizes the slash on the path with the expectation that references to routes using the prefix
will start with a slash as well.
@param {object} site
@returns {string}
|
[
"Get",
"the",
"prefix",
"that",
"normalizes",
"the",
"slash",
"on",
"the",
"path",
"with",
"the",
"expectation",
"that",
"references",
"to",
"routes",
"using",
"the",
"prefix",
"will",
"start",
"with",
"a",
"slash",
"as",
"well",
"."
] |
b883a94cbc38c1891ce568addb6cb280aa1d5353
|
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/render.js#L194-L202
|
train
|
clay/amphora
|
lib/render.js
|
renderUri
|
function renderUri(uri, req, res, hrStart) {
hrStart = hrStart || process.hrtime(); // Check if we actually have a start time
return db.get(uri).then(function (result) {
const route = _.find(uriRoutes, function (item) {
return result.match(item.when);
});
if (!route) {
throw new Error('Invalid URI: ' + uri + ': ' + result);
}
if (route.isUri) {
let newBase64Uri = _.last(result.split('/')),
newUri = buf.decode(newBase64Uri),
newPath = url.parse(`${res.req.protocol}://${newUri}`).path,
newUrl = `${res.req.protocol}://${res.req.hostname}${newPath}`,
queryString = req._parsedUrl.search;
if (queryString) newUrl += queryString;
log('info', `Redirecting to ${newUrl}`);
res.redirect(301, newUrl);
} else {
return route.default(result, req, res, hrStart);
}
});
}
|
javascript
|
function renderUri(uri, req, res, hrStart) {
hrStart = hrStart || process.hrtime(); // Check if we actually have a start time
return db.get(uri).then(function (result) {
const route = _.find(uriRoutes, function (item) {
return result.match(item.when);
});
if (!route) {
throw new Error('Invalid URI: ' + uri + ': ' + result);
}
if (route.isUri) {
let newBase64Uri = _.last(result.split('/')),
newUri = buf.decode(newBase64Uri),
newPath = url.parse(`${res.req.protocol}://${newUri}`).path,
newUrl = `${res.req.protocol}://${res.req.hostname}${newPath}`,
queryString = req._parsedUrl.search;
if (queryString) newUrl += queryString;
log('info', `Redirecting to ${newUrl}`);
res.redirect(301, newUrl);
} else {
return route.default(result, req, res, hrStart);
}
});
}
|
[
"function",
"renderUri",
"(",
"uri",
",",
"req",
",",
"res",
",",
"hrStart",
")",
"{",
"hrStart",
"=",
"hrStart",
"||",
"process",
".",
"hrtime",
"(",
")",
";",
"return",
"db",
".",
"get",
"(",
"uri",
")",
".",
"then",
"(",
"function",
"(",
"result",
")",
"{",
"const",
"route",
"=",
"_",
".",
"find",
"(",
"uriRoutes",
",",
"function",
"(",
"item",
")",
"{",
"return",
"result",
".",
"match",
"(",
"item",
".",
"when",
")",
";",
"}",
")",
";",
"if",
"(",
"!",
"route",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Invalid URI: '",
"+",
"uri",
"+",
"': '",
"+",
"result",
")",
";",
"}",
"if",
"(",
"route",
".",
"isUri",
")",
"{",
"let",
"newBase64Uri",
"=",
"_",
".",
"last",
"(",
"result",
".",
"split",
"(",
"'/'",
")",
")",
",",
"newUri",
"=",
"buf",
".",
"decode",
"(",
"newBase64Uri",
")",
",",
"newPath",
"=",
"url",
".",
"parse",
"(",
"`",
"${",
"res",
".",
"req",
".",
"protocol",
"}",
"${",
"newUri",
"}",
"`",
")",
".",
"path",
",",
"newUrl",
"=",
"`",
"${",
"res",
".",
"req",
".",
"protocol",
"}",
"${",
"res",
".",
"req",
".",
"hostname",
"}",
"${",
"newPath",
"}",
"`",
",",
"queryString",
"=",
"req",
".",
"_parsedUrl",
".",
"search",
";",
"if",
"(",
"queryString",
")",
"newUrl",
"+=",
"queryString",
";",
"log",
"(",
"'info'",
",",
"`",
"${",
"newUrl",
"}",
"`",
")",
";",
"res",
".",
"redirect",
"(",
"301",
",",
"newUrl",
")",
";",
"}",
"else",
"{",
"return",
"route",
".",
"default",
"(",
"result",
",",
"req",
",",
"res",
",",
"hrStart",
")",
";",
"}",
"}",
")",
";",
"}"
] |
Redirect to referenced type.
Depending on what the uri references, load something different.
@param {string} uri
@param {object} req
@param {object} res
@param {object} hrStart
@returns {Promise}
|
[
"Redirect",
"to",
"referenced",
"type",
"."
] |
b883a94cbc38c1891ce568addb6cb280aa1d5353
|
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/render.js#L215-L242
|
train
|
clay/amphora
|
lib/render.js
|
logTime
|
function logTime(hrStart, uri) {
return () => {
const diff = process.hrtime(hrStart),
ms = Math.floor((diff[0] * 1e9 + diff[1]) / 1000000);
log('info', `composed data for: ${uri} (${ms}ms)`, {
composeTime: ms,
uri
});
};
}
|
javascript
|
function logTime(hrStart, uri) {
return () => {
const diff = process.hrtime(hrStart),
ms = Math.floor((diff[0] * 1e9 + diff[1]) / 1000000);
log('info', `composed data for: ${uri} (${ms}ms)`, {
composeTime: ms,
uri
});
};
}
|
[
"function",
"logTime",
"(",
"hrStart",
",",
"uri",
")",
"{",
"return",
"(",
")",
"=>",
"{",
"const",
"diff",
"=",
"process",
".",
"hrtime",
"(",
"hrStart",
")",
",",
"ms",
"=",
"Math",
".",
"floor",
"(",
"(",
"diff",
"[",
"0",
"]",
"*",
"1e9",
"+",
"diff",
"[",
"1",
"]",
")",
"/",
"1000000",
")",
";",
"log",
"(",
"'info'",
",",
"`",
"${",
"uri",
"}",
"${",
"ms",
"}",
"`",
",",
"{",
"composeTime",
":",
"ms",
",",
"uri",
"}",
")",
";",
"}",
";",
"}"
] |
Log the timing for data composition
@param {Object} hrStart
@param {String} uri
@return {Function}
|
[
"Log",
"the",
"timing",
"for",
"data",
"composition"
] |
b883a94cbc38c1891ce568addb6cb280aa1d5353
|
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/render.js#L251-L261
|
train
|
clay/amphora
|
lib/render.js
|
renderExpressRoute
|
function renderExpressRoute(req, res, next) {
var hrStart = process.hrtime(),
site = res.locals.site,
prefix = `${getExpressRoutePrefix(site)}/_uris/`,
pageReference = `${prefix}${buf.encode(req.hostname + req.baseUrl + req.path)}`;
return module.exports.renderUri(pageReference, req, res, hrStart)
.catch((error) => {
if (error.name === 'NotFoundError') {
log('error', `could not find resource ${req.uri}`, {
message: error.message
});
next();
} else {
next(error);
}
});
}
|
javascript
|
function renderExpressRoute(req, res, next) {
var hrStart = process.hrtime(),
site = res.locals.site,
prefix = `${getExpressRoutePrefix(site)}/_uris/`,
pageReference = `${prefix}${buf.encode(req.hostname + req.baseUrl + req.path)}`;
return module.exports.renderUri(pageReference, req, res, hrStart)
.catch((error) => {
if (error.name === 'NotFoundError') {
log('error', `could not find resource ${req.uri}`, {
message: error.message
});
next();
} else {
next(error);
}
});
}
|
[
"function",
"renderExpressRoute",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"var",
"hrStart",
"=",
"process",
".",
"hrtime",
"(",
")",
",",
"site",
"=",
"res",
".",
"locals",
".",
"site",
",",
"prefix",
"=",
"`",
"${",
"getExpressRoutePrefix",
"(",
"site",
")",
"}",
"`",
",",
"pageReference",
"=",
"`",
"${",
"prefix",
"}",
"${",
"buf",
".",
"encode",
"(",
"req",
".",
"hostname",
"+",
"req",
".",
"baseUrl",
"+",
"req",
".",
"path",
")",
"}",
"`",
";",
"return",
"module",
".",
"exports",
".",
"renderUri",
"(",
"pageReference",
",",
"req",
",",
"res",
",",
"hrStart",
")",
".",
"catch",
"(",
"(",
"error",
")",
"=>",
"{",
"if",
"(",
"error",
".",
"name",
"===",
"'NotFoundError'",
")",
"{",
"log",
"(",
"'error'",
",",
"`",
"${",
"req",
".",
"uri",
"}",
"`",
",",
"{",
"message",
":",
"error",
".",
"message",
"}",
")",
";",
"next",
"(",
")",
";",
"}",
"else",
"{",
"next",
"(",
"error",
")",
";",
"}",
"}",
")",
";",
"}"
] |
Run composer by translating url to a "page" by base64ing it. Errors are handled by Express.
@param {Object} req
@param {Object} res
@param {Function} next
@return {Promise}
|
[
"Run",
"composer",
"by",
"translating",
"url",
"to",
"a",
"page",
"by",
"base64ing",
"it",
".",
"Errors",
"are",
"handled",
"by",
"Express",
"."
] |
b883a94cbc38c1891ce568addb6cb280aa1d5353
|
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/render.js#L271-L288
|
train
|
clay/amphora
|
lib/render.js
|
assumePublishedUnlessEditing
|
function assumePublishedUnlessEditing(fn) {
return function (uri, req, res, hrStart) {
// ignore version if they are editing; default to 'published'
if (!_.get(res, 'req.query.edit')) {
uri = clayUtils.replaceVersion(uri, uri.split('@')[1] || 'published');
}
return fn(uri, req, res, hrStart);
};
}
|
javascript
|
function assumePublishedUnlessEditing(fn) {
return function (uri, req, res, hrStart) {
// ignore version if they are editing; default to 'published'
if (!_.get(res, 'req.query.edit')) {
uri = clayUtils.replaceVersion(uri, uri.split('@')[1] || 'published');
}
return fn(uri, req, res, hrStart);
};
}
|
[
"function",
"assumePublishedUnlessEditing",
"(",
"fn",
")",
"{",
"return",
"function",
"(",
"uri",
",",
"req",
",",
"res",
",",
"hrStart",
")",
"{",
"if",
"(",
"!",
"_",
".",
"get",
"(",
"res",
",",
"'req.query.edit'",
")",
")",
"{",
"uri",
"=",
"clayUtils",
".",
"replaceVersion",
"(",
"uri",
",",
"uri",
".",
"split",
"(",
"'@'",
")",
"[",
"1",
"]",
"||",
"'published'",
")",
";",
"}",
"return",
"fn",
"(",
"uri",
",",
"req",
",",
"res",
",",
"hrStart",
")",
";",
"}",
";",
"}"
] |
Assume they're talking about published content unless ?edit
@param {function} fn
@returns {function}
|
[
"Assume",
"they",
"re",
"talking",
"about",
"published",
"content",
"unless",
"?edit"
] |
b883a94cbc38c1891ce568addb6cb280aa1d5353
|
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/render.js#L296-L305
|
train
|
clay/amphora
|
lib/render.js
|
resetUriRouteHandlers
|
function resetUriRouteHandlers() {
/**
* URIs can point to many different things, and this list will probably grow.
* @type {[{when: RegExp, html: function, json: function}]}
*/
uriRoutes = [
// assume published
{
when: /\/_pages\//,
default: assumePublishedUnlessEditing(renderPage),
json: assumePublishedUnlessEditing(getDBObject)
},
// assume published
{
when: /\/_components\//,
default: assumePublishedUnlessEditing(renderComponent),
json: assumePublishedUnlessEditing(components.get)
},
// uris are not published, they only exist
{
when: /\/_uris\//,
isUri: true,
html: renderUri,
json: db.get
}];
}
|
javascript
|
function resetUriRouteHandlers() {
/**
* URIs can point to many different things, and this list will probably grow.
* @type {[{when: RegExp, html: function, json: function}]}
*/
uriRoutes = [
// assume published
{
when: /\/_pages\//,
default: assumePublishedUnlessEditing(renderPage),
json: assumePublishedUnlessEditing(getDBObject)
},
// assume published
{
when: /\/_components\//,
default: assumePublishedUnlessEditing(renderComponent),
json: assumePublishedUnlessEditing(components.get)
},
// uris are not published, they only exist
{
when: /\/_uris\//,
isUri: true,
html: renderUri,
json: db.get
}];
}
|
[
"function",
"resetUriRouteHandlers",
"(",
")",
"{",
"uriRoutes",
"=",
"[",
"{",
"when",
":",
"/",
"\\/_pages\\/",
"/",
",",
"default",
":",
"assumePublishedUnlessEditing",
"(",
"renderPage",
")",
",",
"json",
":",
"assumePublishedUnlessEditing",
"(",
"getDBObject",
")",
"}",
",",
"{",
"when",
":",
"/",
"\\/_components\\/",
"/",
",",
"default",
":",
"assumePublishedUnlessEditing",
"(",
"renderComponent",
")",
",",
"json",
":",
"assumePublishedUnlessEditing",
"(",
"components",
".",
"get",
")",
"}",
",",
"{",
"when",
":",
"/",
"\\/_uris\\/",
"/",
",",
"isUri",
":",
"true",
",",
"html",
":",
"renderUri",
",",
"json",
":",
"db",
".",
"get",
"}",
"]",
";",
"}"
] |
Uris route as following
|
[
"Uris",
"route",
"as",
"following"
] |
b883a94cbc38c1891ce568addb6cb280aa1d5353
|
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/render.js#L327-L352
|
train
|
clay/amphora
|
lib/routes.js
|
addAuthenticationRoutes
|
function addAuthenticationRoutes(router) {
const authRouter = express.Router();
authRouter.use(require('body-parser').json({ strict: true, type: 'application/json', limit: '50mb' }));
authRouter.use(require('body-parser').text({ type: 'text/*' }));
amphoraAuth.addRoutes(authRouter);
router.use('/_users', authRouter);
}
|
javascript
|
function addAuthenticationRoutes(router) {
const authRouter = express.Router();
authRouter.use(require('body-parser').json({ strict: true, type: 'application/json', limit: '50mb' }));
authRouter.use(require('body-parser').text({ type: 'text/*' }));
amphoraAuth.addRoutes(authRouter);
router.use('/_users', authRouter);
}
|
[
"function",
"addAuthenticationRoutes",
"(",
"router",
")",
"{",
"const",
"authRouter",
"=",
"express",
".",
"Router",
"(",
")",
";",
"authRouter",
".",
"use",
"(",
"require",
"(",
"'body-parser'",
")",
".",
"json",
"(",
"{",
"strict",
":",
"true",
",",
"type",
":",
"'application/json'",
",",
"limit",
":",
"'50mb'",
"}",
")",
")",
";",
"authRouter",
".",
"use",
"(",
"require",
"(",
"'body-parser'",
")",
".",
"text",
"(",
"{",
"type",
":",
"'text/*'",
"}",
")",
")",
";",
"amphoraAuth",
".",
"addRoutes",
"(",
"authRouter",
")",
";",
"router",
".",
"use",
"(",
"'/_users'",
",",
"authRouter",
")",
";",
"}"
] |
Add routes from the authentication module that
can be passed in. If no module is passed in at
instantiation time then use the default auth module.
@param {express.Router} router
|
[
"Add",
"routes",
"from",
"the",
"authentication",
"module",
"that",
"can",
"be",
"passed",
"in",
".",
"If",
"no",
"module",
"is",
"passed",
"in",
"at",
"instantiation",
"time",
"then",
"use",
"the",
"default",
"auth",
"module",
"."
] |
b883a94cbc38c1891ce568addb6cb280aa1d5353
|
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/routes.js#L90-L97
|
train
|
clay/amphora
|
lib/routes.js
|
addSiteController
|
function addSiteController(router, site, providers) {
if (site.dir) {
const controller = files.tryRequire(site.dir);
if (controller) {
if (Array.isArray(controller.middleware)) {
router.use(controller.middleware);
}
if (Array.isArray(controller.routes)) {
attachRoutes(router, controller.routes, site);
} else {
log('warn', `There is no router for site: ${site.slug}`);
}
// Providers are the same across all sites, but this is a convenient
// place to store it so that it's available everywhere
_.set(site, 'providers', providers);
// things to remember from controller
_.assign(site, _.pick(controller, 'resolvePublishing'));
_.assign(site, _.pick(controller, 'resolvePublishUrl'));
_.assign(site, _.pick(controller, 'modifyPublishedData'));
}
}
return router;
}
|
javascript
|
function addSiteController(router, site, providers) {
if (site.dir) {
const controller = files.tryRequire(site.dir);
if (controller) {
if (Array.isArray(controller.middleware)) {
router.use(controller.middleware);
}
if (Array.isArray(controller.routes)) {
attachRoutes(router, controller.routes, site);
} else {
log('warn', `There is no router for site: ${site.slug}`);
}
// Providers are the same across all sites, but this is a convenient
// place to store it so that it's available everywhere
_.set(site, 'providers', providers);
// things to remember from controller
_.assign(site, _.pick(controller, 'resolvePublishing'));
_.assign(site, _.pick(controller, 'resolvePublishUrl'));
_.assign(site, _.pick(controller, 'modifyPublishedData'));
}
}
return router;
}
|
[
"function",
"addSiteController",
"(",
"router",
",",
"site",
",",
"providers",
")",
"{",
"if",
"(",
"site",
".",
"dir",
")",
"{",
"const",
"controller",
"=",
"files",
".",
"tryRequire",
"(",
"site",
".",
"dir",
")",
";",
"if",
"(",
"controller",
")",
"{",
"if",
"(",
"Array",
".",
"isArray",
"(",
"controller",
".",
"middleware",
")",
")",
"{",
"router",
".",
"use",
"(",
"controller",
".",
"middleware",
")",
";",
"}",
"if",
"(",
"Array",
".",
"isArray",
"(",
"controller",
".",
"routes",
")",
")",
"{",
"attachRoutes",
"(",
"router",
",",
"controller",
".",
"routes",
",",
"site",
")",
";",
"}",
"else",
"{",
"log",
"(",
"'warn'",
",",
"`",
"${",
"site",
".",
"slug",
"}",
"`",
")",
";",
"}",
"_",
".",
"set",
"(",
"site",
",",
"'providers'",
",",
"providers",
")",
";",
"_",
".",
"assign",
"(",
"site",
",",
"_",
".",
"pick",
"(",
"controller",
",",
"'resolvePublishing'",
")",
")",
";",
"_",
".",
"assign",
"(",
"site",
",",
"_",
".",
"pick",
"(",
"controller",
",",
"'resolvePublishUrl'",
")",
")",
";",
"_",
".",
"assign",
"(",
"site",
",",
"_",
".",
"pick",
"(",
"controller",
",",
"'modifyPublishedData'",
")",
")",
";",
"}",
"}",
"return",
"router",
";",
"}"
] |
Default way to load site controllers.
@param {express.Router} router
@param {Object} site
@param {Array} providers
@returns {express.Router}
|
[
"Default",
"way",
"to",
"load",
"site",
"controllers",
"."
] |
b883a94cbc38c1891ce568addb6cb280aa1d5353
|
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/routes.js#L131-L157
|
train
|
clay/amphora
|
lib/routes.js
|
loadFromConfig
|
function loadFromConfig(router, providers, sessionStore) {
const sitesMap = siteService.sites(),
siteHosts = _.uniq(_.map(sitesMap, 'host'));
// iterate through the hosts
_.each(siteHosts, hostname => {
const sites = _.filter(sitesMap, {host: hostname}).sort(sortByDepthOfPath);
addHost({
router,
hostname,
sites,
providers,
sessionStore
});
});
return router;
}
|
javascript
|
function loadFromConfig(router, providers, sessionStore) {
const sitesMap = siteService.sites(),
siteHosts = _.uniq(_.map(sitesMap, 'host'));
// iterate through the hosts
_.each(siteHosts, hostname => {
const sites = _.filter(sitesMap, {host: hostname}).sort(sortByDepthOfPath);
addHost({
router,
hostname,
sites,
providers,
sessionStore
});
});
return router;
}
|
[
"function",
"loadFromConfig",
"(",
"router",
",",
"providers",
",",
"sessionStore",
")",
"{",
"const",
"sitesMap",
"=",
"siteService",
".",
"sites",
"(",
")",
",",
"siteHosts",
"=",
"_",
".",
"uniq",
"(",
"_",
".",
"map",
"(",
"sitesMap",
",",
"'host'",
")",
")",
";",
"_",
".",
"each",
"(",
"siteHosts",
",",
"hostname",
"=>",
"{",
"const",
"sites",
"=",
"_",
".",
"filter",
"(",
"sitesMap",
",",
"{",
"host",
":",
"hostname",
"}",
")",
".",
"sort",
"(",
"sortByDepthOfPath",
")",
";",
"addHost",
"(",
"{",
"router",
",",
"hostname",
",",
"sites",
",",
"providers",
",",
"sessionStore",
"}",
")",
";",
"}",
")",
";",
"return",
"router",
";",
"}"
] |
Loads sites config and attach the basic routes for each one.
@param {express.Router} router - Often an express app.
@param {Array} [providers]
@param {Object} [sessionStore]
@returns {*}
@example
var app = express();
require('./routes)(app);
|
[
"Loads",
"sites",
"config",
"and",
"attach",
"the",
"basic",
"routes",
"for",
"each",
"one",
"."
] |
b883a94cbc38c1891ce568addb6cb280aa1d5353
|
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/routes.js#L307-L325
|
train
|
clay/amphora
|
lib/bootstrap.js
|
getConfig
|
function getConfig(dir) {
dir = path.resolve(dir);
if (dir.indexOf('.', 2) > 0) {
// remove extension
dir = dir.substring(0, dir.indexOf('.', 2));
}
if (files.isDirectory(dir)) {
// default to bootstrap.yaml or bootstrap.yml
dir = path.join(dir, 'bootstrap');
}
return files.getYaml(dir);
}
|
javascript
|
function getConfig(dir) {
dir = path.resolve(dir);
if (dir.indexOf('.', 2) > 0) {
// remove extension
dir = dir.substring(0, dir.indexOf('.', 2));
}
if (files.isDirectory(dir)) {
// default to bootstrap.yaml or bootstrap.yml
dir = path.join(dir, 'bootstrap');
}
return files.getYaml(dir);
}
|
[
"function",
"getConfig",
"(",
"dir",
")",
"{",
"dir",
"=",
"path",
".",
"resolve",
"(",
"dir",
")",
";",
"if",
"(",
"dir",
".",
"indexOf",
"(",
"'.'",
",",
"2",
")",
">",
"0",
")",
"{",
"dir",
"=",
"dir",
".",
"substring",
"(",
"0",
",",
"dir",
".",
"indexOf",
"(",
"'.'",
",",
"2",
")",
")",
";",
"}",
"if",
"(",
"files",
".",
"isDirectory",
"(",
"dir",
")",
")",
"{",
"dir",
"=",
"path",
".",
"join",
"(",
"dir",
",",
"'bootstrap'",
")",
";",
"}",
"return",
"files",
".",
"getYaml",
"(",
"dir",
")",
";",
"}"
] |
Get yaml file as object
@param {string} dir
@returns {object}
|
[
"Get",
"yaml",
"file",
"as",
"object"
] |
b883a94cbc38c1891ce568addb6cb280aa1d5353
|
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/bootstrap.js#L30-L44
|
train
|
clay/amphora
|
lib/bootstrap.js
|
saveWithInstances
|
function saveWithInstances(dbPath, list, save) {
const promises = [];
// load item defaults
_.each(list, function (item, itemName) {
let obj = _.omit(item, 'instances');
if (_.isObject(item)) {
obj = _.omit(item, 'instances');
if (_.size(obj) > 0) {
promises.push(save(dbPath + itemName, obj));
}
if (item && item.instances) {
// load instances
_.each(item.instances, function (instance, instanceId) {
if (_.size(instance) > 0) {
promises.push(save(dbPath + itemName + '/instances/' + instanceId, instance));
}
});
}
}
});
return bluebird.all(promises);
}
|
javascript
|
function saveWithInstances(dbPath, list, save) {
const promises = [];
// load item defaults
_.each(list, function (item, itemName) {
let obj = _.omit(item, 'instances');
if (_.isObject(item)) {
obj = _.omit(item, 'instances');
if (_.size(obj) > 0) {
promises.push(save(dbPath + itemName, obj));
}
if (item && item.instances) {
// load instances
_.each(item.instances, function (instance, instanceId) {
if (_.size(instance) > 0) {
promises.push(save(dbPath + itemName + '/instances/' + instanceId, instance));
}
});
}
}
});
return bluebird.all(promises);
}
|
[
"function",
"saveWithInstances",
"(",
"dbPath",
",",
"list",
",",
"save",
")",
"{",
"const",
"promises",
"=",
"[",
"]",
";",
"_",
".",
"each",
"(",
"list",
",",
"function",
"(",
"item",
",",
"itemName",
")",
"{",
"let",
"obj",
"=",
"_",
".",
"omit",
"(",
"item",
",",
"'instances'",
")",
";",
"if",
"(",
"_",
".",
"isObject",
"(",
"item",
")",
")",
"{",
"obj",
"=",
"_",
".",
"omit",
"(",
"item",
",",
"'instances'",
")",
";",
"if",
"(",
"_",
".",
"size",
"(",
"obj",
")",
">",
"0",
")",
"{",
"promises",
".",
"push",
"(",
"save",
"(",
"dbPath",
"+",
"itemName",
",",
"obj",
")",
")",
";",
"}",
"if",
"(",
"item",
"&&",
"item",
".",
"instances",
")",
"{",
"_",
".",
"each",
"(",
"item",
".",
"instances",
",",
"function",
"(",
"instance",
",",
"instanceId",
")",
"{",
"if",
"(",
"_",
".",
"size",
"(",
"instance",
")",
">",
"0",
")",
"{",
"promises",
".",
"push",
"(",
"save",
"(",
"dbPath",
"+",
"itemName",
"+",
"'/instances/'",
"+",
"instanceId",
",",
"instance",
")",
")",
";",
"}",
"}",
")",
";",
"}",
"}",
"}",
")",
";",
"return",
"bluebird",
".",
"all",
"(",
"promises",
")",
";",
"}"
] |
Component specific loading.
@param {string} dbPath
@param {object} list
@param {function} save
@returns {Promise}
|
[
"Component",
"specific",
"loading",
"."
] |
b883a94cbc38c1891ce568addb6cb280aa1d5353
|
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/bootstrap.js#L68-L94
|
train
|
clay/amphora
|
lib/bootstrap.js
|
saveBase64Strings
|
function saveBase64Strings(dbPath, list, save) {
return bluebird.all(_.map(list, function (item, itemName) {
return save(dbPath + buf.encode(itemName), item);
}));
}
|
javascript
|
function saveBase64Strings(dbPath, list, save) {
return bluebird.all(_.map(list, function (item, itemName) {
return save(dbPath + buf.encode(itemName), item);
}));
}
|
[
"function",
"saveBase64Strings",
"(",
"dbPath",
",",
"list",
",",
"save",
")",
"{",
"return",
"bluebird",
".",
"all",
"(",
"_",
".",
"map",
"(",
"list",
",",
"function",
"(",
"item",
",",
"itemName",
")",
"{",
"return",
"save",
"(",
"dbPath",
"+",
"buf",
".",
"encode",
"(",
"itemName",
")",
",",
"item",
")",
";",
"}",
")",
")",
";",
"}"
] |
Page specific loading. This will probably grow differently than component loading, so different function to
contain it.
@param {string} dbPath
@param {object} list
@param {function} save
@returns {Promise}
|
[
"Page",
"specific",
"loading",
".",
"This",
"will",
"probably",
"grow",
"differently",
"than",
"component",
"loading",
"so",
"different",
"function",
"to",
"contain",
"it",
"."
] |
b883a94cbc38c1891ce568addb6cb280aa1d5353
|
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/bootstrap.js#L104-L108
|
train
|
clay/amphora
|
lib/bootstrap.js
|
load
|
function load(data, site) {
let promiseComponentsOps, promisePagesOps, promiseUrisOps, promiseListsOps, promiseUsersOps,
prefix = site.prefix,
compData = applyPrefix(data, site);
promiseListsOps = saveObjects(`${prefix}/_lists/`, compData._lists, getPutOperation);
promiseUrisOps = saveBase64Strings(`${prefix}/_uris/`, compData._uris, getPutOperation);
_.each(compData._uris, function (page, uri) {
log('info', `bootstrapped: ${uri} => ${page}`);
});
promiseComponentsOps = saveWithInstances(`${prefix}/_components/`, compData._components, function (name, item) {
return bluebird.join(
dbOps.getPutOperations(components.cmptPut, name, _.cloneDeep(item), locals.getDefaultLocals(site))
).then(_.flatten);
});
promisePagesOps = saveObjects(`${prefix}/_pages/`, compData._pages, (name, item) => [getPutOperation(name, item)]);
promiseUsersOps = saveObjects('', compData._users, (name, item) => [getPutOperation(`/_users/${encode(`${item.username}@${item.provider}`)}`, item)]);
/* eslint max-params: ["error", 5] */
return bluebird.join(promiseComponentsOps, promisePagesOps, promiseUrisOps, promiseListsOps, promiseUsersOps, function (componentsOps, pagesOps, urisOps, listsOps, userOps) {
const flatComponentsOps = _.flatten(componentsOps),
ops = flatComponentsOps.concat(_.flattenDeep(pagesOps.concat(urisOps, listsOps, userOps)));
return db.batch(ops, { fillCache: false, sync: false });
});
}
|
javascript
|
function load(data, site) {
let promiseComponentsOps, promisePagesOps, promiseUrisOps, promiseListsOps, promiseUsersOps,
prefix = site.prefix,
compData = applyPrefix(data, site);
promiseListsOps = saveObjects(`${prefix}/_lists/`, compData._lists, getPutOperation);
promiseUrisOps = saveBase64Strings(`${prefix}/_uris/`, compData._uris, getPutOperation);
_.each(compData._uris, function (page, uri) {
log('info', `bootstrapped: ${uri} => ${page}`);
});
promiseComponentsOps = saveWithInstances(`${prefix}/_components/`, compData._components, function (name, item) {
return bluebird.join(
dbOps.getPutOperations(components.cmptPut, name, _.cloneDeep(item), locals.getDefaultLocals(site))
).then(_.flatten);
});
promisePagesOps = saveObjects(`${prefix}/_pages/`, compData._pages, (name, item) => [getPutOperation(name, item)]);
promiseUsersOps = saveObjects('', compData._users, (name, item) => [getPutOperation(`/_users/${encode(`${item.username}@${item.provider}`)}`, item)]);
/* eslint max-params: ["error", 5] */
return bluebird.join(promiseComponentsOps, promisePagesOps, promiseUrisOps, promiseListsOps, promiseUsersOps, function (componentsOps, pagesOps, urisOps, listsOps, userOps) {
const flatComponentsOps = _.flatten(componentsOps),
ops = flatComponentsOps.concat(_.flattenDeep(pagesOps.concat(urisOps, listsOps, userOps)));
return db.batch(ops, { fillCache: false, sync: false });
});
}
|
[
"function",
"load",
"(",
"data",
",",
"site",
")",
"{",
"let",
"promiseComponentsOps",
",",
"promisePagesOps",
",",
"promiseUrisOps",
",",
"promiseListsOps",
",",
"promiseUsersOps",
",",
"prefix",
"=",
"site",
".",
"prefix",
",",
"compData",
"=",
"applyPrefix",
"(",
"data",
",",
"site",
")",
";",
"promiseListsOps",
"=",
"saveObjects",
"(",
"`",
"${",
"prefix",
"}",
"`",
",",
"compData",
".",
"_lists",
",",
"getPutOperation",
")",
";",
"promiseUrisOps",
"=",
"saveBase64Strings",
"(",
"`",
"${",
"prefix",
"}",
"`",
",",
"compData",
".",
"_uris",
",",
"getPutOperation",
")",
";",
"_",
".",
"each",
"(",
"compData",
".",
"_uris",
",",
"function",
"(",
"page",
",",
"uri",
")",
"{",
"log",
"(",
"'info'",
",",
"`",
"${",
"uri",
"}",
"${",
"page",
"}",
"`",
")",
";",
"}",
")",
";",
"promiseComponentsOps",
"=",
"saveWithInstances",
"(",
"`",
"${",
"prefix",
"}",
"`",
",",
"compData",
".",
"_components",
",",
"function",
"(",
"name",
",",
"item",
")",
"{",
"return",
"bluebird",
".",
"join",
"(",
"dbOps",
".",
"getPutOperations",
"(",
"components",
".",
"cmptPut",
",",
"name",
",",
"_",
".",
"cloneDeep",
"(",
"item",
")",
",",
"locals",
".",
"getDefaultLocals",
"(",
"site",
")",
")",
")",
".",
"then",
"(",
"_",
".",
"flatten",
")",
";",
"}",
")",
";",
"promisePagesOps",
"=",
"saveObjects",
"(",
"`",
"${",
"prefix",
"}",
"`",
",",
"compData",
".",
"_pages",
",",
"(",
"name",
",",
"item",
")",
"=>",
"[",
"getPutOperation",
"(",
"name",
",",
"item",
")",
"]",
")",
";",
"promiseUsersOps",
"=",
"saveObjects",
"(",
"''",
",",
"compData",
".",
"_users",
",",
"(",
"name",
",",
"item",
")",
"=>",
"[",
"getPutOperation",
"(",
"`",
"${",
"encode",
"(",
"`",
"${",
"item",
".",
"username",
"}",
"${",
"item",
".",
"provider",
"}",
"`",
")",
"}",
"`",
",",
"item",
")",
"]",
")",
";",
"return",
"bluebird",
".",
"join",
"(",
"promiseComponentsOps",
",",
"promisePagesOps",
",",
"promiseUrisOps",
",",
"promiseListsOps",
",",
"promiseUsersOps",
",",
"function",
"(",
"componentsOps",
",",
"pagesOps",
",",
"urisOps",
",",
"listsOps",
",",
"userOps",
")",
"{",
"const",
"flatComponentsOps",
"=",
"_",
".",
"flatten",
"(",
"componentsOps",
")",
",",
"ops",
"=",
"flatComponentsOps",
".",
"concat",
"(",
"_",
".",
"flattenDeep",
"(",
"pagesOps",
".",
"concat",
"(",
"urisOps",
",",
"listsOps",
",",
"userOps",
")",
")",
")",
";",
"return",
"db",
".",
"batch",
"(",
"ops",
",",
"{",
"fillCache",
":",
"false",
",",
"sync",
":",
"false",
"}",
")",
";",
"}",
")",
";",
"}"
] |
Load items into db from config object
@param {object} data
@param {object} site
@returns {Promise}
|
[
"Load",
"items",
"into",
"db",
"from",
"config",
"object"
] |
b883a94cbc38c1891ce568addb6cb280aa1d5353
|
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/bootstrap.js#L208-L233
|
train
|
clay/amphora
|
lib/bootstrap.js
|
bootstrapPath
|
function bootstrapPath(dir, site) {
let promise,
data = getConfig(dir);
if (data) {
promise = load(data, site);
} else {
promise = Promise.reject(new Error(`No bootstrap found at ${dir}`));
}
return promise;
}
|
javascript
|
function bootstrapPath(dir, site) {
let promise,
data = getConfig(dir);
if (data) {
promise = load(data, site);
} else {
promise = Promise.reject(new Error(`No bootstrap found at ${dir}`));
}
return promise;
}
|
[
"function",
"bootstrapPath",
"(",
"dir",
",",
"site",
")",
"{",
"let",
"promise",
",",
"data",
"=",
"getConfig",
"(",
"dir",
")",
";",
"if",
"(",
"data",
")",
"{",
"promise",
"=",
"load",
"(",
"data",
",",
"site",
")",
";",
"}",
"else",
"{",
"promise",
"=",
"Promise",
".",
"reject",
"(",
"new",
"Error",
"(",
"`",
"${",
"dir",
"}",
"`",
")",
")",
";",
"}",
"return",
"promise",
";",
"}"
] |
Load items into db from yaml file
@param {string} dir
@param {object} site
@returns {Promise}
|
[
"Load",
"items",
"into",
"db",
"from",
"yaml",
"file"
] |
b883a94cbc38c1891ce568addb6cb280aa1d5353
|
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/bootstrap.js#L241-L252
|
train
|
clay/amphora
|
lib/bootstrap.js
|
bootstrapError
|
function bootstrapError(component, e) {
if (ERRORING_COMPONENTS.indexOf(component) === -1) {
ERRORING_COMPONENTS.push(component);
log('error', `Error bootstrapping component ${component}: ${e.message}`);
}
return bluebird.reject();
}
|
javascript
|
function bootstrapError(component, e) {
if (ERRORING_COMPONENTS.indexOf(component) === -1) {
ERRORING_COMPONENTS.push(component);
log('error', `Error bootstrapping component ${component}: ${e.message}`);
}
return bluebird.reject();
}
|
[
"function",
"bootstrapError",
"(",
"component",
",",
"e",
")",
"{",
"if",
"(",
"ERRORING_COMPONENTS",
".",
"indexOf",
"(",
"component",
")",
"===",
"-",
"1",
")",
"{",
"ERRORING_COMPONENTS",
".",
"push",
"(",
"component",
")",
";",
"log",
"(",
"'error'",
",",
"`",
"${",
"component",
"}",
"${",
"e",
".",
"message",
"}",
"`",
")",
";",
"}",
"return",
"bluebird",
".",
"reject",
"(",
")",
";",
"}"
] |
Log a bootstrapping error for if one exists
for a component.
@param {String} component
@param {Error} e
@return {Promise}
|
[
"Log",
"a",
"bootstrapping",
"error",
"for",
"if",
"one",
"exists",
"for",
"a",
"component",
"."
] |
b883a94cbc38c1891ce568addb6cb280aa1d5353
|
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/bootstrap.js#L274-L281
|
train
|
clay/amphora
|
lib/bootstrap.js
|
bootrapSitesAndComponents
|
function bootrapSitesAndComponents() {
const sites = siteService.sites(),
sitesArray = _.map(Object.keys(sites), site => sites[site]);
return highland(sitesArray)
.flatMap(site => {
return highland(
bootstrapComponents(site)
.then(function () {
return site;
})
.catch(function () {
log('debug', `Errors bootstrapping components for site: ${site.slug}`);
return site;
})
);
})
.flatMap(site => {
return highland(
bootstrapPath(site.dir, site)
.catch(function () {
log('debug', `No bootstrap file found for site: ${site.slug}`);
return site;
})
);
})
.collect()
.toPromise(bluebird);
}
|
javascript
|
function bootrapSitesAndComponents() {
const sites = siteService.sites(),
sitesArray = _.map(Object.keys(sites), site => sites[site]);
return highland(sitesArray)
.flatMap(site => {
return highland(
bootstrapComponents(site)
.then(function () {
return site;
})
.catch(function () {
log('debug', `Errors bootstrapping components for site: ${site.slug}`);
return site;
})
);
})
.flatMap(site => {
return highland(
bootstrapPath(site.dir, site)
.catch(function () {
log('debug', `No bootstrap file found for site: ${site.slug}`);
return site;
})
);
})
.collect()
.toPromise(bluebird);
}
|
[
"function",
"bootrapSitesAndComponents",
"(",
")",
"{",
"const",
"sites",
"=",
"siteService",
".",
"sites",
"(",
")",
",",
"sitesArray",
"=",
"_",
".",
"map",
"(",
"Object",
".",
"keys",
"(",
"sites",
")",
",",
"site",
"=>",
"sites",
"[",
"site",
"]",
")",
";",
"return",
"highland",
"(",
"sitesArray",
")",
".",
"flatMap",
"(",
"site",
"=>",
"{",
"return",
"highland",
"(",
"bootstrapComponents",
"(",
"site",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"return",
"site",
";",
"}",
")",
".",
"catch",
"(",
"function",
"(",
")",
"{",
"log",
"(",
"'debug'",
",",
"`",
"${",
"site",
".",
"slug",
"}",
"`",
")",
";",
"return",
"site",
";",
"}",
")",
")",
";",
"}",
")",
".",
"flatMap",
"(",
"site",
"=>",
"{",
"return",
"highland",
"(",
"bootstrapPath",
"(",
"site",
".",
"dir",
",",
"site",
")",
".",
"catch",
"(",
"function",
"(",
")",
"{",
"log",
"(",
"'debug'",
",",
"`",
"${",
"site",
".",
"slug",
"}",
"`",
")",
";",
"return",
"site",
";",
"}",
")",
")",
";",
"}",
")",
".",
"collect",
"(",
")",
".",
"toPromise",
"(",
"bluebird",
")",
";",
"}"
] |
Bootstrap all sites and the individual
bootstrap files in each component's directory
@return {Promise}
|
[
"Bootstrap",
"all",
"sites",
"and",
"the",
"individual",
"bootstrap",
"files",
"in",
"each",
"component",
"s",
"directory"
] |
b883a94cbc38c1891ce568addb6cb280aa1d5353
|
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/bootstrap.js#L289-L317
|
train
|
clay/amphora
|
lib/services/db-operations.js
|
replacePropagatingVersions
|
function replacePropagatingVersions(uri, data) {
if (references.isPropagatingVersion(uri)) {
references.replaceAllVersions(uri.split('@')[1])(data);
}
return data;
}
|
javascript
|
function replacePropagatingVersions(uri, data) {
if (references.isPropagatingVersion(uri)) {
references.replaceAllVersions(uri.split('@')[1])(data);
}
return data;
}
|
[
"function",
"replacePropagatingVersions",
"(",
"uri",
",",
"data",
")",
"{",
"if",
"(",
"references",
".",
"isPropagatingVersion",
"(",
"uri",
")",
")",
"{",
"references",
".",
"replaceAllVersions",
"(",
"uri",
".",
"split",
"(",
"'@'",
")",
"[",
"1",
"]",
")",
"(",
"data",
")",
";",
"}",
"return",
"data",
";",
"}"
] |
If the ref has a version that is "propagating" like @published or @latest, replace all versions in the data
with the new version (in-place).
@param {string} uri
@param {object} data
@returns {object}
|
[
"If",
"the",
"ref",
"has",
"a",
"version",
"that",
"is",
"propagating",
"like"
] |
b883a94cbc38c1891ce568addb6cb280aa1d5353
|
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/services/db-operations.js#L45-L51
|
train
|
clay/amphora
|
lib/services/db-operations.js
|
splitCascadingData
|
function splitCascadingData(uri, data) {
let ops, list;
// search for _ref with _size greater than 1
list = references.listDeepObjects(data, isReferencedAndReal);
ops = _.map(list.reverse(), function (obj) {
const ref = obj[referenceProperty],
// since children are before parents, no one will see data below them
op = {key: ref, value: _.omit(obj, referenceProperty)};
// omit cloned 1 level deep and we clear what omit cloned from obj
// so the op gets the first level of data, but it's removed from the main obj
clearOwnProperties(obj);
obj[referenceProperty] = ref;
return op;
});
// add the cleaned root object at the end
ops.push({key: uri, value: data});
return ops;
}
|
javascript
|
function splitCascadingData(uri, data) {
let ops, list;
// search for _ref with _size greater than 1
list = references.listDeepObjects(data, isReferencedAndReal);
ops = _.map(list.reverse(), function (obj) {
const ref = obj[referenceProperty],
// since children are before parents, no one will see data below them
op = {key: ref, value: _.omit(obj, referenceProperty)};
// omit cloned 1 level deep and we clear what omit cloned from obj
// so the op gets the first level of data, but it's removed from the main obj
clearOwnProperties(obj);
obj[referenceProperty] = ref;
return op;
});
// add the cleaned root object at the end
ops.push({key: uri, value: data});
return ops;
}
|
[
"function",
"splitCascadingData",
"(",
"uri",
",",
"data",
")",
"{",
"let",
"ops",
",",
"list",
";",
"list",
"=",
"references",
".",
"listDeepObjects",
"(",
"data",
",",
"isReferencedAndReal",
")",
";",
"ops",
"=",
"_",
".",
"map",
"(",
"list",
".",
"reverse",
"(",
")",
",",
"function",
"(",
"obj",
")",
"{",
"const",
"ref",
"=",
"obj",
"[",
"referenceProperty",
"]",
",",
"op",
"=",
"{",
"key",
":",
"ref",
",",
"value",
":",
"_",
".",
"omit",
"(",
"obj",
",",
"referenceProperty",
")",
"}",
";",
"clearOwnProperties",
"(",
"obj",
")",
";",
"obj",
"[",
"referenceProperty",
"]",
"=",
"ref",
";",
"return",
"op",
";",
"}",
")",
";",
"ops",
".",
"push",
"(",
"{",
"key",
":",
"uri",
",",
"value",
":",
"data",
"}",
")",
";",
"return",
"ops",
";",
"}"
] |
Split cascading component data into individual components
@param {string} uri Root reference in uri form
@param {object} data Cascading component data
@returns {[{key: string, value: object}]}
|
[
"Split",
"cascading",
"component",
"data",
"into",
"individual",
"components"
] |
b883a94cbc38c1891ce568addb6cb280aa1d5353
|
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/services/db-operations.js#L59-L81
|
train
|
clay/amphora
|
lib/services/db-operations.js
|
getPutOperations
|
function getPutOperations(putFn, uri, data, locals) {
// potentially propagate version throughout object
const cmptOrLayout = splitCascadingData(uri, replacePropagatingVersions(uri, data));
// if locals exist and there are more than one component being put,
// then we should pass a read-only version to each component so they can't affect each other
// this operation isn't needed in the common case of putting a single object
if (!!locals && cmptOrLayout.length > 0) {
locals = control.setReadOnly(_.cloneDeep(locals));
}
// run each through the normal put, which may or may not hit custom component logic
return bluebird.map(cmptOrLayout, ({ key, value }) => putFn(key, value, locals))
.then(ops => _.filter(_.flattenDeep(ops), _.identity));
}
|
javascript
|
function getPutOperations(putFn, uri, data, locals) {
// potentially propagate version throughout object
const cmptOrLayout = splitCascadingData(uri, replacePropagatingVersions(uri, data));
// if locals exist and there are more than one component being put,
// then we should pass a read-only version to each component so they can't affect each other
// this operation isn't needed in the common case of putting a single object
if (!!locals && cmptOrLayout.length > 0) {
locals = control.setReadOnly(_.cloneDeep(locals));
}
// run each through the normal put, which may or may not hit custom component logic
return bluebird.map(cmptOrLayout, ({ key, value }) => putFn(key, value, locals))
.then(ops => _.filter(_.flattenDeep(ops), _.identity));
}
|
[
"function",
"getPutOperations",
"(",
"putFn",
",",
"uri",
",",
"data",
",",
"locals",
")",
"{",
"const",
"cmptOrLayout",
"=",
"splitCascadingData",
"(",
"uri",
",",
"replacePropagatingVersions",
"(",
"uri",
",",
"data",
")",
")",
";",
"if",
"(",
"!",
"!",
"locals",
"&&",
"cmptOrLayout",
".",
"length",
">",
"0",
")",
"{",
"locals",
"=",
"control",
".",
"setReadOnly",
"(",
"_",
".",
"cloneDeep",
"(",
"locals",
")",
")",
";",
"}",
"return",
"bluebird",
".",
"map",
"(",
"cmptOrLayout",
",",
"(",
"{",
"key",
",",
"value",
"}",
")",
"=>",
"putFn",
"(",
"key",
",",
"value",
",",
"locals",
")",
")",
".",
"then",
"(",
"ops",
"=>",
"_",
".",
"filter",
"(",
"_",
".",
"flattenDeep",
"(",
"ops",
")",
",",
"_",
".",
"identity",
")",
")",
";",
"}"
] |
Get a list of all the put operations needed to complete a cascading PUT
NOTE: this function changes the data object _in-place_ for speed and memory reasons. We are not okay with doing
a deep clone here, because that will significantly slow down this operation. If someone wants to deep clone the data
before this operation, they can.
@param {Function} putFn
@param {String} uri
@param {Object} data
@param {Object} [locals]
@returns {Promise}
|
[
"Get",
"a",
"list",
"of",
"all",
"the",
"put",
"operations",
"needed",
"to",
"complete",
"a",
"cascading",
"PUT"
] |
b883a94cbc38c1891ce568addb6cb280aa1d5353
|
https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/services/db-operations.js#L96-L110
|
train
|
gregtillbrook/parcel-plugin-bundle-visualiser
|
src/buildReportAssets/init.js
|
function(e) {
e.preventDefault();
var group = e.group;
var toZoom;
if (group) {
toZoom = e.secondary ? group.parent : group;
} else {
toZoom = this.get('dataObject');
}
this.zoom(toZoom);
}
|
javascript
|
function(e) {
e.preventDefault();
var group = e.group;
var toZoom;
if (group) {
toZoom = e.secondary ? group.parent : group;
} else {
toZoom = this.get('dataObject');
}
this.zoom(toZoom);
}
|
[
"function",
"(",
"e",
")",
"{",
"e",
".",
"preventDefault",
"(",
")",
";",
"var",
"group",
"=",
"e",
".",
"group",
";",
"var",
"toZoom",
";",
"if",
"(",
"group",
")",
"{",
"toZoom",
"=",
"e",
".",
"secondary",
"?",
"group",
".",
"parent",
":",
"group",
";",
"}",
"else",
"{",
"toZoom",
"=",
"this",
".",
"get",
"(",
"'dataObject'",
")",
";",
"}",
"this",
".",
"zoom",
"(",
"toZoom",
")",
";",
"}"
] |
zoom to group rather than that weird pop out thing
|
[
"zoom",
"to",
"group",
"rather",
"than",
"that",
"weird",
"pop",
"out",
"thing"
] |
ca5440fc61c85e40e7abc220ad99e274c7c104c6
|
https://github.com/gregtillbrook/parcel-plugin-bundle-visualiser/blob/ca5440fc61c85e40e7abc220ad99e274c7c104c6/src/buildReportAssets/init.js#L34-L44
|
train
|
|
gregtillbrook/parcel-plugin-bundle-visualiser
|
src/buildTreeData.js
|
formatProjectPath
|
function formatProjectPath(filePath = '') {
let dir = path.relative(process.cwd(), path.dirname(filePath));
return dir + (dir ? path.sep : '') + path.basename(filePath);
}
|
javascript
|
function formatProjectPath(filePath = '') {
let dir = path.relative(process.cwd(), path.dirname(filePath));
return dir + (dir ? path.sep : '') + path.basename(filePath);
}
|
[
"function",
"formatProjectPath",
"(",
"filePath",
"=",
"''",
")",
"{",
"let",
"dir",
"=",
"path",
".",
"relative",
"(",
"process",
".",
"cwd",
"(",
")",
",",
"path",
".",
"dirname",
"(",
"filePath",
")",
")",
";",
"return",
"dir",
"+",
"(",
"dir",
"?",
"path",
".",
"sep",
":",
"''",
")",
"+",
"path",
".",
"basename",
"(",
"filePath",
")",
";",
"}"
] |
path relative to project root
|
[
"path",
"relative",
"to",
"project",
"root"
] |
ca5440fc61c85e40e7abc220ad99e274c7c104c6
|
https://github.com/gregtillbrook/parcel-plugin-bundle-visualiser/blob/ca5440fc61c85e40e7abc220ad99e274c7c104c6/src/buildTreeData.js#L132-L135
|
train
|
jdalton/docdown
|
lib/util.js
|
format
|
function format(string) {
string = _.toString(string);
// Replace all code snippets with a token.
var snippets = [];
string = string.replace(reCode, function(match) {
snippets.push(match);
return token;
});
return string
// Add line breaks.
.replace(/:\n(?=[\t ]*\S)/g, ':<br>\n')
.replace(/\n( *)[-*](?=[\t ]+\S)/g, '\n<br>\n$1*')
.replace(/^[\t ]*\n/gm, '<br>\n<br>\n')
// Normalize whitespace.
.replace(/\n +/g, ' ')
// Italicize parentheses.
.replace(/(^|\s)(\(.+\))/g, '$1*$2*')
// Mark numbers as inline code.
.replace(/[\t ](-?\d+(?:.\d+)?)(?!\.[^\n])/g, ' `$1`')
// Replace all tokens with code snippets.
.replace(reToken, function(match) {
return snippets.shift();
})
.trim();
}
|
javascript
|
function format(string) {
string = _.toString(string);
// Replace all code snippets with a token.
var snippets = [];
string = string.replace(reCode, function(match) {
snippets.push(match);
return token;
});
return string
// Add line breaks.
.replace(/:\n(?=[\t ]*\S)/g, ':<br>\n')
.replace(/\n( *)[-*](?=[\t ]+\S)/g, '\n<br>\n$1*')
.replace(/^[\t ]*\n/gm, '<br>\n<br>\n')
// Normalize whitespace.
.replace(/\n +/g, ' ')
// Italicize parentheses.
.replace(/(^|\s)(\(.+\))/g, '$1*$2*')
// Mark numbers as inline code.
.replace(/[\t ](-?\d+(?:.\d+)?)(?!\.[^\n])/g, ' `$1`')
// Replace all tokens with code snippets.
.replace(reToken, function(match) {
return snippets.shift();
})
.trim();
}
|
[
"function",
"format",
"(",
"string",
")",
"{",
"string",
"=",
"_",
".",
"toString",
"(",
"string",
")",
";",
"var",
"snippets",
"=",
"[",
"]",
";",
"string",
"=",
"string",
".",
"replace",
"(",
"reCode",
",",
"function",
"(",
"match",
")",
"{",
"snippets",
".",
"push",
"(",
"match",
")",
";",
"return",
"token",
";",
"}",
")",
";",
"return",
"string",
".",
"replace",
"(",
"/",
":\\n(?=[\\t ]*\\S)",
"/",
"g",
",",
"':<br>\\n'",
")",
".",
"\\n",
"replace",
".",
"(",
"/",
"\\n( *)[-*](?=[\\t ]+\\S)",
"/",
"g",
",",
"'\\n<br>\\n$1*'",
")",
"\\n",
".",
"\\n",
"replace",
".",
"(",
"/",
"^[\\t ]*\\n",
"/",
"gm",
",",
"'<br>\\n<br>\\n'",
")",
"\\n",
".",
"\\n",
"replace",
".",
"(",
"/",
"\\n +",
"/",
"g",
",",
"' '",
")",
"replace",
".",
"(",
"/",
"(^|\\s)(\\(.+\\))",
"/",
"g",
",",
"'$1*$2*'",
")",
"replace",
";",
"}"
] |
Performs common string formatting operations.
@memberOf util
@param {string} string The string to format.
@returns {string} Returns the formatted string.
|
[
"Performs",
"common",
"string",
"formatting",
"operations",
"."
] |
297e61f2ef179b4cebca9656cb4eac2dbdd18669
|
https://github.com/jdalton/docdown/blob/297e61f2ef179b4cebca9656cb4eac2dbdd18669/lib/util.js#L50-L76
|
train
|
jdalton/docdown
|
index.js
|
docdown
|
function docdown(options) {
options = _.defaults(options, {
'lang': 'js',
'sort': true,
'style': 'default',
'title': path.basename(options.path) + ' API documentation',
'toc': 'properties'
});
if (!options.path || !options.url) {
throw new Error('Path and URL must be specified');
}
return generator(fs.readFileSync(options.path, 'utf8'), options);
}
|
javascript
|
function docdown(options) {
options = _.defaults(options, {
'lang': 'js',
'sort': true,
'style': 'default',
'title': path.basename(options.path) + ' API documentation',
'toc': 'properties'
});
if (!options.path || !options.url) {
throw new Error('Path and URL must be specified');
}
return generator(fs.readFileSync(options.path, 'utf8'), options);
}
|
[
"function",
"docdown",
"(",
"options",
")",
"{",
"options",
"=",
"_",
".",
"defaults",
"(",
"options",
",",
"{",
"'lang'",
":",
"'js'",
",",
"'sort'",
":",
"true",
",",
"'style'",
":",
"'default'",
",",
"'title'",
":",
"path",
".",
"basename",
"(",
"options",
".",
"path",
")",
"+",
"' API documentation'",
",",
"'toc'",
":",
"'properties'",
"}",
")",
";",
"if",
"(",
"!",
"options",
".",
"path",
"||",
"!",
"options",
".",
"url",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Path and URL must be specified'",
")",
";",
"}",
"return",
"generator",
"(",
"fs",
".",
"readFileSync",
"(",
"options",
".",
"path",
",",
"'utf8'",
")",
",",
"options",
")",
";",
"}"
] |
Generates Markdown documentation based on JSDoc comments.
@param {Object} options The options object.
@param {string} options.path The input file path.
@param {string} options.url The source URL.
@param {string} [options.lang='js'] The language indicator for code blocks.
@param {boolean} [options.sort=true] Specify whether entries are sorted.
@param {string} [options.style='default'] The hash style for links ('default' or 'github').
@param {string} [options.title='<%= basename(options.path) %> API documentation'] The documentation title.
@param {string} [options.toc='properties'] The table of contents organization style ('categories' or 'properties').
@returns {string} The generated Markdown code.
|
[
"Generates",
"Markdown",
"documentation",
"based",
"on",
"JSDoc",
"comments",
"."
] |
297e61f2ef179b4cebca9656cb4eac2dbdd18669
|
https://github.com/jdalton/docdown/blob/297e61f2ef179b4cebca9656cb4eac2dbdd18669/index.js#L26-L39
|
train
|
jdalton/docdown
|
lib/entry.js
|
getTag
|
function getTag(entry, tagName) {
var parsed = entry.parsed;
return _.find(parsed.tags, ['title', tagName]) || null;
}
|
javascript
|
function getTag(entry, tagName) {
var parsed = entry.parsed;
return _.find(parsed.tags, ['title', tagName]) || null;
}
|
[
"function",
"getTag",
"(",
"entry",
",",
"tagName",
")",
"{",
"var",
"parsed",
"=",
"entry",
".",
"parsed",
";",
"return",
"_",
".",
"find",
"(",
"parsed",
".",
"tags",
",",
"[",
"'title'",
",",
"tagName",
"]",
")",
"||",
"null",
";",
"}"
] |
Gets an `entry` tag by `tagName`.
@private
@param {Object} entry The entry to inspect.
@param {string} tagName The name of the tag.
@returns {null|Object} Returns the tag.
|
[
"Gets",
"an",
"entry",
"tag",
"by",
"tagName",
"."
] |
297e61f2ef179b4cebca9656cb4eac2dbdd18669
|
https://github.com/jdalton/docdown/blob/297e61f2ef179b4cebca9656cb4eac2dbdd18669/lib/entry.js#L72-L75
|
train
|
jdalton/docdown
|
lib/entry.js
|
getValue
|
function getValue(entry, tagName) {
var parsed = entry.parsed,
result = parsed.description,
tag = getTag(entry, tagName);
if (tagName == 'alias') {
result = _.get(tag, 'name') ;
// Doctrine can't parse alias tags containing multiple values so extract
// them from the error message.
var error = _.first(_.get(tag, 'errors'));
if (error) {
result += error.replace(/^[^']*'|'[^']*$/g, '');
}
}
else if (tagName == 'type') {
result = _.get(tag, 'type.name');
}
else if (tagName != 'description') {
result = _.get(tag, 'name') || _.get(tag, 'description');
}
return tagName == 'example'
? _.toString(result)
: util.format(result);
}
|
javascript
|
function getValue(entry, tagName) {
var parsed = entry.parsed,
result = parsed.description,
tag = getTag(entry, tagName);
if (tagName == 'alias') {
result = _.get(tag, 'name') ;
// Doctrine can't parse alias tags containing multiple values so extract
// them from the error message.
var error = _.first(_.get(tag, 'errors'));
if (error) {
result += error.replace(/^[^']*'|'[^']*$/g, '');
}
}
else if (tagName == 'type') {
result = _.get(tag, 'type.name');
}
else if (tagName != 'description') {
result = _.get(tag, 'name') || _.get(tag, 'description');
}
return tagName == 'example'
? _.toString(result)
: util.format(result);
}
|
[
"function",
"getValue",
"(",
"entry",
",",
"tagName",
")",
"{",
"var",
"parsed",
"=",
"entry",
".",
"parsed",
",",
"result",
"=",
"parsed",
".",
"description",
",",
"tag",
"=",
"getTag",
"(",
"entry",
",",
"tagName",
")",
";",
"if",
"(",
"tagName",
"==",
"'alias'",
")",
"{",
"result",
"=",
"_",
".",
"get",
"(",
"tag",
",",
"'name'",
")",
";",
"var",
"error",
"=",
"_",
".",
"first",
"(",
"_",
".",
"get",
"(",
"tag",
",",
"'errors'",
")",
")",
";",
"if",
"(",
"error",
")",
"{",
"result",
"+=",
"error",
".",
"replace",
"(",
"/",
"^[^']*'|'[^']*$",
"/",
"g",
",",
"''",
")",
";",
"}",
"}",
"else",
"if",
"(",
"tagName",
"==",
"'type'",
")",
"{",
"result",
"=",
"_",
".",
"get",
"(",
"tag",
",",
"'type.name'",
")",
";",
"}",
"else",
"if",
"(",
"tagName",
"!=",
"'description'",
")",
"{",
"result",
"=",
"_",
".",
"get",
"(",
"tag",
",",
"'name'",
")",
"||",
"_",
".",
"get",
"(",
"tag",
",",
"'description'",
")",
";",
"}",
"return",
"tagName",
"==",
"'example'",
"?",
"_",
".",
"toString",
"(",
"result",
")",
":",
"util",
".",
"format",
"(",
"result",
")",
";",
"}"
] |
Gets an `entry` tag value by `tagName`.
@private
@param {Object} entry The entry to inspect.
@param {string} tagName The name of the tag.
@returns {string} Returns the tag value.
|
[
"Gets",
"an",
"entry",
"tag",
"value",
"by",
"tagName",
"."
] |
297e61f2ef179b4cebca9656cb4eac2dbdd18669
|
https://github.com/jdalton/docdown/blob/297e61f2ef179b4cebca9656cb4eac2dbdd18669/lib/entry.js#L85-L109
|
train
|
jdalton/docdown
|
lib/entry.js
|
getAliases
|
function getAliases(index) {
if (this._aliases === undefined) {
var owner = this;
this._aliases = _(getValue(this, 'alias'))
.split(/,\s*/)
.compact()
.sort(util.compareNatural)
.map(function(value) { return new Alias(value, owner); })
.value();
}
var result = this._aliases;
return index === undefined ? result : result[index];
}
|
javascript
|
function getAliases(index) {
if (this._aliases === undefined) {
var owner = this;
this._aliases = _(getValue(this, 'alias'))
.split(/,\s*/)
.compact()
.sort(util.compareNatural)
.map(function(value) { return new Alias(value, owner); })
.value();
}
var result = this._aliases;
return index === undefined ? result : result[index];
}
|
[
"function",
"getAliases",
"(",
"index",
")",
"{",
"if",
"(",
"this",
".",
"_aliases",
"===",
"undefined",
")",
"{",
"var",
"owner",
"=",
"this",
";",
"this",
".",
"_aliases",
"=",
"_",
"(",
"getValue",
"(",
"this",
",",
"'alias'",
")",
")",
".",
"split",
"(",
"/",
",\\s*",
"/",
")",
".",
"compact",
"(",
")",
".",
"sort",
"(",
"util",
".",
"compareNatural",
")",
".",
"map",
"(",
"function",
"(",
"value",
")",
"{",
"return",
"new",
"Alias",
"(",
"value",
",",
"owner",
")",
";",
"}",
")",
".",
"value",
"(",
")",
";",
"}",
"var",
"result",
"=",
"this",
".",
"_aliases",
";",
"return",
"index",
"===",
"undefined",
"?",
"result",
":",
"result",
"[",
"index",
"]",
";",
"}"
] |
Extracts the entry's `alias` objects.
@memberOf Entry
@param {number} index The index of the array value to return.
@returns {Array|string} Returns the entry's `alias` objects.
|
[
"Extracts",
"the",
"entry",
"s",
"alias",
"objects",
"."
] |
297e61f2ef179b4cebca9656cb4eac2dbdd18669
|
https://github.com/jdalton/docdown/blob/297e61f2ef179b4cebca9656cb4eac2dbdd18669/lib/entry.js#L191-L203
|
train
|
jdalton/docdown
|
lib/entry.js
|
getCall
|
function getCall() {
var result = _.trim(_.get(/\*\/\s*(?:function\s+)?([^\s(]+)\s*\(/.exec(this.entry), 1));
if (!result) {
result = _.trim(_.get(/\*\/\s*(.*?)[:=,]/.exec(this.entry), 1));
result = /['"]$/.test(result)
? _.trim(result, '"\'')
: result.split('.').pop().split(/^(?:const|let|var) /).pop();
}
var name = getValue(this, 'name') || result;
if (!this.isFunction()) {
return name;
}
var params = this.getParams();
result = _.castArray(result);
// Compile the function call syntax.
_.each(params, function(param) {
var paramValue = param[1],
parentParam = _.get(/\w+(?=\.[\w.]+)/.exec(paramValue), 0);
var parentIndex = parentParam == null ? -1 : _.findIndex(params, function(param) {
return _.trim(param[1], '[]').split(/\s*=/)[0] == parentParam;
});
// Skip params that are properties of other params (e.g. `options.leading`).
if (_.get(params[parentIndex], 0) != 'Object') {
result.push(paramValue);
}
});
// Format the function call.
return name + '(' + result.slice(1).join(', ') + ')';
}
|
javascript
|
function getCall() {
var result = _.trim(_.get(/\*\/\s*(?:function\s+)?([^\s(]+)\s*\(/.exec(this.entry), 1));
if (!result) {
result = _.trim(_.get(/\*\/\s*(.*?)[:=,]/.exec(this.entry), 1));
result = /['"]$/.test(result)
? _.trim(result, '"\'')
: result.split('.').pop().split(/^(?:const|let|var) /).pop();
}
var name = getValue(this, 'name') || result;
if (!this.isFunction()) {
return name;
}
var params = this.getParams();
result = _.castArray(result);
// Compile the function call syntax.
_.each(params, function(param) {
var paramValue = param[1],
parentParam = _.get(/\w+(?=\.[\w.]+)/.exec(paramValue), 0);
var parentIndex = parentParam == null ? -1 : _.findIndex(params, function(param) {
return _.trim(param[1], '[]').split(/\s*=/)[0] == parentParam;
});
// Skip params that are properties of other params (e.g. `options.leading`).
if (_.get(params[parentIndex], 0) != 'Object') {
result.push(paramValue);
}
});
// Format the function call.
return name + '(' + result.slice(1).join(', ') + ')';
}
|
[
"function",
"getCall",
"(",
")",
"{",
"var",
"result",
"=",
"_",
".",
"trim",
"(",
"_",
".",
"get",
"(",
"/",
"\\*\\/\\s*(?:function\\s+)?([^\\s(]+)\\s*\\(",
"/",
".",
"exec",
"(",
"this",
".",
"entry",
")",
",",
"1",
")",
")",
";",
"if",
"(",
"!",
"result",
")",
"{",
"result",
"=",
"_",
".",
"trim",
"(",
"_",
".",
"get",
"(",
"/",
"\\*\\/\\s*(.*?)[:=,]",
"/",
".",
"exec",
"(",
"this",
".",
"entry",
")",
",",
"1",
")",
")",
";",
"result",
"=",
"/",
"['\"]$",
"/",
".",
"test",
"(",
"result",
")",
"?",
"_",
".",
"trim",
"(",
"result",
",",
"'\"\\''",
")",
":",
"\\'",
";",
"}",
"result",
".",
"split",
"(",
"'.'",
")",
".",
"pop",
"(",
")",
".",
"split",
"(",
"/",
"^(?:const|let|var) ",
"/",
")",
".",
"pop",
"(",
")",
"var",
"name",
"=",
"getValue",
"(",
"this",
",",
"'name'",
")",
"||",
"result",
";",
"if",
"(",
"!",
"this",
".",
"isFunction",
"(",
")",
")",
"{",
"return",
"name",
";",
"}",
"var",
"params",
"=",
"this",
".",
"getParams",
"(",
")",
";",
"result",
"=",
"_",
".",
"castArray",
"(",
"result",
")",
";",
"_",
".",
"each",
"(",
"params",
",",
"function",
"(",
"param",
")",
"{",
"var",
"paramValue",
"=",
"param",
"[",
"1",
"]",
",",
"parentParam",
"=",
"_",
".",
"get",
"(",
"/",
"\\w+(?=\\.[\\w.]+)",
"/",
".",
"exec",
"(",
"paramValue",
")",
",",
"0",
")",
";",
"var",
"parentIndex",
"=",
"parentParam",
"==",
"null",
"?",
"-",
"1",
":",
"_",
".",
"findIndex",
"(",
"params",
",",
"function",
"(",
"param",
")",
"{",
"return",
"_",
".",
"trim",
"(",
"param",
"[",
"1",
"]",
",",
"'[]'",
")",
".",
"split",
"(",
"/",
"\\s*=",
"/",
")",
"[",
"0",
"]",
"==",
"parentParam",
";",
"}",
")",
";",
"if",
"(",
"_",
".",
"get",
"(",
"params",
"[",
"parentIndex",
"]",
",",
"0",
")",
"!=",
"'Object'",
")",
"{",
"result",
".",
"push",
"(",
"paramValue",
")",
";",
"}",
"}",
")",
";",
"}"
] |
Extracts the function call from the entry.
@memberOf Entry
@returns {string} Returns the function call.
|
[
"Extracts",
"the",
"function",
"call",
"from",
"the",
"entry",
"."
] |
297e61f2ef179b4cebca9656cb4eac2dbdd18669
|
https://github.com/jdalton/docdown/blob/297e61f2ef179b4cebca9656cb4eac2dbdd18669/lib/entry.js#L211-L243
|
train
|
jdalton/docdown
|
lib/entry.js
|
getDesc
|
function getDesc() {
var type = this.getType(),
result = getValue(this, 'description');
return (!result || type == 'Function' || type == 'unknown')
? result
: ('(' + _.trim(type.replace(/\|/g, ', '), '()') + '): ' + result);
}
|
javascript
|
function getDesc() {
var type = this.getType(),
result = getValue(this, 'description');
return (!result || type == 'Function' || type == 'unknown')
? result
: ('(' + _.trim(type.replace(/\|/g, ', '), '()') + '): ' + result);
}
|
[
"function",
"getDesc",
"(",
")",
"{",
"var",
"type",
"=",
"this",
".",
"getType",
"(",
")",
",",
"result",
"=",
"getValue",
"(",
"this",
",",
"'description'",
")",
";",
"return",
"(",
"!",
"result",
"||",
"type",
"==",
"'Function'",
"||",
"type",
"==",
"'unknown'",
")",
"?",
"result",
":",
"(",
"'('",
"+",
"_",
".",
"trim",
"(",
"type",
".",
"replace",
"(",
"/",
"\\|",
"/",
"g",
",",
"', '",
")",
",",
"'()'",
")",
"+",
"'): '",
"+",
"result",
")",
";",
"}"
] |
Extracts the entry's description.
@memberOf Entry
@returns {string} Returns the entry's description.
|
[
"Extracts",
"the",
"entry",
"s",
"description",
"."
] |
297e61f2ef179b4cebca9656cb4eac2dbdd18669
|
https://github.com/jdalton/docdown/blob/297e61f2ef179b4cebca9656cb4eac2dbdd18669/lib/entry.js#L262-L269
|
train
|
jdalton/docdown
|
lib/entry.js
|
getHash
|
function getHash(style) {
var result = _.toString(this.getMembers(0));
if (style == 'github') {
if (result) {
result += this.isPlugin() ? 'prototype' : '';
}
result += this.getCall();
return result
.replace(/[\\.=|'"(){}\[\]\t ]/g, '')
.replace(/[#,]+/g, '-')
.toLowerCase();
}
if (result) {
result += '-' + (this.isPlugin() ? 'prototype-' : '');
}
result += this.isAlias() ? this.getOwner().getName() : this.getName();
return result
.replace(/\./g, '-')
.replace(/^_-/, '');
}
|
javascript
|
function getHash(style) {
var result = _.toString(this.getMembers(0));
if (style == 'github') {
if (result) {
result += this.isPlugin() ? 'prototype' : '';
}
result += this.getCall();
return result
.replace(/[\\.=|'"(){}\[\]\t ]/g, '')
.replace(/[#,]+/g, '-')
.toLowerCase();
}
if (result) {
result += '-' + (this.isPlugin() ? 'prototype-' : '');
}
result += this.isAlias() ? this.getOwner().getName() : this.getName();
return result
.replace(/\./g, '-')
.replace(/^_-/, '');
}
|
[
"function",
"getHash",
"(",
"style",
")",
"{",
"var",
"result",
"=",
"_",
".",
"toString",
"(",
"this",
".",
"getMembers",
"(",
"0",
")",
")",
";",
"if",
"(",
"style",
"==",
"'github'",
")",
"{",
"if",
"(",
"result",
")",
"{",
"result",
"+=",
"this",
".",
"isPlugin",
"(",
")",
"?",
"'prototype'",
":",
"''",
";",
"}",
"result",
"+=",
"this",
".",
"getCall",
"(",
")",
";",
"return",
"result",
".",
"replace",
"(",
"/",
"[\\\\.=|'\"(){}\\[\\]\\t ]",
"/",
"g",
",",
"''",
")",
".",
"replace",
"(",
"/",
"[#,]+",
"/",
"g",
",",
"'-'",
")",
".",
"toLowerCase",
"(",
")",
";",
"}",
"if",
"(",
"result",
")",
"{",
"result",
"+=",
"'-'",
"+",
"(",
"this",
".",
"isPlugin",
"(",
")",
"?",
"'prototype-'",
":",
"''",
")",
";",
"}",
"result",
"+=",
"this",
".",
"isAlias",
"(",
")",
"?",
"this",
".",
"getOwner",
"(",
")",
".",
"getName",
"(",
")",
":",
"this",
".",
"getName",
"(",
")",
";",
"return",
"result",
".",
"replace",
"(",
"/",
"\\.",
"/",
"g",
",",
"'-'",
")",
".",
"replace",
"(",
"/",
"^_-",
"/",
",",
"''",
")",
";",
"}"
] |
Extracts the entry's hash value for permalinking.
@memberOf Entry
@param {string} [style] The hash style.
@returns {string} Returns the entry's hash value (without a hash itself).
|
[
"Extracts",
"the",
"entry",
"s",
"hash",
"value",
"for",
"permalinking",
"."
] |
297e61f2ef179b4cebca9656cb4eac2dbdd18669
|
https://github.com/jdalton/docdown/blob/297e61f2ef179b4cebca9656cb4eac2dbdd18669/lib/entry.js#L289-L308
|
train
|
jdalton/docdown
|
lib/entry.js
|
getLineNumber
|
function getLineNumber() {
var lines = this.source
.slice(0, this.source.indexOf(this.entry) + this.entry.length)
.match(/\n/g)
.slice(1);
// Offset by 2 because the first line number is before a line break and the
// last line doesn't include a line break.
return lines.length + 2;
}
|
javascript
|
function getLineNumber() {
var lines = this.source
.slice(0, this.source.indexOf(this.entry) + this.entry.length)
.match(/\n/g)
.slice(1);
// Offset by 2 because the first line number is before a line break and the
// last line doesn't include a line break.
return lines.length + 2;
}
|
[
"function",
"getLineNumber",
"(",
")",
"{",
"var",
"lines",
"=",
"this",
".",
"source",
".",
"slice",
"(",
"0",
",",
"this",
".",
"source",
".",
"indexOf",
"(",
"this",
".",
"entry",
")",
"+",
"this",
".",
"entry",
".",
"length",
")",
".",
"match",
"(",
"/",
"\\n",
"/",
"g",
")",
".",
"slice",
"(",
"1",
")",
";",
"return",
"lines",
".",
"length",
"+",
"2",
";",
"}"
] |
Resolves the entry's line number.
@memberOf Entry
@returns {number} Returns the entry's line number.
|
[
"Resolves",
"the",
"entry",
"s",
"line",
"number",
"."
] |
297e61f2ef179b4cebca9656cb4eac2dbdd18669
|
https://github.com/jdalton/docdown/blob/297e61f2ef179b4cebca9656cb4eac2dbdd18669/lib/entry.js#L316-L325
|
train
|
jdalton/docdown
|
lib/entry.js
|
getMembers
|
function getMembers(index) {
if (this._members === undefined) {
this._members = _(getValue(this, 'member') || getValue(this, 'memberOf'))
.split(/,\s*/)
.compact()
.sort(util.compareNatural)
.value();
}
var result = this._members;
return index === undefined ? result : result[index];
}
|
javascript
|
function getMembers(index) {
if (this._members === undefined) {
this._members = _(getValue(this, 'member') || getValue(this, 'memberOf'))
.split(/,\s*/)
.compact()
.sort(util.compareNatural)
.value();
}
var result = this._members;
return index === undefined ? result : result[index];
}
|
[
"function",
"getMembers",
"(",
"index",
")",
"{",
"if",
"(",
"this",
".",
"_members",
"===",
"undefined",
")",
"{",
"this",
".",
"_members",
"=",
"_",
"(",
"getValue",
"(",
"this",
",",
"'member'",
")",
"||",
"getValue",
"(",
"this",
",",
"'memberOf'",
")",
")",
".",
"split",
"(",
"/",
",\\s*",
"/",
")",
".",
"compact",
"(",
")",
".",
"sort",
"(",
"util",
".",
"compareNatural",
")",
".",
"value",
"(",
")",
";",
"}",
"var",
"result",
"=",
"this",
".",
"_members",
";",
"return",
"index",
"===",
"undefined",
"?",
"result",
":",
"result",
"[",
"index",
"]",
";",
"}"
] |
Extracts the entry's `member` data.
@memberOf Entry
@param {number} [index] The index of the array value to return.
@returns {Array|string} Returns the entry's `member` data.
|
[
"Extracts",
"the",
"entry",
"s",
"member",
"data",
"."
] |
297e61f2ef179b4cebca9656cb4eac2dbdd18669
|
https://github.com/jdalton/docdown/blob/297e61f2ef179b4cebca9656cb4eac2dbdd18669/lib/entry.js#L334-L344
|
train
|
jdalton/docdown
|
lib/entry.js
|
getParams
|
function getParams(index) {
if (this._params === undefined) {
this._params = _(this.parsed.tags)
.filter(['title', 'param'])
.filter('name')
.map(function(tag) {
var defaultValue = tag['default'],
desc = util.format(tag.description),
name = _.toString(tag.name),
type = getParamType(tag.type);
if (defaultValue != null) {
name += '=' + defaultValue;
}
if (_.get(tag, 'type.type') == 'OptionalType') {
name = '[' + name + ']';
}
return [type, name, desc];
})
.value();
}
var result = this._params;
return index === undefined ? result : result[index];
}
|
javascript
|
function getParams(index) {
if (this._params === undefined) {
this._params = _(this.parsed.tags)
.filter(['title', 'param'])
.filter('name')
.map(function(tag) {
var defaultValue = tag['default'],
desc = util.format(tag.description),
name = _.toString(tag.name),
type = getParamType(tag.type);
if (defaultValue != null) {
name += '=' + defaultValue;
}
if (_.get(tag, 'type.type') == 'OptionalType') {
name = '[' + name + ']';
}
return [type, name, desc];
})
.value();
}
var result = this._params;
return index === undefined ? result : result[index];
}
|
[
"function",
"getParams",
"(",
"index",
")",
"{",
"if",
"(",
"this",
".",
"_params",
"===",
"undefined",
")",
"{",
"this",
".",
"_params",
"=",
"_",
"(",
"this",
".",
"parsed",
".",
"tags",
")",
".",
"filter",
"(",
"[",
"'title'",
",",
"'param'",
"]",
")",
".",
"filter",
"(",
"'name'",
")",
".",
"map",
"(",
"function",
"(",
"tag",
")",
"{",
"var",
"defaultValue",
"=",
"tag",
"[",
"'default'",
"]",
",",
"desc",
"=",
"util",
".",
"format",
"(",
"tag",
".",
"description",
")",
",",
"name",
"=",
"_",
".",
"toString",
"(",
"tag",
".",
"name",
")",
",",
"type",
"=",
"getParamType",
"(",
"tag",
".",
"type",
")",
";",
"if",
"(",
"defaultValue",
"!=",
"null",
")",
"{",
"name",
"+=",
"'='",
"+",
"defaultValue",
";",
"}",
"if",
"(",
"_",
".",
"get",
"(",
"tag",
",",
"'type.type'",
")",
"==",
"'OptionalType'",
")",
"{",
"name",
"=",
"'['",
"+",
"name",
"+",
"']'",
";",
"}",
"return",
"[",
"type",
",",
"name",
",",
"desc",
"]",
";",
"}",
")",
".",
"value",
"(",
")",
";",
"}",
"var",
"result",
"=",
"this",
".",
"_params",
";",
"return",
"index",
"===",
"undefined",
"?",
"result",
":",
"result",
"[",
"index",
"]",
";",
"}"
] |
Extracts the entry's `param` data.
@memberOf Entry
@param {number} [index] The index of the array value to return.
@returns {Array} Returns the entry's `param` data.
|
[
"Extracts",
"the",
"entry",
"s",
"param",
"data",
"."
] |
297e61f2ef179b4cebca9656cb4eac2dbdd18669
|
https://github.com/jdalton/docdown/blob/297e61f2ef179b4cebca9656cb4eac2dbdd18669/lib/entry.js#L365-L388
|
train
|
jdalton/docdown
|
lib/entry.js
|
getRelated
|
function getRelated() {
var relatedValues = getValue(this, 'see');
if (relatedValues && relatedValues.trim().length > 0) {
var relatedItems = relatedValues.split(',').map((relatedItem) => relatedItem.trim());
return relatedItems.map((relatedItem) => '[' + relatedItem + '](#' + relatedItem + ')');
} else {
return [];
}
}
|
javascript
|
function getRelated() {
var relatedValues = getValue(this, 'see');
if (relatedValues && relatedValues.trim().length > 0) {
var relatedItems = relatedValues.split(',').map((relatedItem) => relatedItem.trim());
return relatedItems.map((relatedItem) => '[' + relatedItem + '](#' + relatedItem + ')');
} else {
return [];
}
}
|
[
"function",
"getRelated",
"(",
")",
"{",
"var",
"relatedValues",
"=",
"getValue",
"(",
"this",
",",
"'see'",
")",
";",
"if",
"(",
"relatedValues",
"&&",
"relatedValues",
".",
"trim",
"(",
")",
".",
"length",
">",
"0",
")",
"{",
"var",
"relatedItems",
"=",
"relatedValues",
".",
"split",
"(",
"','",
")",
".",
"map",
"(",
"(",
"relatedItem",
")",
"=>",
"relatedItem",
".",
"trim",
"(",
")",
")",
";",
"return",
"relatedItems",
".",
"map",
"(",
"(",
"relatedItem",
")",
"=>",
"'['",
"+",
"relatedItem",
"+",
"'](#'",
"+",
"relatedItem",
"+",
"')'",
")",
";",
"}",
"else",
"{",
"return",
"[",
"]",
";",
"}",
"}"
] |
Extracts the entry's `see` data.
@memberOf Entry
@returns {array} Returns the entry's `see` data as links.
|
[
"Extracts",
"the",
"entry",
"s",
"see",
"data",
"."
] |
297e61f2ef179b4cebca9656cb4eac2dbdd18669
|
https://github.com/jdalton/docdown/blob/297e61f2ef179b4cebca9656cb4eac2dbdd18669/lib/entry.js#L396-L404
|
train
|
jdalton/docdown
|
lib/entry.js
|
getReturns
|
function getReturns() {
var tag = getTag(this, 'returns'),
desc = _.toString(_.get(tag, 'description')),
type = _.toString(_.get(tag, 'type.name')) || '*';
return tag ? [type, desc] : [];
}
|
javascript
|
function getReturns() {
var tag = getTag(this, 'returns'),
desc = _.toString(_.get(tag, 'description')),
type = _.toString(_.get(tag, 'type.name')) || '*';
return tag ? [type, desc] : [];
}
|
[
"function",
"getReturns",
"(",
")",
"{",
"var",
"tag",
"=",
"getTag",
"(",
"this",
",",
"'returns'",
")",
",",
"desc",
"=",
"_",
".",
"toString",
"(",
"_",
".",
"get",
"(",
"tag",
",",
"'description'",
")",
")",
",",
"type",
"=",
"_",
".",
"toString",
"(",
"_",
".",
"get",
"(",
"tag",
",",
"'type.name'",
")",
")",
"||",
"'*'",
";",
"return",
"tag",
"?",
"[",
"type",
",",
"desc",
"]",
":",
"[",
"]",
";",
"}"
] |
Extracts the entry's `returns` data.
@memberOf Entry
@returns {array} Returns the entry's `returns` data.
|
[
"Extracts",
"the",
"entry",
"s",
"returns",
"data",
"."
] |
297e61f2ef179b4cebca9656cb4eac2dbdd18669
|
https://github.com/jdalton/docdown/blob/297e61f2ef179b4cebca9656cb4eac2dbdd18669/lib/entry.js#L412-L418
|
train
|
jdalton/docdown
|
lib/entry.js
|
getType
|
function getType() {
var result = getValue(this, 'type');
if (!result) {
return this.isFunction() ? 'Function' : 'unknown';
}
return /^(?:array|function|object|regexp)$/.test(result)
? _.capitalize(result)
: result;
}
|
javascript
|
function getType() {
var result = getValue(this, 'type');
if (!result) {
return this.isFunction() ? 'Function' : 'unknown';
}
return /^(?:array|function|object|regexp)$/.test(result)
? _.capitalize(result)
: result;
}
|
[
"function",
"getType",
"(",
")",
"{",
"var",
"result",
"=",
"getValue",
"(",
"this",
",",
"'type'",
")",
";",
"if",
"(",
"!",
"result",
")",
"{",
"return",
"this",
".",
"isFunction",
"(",
")",
"?",
"'Function'",
":",
"'unknown'",
";",
"}",
"return",
"/",
"^(?:array|function|object|regexp)$",
"/",
".",
"test",
"(",
"result",
")",
"?",
"_",
".",
"capitalize",
"(",
"result",
")",
":",
"result",
";",
"}"
] |
Extracts the entry's `type` data.
@memberOf Entry
@returns {string} Returns the entry's `type` data.
|
[
"Extracts",
"the",
"entry",
"s",
"type",
"data",
"."
] |
297e61f2ef179b4cebca9656cb4eac2dbdd18669
|
https://github.com/jdalton/docdown/blob/297e61f2ef179b4cebca9656cb4eac2dbdd18669/lib/entry.js#L436-L444
|
train
|
jdalton/docdown
|
lib/entry.js
|
isFunction
|
function isFunction() {
return !!(
this.isCtor() ||
_.size(this.getParams()) ||
_.size(this.getReturns()) ||
hasTag(this, 'function') ||
/\*\/\s*(?:function\s+)?[^\s(]+\s*\(/.test(this.entry)
);
}
|
javascript
|
function isFunction() {
return !!(
this.isCtor() ||
_.size(this.getParams()) ||
_.size(this.getReturns()) ||
hasTag(this, 'function') ||
/\*\/\s*(?:function\s+)?[^\s(]+\s*\(/.test(this.entry)
);
}
|
[
"function",
"isFunction",
"(",
")",
"{",
"return",
"!",
"!",
"(",
"this",
".",
"isCtor",
"(",
")",
"||",
"_",
".",
"size",
"(",
"this",
".",
"getParams",
"(",
")",
")",
"||",
"_",
".",
"size",
"(",
"this",
".",
"getReturns",
"(",
")",
")",
"||",
"hasTag",
"(",
"this",
",",
"'function'",
")",
"||",
"/",
"\\*\\/\\s*(?:function\\s+)?[^\\s(]+\\s*\\(",
"/",
".",
"test",
"(",
"this",
".",
"entry",
")",
")",
";",
"}"
] |
Checks if the entry is a function reference.
@memberOf Entry
@returns {boolean} Returns `true` if the entry is a function reference, else `false`.
|
[
"Checks",
"if",
"the",
"entry",
"is",
"a",
"function",
"reference",
"."
] |
297e61f2ef179b4cebca9656cb4eac2dbdd18669
|
https://github.com/jdalton/docdown/blob/297e61f2ef179b4cebca9656cb4eac2dbdd18669/lib/entry.js#L471-L479
|
train
|
emberjs/list-view
|
addon/list-view-mixin.js
|
function (buffer) {
var element = buffer.element();
var dom = buffer.dom;
var container = dom.createElement('div');
container.className = 'ember-list-container';
element.appendChild(container);
this._childViewsMorph = dom.appendMorph(container, container, null);
return container;
}
|
javascript
|
function (buffer) {
var element = buffer.element();
var dom = buffer.dom;
var container = dom.createElement('div');
container.className = 'ember-list-container';
element.appendChild(container);
this._childViewsMorph = dom.appendMorph(container, container, null);
return container;
}
|
[
"function",
"(",
"buffer",
")",
"{",
"var",
"element",
"=",
"buffer",
".",
"element",
"(",
")",
";",
"var",
"dom",
"=",
"buffer",
".",
"dom",
";",
"var",
"container",
"=",
"dom",
".",
"createElement",
"(",
"'div'",
")",
";",
"container",
".",
"className",
"=",
"'ember-list-container'",
";",
"element",
".",
"appendChild",
"(",
"container",
")",
";",
"this",
".",
"_childViewsMorph",
"=",
"dom",
".",
"appendMorph",
"(",
"container",
",",
"container",
",",
"null",
")",
";",
"return",
"container",
";",
"}"
] |
Called on your view when it should push strings of HTML into a
`Ember.RenderBuffer`.
Adds a [div](https://developer.mozilla.org/en-US/docs/HTML/Element/div)
with a required `ember-list-container` class.
@method render
@param {Ember.RenderBuffer} buffer The render buffer
|
[
"Called",
"on",
"your",
"view",
"when",
"it",
"should",
"push",
"strings",
"of",
"HTML",
"into",
"a",
"Ember",
".",
"RenderBuffer",
"."
] |
d463fa6f874c143fe4766379594b6c11cdf7a5d0
|
https://github.com/emberjs/list-view/blob/d463fa6f874c143fe4766379594b6c11cdf7a5d0/addon/list-view-mixin.js#L142-L152
|
train
|
|
joyent/node-docker-registry-client
|
lib/registry-client-v2.js
|
_getRegistryErrorMessage
|
function _getRegistryErrorMessage(err) {
if (err.body && Array.isArray(err.body.errors) && err.body.errors[0]) {
return err.body.errors[0].message;
} else if (err.body && err.body.details) {
return err.body.details;
} else if (Array.isArray(err.errors) && err.errors[0].message) {
return err.errors[0].message;
} else if (err.message) {
return err.message;
}
return err.toString();
}
|
javascript
|
function _getRegistryErrorMessage(err) {
if (err.body && Array.isArray(err.body.errors) && err.body.errors[0]) {
return err.body.errors[0].message;
} else if (err.body && err.body.details) {
return err.body.details;
} else if (Array.isArray(err.errors) && err.errors[0].message) {
return err.errors[0].message;
} else if (err.message) {
return err.message;
}
return err.toString();
}
|
[
"function",
"_getRegistryErrorMessage",
"(",
"err",
")",
"{",
"if",
"(",
"err",
".",
"body",
"&&",
"Array",
".",
"isArray",
"(",
"err",
".",
"body",
".",
"errors",
")",
"&&",
"err",
".",
"body",
".",
"errors",
"[",
"0",
"]",
")",
"{",
"return",
"err",
".",
"body",
".",
"errors",
"[",
"0",
"]",
".",
"message",
";",
"}",
"else",
"if",
"(",
"err",
".",
"body",
"&&",
"err",
".",
"body",
".",
"details",
")",
"{",
"return",
"err",
".",
"body",
".",
"details",
";",
"}",
"else",
"if",
"(",
"Array",
".",
"isArray",
"(",
"err",
".",
"errors",
")",
"&&",
"err",
".",
"errors",
"[",
"0",
"]",
".",
"message",
")",
"{",
"return",
"err",
".",
"errors",
"[",
"0",
"]",
".",
"message",
";",
"}",
"else",
"if",
"(",
"err",
".",
"message",
")",
"{",
"return",
"err",
".",
"message",
";",
"}",
"return",
"err",
".",
"toString",
"(",
")",
";",
"}"
] |
Special handling of errors from the registry server.
Some registry errors will use a custom error format, so detect those
and convert these as necessary.
Example JSON response for a missing repo:
{
"jse_shortmsg": "",
"jse_info": {},
"message": "{\"errors\":[{\"code\":\"UNAUTHORIZED\",\"message\":\"...}\n",
"body": {
"errors": [{
"code": "UNAUTHORIZED",
"message": "authentication required",
"detail": [{
"Type": "repository",
"Class": "",
"Name": "library/idontexist",
"Action": "pull"
}]
}]
}
}
Example JSON response for bad username/password:
{
"statusCode": 401,
"jse_shortmsg":"",
"jse_info":{},
"message":"{\"details\":\"incorrect username or password\"}\n",
"body":{
"details": "incorrect username or password"
}
}
Example AWS token error:
{
"statusCode": 400,
"errors": [
{
"code": "DENIED",
"message": "Your Authorization Token is invalid."
}
]
}
|
[
"Special",
"handling",
"of",
"errors",
"from",
"the",
"registry",
"server",
"."
] |
389a27229744094bb4784087723ce8be50c703dc
|
https://github.com/joyent/node-docker-registry-client/blob/389a27229744094bb4784087723ce8be50c703dc/lib/registry-client-v2.js#L140-L151
|
train
|
joyent/node-docker-registry-client
|
lib/registry-client-v2.js
|
_getRegistryErrMessage
|
function _getRegistryErrMessage(body) {
if (!body) {
return null;
}
var obj = body;
if (typeof (obj) === 'string' && obj.length <= MAX_REGISTRY_ERROR_LENGTH) {
try {
obj = JSON.parse(obj);
} catch (ex) {
// Just return the error as a string.
return obj;
}
}
if (typeof (obj) !== 'object' || !obj.hasOwnProperty('errors')) {
return null;
}
if (!Array.isArray(obj.errors)) {
return null;
}
// Example obj:
// {
// "errors": [
// {
// "code": "MANIFEST_INVALID",
// "message": "manifest invalid",
// "detail": {}
// }
// ]
// }
if (obj.errors.length === 1) {
return obj.errors[0].message;
} else {
return obj.errors.map(function (o) {
return o.message;
}).join(', ');
}
}
|
javascript
|
function _getRegistryErrMessage(body) {
if (!body) {
return null;
}
var obj = body;
if (typeof (obj) === 'string' && obj.length <= MAX_REGISTRY_ERROR_LENGTH) {
try {
obj = JSON.parse(obj);
} catch (ex) {
// Just return the error as a string.
return obj;
}
}
if (typeof (obj) !== 'object' || !obj.hasOwnProperty('errors')) {
return null;
}
if (!Array.isArray(obj.errors)) {
return null;
}
// Example obj:
// {
// "errors": [
// {
// "code": "MANIFEST_INVALID",
// "message": "manifest invalid",
// "detail": {}
// }
// ]
// }
if (obj.errors.length === 1) {
return obj.errors[0].message;
} else {
return obj.errors.map(function (o) {
return o.message;
}).join(', ');
}
}
|
[
"function",
"_getRegistryErrMessage",
"(",
"body",
")",
"{",
"if",
"(",
"!",
"body",
")",
"{",
"return",
"null",
";",
"}",
"var",
"obj",
"=",
"body",
";",
"if",
"(",
"typeof",
"(",
"obj",
")",
"===",
"'string'",
"&&",
"obj",
".",
"length",
"<=",
"MAX_REGISTRY_ERROR_LENGTH",
")",
"{",
"try",
"{",
"obj",
"=",
"JSON",
".",
"parse",
"(",
"obj",
")",
";",
"}",
"catch",
"(",
"ex",
")",
"{",
"return",
"obj",
";",
"}",
"}",
"if",
"(",
"typeof",
"(",
"obj",
")",
"!==",
"'object'",
"||",
"!",
"obj",
".",
"hasOwnProperty",
"(",
"'errors'",
")",
")",
"{",
"return",
"null",
";",
"}",
"if",
"(",
"!",
"Array",
".",
"isArray",
"(",
"obj",
".",
"errors",
")",
")",
"{",
"return",
"null",
";",
"}",
"if",
"(",
"obj",
".",
"errors",
".",
"length",
"===",
"1",
")",
"{",
"return",
"obj",
".",
"errors",
"[",
"0",
"]",
".",
"message",
";",
"}",
"else",
"{",
"return",
"obj",
".",
"errors",
".",
"map",
"(",
"function",
"(",
"o",
")",
"{",
"return",
"o",
".",
"message",
";",
"}",
")",
".",
"join",
"(",
"', '",
")",
";",
"}",
"}"
] |
Special handling of JSON body errors from the registry server.
POST/PUT endpoints can return an error in the body of the response.
We want to check for that and get the error body message and return it.
Usage:
var regErr = _getRegistryErrMessage(body));
|
[
"Special",
"handling",
"of",
"JSON",
"body",
"errors",
"from",
"the",
"registry",
"server",
"."
] |
389a27229744094bb4784087723ce8be50c703dc
|
https://github.com/joyent/node-docker-registry-client/blob/389a27229744094bb4784087723ce8be50c703dc/lib/registry-client-v2.js#L170-L206
|
train
|
joyent/node-docker-registry-client
|
lib/registry-client-v2.js
|
registryError
|
function registryError(err, res, callback) {
var body = '';
res.on('data', function onResChunk(chunk) {
body += chunk;
});
res.on('end', function onResEnd() {
// Parse errors in the response body.
var message = _getRegistryErrMessage(body);
if (message) {
err.message = message;
}
callback(err);
});
}
|
javascript
|
function registryError(err, res, callback) {
var body = '';
res.on('data', function onResChunk(chunk) {
body += chunk;
});
res.on('end', function onResEnd() {
// Parse errors in the response body.
var message = _getRegistryErrMessage(body);
if (message) {
err.message = message;
}
callback(err);
});
}
|
[
"function",
"registryError",
"(",
"err",
",",
"res",
",",
"callback",
")",
"{",
"var",
"body",
"=",
"''",
";",
"res",
".",
"on",
"(",
"'data'",
",",
"function",
"onResChunk",
"(",
"chunk",
")",
"{",
"body",
"+=",
"chunk",
";",
"}",
")",
";",
"res",
".",
"on",
"(",
"'end'",
",",
"function",
"onResEnd",
"(",
")",
"{",
"var",
"message",
"=",
"_getRegistryErrMessage",
"(",
"body",
")",
";",
"if",
"(",
"message",
")",
"{",
"err",
".",
"message",
"=",
"message",
";",
"}",
"callback",
"(",
"err",
")",
";",
"}",
")",
";",
"}"
] |
The Docker Registry will usually provide a more detailed JSON error message in the response body, so try to read that data in order to get a more detailed error msg.
|
[
"The",
"Docker",
"Registry",
"will",
"usually",
"provide",
"a",
"more",
"detailed",
"JSON",
"error",
"message",
"in",
"the",
"response",
"body",
"so",
"try",
"to",
"read",
"that",
"data",
"in",
"order",
"to",
"get",
"a",
"more",
"detailed",
"error",
"msg",
"."
] |
389a27229744094bb4784087723ce8be50c703dc
|
https://github.com/joyent/node-docker-registry-client/blob/389a27229744094bb4784087723ce8be50c703dc/lib/registry-client-v2.js#L212-L225
|
train
|
joyent/node-docker-registry-client
|
lib/registry-client-v2.js
|
digestFromManifestStr
|
function digestFromManifestStr(manifestStr) {
assert.string(manifestStr, 'manifestStr');
var hash = crypto.createHash('sha256');
var digestPrefix = 'sha256:';
var manifest;
try {
manifest = JSON.parse(manifestStr);
} catch (err) {
throw new restifyErrors.InvalidContentError(err, fmt(
'could not parse manifest: %s', manifestStr));
}
if (manifest.schemaVersion === 1) {
try {
var manifestBuffer = Buffer(manifestStr);
var jws = _jwsFromManifest(manifest, manifestBuffer);
hash.update(jws.payload, 'binary');
return digestPrefix + hash.digest('hex');
} catch (verifyErr) {
if (!(verifyErr instanceof restifyErrors.InvalidContentError)) {
throw verifyErr;
}
// Couldn't parse (or doesn't have) the signatures section,
// fall through.
}
}
hash.update(manifestStr);
return digestPrefix + hash.digest('hex');
}
|
javascript
|
function digestFromManifestStr(manifestStr) {
assert.string(manifestStr, 'manifestStr');
var hash = crypto.createHash('sha256');
var digestPrefix = 'sha256:';
var manifest;
try {
manifest = JSON.parse(manifestStr);
} catch (err) {
throw new restifyErrors.InvalidContentError(err, fmt(
'could not parse manifest: %s', manifestStr));
}
if (manifest.schemaVersion === 1) {
try {
var manifestBuffer = Buffer(manifestStr);
var jws = _jwsFromManifest(manifest, manifestBuffer);
hash.update(jws.payload, 'binary');
return digestPrefix + hash.digest('hex');
} catch (verifyErr) {
if (!(verifyErr instanceof restifyErrors.InvalidContentError)) {
throw verifyErr;
}
// Couldn't parse (or doesn't have) the signatures section,
// fall through.
}
}
hash.update(manifestStr);
return digestPrefix + hash.digest('hex');
}
|
[
"function",
"digestFromManifestStr",
"(",
"manifestStr",
")",
"{",
"assert",
".",
"string",
"(",
"manifestStr",
",",
"'manifestStr'",
")",
";",
"var",
"hash",
"=",
"crypto",
".",
"createHash",
"(",
"'sha256'",
")",
";",
"var",
"digestPrefix",
"=",
"'sha256:'",
";",
"var",
"manifest",
";",
"try",
"{",
"manifest",
"=",
"JSON",
".",
"parse",
"(",
"manifestStr",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"throw",
"new",
"restifyErrors",
".",
"InvalidContentError",
"(",
"err",
",",
"fmt",
"(",
"'could not parse manifest: %s'",
",",
"manifestStr",
")",
")",
";",
"}",
"if",
"(",
"manifest",
".",
"schemaVersion",
"===",
"1",
")",
"{",
"try",
"{",
"var",
"manifestBuffer",
"=",
"Buffer",
"(",
"manifestStr",
")",
";",
"var",
"jws",
"=",
"_jwsFromManifest",
"(",
"manifest",
",",
"manifestBuffer",
")",
";",
"hash",
".",
"update",
"(",
"jws",
".",
"payload",
",",
"'binary'",
")",
";",
"return",
"digestPrefix",
"+",
"hash",
".",
"digest",
"(",
"'hex'",
")",
";",
"}",
"catch",
"(",
"verifyErr",
")",
"{",
"if",
"(",
"!",
"(",
"verifyErr",
"instanceof",
"restifyErrors",
".",
"InvalidContentError",
")",
")",
"{",
"throw",
"verifyErr",
";",
"}",
"}",
"}",
"hash",
".",
"update",
"(",
"manifestStr",
")",
";",
"return",
"digestPrefix",
"+",
"hash",
".",
"digest",
"(",
"'hex'",
")",
";",
"}"
] |
Calculate the 'Docker-Content-Digest' header for the given manifest.
@returns {String} The docker digest string.
@throws {InvalidContentError} if there is a problem parsing the manifest.
|
[
"Calculate",
"the",
"Docker",
"-",
"Content",
"-",
"Digest",
"header",
"for",
"the",
"given",
"manifest",
"."
] |
389a27229744094bb4784087723ce8be50c703dc
|
https://github.com/joyent/node-docker-registry-client/blob/389a27229744094bb4784087723ce8be50c703dc/lib/registry-client-v2.js#L1010-L1039
|
train
|
dominictarr/map-stream
|
index.js
|
wrappedMapper
|
function wrappedMapper (input, number, callback) {
return mapper.call(null, input, function(err, data){
callback(err, data, number)
})
}
|
javascript
|
function wrappedMapper (input, number, callback) {
return mapper.call(null, input, function(err, data){
callback(err, data, number)
})
}
|
[
"function",
"wrappedMapper",
"(",
"input",
",",
"number",
",",
"callback",
")",
"{",
"return",
"mapper",
".",
"call",
"(",
"null",
",",
"input",
",",
"function",
"(",
"err",
",",
"data",
")",
"{",
"callback",
"(",
"err",
",",
"data",
",",
"number",
")",
"}",
")",
"}"
] |
Wrap the mapper function by calling its callback with the order number of the item in the stream.
|
[
"Wrap",
"the",
"mapper",
"function",
"by",
"calling",
"its",
"callback",
"with",
"the",
"order",
"number",
"of",
"the",
"item",
"in",
"the",
"stream",
"."
] |
70794870aab81a7081be50eab59f6789253368da
|
https://github.com/dominictarr/map-stream/blob/70794870aab81a7081be50eab59f6789253368da/index.js#L82-L86
|
train
|
fdecampredon/rx-react
|
lib/funcSubject.js
|
factory
|
function factory(BaseClass, mapFunction) {
function subject(value) {
if (typeof mapFunction === 'function') {
value = mapFunction.apply(undefined, arguments);
} else if (typeof mapFunction !== 'undefined') {
value = mapFunction;
}
subject.onNext(value);
return value;
}
for (var key in BaseClass.prototype) {
subject[key] = BaseClass.prototype[key];
}
BaseClass.apply(subject, [].slice.call(arguments, 2));
return subject;
}
|
javascript
|
function factory(BaseClass, mapFunction) {
function subject(value) {
if (typeof mapFunction === 'function') {
value = mapFunction.apply(undefined, arguments);
} else if (typeof mapFunction !== 'undefined') {
value = mapFunction;
}
subject.onNext(value);
return value;
}
for (var key in BaseClass.prototype) {
subject[key] = BaseClass.prototype[key];
}
BaseClass.apply(subject, [].slice.call(arguments, 2));
return subject;
}
|
[
"function",
"factory",
"(",
"BaseClass",
",",
"mapFunction",
")",
"{",
"function",
"subject",
"(",
"value",
")",
"{",
"if",
"(",
"typeof",
"mapFunction",
"===",
"'function'",
")",
"{",
"value",
"=",
"mapFunction",
".",
"apply",
"(",
"undefined",
",",
"arguments",
")",
";",
"}",
"else",
"if",
"(",
"typeof",
"mapFunction",
"!==",
"'undefined'",
")",
"{",
"value",
"=",
"mapFunction",
";",
"}",
"subject",
".",
"onNext",
"(",
"value",
")",
";",
"return",
"value",
";",
"}",
"for",
"(",
"var",
"key",
"in",
"BaseClass",
".",
"prototype",
")",
"{",
"subject",
"[",
"key",
"]",
"=",
"BaseClass",
".",
"prototype",
"[",
"key",
"]",
";",
"}",
"BaseClass",
".",
"apply",
"(",
"subject",
",",
"[",
"]",
".",
"slice",
".",
"call",
"(",
"arguments",
",",
"2",
")",
")",
";",
"return",
"subject",
";",
"}"
] |
Factory that allows you to create your custom `FuncSuject`
example:
var myFuncSubject = FuncSubject.factory(MyCustomSubject, (val1, val2) => val1 + val2, ...arguments);
|
[
"Factory",
"that",
"allows",
"you",
"to",
"create",
"your",
"custom",
"FuncSuject"
] |
c86411a5dbeee4a8fb08ea8655a3bf2cc32a6d9c
|
https://github.com/fdecampredon/rx-react/blob/c86411a5dbeee4a8fb08ea8655a3bf2cc32a6d9c/lib/funcSubject.js#L27-L45
|
train
|
pubkey/async-test-util
|
dist/lib/wait-until.js
|
waitUntil
|
function waitUntil(fun) {
var timeout = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
var interval = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 20;
var timedOut = false;
var ok = false;
if (timeout !== 0) (0, _wait2['default'])(timeout).then(function () {
return timedOut = true;
});
return new Promise(function (resolve, reject) {
var runLoop = function runLoop() {
if (ok) {
resolve();
return;
}
if (timedOut) {
reject(new Error('AsyncTestUtil.waitUntil(): reached timeout of ' + timeout + 'ms'));
return;
}
(0, _wait2['default'])(interval).then(function () {
var value = (0, _promisify2['default'])(fun());
value.then(function (val) {
ok = val;
runLoop();
});
});
};
runLoop();
});
}
|
javascript
|
function waitUntil(fun) {
var timeout = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
var interval = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 20;
var timedOut = false;
var ok = false;
if (timeout !== 0) (0, _wait2['default'])(timeout).then(function () {
return timedOut = true;
});
return new Promise(function (resolve, reject) {
var runLoop = function runLoop() {
if (ok) {
resolve();
return;
}
if (timedOut) {
reject(new Error('AsyncTestUtil.waitUntil(): reached timeout of ' + timeout + 'ms'));
return;
}
(0, _wait2['default'])(interval).then(function () {
var value = (0, _promisify2['default'])(fun());
value.then(function (val) {
ok = val;
runLoop();
});
});
};
runLoop();
});
}
|
[
"function",
"waitUntil",
"(",
"fun",
")",
"{",
"var",
"timeout",
"=",
"arguments",
".",
"length",
">",
"1",
"&&",
"arguments",
"[",
"1",
"]",
"!==",
"undefined",
"?",
"arguments",
"[",
"1",
"]",
":",
"0",
";",
"var",
"interval",
"=",
"arguments",
".",
"length",
">",
"2",
"&&",
"arguments",
"[",
"2",
"]",
"!==",
"undefined",
"?",
"arguments",
"[",
"2",
"]",
":",
"20",
";",
"var",
"timedOut",
"=",
"false",
";",
"var",
"ok",
"=",
"false",
";",
"if",
"(",
"timeout",
"!==",
"0",
")",
"(",
"0",
",",
"_wait2",
"[",
"'default'",
"]",
")",
"(",
"timeout",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"return",
"timedOut",
"=",
"true",
";",
"}",
")",
";",
"return",
"new",
"Promise",
"(",
"function",
"(",
"resolve",
",",
"reject",
")",
"{",
"var",
"runLoop",
"=",
"function",
"runLoop",
"(",
")",
"{",
"if",
"(",
"ok",
")",
"{",
"resolve",
"(",
")",
";",
"return",
";",
"}",
"if",
"(",
"timedOut",
")",
"{",
"reject",
"(",
"new",
"Error",
"(",
"'AsyncTestUtil.waitUntil(): reached timeout of '",
"+",
"timeout",
"+",
"'ms'",
")",
")",
";",
"return",
";",
"}",
"(",
"0",
",",
"_wait2",
"[",
"'default'",
"]",
")",
"(",
"interval",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"var",
"value",
"=",
"(",
"0",
",",
"_promisify2",
"[",
"'default'",
"]",
")",
"(",
"fun",
"(",
")",
")",
";",
"value",
".",
"then",
"(",
"function",
"(",
"val",
")",
"{",
"ok",
"=",
"val",
";",
"runLoop",
"(",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}",
";",
"runLoop",
"(",
")",
";",
"}",
")",
";",
"}"
] |
waits until the given function returns true
@param {function} fun
@return {Promise}
|
[
"waits",
"until",
"the",
"given",
"function",
"returns",
"true"
] |
5f8bf587cd9d16217f4a19755303a88c30b1f2db
|
https://github.com/pubkey/async-test-util/blob/5f8bf587cd9d16217f4a19755303a88c30b1f2db/dist/lib/wait-until.js#L23-L54
|
train
|
pubkey/async-test-util
|
dist/lib/resolve-values.js
|
resolveValues
|
function resolveValues(obj) {
var ret = {};
return Promise.all(Object.keys(obj).map(function (k) {
var val = (0, _promisify2['default'])(obj[k]);
return val.then(function (v) {
return ret[k] = v;
});
})).then(function () {
return ret;
});
}
|
javascript
|
function resolveValues(obj) {
var ret = {};
return Promise.all(Object.keys(obj).map(function (k) {
var val = (0, _promisify2['default'])(obj[k]);
return val.then(function (v) {
return ret[k] = v;
});
})).then(function () {
return ret;
});
}
|
[
"function",
"resolveValues",
"(",
"obj",
")",
"{",
"var",
"ret",
"=",
"{",
"}",
";",
"return",
"Promise",
".",
"all",
"(",
"Object",
".",
"keys",
"(",
"obj",
")",
".",
"map",
"(",
"function",
"(",
"k",
")",
"{",
"var",
"val",
"=",
"(",
"0",
",",
"_promisify2",
"[",
"'default'",
"]",
")",
"(",
"obj",
"[",
"k",
"]",
")",
";",
"return",
"val",
".",
"then",
"(",
"function",
"(",
"v",
")",
"{",
"return",
"ret",
"[",
"k",
"]",
"=",
"v",
";",
"}",
")",
";",
"}",
")",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"return",
"ret",
";",
"}",
")",
";",
"}"
] |
resolves all values if they are promises
returns equal object with resolved
|
[
"resolves",
"all",
"values",
"if",
"they",
"are",
"promises",
"returns",
"equal",
"object",
"with",
"resolved"
] |
5f8bf587cd9d16217f4a19755303a88c30b1f2db
|
https://github.com/pubkey/async-test-util/blob/5f8bf587cd9d16217f4a19755303a88c30b1f2db/dist/lib/resolve-values.js#L18-L28
|
train
|
pubkey/async-test-util
|
dist/lib/assert-throws.js
|
assertThrows
|
function assertThrows(test) {
var error = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : Error;
var contains = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
if (!Array.isArray(contains)) contains = [contains];
var shouldErrorName = typeof error === 'string' ? error : error.name;
var nonThrown = new Error('util.assertThrowsAsync(): Missing rejection' + (error ? ' with ' + error.name : ''));
var ensureErrorMatches = function ensureErrorMatches(error) {
// wrong type
if (error.constructor.name != shouldErrorName) {
return new Error('\n util.assertThrowsAsync(): Wrong Error-type\n - is : ' + error.constructor.name + '\n - should: ' + shouldErrorName + '\n - error: ' + error.toString() + '\n ');
}
// check if contains
var errorString = error.toString();
if (contains.length > 0 && (0, _utils.oneOfArrayNotInString)(contains, errorString)) {
return new Error('\n util.assertThrowsAsync(): Error does not contain\n - should contain: ' + contains + '\n - is string: ' + error.toString() + '\n ');
}
return false;
};
return new Promise(function (res, rej) {
var val = void 0;
try {
val = test();
} catch (err) {
var wrong = ensureErrorMatches(err);
if (wrong) rej(wrong);else res(err);
return;
}
if ((0, _isPromise2['default'])(val)) {
val.then(function () {
// has not thrown
rej(nonThrown);
})['catch'](function (err) {
var wrong = ensureErrorMatches(err);
if (wrong) rej(wrong);else res(err);
});
} else rej(nonThrown);
});
}
|
javascript
|
function assertThrows(test) {
var error = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : Error;
var contains = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
if (!Array.isArray(contains)) contains = [contains];
var shouldErrorName = typeof error === 'string' ? error : error.name;
var nonThrown = new Error('util.assertThrowsAsync(): Missing rejection' + (error ? ' with ' + error.name : ''));
var ensureErrorMatches = function ensureErrorMatches(error) {
// wrong type
if (error.constructor.name != shouldErrorName) {
return new Error('\n util.assertThrowsAsync(): Wrong Error-type\n - is : ' + error.constructor.name + '\n - should: ' + shouldErrorName + '\n - error: ' + error.toString() + '\n ');
}
// check if contains
var errorString = error.toString();
if (contains.length > 0 && (0, _utils.oneOfArrayNotInString)(contains, errorString)) {
return new Error('\n util.assertThrowsAsync(): Error does not contain\n - should contain: ' + contains + '\n - is string: ' + error.toString() + '\n ');
}
return false;
};
return new Promise(function (res, rej) {
var val = void 0;
try {
val = test();
} catch (err) {
var wrong = ensureErrorMatches(err);
if (wrong) rej(wrong);else res(err);
return;
}
if ((0, _isPromise2['default'])(val)) {
val.then(function () {
// has not thrown
rej(nonThrown);
})['catch'](function (err) {
var wrong = ensureErrorMatches(err);
if (wrong) rej(wrong);else res(err);
});
} else rej(nonThrown);
});
}
|
[
"function",
"assertThrows",
"(",
"test",
")",
"{",
"var",
"error",
"=",
"arguments",
".",
"length",
">",
"1",
"&&",
"arguments",
"[",
"1",
"]",
"!==",
"undefined",
"?",
"arguments",
"[",
"1",
"]",
":",
"Error",
";",
"var",
"contains",
"=",
"arguments",
".",
"length",
">",
"2",
"&&",
"arguments",
"[",
"2",
"]",
"!==",
"undefined",
"?",
"arguments",
"[",
"2",
"]",
":",
"[",
"]",
";",
"if",
"(",
"!",
"Array",
".",
"isArray",
"(",
"contains",
")",
")",
"contains",
"=",
"[",
"contains",
"]",
";",
"var",
"shouldErrorName",
"=",
"typeof",
"error",
"===",
"'string'",
"?",
"error",
":",
"error",
".",
"name",
";",
"var",
"nonThrown",
"=",
"new",
"Error",
"(",
"'util.assertThrowsAsync(): Missing rejection'",
"+",
"(",
"error",
"?",
"' with '",
"+",
"error",
".",
"name",
":",
"''",
")",
")",
";",
"var",
"ensureErrorMatches",
"=",
"function",
"ensureErrorMatches",
"(",
"error",
")",
"{",
"if",
"(",
"error",
".",
"constructor",
".",
"name",
"!=",
"shouldErrorName",
")",
"{",
"return",
"new",
"Error",
"(",
"'\\n util.assertThrowsAsync(): Wrong Error-type\\n - is : '",
"+",
"\\n",
"+",
"\\n",
"+",
"error",
".",
"constructor",
".",
"name",
"+",
"'\\n - should: '",
"+",
"\\n",
"+",
"shouldErrorName",
")",
";",
"}",
"'\\n - error: '",
"\\n",
"error",
".",
"toString",
"(",
")",
"}",
";",
"'\\n '",
"}"
] |
async version of assert.throws
@param {function} test
@param {Error|TypeError|string} [error=Error] error
@param {?string} [contains=''] contains
@return {Promise} [description]
|
[
"async",
"version",
"of",
"assert",
".",
"throws"
] |
5f8bf587cd9d16217f4a19755303a88c30b1f2db
|
https://github.com/pubkey/async-test-util/blob/5f8bf587cd9d16217f4a19755303a88c30b1f2db/dist/lib/assert-throws.js#L23-L65
|
train
|
pubkey/async-test-util
|
dist/lib/wait-resolveable.js
|
waitResolveable
|
function waitResolveable() {
var ms = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
var ret = {};
ret.promise = new Promise(function (res) {
ret.resolve = function (x) {
return res(x);
};
setTimeout(res, ms);
});
return ret;
}
|
javascript
|
function waitResolveable() {
var ms = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
var ret = {};
ret.promise = new Promise(function (res) {
ret.resolve = function (x) {
return res(x);
};
setTimeout(res, ms);
});
return ret;
}
|
[
"function",
"waitResolveable",
"(",
")",
"{",
"var",
"ms",
"=",
"arguments",
".",
"length",
">",
"0",
"&&",
"arguments",
"[",
"0",
"]",
"!==",
"undefined",
"?",
"arguments",
"[",
"0",
"]",
":",
"0",
";",
"var",
"ret",
"=",
"{",
"}",
";",
"ret",
".",
"promise",
"=",
"new",
"Promise",
"(",
"function",
"(",
"res",
")",
"{",
"ret",
".",
"resolve",
"=",
"function",
"(",
"x",
")",
"{",
"return",
"res",
"(",
"x",
")",
";",
"}",
";",
"setTimeout",
"(",
"res",
",",
"ms",
")",
";",
"}",
")",
";",
"return",
"ret",
";",
"}"
] |
this returns a promise and the resolve-function
which can be called to resolve before the timeout has passed
@param {Number} [ms=0] [description]
|
[
"this",
"returns",
"a",
"promise",
"and",
"the",
"resolve",
"-",
"function",
"which",
"can",
"be",
"called",
"to",
"resolve",
"before",
"the",
"timeout",
"has",
"passed"
] |
5f8bf587cd9d16217f4a19755303a88c30b1f2db
|
https://github.com/pubkey/async-test-util/blob/5f8bf587cd9d16217f4a19755303a88c30b1f2db/dist/lib/wait-resolveable.js#L12-L23
|
train
|
pubkey/async-test-util
|
dist/lib/random-number.js
|
randomNumber
|
function randomNumber() {
var min = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
var max = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1000;
return Math.floor(Math.random() * (max - min + 1)) + min;
}
|
javascript
|
function randomNumber() {
var min = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
var max = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1000;
return Math.floor(Math.random() * (max - min + 1)) + min;
}
|
[
"function",
"randomNumber",
"(",
")",
"{",
"var",
"min",
"=",
"arguments",
".",
"length",
">",
"0",
"&&",
"arguments",
"[",
"0",
"]",
"!==",
"undefined",
"?",
"arguments",
"[",
"0",
"]",
":",
"0",
";",
"var",
"max",
"=",
"arguments",
".",
"length",
">",
"1",
"&&",
"arguments",
"[",
"1",
"]",
"!==",
"undefined",
"?",
"arguments",
"[",
"1",
"]",
":",
"1000",
";",
"return",
"Math",
".",
"floor",
"(",
"Math",
".",
"random",
"(",
")",
"*",
"(",
"max",
"-",
"min",
"+",
"1",
")",
")",
"+",
"min",
";",
"}"
] |
returns a random number
@param {number} [min=0] inclusive
@param {number} [max=1000] inclusive
@return {number}
|
[
"returns",
"a",
"random",
"number"
] |
5f8bf587cd9d16217f4a19755303a88c30b1f2db
|
https://github.com/pubkey/async-test-util/blob/5f8bf587cd9d16217f4a19755303a88c30b1f2db/dist/lib/random-number.js#L13-L18
|
train
|
lucalanca/grunt-a11y
|
tasks/a11y.js
|
a11yPromise
|
function a11yPromise (url, viewportSize, verbose) {
var deferred = Q.defer();
a11y(url, {viewportSize: viewportSize}, function (err, reports) {
if (err) {
deferred.reject(new Error(err));
} else {
deferred.resolve({url: url, reports: reports, verbose: verbose});
}
});
return deferred.promise;
}
|
javascript
|
function a11yPromise (url, viewportSize, verbose) {
var deferred = Q.defer();
a11y(url, {viewportSize: viewportSize}, function (err, reports) {
if (err) {
deferred.reject(new Error(err));
} else {
deferred.resolve({url: url, reports: reports, verbose: verbose});
}
});
return deferred.promise;
}
|
[
"function",
"a11yPromise",
"(",
"url",
",",
"viewportSize",
",",
"verbose",
")",
"{",
"var",
"deferred",
"=",
"Q",
".",
"defer",
"(",
")",
";",
"a11y",
"(",
"url",
",",
"{",
"viewportSize",
":",
"viewportSize",
"}",
",",
"function",
"(",
"err",
",",
"reports",
")",
"{",
"if",
"(",
"err",
")",
"{",
"deferred",
".",
"reject",
"(",
"new",
"Error",
"(",
"err",
")",
")",
";",
"}",
"else",
"{",
"deferred",
".",
"resolve",
"(",
"{",
"url",
":",
"url",
",",
"reports",
":",
"reports",
",",
"verbose",
":",
"verbose",
"}",
")",
";",
"}",
"}",
")",
";",
"return",
"deferred",
".",
"promise",
";",
"}"
] |
A promise-based wrapper on a11y.
@param {String} url
@param {String} viewportSize
@param {Boolean} verbose
@return {Promise}
|
[
"A",
"promise",
"-",
"based",
"wrapper",
"on",
"a11y",
"."
] |
b11f0175d69cc0dbd6dd2b452616cb40fad545d8
|
https://github.com/lucalanca/grunt-a11y/blob/b11f0175d69cc0dbd6dd2b452616cb40fad545d8/tasks/a11y.js#L32-L42
|
train
|
lucalanca/grunt-a11y
|
tasks/a11y.js
|
logReports
|
function logReports (url, reports, verbose) {
var passes = '';
var failures = '';
grunt.log.writeln(chalk.underline(chalk.cyan('\nReport for ' + url + '\n')));
reports.audit.forEach(function (el) {
if (el.result === 'PASS') {
passes += logSymbols.success + ' ' + el.heading + '\n';
}
if (el.result === 'FAIL') {
failures += logSymbols.error + ' ' + el.heading + '\n';
failures += el.elements + '\n\n';
}
});
grunt.log.writeln(indent(failures, ' ', 2));
grunt.log.writeln(indent(passes , ' ', 2));
if (verbose) {
grunt.log.writeln('VERBOSE OUTPUT\n', reports.audit);
}
return !failures.length;
}
|
javascript
|
function logReports (url, reports, verbose) {
var passes = '';
var failures = '';
grunt.log.writeln(chalk.underline(chalk.cyan('\nReport for ' + url + '\n')));
reports.audit.forEach(function (el) {
if (el.result === 'PASS') {
passes += logSymbols.success + ' ' + el.heading + '\n';
}
if (el.result === 'FAIL') {
failures += logSymbols.error + ' ' + el.heading + '\n';
failures += el.elements + '\n\n';
}
});
grunt.log.writeln(indent(failures, ' ', 2));
grunt.log.writeln(indent(passes , ' ', 2));
if (verbose) {
grunt.log.writeln('VERBOSE OUTPUT\n', reports.audit);
}
return !failures.length;
}
|
[
"function",
"logReports",
"(",
"url",
",",
"reports",
",",
"verbose",
")",
"{",
"var",
"passes",
"=",
"''",
";",
"var",
"failures",
"=",
"''",
";",
"grunt",
".",
"log",
".",
"writeln",
"(",
"chalk",
".",
"underline",
"(",
"chalk",
".",
"cyan",
"(",
"'\\nReport for '",
"+",
"\\n",
"+",
"url",
")",
")",
")",
";",
"'\\n'",
"\\n",
"reports",
".",
"audit",
".",
"forEach",
"(",
"function",
"(",
"el",
")",
"{",
"if",
"(",
"el",
".",
"result",
"===",
"'PASS'",
")",
"{",
"passes",
"+=",
"logSymbols",
".",
"success",
"+",
"' '",
"+",
"el",
".",
"heading",
"+",
"'\\n'",
";",
"}",
"\\n",
"}",
")",
";",
"if",
"(",
"el",
".",
"result",
"===",
"'FAIL'",
")",
"{",
"failures",
"+=",
"logSymbols",
".",
"error",
"+",
"' '",
"+",
"el",
".",
"heading",
"+",
"'\\n'",
";",
"\\n",
"}",
"failures",
"+=",
"el",
".",
"elements",
"+",
"'\\n\\n'",
";",
"}"
] |
Utility function that logs an audit in the console and
returns a boolean with the validity of the audit.
@param {String} url
@param {a11y reports} reports
@return {Boolean} if the audit is valid
|
[
"Utility",
"function",
"that",
"logs",
"an",
"audit",
"in",
"the",
"console",
"and",
"returns",
"a",
"boolean",
"with",
"the",
"validity",
"of",
"the",
"audit",
"."
] |
b11f0175d69cc0dbd6dd2b452616cb40fad545d8
|
https://github.com/lucalanca/grunt-a11y/blob/b11f0175d69cc0dbd6dd2b452616cb40fad545d8/tasks/a11y.js#L52-L76
|
train
|
pubkey/async-test-util
|
dist/lib/random-string.js
|
randomString
|
function randomString() {
var length = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 8;
var charset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'abcdefghijklmnopqrstuvwxyz';
var text = '';
for (var i = 0; i < length; i++) {
text += charset.charAt(Math.floor(Math.random() * charset.length));
}return text;
}
|
javascript
|
function randomString() {
var length = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 8;
var charset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'abcdefghijklmnopqrstuvwxyz';
var text = '';
for (var i = 0; i < length; i++) {
text += charset.charAt(Math.floor(Math.random() * charset.length));
}return text;
}
|
[
"function",
"randomString",
"(",
")",
"{",
"var",
"length",
"=",
"arguments",
".",
"length",
">",
"0",
"&&",
"arguments",
"[",
"0",
"]",
"!==",
"undefined",
"?",
"arguments",
"[",
"0",
"]",
":",
"8",
";",
"var",
"charset",
"=",
"arguments",
".",
"length",
">",
"1",
"&&",
"arguments",
"[",
"1",
"]",
"!==",
"undefined",
"?",
"arguments",
"[",
"1",
"]",
":",
"'abcdefghijklmnopqrstuvwxyz'",
";",
"var",
"text",
"=",
"''",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"length",
";",
"i",
"++",
")",
"{",
"text",
"+=",
"charset",
".",
"charAt",
"(",
"Math",
".",
"floor",
"(",
"Math",
".",
"random",
"(",
")",
"*",
"charset",
".",
"length",
")",
")",
";",
"}",
"return",
"text",
";",
"}"
] |
create a random string
@return {string}
|
[
"create",
"a",
"random",
"string"
] |
5f8bf587cd9d16217f4a19755303a88c30b1f2db
|
https://github.com/pubkey/async-test-util/blob/5f8bf587cd9d16217f4a19755303a88c30b1f2db/dist/lib/random-string.js#L11-L19
|
train
|
FineLinePrototyping/angularjs-rails-resource
|
dist/extensions/snapshots.js
|
_prepSnapshot
|
function _prepSnapshot() {
var config = this.constructor.config,
copy = (config.snapshotSerializer || config.serializer).serialize(this);
// we don't want to store our snapshots in the snapshots because that would make the rollback kind of funny
// not to mention using more memory for each snapshot.
delete copy.$$snapshots;
return copy
}
|
javascript
|
function _prepSnapshot() {
var config = this.constructor.config,
copy = (config.snapshotSerializer || config.serializer).serialize(this);
// we don't want to store our snapshots in the snapshots because that would make the rollback kind of funny
// not to mention using more memory for each snapshot.
delete copy.$$snapshots;
return copy
}
|
[
"function",
"_prepSnapshot",
"(",
")",
"{",
"var",
"config",
"=",
"this",
".",
"constructor",
".",
"config",
",",
"copy",
"=",
"(",
"config",
".",
"snapshotSerializer",
"||",
"config",
".",
"serializer",
")",
".",
"serialize",
"(",
"this",
")",
";",
"delete",
"copy",
".",
"$$snapshots",
";",
"return",
"copy",
"}"
] |
Prepares a copy of the resource to be stored as a snapshot
@returns {Resource} the copied resource, sans $$snapshots
|
[
"Prepares",
"a",
"copy",
"of",
"the",
"resource",
"to",
"be",
"stored",
"as",
"a",
"snapshot"
] |
1edf9a4d924b060e62ed7a44041dea00898b0a3b
|
https://github.com/FineLinePrototyping/angularjs-rails-resource/blob/1edf9a4d924b060e62ed7a44041dea00898b0a3b/dist/extensions/snapshots.js#L32-L41
|
train
|
FineLinePrototyping/angularjs-rails-resource
|
dist/extensions/snapshots.js
|
rollback
|
function rollback(numVersions) {
var snapshotsLength = this.$$snapshots ? this.$$snapshots.length : 0;
numVersions = Math.min(numVersions || 1, snapshotsLength);
if (numVersions < 0) {
numVersions = snapshotsLength;
}
if (snapshotsLength) {
this.rollbackTo(this.$$snapshots.length - numVersions);
}
return true;
}
|
javascript
|
function rollback(numVersions) {
var snapshotsLength = this.$$snapshots ? this.$$snapshots.length : 0;
numVersions = Math.min(numVersions || 1, snapshotsLength);
if (numVersions < 0) {
numVersions = snapshotsLength;
}
if (snapshotsLength) {
this.rollbackTo(this.$$snapshots.length - numVersions);
}
return true;
}
|
[
"function",
"rollback",
"(",
"numVersions",
")",
"{",
"var",
"snapshotsLength",
"=",
"this",
".",
"$$snapshots",
"?",
"this",
".",
"$$snapshots",
".",
"length",
":",
"0",
";",
"numVersions",
"=",
"Math",
".",
"min",
"(",
"numVersions",
"||",
"1",
",",
"snapshotsLength",
")",
";",
"if",
"(",
"numVersions",
"<",
"0",
")",
"{",
"numVersions",
"=",
"snapshotsLength",
";",
"}",
"if",
"(",
"snapshotsLength",
")",
"{",
"this",
".",
"rollbackTo",
"(",
"this",
".",
"$$snapshots",
".",
"length",
"-",
"numVersions",
")",
";",
"}",
"return",
"true",
";",
"}"
] |
Rolls back the resource to a previous snapshot.
When numVersions is undefined or 0 then a single version is rolled back.
When numVersions exceeds the stored number of snapshots then the resource is rolled back to the first snapshot version.
When numVersions is less than 0 then the resource is rolled back to the first snapshot version.
@param {Number|undefined} numVersions The number of versions to roll back to. If undefined then
@returns {Boolean} true if rollback was successful, false otherwise
|
[
"Rolls",
"back",
"the",
"resource",
"to",
"a",
"previous",
"snapshot",
"."
] |
1edf9a4d924b060e62ed7a44041dea00898b0a3b
|
https://github.com/FineLinePrototyping/angularjs-rails-resource/blob/1edf9a4d924b060e62ed7a44041dea00898b0a3b/dist/extensions/snapshots.js#L117-L130
|
train
|
FineLinePrototyping/angularjs-rails-resource
|
dist/extensions/snapshots.js
|
unsnappedChanges
|
function unsnappedChanges() {
if (!this.$$snapshots) {
return true
}
var copy = this._prepSnapshot(),
latestSnap = this.$$snapshots[this.$$snapshots.length - 1]
return !angular.equals(copy, latestSnap)
}
|
javascript
|
function unsnappedChanges() {
if (!this.$$snapshots) {
return true
}
var copy = this._prepSnapshot(),
latestSnap = this.$$snapshots[this.$$snapshots.length - 1]
return !angular.equals(copy, latestSnap)
}
|
[
"function",
"unsnappedChanges",
"(",
")",
"{",
"if",
"(",
"!",
"this",
".",
"$$snapshots",
")",
"{",
"return",
"true",
"}",
"var",
"copy",
"=",
"this",
".",
"_prepSnapshot",
"(",
")",
",",
"latestSnap",
"=",
"this",
".",
"$$snapshots",
"[",
"this",
".",
"$$snapshots",
".",
"length",
"-",
"1",
"]",
"return",
"!",
"angular",
".",
"equals",
"(",
"copy",
",",
"latestSnap",
")",
"}"
] |
Checks if resource is changed from the most recent snapshot.
@returns {Boolean} true if the latest snapshot differs from resource as-is
|
[
"Checks",
"if",
"resource",
"is",
"changed",
"from",
"the",
"most",
"recent",
"snapshot",
"."
] |
1edf9a4d924b060e62ed7a44041dea00898b0a3b
|
https://github.com/FineLinePrototyping/angularjs-rails-resource/blob/1edf9a4d924b060e62ed7a44041dea00898b0a3b/dist/extensions/snapshots.js#L136-L145
|
train
|
FineLinePrototyping/angularjs-rails-resource
|
dist/angularjs-rails-resource.js
|
getService
|
function getService(service) {
// strings and functions are not considered objects by angular.isObject()
if (angular.isObject(service)) {
return service;
} else if (service) {
return createService(service);
}
return undefined;
}
|
javascript
|
function getService(service) {
// strings and functions are not considered objects by angular.isObject()
if (angular.isObject(service)) {
return service;
} else if (service) {
return createService(service);
}
return undefined;
}
|
[
"function",
"getService",
"(",
"service",
")",
"{",
"if",
"(",
"angular",
".",
"isObject",
"(",
"service",
")",
")",
"{",
"return",
"service",
";",
"}",
"else",
"if",
"(",
"service",
")",
"{",
"return",
"createService",
"(",
"service",
")",
";",
"}",
"return",
"undefined",
";",
"}"
] |
Looks up and instantiates an instance of the requested service if .
@param {String|function|Object} service The service to instantiate
@returns {*}
|
[
"Looks",
"up",
"and",
"instantiates",
"an",
"instance",
"of",
"the",
"requested",
"service",
"if",
"."
] |
1edf9a4d924b060e62ed7a44041dea00898b0a3b
|
https://github.com/FineLinePrototyping/angularjs-rails-resource/blob/1edf9a4d924b060e62ed7a44041dea00898b0a3b/dist/angularjs-rails-resource.js#L87-L96
|
train
|
marcello3d/node-mongolian
|
lib/gridfile.js
|
MongolianGridFileWriteStream
|
function MongolianGridFileWriteStream(file) {
if (file.chunkSize instanceof Long) throw new Error("Long (64bit) chunkSize unsupported")
if (file.chunkSize <= 0) throw new Error("File has invalid chunkSize: "+file.chunkSize)
stream.Stream.call(this)
this.file = file
this.writable = true
this.encoding = 'binary'
this._hash = crypto.createHash('md5')
this._chunkIndex = 0
file.length = 0
this._chunkSize = file.chunkSize
}
|
javascript
|
function MongolianGridFileWriteStream(file) {
if (file.chunkSize instanceof Long) throw new Error("Long (64bit) chunkSize unsupported")
if (file.chunkSize <= 0) throw new Error("File has invalid chunkSize: "+file.chunkSize)
stream.Stream.call(this)
this.file = file
this.writable = true
this.encoding = 'binary'
this._hash = crypto.createHash('md5')
this._chunkIndex = 0
file.length = 0
this._chunkSize = file.chunkSize
}
|
[
"function",
"MongolianGridFileWriteStream",
"(",
"file",
")",
"{",
"if",
"(",
"file",
".",
"chunkSize",
"instanceof",
"Long",
")",
"throw",
"new",
"Error",
"(",
"\"Long (64bit) chunkSize unsupported\"",
")",
"if",
"(",
"file",
".",
"chunkSize",
"<=",
"0",
")",
"throw",
"new",
"Error",
"(",
"\"File has invalid chunkSize: \"",
"+",
"file",
".",
"chunkSize",
")",
"stream",
".",
"Stream",
".",
"call",
"(",
"this",
")",
"this",
".",
"file",
"=",
"file",
"this",
".",
"writable",
"=",
"true",
"this",
".",
"encoding",
"=",
"'binary'",
"this",
".",
"_hash",
"=",
"crypto",
".",
"createHash",
"(",
"'md5'",
")",
"this",
".",
"_chunkIndex",
"=",
"0",
"file",
".",
"length",
"=",
"0",
"this",
".",
"_chunkSize",
"=",
"file",
".",
"chunkSize",
"}"
] |
Treats a MongolianGridFile as a node.js Writeable Stream
|
[
"Treats",
"a",
"MongolianGridFile",
"as",
"a",
"node",
".",
"js",
"Writeable",
"Stream"
] |
4a337462c712a400cd4644d2cdf5177ed964163e
|
https://github.com/marcello3d/node-mongolian/blob/4a337462c712a400cd4644d2cdf5177ed964163e/lib/gridfile.js#L115-L126
|
train
|
marcello3d/node-mongolian
|
lib/gridfile.js
|
MongolianGridFileReadStream
|
function MongolianGridFileReadStream(file) {
if (!file._id) throw new Error("Can only read files retrieved from the database")
if (file.chunkSize instanceof Long) throw new Error("Long (64bit) chunkSize unsupported")
if (file.chunkSize <= 0) throw new Error("File has invalid chunkSize: "+file.chunkSize)
stream.Stream.call(this)
this.file = file
this.readable = true
this._chunkCount = file.chunkCount()
this._chunkIndex = 0
process.nextTick(this._nextChunk.bind(this))
}
|
javascript
|
function MongolianGridFileReadStream(file) {
if (!file._id) throw new Error("Can only read files retrieved from the database")
if (file.chunkSize instanceof Long) throw new Error("Long (64bit) chunkSize unsupported")
if (file.chunkSize <= 0) throw new Error("File has invalid chunkSize: "+file.chunkSize)
stream.Stream.call(this)
this.file = file
this.readable = true
this._chunkCount = file.chunkCount()
this._chunkIndex = 0
process.nextTick(this._nextChunk.bind(this))
}
|
[
"function",
"MongolianGridFileReadStream",
"(",
"file",
")",
"{",
"if",
"(",
"!",
"file",
".",
"_id",
")",
"throw",
"new",
"Error",
"(",
"\"Can only read files retrieved from the database\"",
")",
"if",
"(",
"file",
".",
"chunkSize",
"instanceof",
"Long",
")",
"throw",
"new",
"Error",
"(",
"\"Long (64bit) chunkSize unsupported\"",
")",
"if",
"(",
"file",
".",
"chunkSize",
"<=",
"0",
")",
"throw",
"new",
"Error",
"(",
"\"File has invalid chunkSize: \"",
"+",
"file",
".",
"chunkSize",
")",
"stream",
".",
"Stream",
".",
"call",
"(",
"this",
")",
"this",
".",
"file",
"=",
"file",
"this",
".",
"readable",
"=",
"true",
"this",
".",
"_chunkCount",
"=",
"file",
".",
"chunkCount",
"(",
")",
"this",
".",
"_chunkIndex",
"=",
"0",
"process",
".",
"nextTick",
"(",
"this",
".",
"_nextChunk",
".",
"bind",
"(",
"this",
")",
")",
"}"
] |
Treats a MongolianGridFile as a node.js Readable Stream
|
[
"Treats",
"a",
"MongolianGridFile",
"as",
"a",
"node",
".",
"js",
"Readable",
"Stream"
] |
4a337462c712a400cd4644d2cdf5177ed964163e
|
https://github.com/marcello3d/node-mongolian/blob/4a337462c712a400cd4644d2cdf5177ed964163e/lib/gridfile.js#L211-L224
|
train
|
marcello3d/node-mongolian
|
lib/server.js
|
MongolianServer
|
function MongolianServer(mongolian, url) {
var self = this
this.mongolian = mongolian
this.url = url
this._callbacks = []
this._callbackCount = 0
this._connection = taxman(function(callback) {
var connection = new Connection
var connected = false
connection.requestId = 0
connection.on('error', function(error) {
mongolian.log.error(self+": "+require('util').inspect(error))
if (!connected) callback(error)
self.close(error)
})
connection.on('close', function() {
mongolian.log.debug(self+": Disconnected")
self.close()
})
connection.on('connect',function() {
mongolian.log.debug(self+": Connected")
connected = true
callback(null, connection)
})
connection.on('message', function(message) {
var response = new mongo.Response(message)
// mongolian.log.debug("<<<--- "+require('util').inspect(response,undefined,5,true).slice(0,5000))
var cb = self._callbacks[response.responseTo]
if (cb) {
delete self._callbacks[response.responseTo]
self._callbackCount--
cb(null,response)
}
})
connection.connect(url.port, url.host)
})
}
|
javascript
|
function MongolianServer(mongolian, url) {
var self = this
this.mongolian = mongolian
this.url = url
this._callbacks = []
this._callbackCount = 0
this._connection = taxman(function(callback) {
var connection = new Connection
var connected = false
connection.requestId = 0
connection.on('error', function(error) {
mongolian.log.error(self+": "+require('util').inspect(error))
if (!connected) callback(error)
self.close(error)
})
connection.on('close', function() {
mongolian.log.debug(self+": Disconnected")
self.close()
})
connection.on('connect',function() {
mongolian.log.debug(self+": Connected")
connected = true
callback(null, connection)
})
connection.on('message', function(message) {
var response = new mongo.Response(message)
// mongolian.log.debug("<<<--- "+require('util').inspect(response,undefined,5,true).slice(0,5000))
var cb = self._callbacks[response.responseTo]
if (cb) {
delete self._callbacks[response.responseTo]
self._callbackCount--
cb(null,response)
}
})
connection.connect(url.port, url.host)
})
}
|
[
"function",
"MongolianServer",
"(",
"mongolian",
",",
"url",
")",
"{",
"var",
"self",
"=",
"this",
"this",
".",
"mongolian",
"=",
"mongolian",
"this",
".",
"url",
"=",
"url",
"this",
".",
"_callbacks",
"=",
"[",
"]",
"this",
".",
"_callbackCount",
"=",
"0",
"this",
".",
"_connection",
"=",
"taxman",
"(",
"function",
"(",
"callback",
")",
"{",
"var",
"connection",
"=",
"new",
"Connection",
"var",
"connected",
"=",
"false",
"connection",
".",
"requestId",
"=",
"0",
"connection",
".",
"on",
"(",
"'error'",
",",
"function",
"(",
"error",
")",
"{",
"mongolian",
".",
"log",
".",
"error",
"(",
"self",
"+",
"\": \"",
"+",
"require",
"(",
"'util'",
")",
".",
"inspect",
"(",
"error",
")",
")",
"if",
"(",
"!",
"connected",
")",
"callback",
"(",
"error",
")",
"self",
".",
"close",
"(",
"error",
")",
"}",
")",
"connection",
".",
"on",
"(",
"'close'",
",",
"function",
"(",
")",
"{",
"mongolian",
".",
"log",
".",
"debug",
"(",
"self",
"+",
"\": Disconnected\"",
")",
"self",
".",
"close",
"(",
")",
"}",
")",
"connection",
".",
"on",
"(",
"'connect'",
",",
"function",
"(",
")",
"{",
"mongolian",
".",
"log",
".",
"debug",
"(",
"self",
"+",
"\": Connected\"",
")",
"connected",
"=",
"true",
"callback",
"(",
"null",
",",
"connection",
")",
"}",
")",
"connection",
".",
"on",
"(",
"'message'",
",",
"function",
"(",
"message",
")",
"{",
"var",
"response",
"=",
"new",
"mongo",
".",
"Response",
"(",
"message",
")",
"var",
"cb",
"=",
"self",
".",
"_callbacks",
"[",
"response",
".",
"responseTo",
"]",
"if",
"(",
"cb",
")",
"{",
"delete",
"self",
".",
"_callbacks",
"[",
"response",
".",
"responseTo",
"]",
"self",
".",
"_callbackCount",
"--",
"cb",
"(",
"null",
",",
"response",
")",
"}",
"}",
")",
"connection",
".",
"connect",
"(",
"url",
".",
"port",
",",
"url",
".",
"host",
")",
"}",
")",
"}"
] |
Constructs a new MongolianServer object
|
[
"Constructs",
"a",
"new",
"MongolianServer",
"object"
] |
4a337462c712a400cd4644d2cdf5177ed964163e
|
https://github.com/marcello3d/node-mongolian/blob/4a337462c712a400cd4644d2cdf5177ed964163e/lib/server.js#L202-L239
|
train
|
marcello3d/node-mongolian
|
examples/mongolian_trainer.js
|
fillCollection
|
function fillCollection(collection, max, callback) {
collection.count(function(err,count) {
console.log(collection+" count = "+count)
while (count < max) {
var toInsert = []
while (count < max) {
toInsert.push({ foo: Math.random(), index: count++ })
if (toInsert.length == 300) {
break
}
}
console.log("inserting "+toInsert.length+" document(s) into "+collection)
collection.insert(toInsert)
}
callback()
})
}
|
javascript
|
function fillCollection(collection, max, callback) {
collection.count(function(err,count) {
console.log(collection+" count = "+count)
while (count < max) {
var toInsert = []
while (count < max) {
toInsert.push({ foo: Math.random(), index: count++ })
if (toInsert.length == 300) {
break
}
}
console.log("inserting "+toInsert.length+" document(s) into "+collection)
collection.insert(toInsert)
}
callback()
})
}
|
[
"function",
"fillCollection",
"(",
"collection",
",",
"max",
",",
"callback",
")",
"{",
"collection",
".",
"count",
"(",
"function",
"(",
"err",
",",
"count",
")",
"{",
"console",
".",
"log",
"(",
"collection",
"+",
"\" count = \"",
"+",
"count",
")",
"while",
"(",
"count",
"<",
"max",
")",
"{",
"var",
"toInsert",
"=",
"[",
"]",
"while",
"(",
"count",
"<",
"max",
")",
"{",
"toInsert",
".",
"push",
"(",
"{",
"foo",
":",
"Math",
".",
"random",
"(",
")",
",",
"index",
":",
"count",
"++",
"}",
")",
"if",
"(",
"toInsert",
".",
"length",
"==",
"300",
")",
"{",
"break",
"}",
"}",
"console",
".",
"log",
"(",
"\"inserting \"",
"+",
"toInsert",
".",
"length",
"+",
"\" document(s) into \"",
"+",
"collection",
")",
"collection",
".",
"insert",
"(",
"toInsert",
")",
"}",
"callback",
"(",
")",
"}",
")",
"}"
] |
Adds some junk to the database
|
[
"Adds",
"some",
"junk",
"to",
"the",
"database"
] |
4a337462c712a400cd4644d2cdf5177ed964163e
|
https://github.com/marcello3d/node-mongolian/blob/4a337462c712a400cd4644d2cdf5177ed964163e/examples/mongolian_trainer.js#L21-L37
|
train
|
marcello3d/node-mongolian
|
examples/mongolian_trainer.js
|
funBuffer
|
function funBuffer(size) {
var buffer = new Buffer(size)
for (var i=0; i<size; i++) {
if (i%1000 == 0) buffer[i++] = 13
buffer[i] = 97 + (i%26)
}
return buffer
}
|
javascript
|
function funBuffer(size) {
var buffer = new Buffer(size)
for (var i=0; i<size; i++) {
if (i%1000 == 0) buffer[i++] = 13
buffer[i] = 97 + (i%26)
}
return buffer
}
|
[
"function",
"funBuffer",
"(",
"size",
")",
"{",
"var",
"buffer",
"=",
"new",
"Buffer",
"(",
"size",
")",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"size",
";",
"i",
"++",
")",
"{",
"if",
"(",
"i",
"%",
"1000",
"==",
"0",
")",
"buffer",
"[",
"i",
"++",
"]",
"=",
"13",
"buffer",
"[",
"i",
"]",
"=",
"97",
"+",
"(",
"i",
"%",
"26",
")",
"}",
"return",
"buffer",
"}"
] |
Generates alphabet buffers
|
[
"Generates",
"alphabet",
"buffers"
] |
4a337462c712a400cd4644d2cdf5177ed964163e
|
https://github.com/marcello3d/node-mongolian/blob/4a337462c712a400cd4644d2cdf5177ed964163e/examples/mongolian_trainer.js#L152-L159
|
train
|
jsreport/jsreport-xlsx
|
static/helpers.js
|
safeGet
|
function safeGet (obj, path) {
// split ['c:chart'].row[0] into ['c:chart', 'row', 0]
var paths = path.replace(/\[/g, '.').replace(/\]/g, '').replace(/'/g, '').split('.')
for (var i = 0; i < paths.length; i++) {
if (paths[i] === '') {
// the first can be empty string if the path starts with ['chart:c']
continue
}
var objReference = 'obj["' + paths[i] + '"]'
// the last must be always array, also if accessor is number, we want to initialize as array
var emptySafe = ((i === paths.length - 1) || !isNaN(paths[i + 1])) ? '[]' : '{}'
new Function('obj', objReference + ' = ' + objReference + ' || ' + emptySafe)(obj)
obj = new Function('obj', 'return ' + objReference)(obj)
}
return obj
}
|
javascript
|
function safeGet (obj, path) {
// split ['c:chart'].row[0] into ['c:chart', 'row', 0]
var paths = path.replace(/\[/g, '.').replace(/\]/g, '').replace(/'/g, '').split('.')
for (var i = 0; i < paths.length; i++) {
if (paths[i] === '') {
// the first can be empty string if the path starts with ['chart:c']
continue
}
var objReference = 'obj["' + paths[i] + '"]'
// the last must be always array, also if accessor is number, we want to initialize as array
var emptySafe = ((i === paths.length - 1) || !isNaN(paths[i + 1])) ? '[]' : '{}'
new Function('obj', objReference + ' = ' + objReference + ' || ' + emptySafe)(obj)
obj = new Function('obj', 'return ' + objReference)(obj)
}
return obj
}
|
[
"function",
"safeGet",
"(",
"obj",
",",
"path",
")",
"{",
"var",
"paths",
"=",
"path",
".",
"replace",
"(",
"/",
"\\[",
"/",
"g",
",",
"'.'",
")",
".",
"replace",
"(",
"/",
"\\]",
"/",
"g",
",",
"''",
")",
".",
"replace",
"(",
"/",
"'",
"/",
"g",
",",
"''",
")",
".",
"split",
"(",
"'.'",
")",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"paths",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"paths",
"[",
"i",
"]",
"===",
"''",
")",
"{",
"continue",
"}",
"var",
"objReference",
"=",
"'obj[\"'",
"+",
"paths",
"[",
"i",
"]",
"+",
"'\"]'",
"var",
"emptySafe",
"=",
"(",
"(",
"i",
"===",
"paths",
".",
"length",
"-",
"1",
")",
"||",
"!",
"isNaN",
"(",
"paths",
"[",
"i",
"+",
"1",
"]",
")",
")",
"?",
"'[]'",
":",
"'{}'",
"new",
"Function",
"(",
"'obj'",
",",
"objReference",
"+",
"' = '",
"+",
"objReference",
"+",
"' || '",
"+",
"emptySafe",
")",
"(",
"obj",
")",
"obj",
"=",
"new",
"Function",
"(",
"'obj'",
",",
"'return '",
"+",
"objReference",
")",
"(",
"obj",
")",
"}",
"return",
"obj",
"}"
] |
Safely go through object path and create the missing object parts with
empty array or object to be compatible with xml -> json represantation
|
[
"Safely",
"go",
"through",
"object",
"path",
"and",
"create",
"the",
"missing",
"object",
"parts",
"with",
"empty",
"array",
"or",
"object",
"to",
"be",
"compatible",
"with",
"xml",
"-",
">",
"json",
"represantation"
] |
8dbadd5af87dd9eb4386919e306aa5458f273b54
|
https://github.com/jsreport/jsreport-xlsx/blob/8dbadd5af87dd9eb4386919e306aa5458f273b54/static/helpers.js#L196-L215
|
train
|
massgov/mayflower
|
patternlab/styleguide/public/styleguide/js/patternlab-viewer.js
|
function (name,val) {
var cookieVal = $.cookie(this.cookieName);
cookieVal = ((cookieVal === null) || (cookieVal === "")) ? name+"~"+val : cookieVal+"|"+name+"~"+val;
$.cookie(this.cookieName,cookieVal);
}
|
javascript
|
function (name,val) {
var cookieVal = $.cookie(this.cookieName);
cookieVal = ((cookieVal === null) || (cookieVal === "")) ? name+"~"+val : cookieVal+"|"+name+"~"+val;
$.cookie(this.cookieName,cookieVal);
}
|
[
"function",
"(",
"name",
",",
"val",
")",
"{",
"var",
"cookieVal",
"=",
"$",
".",
"cookie",
"(",
"this",
".",
"cookieName",
")",
";",
"cookieVal",
"=",
"(",
"(",
"cookieVal",
"===",
"null",
")",
"||",
"(",
"cookieVal",
"===",
"\"\"",
")",
")",
"?",
"name",
"+",
"\"~\"",
"+",
"val",
":",
"cookieVal",
"+",
"\"|\"",
"+",
"name",
"+",
"\"~\"",
"+",
"val",
";",
"$",
".",
"cookie",
"(",
"this",
".",
"cookieName",
",",
"cookieVal",
")",
";",
"}"
] |
Add a given value to the cookie
@param {String} the name of the key
@param {String} the value
|
[
"Add",
"a",
"given",
"value",
"to",
"the",
"cookie"
] |
6ae90009c5d611f9fdbcc208f9bd5f1e22926094
|
https://github.com/massgov/mayflower/blob/6ae90009c5d611f9fdbcc208f9bd5f1e22926094/patternlab/styleguide/public/styleguide/js/patternlab-viewer.js#L91-L95
|
train
|
|
massgov/mayflower
|
patternlab/styleguide/public/styleguide/js/patternlab-viewer.js
|
function (name,val) {
if (this.findValue(name)) {
var updateCookieVals = "";
var cookieVals = $.cookie(this.cookieName).split("|");
for (var i = 0; i < cookieVals.length; i++) {
var fieldVals = cookieVals[i].split("~");
if (fieldVals[0] == name) {
fieldVals[1] = val;
}
updateCookieVals += (i > 0) ? "|"+fieldVals[0]+"~"+fieldVals[1] : fieldVals[0]+"~"+fieldVals[1];
}
$.cookie(this.cookieName,updateCookieVals);
} else {
this.addValue(name,val);
}
}
|
javascript
|
function (name,val) {
if (this.findValue(name)) {
var updateCookieVals = "";
var cookieVals = $.cookie(this.cookieName).split("|");
for (var i = 0; i < cookieVals.length; i++) {
var fieldVals = cookieVals[i].split("~");
if (fieldVals[0] == name) {
fieldVals[1] = val;
}
updateCookieVals += (i > 0) ? "|"+fieldVals[0]+"~"+fieldVals[1] : fieldVals[0]+"~"+fieldVals[1];
}
$.cookie(this.cookieName,updateCookieVals);
} else {
this.addValue(name,val);
}
}
|
[
"function",
"(",
"name",
",",
"val",
")",
"{",
"if",
"(",
"this",
".",
"findValue",
"(",
"name",
")",
")",
"{",
"var",
"updateCookieVals",
"=",
"\"\"",
";",
"var",
"cookieVals",
"=",
"$",
".",
"cookie",
"(",
"this",
".",
"cookieName",
")",
".",
"split",
"(",
"\"|\"",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"cookieVals",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"fieldVals",
"=",
"cookieVals",
"[",
"i",
"]",
".",
"split",
"(",
"\"~\"",
")",
";",
"if",
"(",
"fieldVals",
"[",
"0",
"]",
"==",
"name",
")",
"{",
"fieldVals",
"[",
"1",
"]",
"=",
"val",
";",
"}",
"updateCookieVals",
"+=",
"(",
"i",
">",
"0",
")",
"?",
"\"|\"",
"+",
"fieldVals",
"[",
"0",
"]",
"+",
"\"~\"",
"+",
"fieldVals",
"[",
"1",
"]",
":",
"fieldVals",
"[",
"0",
"]",
"+",
"\"~\"",
"+",
"fieldVals",
"[",
"1",
"]",
";",
"}",
"$",
".",
"cookie",
"(",
"this",
".",
"cookieName",
",",
"updateCookieVals",
")",
";",
"}",
"else",
"{",
"this",
".",
"addValue",
"(",
"name",
",",
"val",
")",
";",
"}",
"}"
] |
Update a value found in the cookie. If the key doesn't exist add the value
@param {String} the name of the key
@param {String} the value
|
[
"Update",
"a",
"value",
"found",
"in",
"the",
"cookie",
".",
"If",
"the",
"key",
"doesn",
"t",
"exist",
"add",
"the",
"value"
] |
6ae90009c5d611f9fdbcc208f9bd5f1e22926094
|
https://github.com/massgov/mayflower/blob/6ae90009c5d611f9fdbcc208f9bd5f1e22926094/patternlab/styleguide/public/styleguide/js/patternlab-viewer.js#L102-L117
|
train
|
|
massgov/mayflower
|
patternlab/styleguide/public/styleguide/js/patternlab-viewer.js
|
function (name) {
var updateCookieVals = "";
var cookieVals = $.cookie(this.cookieName).split("|");
var k = 0;
for (var i = 0; i < cookieVals.length; i++) {
var fieldVals = cookieVals[i].split("~");
if (fieldVals[0] != name) {
updateCookieVals += (k === 0) ? fieldVals[0]+"~"+fieldVals[1] : "|"+fieldVals[0]+"~"+fieldVals[1];
k++;
}
}
$.cookie(this.cookieName,updateCookieVals);
}
|
javascript
|
function (name) {
var updateCookieVals = "";
var cookieVals = $.cookie(this.cookieName).split("|");
var k = 0;
for (var i = 0; i < cookieVals.length; i++) {
var fieldVals = cookieVals[i].split("~");
if (fieldVals[0] != name) {
updateCookieVals += (k === 0) ? fieldVals[0]+"~"+fieldVals[1] : "|"+fieldVals[0]+"~"+fieldVals[1];
k++;
}
}
$.cookie(this.cookieName,updateCookieVals);
}
|
[
"function",
"(",
"name",
")",
"{",
"var",
"updateCookieVals",
"=",
"\"\"",
";",
"var",
"cookieVals",
"=",
"$",
".",
"cookie",
"(",
"this",
".",
"cookieName",
")",
".",
"split",
"(",
"\"|\"",
")",
";",
"var",
"k",
"=",
"0",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"cookieVals",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"fieldVals",
"=",
"cookieVals",
"[",
"i",
"]",
".",
"split",
"(",
"\"~\"",
")",
";",
"if",
"(",
"fieldVals",
"[",
"0",
"]",
"!=",
"name",
")",
"{",
"updateCookieVals",
"+=",
"(",
"k",
"===",
"0",
")",
"?",
"fieldVals",
"[",
"0",
"]",
"+",
"\"~\"",
"+",
"fieldVals",
"[",
"1",
"]",
":",
"\"|\"",
"+",
"fieldVals",
"[",
"0",
"]",
"+",
"\"~\"",
"+",
"fieldVals",
"[",
"1",
"]",
";",
"k",
"++",
";",
"}",
"}",
"$",
".",
"cookie",
"(",
"this",
".",
"cookieName",
",",
"updateCookieVals",
")",
";",
"}"
] |
Remove the given key
@param {String} the name of the key
|
[
"Remove",
"the",
"given",
"key"
] |
6ae90009c5d611f9fdbcc208f9bd5f1e22926094
|
https://github.com/massgov/mayflower/blob/6ae90009c5d611f9fdbcc208f9bd5f1e22926094/patternlab/styleguide/public/styleguide/js/patternlab-viewer.js#L123-L135
|
train
|
|
massgov/mayflower
|
patternlab/styleguide/public/styleguide/js/patternlab-viewer.js
|
function() {
// the following is taken from https://developer.mozilla.org/en-US/docs/Web/API/window.location
var oGetVars = new (function (sSearch) {
if (sSearch.length > 1) {
for (var aItKey, nKeyId = 0, aCouples = sSearch.substr(1).split("&"); nKeyId < aCouples.length; nKeyId++) {
aItKey = aCouples[nKeyId].split("=");
this[unescape(aItKey[0])] = aItKey.length > 1 ? unescape(aItKey[1]) : "";
}
}
})(window.location.search);
return oGetVars;
}
|
javascript
|
function() {
// the following is taken from https://developer.mozilla.org/en-US/docs/Web/API/window.location
var oGetVars = new (function (sSearch) {
if (sSearch.length > 1) {
for (var aItKey, nKeyId = 0, aCouples = sSearch.substr(1).split("&"); nKeyId < aCouples.length; nKeyId++) {
aItKey = aCouples[nKeyId].split("=");
this[unescape(aItKey[0])] = aItKey.length > 1 ? unescape(aItKey[1]) : "";
}
}
})(window.location.search);
return oGetVars;
}
|
[
"function",
"(",
")",
"{",
"var",
"oGetVars",
"=",
"new",
"(",
"function",
"(",
"sSearch",
")",
"{",
"if",
"(",
"sSearch",
".",
"length",
">",
"1",
")",
"{",
"for",
"(",
"var",
"aItKey",
",",
"nKeyId",
"=",
"0",
",",
"aCouples",
"=",
"sSearch",
".",
"substr",
"(",
"1",
")",
".",
"split",
"(",
"\"&\"",
")",
";",
"nKeyId",
"<",
"aCouples",
".",
"length",
";",
"nKeyId",
"++",
")",
"{",
"aItKey",
"=",
"aCouples",
"[",
"nKeyId",
"]",
".",
"split",
"(",
"\"=\"",
")",
";",
"this",
"[",
"unescape",
"(",
"aItKey",
"[",
"0",
"]",
")",
"]",
"=",
"aItKey",
".",
"length",
">",
"1",
"?",
"unescape",
"(",
"aItKey",
"[",
"1",
"]",
")",
":",
"\"\"",
";",
"}",
"}",
"}",
")",
"(",
"window",
".",
"location",
".",
"search",
")",
";",
"return",
"oGetVars",
";",
"}"
] |
search the request vars for a particular item
@return {Object} a search of the window.location.search vars
|
[
"search",
"the",
"request",
"vars",
"for",
"a",
"particular",
"item"
] |
6ae90009c5d611f9fdbcc208f9bd5f1e22926094
|
https://github.com/massgov/mayflower/blob/6ae90009c5d611f9fdbcc208f9bd5f1e22926094/patternlab/styleguide/public/styleguide/js/patternlab-viewer.js#L303-L317
|
train
|
|
massgov/mayflower
|
patternlab/styleguide/public/styleguide/js/patternlab-viewer.js
|
function (pattern, givenPath) {
var data = { "pattern": pattern };
var fileName = urlHandler.getFileName(pattern);
var path = window.location.pathname;
path = (window.location.protocol === "file") ? path.replace("/public/index.html","public/") : path.replace(/\/index\.html/,"/");
var expectedPath = window.location.protocol+"//"+window.location.host+path+fileName;
if (givenPath != expectedPath) {
// make sure to update the iframe because there was a click
var obj = JSON.stringify({ "event": "patternLab.updatePath", "path": fileName });
document.getElementById("sg-viewport").contentWindow.postMessage(obj, urlHandler.targetOrigin);
} else {
// add to the history
var addressReplacement = (window.location.protocol == "file:") ? null : window.location.protocol+"//"+window.location.host+window.location.pathname.replace("index.html","")+"?p="+pattern;
if (history.pushState !== undefined) {
history.pushState(data, null, addressReplacement);
}
document.getElementById("title").innerHTML = "Pattern Lab - "+pattern;
if (document.getElementById("sg-raw") !== null) {
document.getElementById("sg-raw").setAttribute("href",urlHandler.getFileName(pattern));
}
}
}
|
javascript
|
function (pattern, givenPath) {
var data = { "pattern": pattern };
var fileName = urlHandler.getFileName(pattern);
var path = window.location.pathname;
path = (window.location.protocol === "file") ? path.replace("/public/index.html","public/") : path.replace(/\/index\.html/,"/");
var expectedPath = window.location.protocol+"//"+window.location.host+path+fileName;
if (givenPath != expectedPath) {
// make sure to update the iframe because there was a click
var obj = JSON.stringify({ "event": "patternLab.updatePath", "path": fileName });
document.getElementById("sg-viewport").contentWindow.postMessage(obj, urlHandler.targetOrigin);
} else {
// add to the history
var addressReplacement = (window.location.protocol == "file:") ? null : window.location.protocol+"//"+window.location.host+window.location.pathname.replace("index.html","")+"?p="+pattern;
if (history.pushState !== undefined) {
history.pushState(data, null, addressReplacement);
}
document.getElementById("title").innerHTML = "Pattern Lab - "+pattern;
if (document.getElementById("sg-raw") !== null) {
document.getElementById("sg-raw").setAttribute("href",urlHandler.getFileName(pattern));
}
}
}
|
[
"function",
"(",
"pattern",
",",
"givenPath",
")",
"{",
"var",
"data",
"=",
"{",
"\"pattern\"",
":",
"pattern",
"}",
";",
"var",
"fileName",
"=",
"urlHandler",
".",
"getFileName",
"(",
"pattern",
")",
";",
"var",
"path",
"=",
"window",
".",
"location",
".",
"pathname",
";",
"path",
"=",
"(",
"window",
".",
"location",
".",
"protocol",
"===",
"\"file\"",
")",
"?",
"path",
".",
"replace",
"(",
"\"/public/index.html\"",
",",
"\"public/\"",
")",
":",
"path",
".",
"replace",
"(",
"/",
"\\/index\\.html",
"/",
",",
"\"/\"",
")",
";",
"var",
"expectedPath",
"=",
"window",
".",
"location",
".",
"protocol",
"+",
"\"//\"",
"+",
"window",
".",
"location",
".",
"host",
"+",
"path",
"+",
"fileName",
";",
"if",
"(",
"givenPath",
"!=",
"expectedPath",
")",
"{",
"var",
"obj",
"=",
"JSON",
".",
"stringify",
"(",
"{",
"\"event\"",
":",
"\"patternLab.updatePath\"",
",",
"\"path\"",
":",
"fileName",
"}",
")",
";",
"document",
".",
"getElementById",
"(",
"\"sg-viewport\"",
")",
".",
"contentWindow",
".",
"postMessage",
"(",
"obj",
",",
"urlHandler",
".",
"targetOrigin",
")",
";",
"}",
"else",
"{",
"var",
"addressReplacement",
"=",
"(",
"window",
".",
"location",
".",
"protocol",
"==",
"\"file:\"",
")",
"?",
"null",
":",
"window",
".",
"location",
".",
"protocol",
"+",
"\"//\"",
"+",
"window",
".",
"location",
".",
"host",
"+",
"window",
".",
"location",
".",
"pathname",
".",
"replace",
"(",
"\"index.html\"",
",",
"\"\"",
")",
"+",
"\"?p=\"",
"+",
"pattern",
";",
"if",
"(",
"history",
".",
"pushState",
"!==",
"undefined",
")",
"{",
"history",
".",
"pushState",
"(",
"data",
",",
"null",
",",
"addressReplacement",
")",
";",
"}",
"document",
".",
"getElementById",
"(",
"\"title\"",
")",
".",
"innerHTML",
"=",
"\"Pattern Lab - \"",
"+",
"pattern",
";",
"if",
"(",
"document",
".",
"getElementById",
"(",
"\"sg-raw\"",
")",
"!==",
"null",
")",
"{",
"document",
".",
"getElementById",
"(",
"\"sg-raw\"",
")",
".",
"setAttribute",
"(",
"\"href\"",
",",
"urlHandler",
".",
"getFileName",
"(",
"pattern",
")",
")",
";",
"}",
"}",
"}"
] |
push a pattern onto the current history based on a click
@param {String} the shorthand partials syntax for a given pattern
@param {String} the path given by the loaded iframe
|
[
"push",
"a",
"pattern",
"onto",
"the",
"current",
"history",
"based",
"on",
"a",
"click"
] |
6ae90009c5d611f9fdbcc208f9bd5f1e22926094
|
https://github.com/massgov/mayflower/blob/6ae90009c5d611f9fdbcc208f9bd5f1e22926094/patternlab/styleguide/public/styleguide/js/patternlab-viewer.js#L324-L345
|
train
|
|
massgov/mayflower
|
patternlab/styleguide/public/styleguide/js/patternlab-viewer.js
|
function() {
// make sure the modal viewer and other options are off just in case
modalViewer.close();
// note it's turned on in the viewer
DataSaver.updateValue('modalActive', 'true');
modalViewer.active = true;
// add an active class to the button that matches this template
$('#sg-t-'+modalViewer.template+' .sg-checkbox').addClass('active');
//Add active class to modal
$('#sg-modal-container').addClass('active');
// show the modal
modalViewer.show();
}
|
javascript
|
function() {
// make sure the modal viewer and other options are off just in case
modalViewer.close();
// note it's turned on in the viewer
DataSaver.updateValue('modalActive', 'true');
modalViewer.active = true;
// add an active class to the button that matches this template
$('#sg-t-'+modalViewer.template+' .sg-checkbox').addClass('active');
//Add active class to modal
$('#sg-modal-container').addClass('active');
// show the modal
modalViewer.show();
}
|
[
"function",
"(",
")",
"{",
"modalViewer",
".",
"close",
"(",
")",
";",
"DataSaver",
".",
"updateValue",
"(",
"'modalActive'",
",",
"'true'",
")",
";",
"modalViewer",
".",
"active",
"=",
"true",
";",
"$",
"(",
"'#sg-t-'",
"+",
"modalViewer",
".",
"template",
"+",
"' .sg-checkbox'",
")",
".",
"addClass",
"(",
"'active'",
")",
";",
"$",
"(",
"'#sg-modal-container'",
")",
".",
"addClass",
"(",
"'active'",
")",
";",
"modalViewer",
".",
"show",
"(",
")",
";",
"}"
] |
open the modal window
|
[
"open",
"the",
"modal",
"window"
] |
6ae90009c5d611f9fdbcc208f9bd5f1e22926094
|
https://github.com/massgov/mayflower/blob/6ae90009c5d611f9fdbcc208f9bd5f1e22926094/patternlab/styleguide/public/styleguide/js/patternlab-viewer.js#L492-L510
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.