id
int32 0
58k
| repo
stringlengths 5
67
| path
stringlengths 4
116
| func_name
stringlengths 0
58
| original_string
stringlengths 52
373k
| language
stringclasses 1
value | code
stringlengths 52
373k
| code_tokens
list | docstring
stringlengths 4
11.8k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 86
226
|
|---|---|---|---|---|---|---|---|---|---|---|---|
9,200
|
bencoveney/barrelsby
|
bin/modules.js
|
getModules
|
function getModules(directory, logger, local) {
logger(`Getting modules @ ${directory.path}`);
if (directory.barrel) {
// If theres a barrel then use that as it *should* contain descendant modules.
logger(`Found existing barrel @ ${directory.barrel.path}`);
return [directory.barrel];
}
const files = [].concat(directory.files);
if (!local) {
directory.directories.forEach((childDirectory) => {
// Recurse.
files.push(...getModules(childDirectory, logger, local));
});
}
// Only return files that look like TypeScript modules.
return files.filter((file) => file.name.match(utilities_1.isTypeScriptFile));
}
|
javascript
|
function getModules(directory, logger, local) {
logger(`Getting modules @ ${directory.path}`);
if (directory.barrel) {
// If theres a barrel then use that as it *should* contain descendant modules.
logger(`Found existing barrel @ ${directory.barrel.path}`);
return [directory.barrel];
}
const files = [].concat(directory.files);
if (!local) {
directory.directories.forEach((childDirectory) => {
// Recurse.
files.push(...getModules(childDirectory, logger, local));
});
}
// Only return files that look like TypeScript modules.
return files.filter((file) => file.name.match(utilities_1.isTypeScriptFile));
}
|
[
"function",
"getModules",
"(",
"directory",
",",
"logger",
",",
"local",
")",
"{",
"logger",
"(",
"`",
"${",
"directory",
".",
"path",
"}",
"`",
")",
";",
"if",
"(",
"directory",
".",
"barrel",
")",
"{",
"// If theres a barrel then use that as it *should* contain descendant modules.",
"logger",
"(",
"`",
"${",
"directory",
".",
"barrel",
".",
"path",
"}",
"`",
")",
";",
"return",
"[",
"directory",
".",
"barrel",
"]",
";",
"}",
"const",
"files",
"=",
"[",
"]",
".",
"concat",
"(",
"directory",
".",
"files",
")",
";",
"if",
"(",
"!",
"local",
")",
"{",
"directory",
".",
"directories",
".",
"forEach",
"(",
"(",
"childDirectory",
")",
"=>",
"{",
"// Recurse.",
"files",
".",
"push",
"(",
"...",
"getModules",
"(",
"childDirectory",
",",
"logger",
",",
"local",
")",
")",
";",
"}",
")",
";",
"}",
"// Only return files that look like TypeScript modules.",
"return",
"files",
".",
"filter",
"(",
"(",
"file",
")",
"=>",
"file",
".",
"name",
".",
"match",
"(",
"utilities_1",
".",
"isTypeScriptFile",
")",
")",
";",
"}"
] |
Get any typescript modules contained at any depth in the current directory.
|
[
"Get",
"any",
"typescript",
"modules",
"contained",
"at",
"any",
"depth",
"in",
"the",
"current",
"directory",
"."
] |
7271065d27ad9060a899a5c64c6b03c749ad7867
|
https://github.com/bencoveney/barrelsby/blob/7271065d27ad9060a899a5c64c6b03c749ad7867/bin/modules.js#L5-L21
|
9,201
|
bencoveney/barrelsby
|
bin/builder.js
|
buildBarrel
|
function buildBarrel(directory, builder, quoteCharacter, semicolonCharacter, barrelName, logger, baseUrl, local, include, exclude) {
logger(`Building barrel @ ${directory.path}`);
const content = builder(directory, modules_1.loadDirectoryModules(directory, logger, include, exclude, local), quoteCharacter, semicolonCharacter, logger, baseUrl);
const destination = path_1.default.join(directory.path, barrelName);
if (content.length === 0) {
// Skip empty barrels.
return;
}
// Add the header
const contentWithHeader = header_1.addHeaderPrefix(content);
fs_1.default.writeFileSync(destination, contentWithHeader);
// Update the file tree model with the new barrel.
if (!directory.files.some((file) => file.name === barrelName)) {
const convertedPath = utilities_1.convertPathSeparator(destination);
const barrel = {
name: barrelName,
path: convertedPath
};
logger(`Updating model barrel @ ${convertedPath}`);
directory.files.push(barrel);
directory.barrel = barrel;
}
}
|
javascript
|
function buildBarrel(directory, builder, quoteCharacter, semicolonCharacter, barrelName, logger, baseUrl, local, include, exclude) {
logger(`Building barrel @ ${directory.path}`);
const content = builder(directory, modules_1.loadDirectoryModules(directory, logger, include, exclude, local), quoteCharacter, semicolonCharacter, logger, baseUrl);
const destination = path_1.default.join(directory.path, barrelName);
if (content.length === 0) {
// Skip empty barrels.
return;
}
// Add the header
const contentWithHeader = header_1.addHeaderPrefix(content);
fs_1.default.writeFileSync(destination, contentWithHeader);
// Update the file tree model with the new barrel.
if (!directory.files.some((file) => file.name === barrelName)) {
const convertedPath = utilities_1.convertPathSeparator(destination);
const barrel = {
name: barrelName,
path: convertedPath
};
logger(`Updating model barrel @ ${convertedPath}`);
directory.files.push(barrel);
directory.barrel = barrel;
}
}
|
[
"function",
"buildBarrel",
"(",
"directory",
",",
"builder",
",",
"quoteCharacter",
",",
"semicolonCharacter",
",",
"barrelName",
",",
"logger",
",",
"baseUrl",
",",
"local",
",",
"include",
",",
"exclude",
")",
"{",
"logger",
"(",
"`",
"${",
"directory",
".",
"path",
"}",
"`",
")",
";",
"const",
"content",
"=",
"builder",
"(",
"directory",
",",
"modules_1",
".",
"loadDirectoryModules",
"(",
"directory",
",",
"logger",
",",
"include",
",",
"exclude",
",",
"local",
")",
",",
"quoteCharacter",
",",
"semicolonCharacter",
",",
"logger",
",",
"baseUrl",
")",
";",
"const",
"destination",
"=",
"path_1",
".",
"default",
".",
"join",
"(",
"directory",
".",
"path",
",",
"barrelName",
")",
";",
"if",
"(",
"content",
".",
"length",
"===",
"0",
")",
"{",
"// Skip empty barrels.",
"return",
";",
"}",
"// Add the header",
"const",
"contentWithHeader",
"=",
"header_1",
".",
"addHeaderPrefix",
"(",
"content",
")",
";",
"fs_1",
".",
"default",
".",
"writeFileSync",
"(",
"destination",
",",
"contentWithHeader",
")",
";",
"// Update the file tree model with the new barrel.",
"if",
"(",
"!",
"directory",
".",
"files",
".",
"some",
"(",
"(",
"file",
")",
"=>",
"file",
".",
"name",
"===",
"barrelName",
")",
")",
"{",
"const",
"convertedPath",
"=",
"utilities_1",
".",
"convertPathSeparator",
"(",
"destination",
")",
";",
"const",
"barrel",
"=",
"{",
"name",
":",
"barrelName",
",",
"path",
":",
"convertedPath",
"}",
";",
"logger",
"(",
"`",
"${",
"convertedPath",
"}",
"`",
")",
";",
"directory",
".",
"files",
".",
"push",
"(",
"barrel",
")",
";",
"directory",
".",
"barrel",
"=",
"barrel",
";",
"}",
"}"
] |
Build a barrel for the specified directory.
|
[
"Build",
"a",
"barrel",
"for",
"the",
"specified",
"directory",
"."
] |
7271065d27ad9060a899a5c64c6b03c749ad7867
|
https://github.com/bencoveney/barrelsby/blob/7271065d27ad9060a899a5c64c6b03c749ad7867/bin/builder.js#L29-L51
|
9,202
|
bencoveney/barrelsby
|
bin/builder.js
|
buildImportPath
|
function buildImportPath(directory, target, baseUrl) {
// If the base URL option is set then imports should be relative to there.
const startLocation = baseUrl ? baseUrl : directory.path;
const relativePath = path_1.default.relative(startLocation, target.path);
// Get the route and ensure it's relative
let directoryPath = path_1.default.dirname(relativePath);
if (directoryPath !== ".") {
directoryPath = `.${path_1.default.sep}${directoryPath}`;
}
// Strip off the .ts or .tsx from the file name.
const fileName = getBasename(relativePath);
// Build the final path string. Use posix-style seperators.
const location = `${directoryPath}${path_1.default.sep}${fileName}`;
const convertedLocation = utilities_1.convertPathSeparator(location);
return stripThisDirectory(convertedLocation, baseUrl);
}
|
javascript
|
function buildImportPath(directory, target, baseUrl) {
// If the base URL option is set then imports should be relative to there.
const startLocation = baseUrl ? baseUrl : directory.path;
const relativePath = path_1.default.relative(startLocation, target.path);
// Get the route and ensure it's relative
let directoryPath = path_1.default.dirname(relativePath);
if (directoryPath !== ".") {
directoryPath = `.${path_1.default.sep}${directoryPath}`;
}
// Strip off the .ts or .tsx from the file name.
const fileName = getBasename(relativePath);
// Build the final path string. Use posix-style seperators.
const location = `${directoryPath}${path_1.default.sep}${fileName}`;
const convertedLocation = utilities_1.convertPathSeparator(location);
return stripThisDirectory(convertedLocation, baseUrl);
}
|
[
"function",
"buildImportPath",
"(",
"directory",
",",
"target",
",",
"baseUrl",
")",
"{",
"// If the base URL option is set then imports should be relative to there.",
"const",
"startLocation",
"=",
"baseUrl",
"?",
"baseUrl",
":",
"directory",
".",
"path",
";",
"const",
"relativePath",
"=",
"path_1",
".",
"default",
".",
"relative",
"(",
"startLocation",
",",
"target",
".",
"path",
")",
";",
"// Get the route and ensure it's relative",
"let",
"directoryPath",
"=",
"path_1",
".",
"default",
".",
"dirname",
"(",
"relativePath",
")",
";",
"if",
"(",
"directoryPath",
"!==",
"\".\"",
")",
"{",
"directoryPath",
"=",
"`",
"${",
"path_1",
".",
"default",
".",
"sep",
"}",
"${",
"directoryPath",
"}",
"`",
";",
"}",
"// Strip off the .ts or .tsx from the file name.",
"const",
"fileName",
"=",
"getBasename",
"(",
"relativePath",
")",
";",
"// Build the final path string. Use posix-style seperators.",
"const",
"location",
"=",
"`",
"${",
"directoryPath",
"}",
"${",
"path_1",
".",
"default",
".",
"sep",
"}",
"${",
"fileName",
"}",
"`",
";",
"const",
"convertedLocation",
"=",
"utilities_1",
".",
"convertPathSeparator",
"(",
"location",
")",
";",
"return",
"stripThisDirectory",
"(",
"convertedLocation",
",",
"baseUrl",
")",
";",
"}"
] |
Builds the TypeScript
|
[
"Builds",
"the",
"TypeScript"
] |
7271065d27ad9060a899a5c64c6b03c749ad7867
|
https://github.com/bencoveney/barrelsby/blob/7271065d27ad9060a899a5c64c6b03c749ad7867/bin/builder.js#L53-L68
|
9,203
|
bencoveney/barrelsby
|
bin/builder.js
|
getBasename
|
function getBasename(relativePath) {
const mayBeSuffix = [".ts", ".tsx", ".d.ts"];
let mayBePath = relativePath;
mayBeSuffix.map(suffix => {
const tmpPath = path_1.default.basename(relativePath, suffix);
if (tmpPath.length < mayBePath.length) {
mayBePath = tmpPath;
}
});
// Return whichever path is shorter. If they're the same length then nothing was stripped.
return mayBePath;
}
|
javascript
|
function getBasename(relativePath) {
const mayBeSuffix = [".ts", ".tsx", ".d.ts"];
let mayBePath = relativePath;
mayBeSuffix.map(suffix => {
const tmpPath = path_1.default.basename(relativePath, suffix);
if (tmpPath.length < mayBePath.length) {
mayBePath = tmpPath;
}
});
// Return whichever path is shorter. If they're the same length then nothing was stripped.
return mayBePath;
}
|
[
"function",
"getBasename",
"(",
"relativePath",
")",
"{",
"const",
"mayBeSuffix",
"=",
"[",
"\".ts\"",
",",
"\".tsx\"",
",",
"\".d.ts\"",
"]",
";",
"let",
"mayBePath",
"=",
"relativePath",
";",
"mayBeSuffix",
".",
"map",
"(",
"suffix",
"=>",
"{",
"const",
"tmpPath",
"=",
"path_1",
".",
"default",
".",
"basename",
"(",
"relativePath",
",",
"suffix",
")",
";",
"if",
"(",
"tmpPath",
".",
"length",
"<",
"mayBePath",
".",
"length",
")",
"{",
"mayBePath",
"=",
"tmpPath",
";",
"}",
"}",
")",
";",
"// Return whichever path is shorter. If they're the same length then nothing was stripped.",
"return",
"mayBePath",
";",
"}"
] |
Strips the .ts or .tsx file extension from a path and returns the base filename.
|
[
"Strips",
"the",
".",
"ts",
"or",
".",
"tsx",
"file",
"extension",
"from",
"a",
"path",
"and",
"returns",
"the",
"base",
"filename",
"."
] |
7271065d27ad9060a899a5c64c6b03c749ad7867
|
https://github.com/bencoveney/barrelsby/blob/7271065d27ad9060a899a5c64c6b03c749ad7867/bin/builder.js#L74-L85
|
9,204
|
bencoveney/barrelsby
|
bin/destinations.js
|
getDestinations
|
function getDestinations(rootTree, locationOption, barrelName, logger) {
let destinations;
switch (locationOption) {
case "top":
default:
destinations = [rootTree];
break;
case "below":
destinations = rootTree.directories;
break;
case "all":
destinations = [];
fileTree_1.walkTree(rootTree, (directory) => {
destinations.push(directory);
});
break;
case "replace":
destinations = [];
fileTree_1.walkTree(rootTree, (directory) => {
if (directory.files.some((location) => location.name === barrelName)) {
destinations.push(directory);
}
});
break;
case "branch":
destinations = [];
fileTree_1.walkTree(rootTree, (directory) => {
if (directory.directories.length > 0) {
destinations.push(directory);
}
});
break;
}
// Sort by length. This means barrels will be created deepest first.
destinations = destinations.sort((a, b) => {
return b.path.length - a.path.length;
});
logger("Destinations:");
destinations.forEach(destination => logger(destination.path));
return destinations;
}
|
javascript
|
function getDestinations(rootTree, locationOption, barrelName, logger) {
let destinations;
switch (locationOption) {
case "top":
default:
destinations = [rootTree];
break;
case "below":
destinations = rootTree.directories;
break;
case "all":
destinations = [];
fileTree_1.walkTree(rootTree, (directory) => {
destinations.push(directory);
});
break;
case "replace":
destinations = [];
fileTree_1.walkTree(rootTree, (directory) => {
if (directory.files.some((location) => location.name === barrelName)) {
destinations.push(directory);
}
});
break;
case "branch":
destinations = [];
fileTree_1.walkTree(rootTree, (directory) => {
if (directory.directories.length > 0) {
destinations.push(directory);
}
});
break;
}
// Sort by length. This means barrels will be created deepest first.
destinations = destinations.sort((a, b) => {
return b.path.length - a.path.length;
});
logger("Destinations:");
destinations.forEach(destination => logger(destination.path));
return destinations;
}
|
[
"function",
"getDestinations",
"(",
"rootTree",
",",
"locationOption",
",",
"barrelName",
",",
"logger",
")",
"{",
"let",
"destinations",
";",
"switch",
"(",
"locationOption",
")",
"{",
"case",
"\"top\"",
":",
"default",
":",
"destinations",
"=",
"[",
"rootTree",
"]",
";",
"break",
";",
"case",
"\"below\"",
":",
"destinations",
"=",
"rootTree",
".",
"directories",
";",
"break",
";",
"case",
"\"all\"",
":",
"destinations",
"=",
"[",
"]",
";",
"fileTree_1",
".",
"walkTree",
"(",
"rootTree",
",",
"(",
"directory",
")",
"=>",
"{",
"destinations",
".",
"push",
"(",
"directory",
")",
";",
"}",
")",
";",
"break",
";",
"case",
"\"replace\"",
":",
"destinations",
"=",
"[",
"]",
";",
"fileTree_1",
".",
"walkTree",
"(",
"rootTree",
",",
"(",
"directory",
")",
"=>",
"{",
"if",
"(",
"directory",
".",
"files",
".",
"some",
"(",
"(",
"location",
")",
"=>",
"location",
".",
"name",
"===",
"barrelName",
")",
")",
"{",
"destinations",
".",
"push",
"(",
"directory",
")",
";",
"}",
"}",
")",
";",
"break",
";",
"case",
"\"branch\"",
":",
"destinations",
"=",
"[",
"]",
";",
"fileTree_1",
".",
"walkTree",
"(",
"rootTree",
",",
"(",
"directory",
")",
"=>",
"{",
"if",
"(",
"directory",
".",
"directories",
".",
"length",
">",
"0",
")",
"{",
"destinations",
".",
"push",
"(",
"directory",
")",
";",
"}",
"}",
")",
";",
"break",
";",
"}",
"// Sort by length. This means barrels will be created deepest first.",
"destinations",
"=",
"destinations",
".",
"sort",
"(",
"(",
"a",
",",
"b",
")",
"=>",
"{",
"return",
"b",
".",
"path",
".",
"length",
"-",
"a",
".",
"path",
".",
"length",
";",
"}",
")",
";",
"logger",
"(",
"\"Destinations:\"",
")",
";",
"destinations",
".",
"forEach",
"(",
"destination",
"=>",
"logger",
"(",
"destination",
".",
"path",
")",
")",
";",
"return",
"destinations",
";",
"}"
] |
Assess which directories in the tree should contain barrels.
|
[
"Assess",
"which",
"directories",
"in",
"the",
"tree",
"should",
"contain",
"barrels",
"."
] |
7271065d27ad9060a899a5c64c6b03c749ad7867
|
https://github.com/bencoveney/barrelsby/blob/7271065d27ad9060a899a5c64c6b03c749ad7867/bin/destinations.js#L5-L45
|
9,205
|
bencoveney/barrelsby
|
bin/fileTree.js
|
buildTree
|
function buildTree(directory, barrelName, logger) {
logger(`Building directory tree for ${utilities_1.convertPathSeparator(directory)}`);
const names = fs_1.default.readdirSync(directory);
const result = {
directories: [],
files: [],
name: path_1.default.basename(directory),
path: utilities_1.convertPathSeparator(directory)
};
names.forEach((name) => {
const fullPath = path_1.default.join(directory, name);
if (fs_1.default.statSync(fullPath).isDirectory()) {
result.directories.push(buildTree(fullPath, barrelName, logger));
}
else {
const convertedPath = utilities_1.convertPathSeparator(fullPath);
const file = {
name,
path: convertedPath
};
result.files.push(file);
if (file.name === barrelName) {
logger(`Found existing barrel @ ${convertedPath}`);
result.barrel = file;
}
}
});
return result;
}
|
javascript
|
function buildTree(directory, barrelName, logger) {
logger(`Building directory tree for ${utilities_1.convertPathSeparator(directory)}`);
const names = fs_1.default.readdirSync(directory);
const result = {
directories: [],
files: [],
name: path_1.default.basename(directory),
path: utilities_1.convertPathSeparator(directory)
};
names.forEach((name) => {
const fullPath = path_1.default.join(directory, name);
if (fs_1.default.statSync(fullPath).isDirectory()) {
result.directories.push(buildTree(fullPath, barrelName, logger));
}
else {
const convertedPath = utilities_1.convertPathSeparator(fullPath);
const file = {
name,
path: convertedPath
};
result.files.push(file);
if (file.name === barrelName) {
logger(`Found existing barrel @ ${convertedPath}`);
result.barrel = file;
}
}
});
return result;
}
|
[
"function",
"buildTree",
"(",
"directory",
",",
"barrelName",
",",
"logger",
")",
"{",
"logger",
"(",
"`",
"${",
"utilities_1",
".",
"convertPathSeparator",
"(",
"directory",
")",
"}",
"`",
")",
";",
"const",
"names",
"=",
"fs_1",
".",
"default",
".",
"readdirSync",
"(",
"directory",
")",
";",
"const",
"result",
"=",
"{",
"directories",
":",
"[",
"]",
",",
"files",
":",
"[",
"]",
",",
"name",
":",
"path_1",
".",
"default",
".",
"basename",
"(",
"directory",
")",
",",
"path",
":",
"utilities_1",
".",
"convertPathSeparator",
"(",
"directory",
")",
"}",
";",
"names",
".",
"forEach",
"(",
"(",
"name",
")",
"=>",
"{",
"const",
"fullPath",
"=",
"path_1",
".",
"default",
".",
"join",
"(",
"directory",
",",
"name",
")",
";",
"if",
"(",
"fs_1",
".",
"default",
".",
"statSync",
"(",
"fullPath",
")",
".",
"isDirectory",
"(",
")",
")",
"{",
"result",
".",
"directories",
".",
"push",
"(",
"buildTree",
"(",
"fullPath",
",",
"barrelName",
",",
"logger",
")",
")",
";",
"}",
"else",
"{",
"const",
"convertedPath",
"=",
"utilities_1",
".",
"convertPathSeparator",
"(",
"fullPath",
")",
";",
"const",
"file",
"=",
"{",
"name",
",",
"path",
":",
"convertedPath",
"}",
";",
"result",
".",
"files",
".",
"push",
"(",
"file",
")",
";",
"if",
"(",
"file",
".",
"name",
"===",
"barrelName",
")",
"{",
"logger",
"(",
"`",
"${",
"convertedPath",
"}",
"`",
")",
";",
"result",
".",
"barrel",
"=",
"file",
";",
"}",
"}",
"}",
")",
";",
"return",
"result",
";",
"}"
] |
Build directory information recursively.
|
[
"Build",
"directory",
"information",
"recursively",
"."
] |
7271065d27ad9060a899a5c64c6b03c749ad7867
|
https://github.com/bencoveney/barrelsby/blob/7271065d27ad9060a899a5c64c6b03c749ad7867/bin/fileTree.js#L10-L38
|
9,206
|
bencoveney/barrelsby
|
bin/fileTree.js
|
walkTree
|
function walkTree(directory, callback) {
callback(directory);
directory.directories.forEach(childDirectory => walkTree(childDirectory, callback));
}
|
javascript
|
function walkTree(directory, callback) {
callback(directory);
directory.directories.forEach(childDirectory => walkTree(childDirectory, callback));
}
|
[
"function",
"walkTree",
"(",
"directory",
",",
"callback",
")",
"{",
"callback",
"(",
"directory",
")",
";",
"directory",
".",
"directories",
".",
"forEach",
"(",
"childDirectory",
"=>",
"walkTree",
"(",
"childDirectory",
",",
"callback",
")",
")",
";",
"}"
] |
Walk an entire directory tree recursively.
|
[
"Walk",
"an",
"entire",
"directory",
"tree",
"recursively",
"."
] |
7271065d27ad9060a899a5c64c6b03c749ad7867
|
https://github.com/bencoveney/barrelsby/blob/7271065d27ad9060a899a5c64c6b03c749ad7867/bin/fileTree.js#L41-L44
|
9,207
|
JKHeadley/rest-hapi
|
utilities/rest-helper-factory.js
|
function(server, model, options) {
// TODO: generate multiple DELETE routes at /RESOURCE and at
// TODO: /RESOURCE/{ownerId}/ASSOCIATION that take a list of Id's as a payload
try {
validationHelper.validateModel(model, logger)
let collectionName = model.collectionDisplayName || model.modelName
let Log = logger.bind(chalk.blue(collectionName))
options = options || {}
if (model.routeOptions.allowRead !== false) {
this.generateListEndpoint(server, model, options, Log)
this.generateFindEndpoint(server, model, options, Log)
}
if (model.routeOptions.allowCreate !== false) {
this.generateCreateEndpoint(server, model, options, Log)
}
if (model.routeOptions.allowUpdate !== false) {
this.generateUpdateEndpoint(server, model, options, Log)
}
if (model.routeOptions.allowDelete !== false) {
this.generateDeleteOneEndpoint(server, model, options, Log)
this.generateDeleteManyEndpoint(server, model, options, Log)
}
if (model.routeOptions.associations) {
for (let associationName in model.routeOptions.associations) {
let association = model.routeOptions.associations[associationName]
if (
association.type === 'MANY_MANY' ||
association.type === 'ONE_MANY' ||
association.type === '_MANY'
) {
if (association.allowAdd !== false) {
this.generateAssociationAddOneEndpoint(
server,
model,
association,
options,
Log
)
this.generateAssociationAddManyEndpoint(
server,
model,
association,
options,
Log
)
}
if (association.allowRemove !== false) {
this.generateAssociationRemoveOneEndpoint(
server,
model,
association,
options,
Log
)
this.generateAssociationRemoveManyEndpoint(
server,
model,
association,
options,
Log
)
}
if (association.allowRead !== false) {
this.generateAssociationGetAllEndpoint(
server,
model,
association,
options,
Log
)
}
}
}
}
if (model.routeOptions && model.routeOptions.extraEndpoints) {
for (let extraEndpointIndex in model.routeOptions.extraEndpoints) {
let extraEndpointFunction =
model.routeOptions.extraEndpoints[extraEndpointIndex]
extraEndpointFunction(server, model, options, Log)
}
}
} catch (error) {
logger.error('Error:', error)
throw error
}
}
|
javascript
|
function(server, model, options) {
// TODO: generate multiple DELETE routes at /RESOURCE and at
// TODO: /RESOURCE/{ownerId}/ASSOCIATION that take a list of Id's as a payload
try {
validationHelper.validateModel(model, logger)
let collectionName = model.collectionDisplayName || model.modelName
let Log = logger.bind(chalk.blue(collectionName))
options = options || {}
if (model.routeOptions.allowRead !== false) {
this.generateListEndpoint(server, model, options, Log)
this.generateFindEndpoint(server, model, options, Log)
}
if (model.routeOptions.allowCreate !== false) {
this.generateCreateEndpoint(server, model, options, Log)
}
if (model.routeOptions.allowUpdate !== false) {
this.generateUpdateEndpoint(server, model, options, Log)
}
if (model.routeOptions.allowDelete !== false) {
this.generateDeleteOneEndpoint(server, model, options, Log)
this.generateDeleteManyEndpoint(server, model, options, Log)
}
if (model.routeOptions.associations) {
for (let associationName in model.routeOptions.associations) {
let association = model.routeOptions.associations[associationName]
if (
association.type === 'MANY_MANY' ||
association.type === 'ONE_MANY' ||
association.type === '_MANY'
) {
if (association.allowAdd !== false) {
this.generateAssociationAddOneEndpoint(
server,
model,
association,
options,
Log
)
this.generateAssociationAddManyEndpoint(
server,
model,
association,
options,
Log
)
}
if (association.allowRemove !== false) {
this.generateAssociationRemoveOneEndpoint(
server,
model,
association,
options,
Log
)
this.generateAssociationRemoveManyEndpoint(
server,
model,
association,
options,
Log
)
}
if (association.allowRead !== false) {
this.generateAssociationGetAllEndpoint(
server,
model,
association,
options,
Log
)
}
}
}
}
if (model.routeOptions && model.routeOptions.extraEndpoints) {
for (let extraEndpointIndex in model.routeOptions.extraEndpoints) {
let extraEndpointFunction =
model.routeOptions.extraEndpoints[extraEndpointIndex]
extraEndpointFunction(server, model, options, Log)
}
}
} catch (error) {
logger.error('Error:', error)
throw error
}
}
|
[
"function",
"(",
"server",
",",
"model",
",",
"options",
")",
"{",
"// TODO: generate multiple DELETE routes at /RESOURCE and at",
"// TODO: /RESOURCE/{ownerId}/ASSOCIATION that take a list of Id's as a payload",
"try",
"{",
"validationHelper",
".",
"validateModel",
"(",
"model",
",",
"logger",
")",
"let",
"collectionName",
"=",
"model",
".",
"collectionDisplayName",
"||",
"model",
".",
"modelName",
"let",
"Log",
"=",
"logger",
".",
"bind",
"(",
"chalk",
".",
"blue",
"(",
"collectionName",
")",
")",
"options",
"=",
"options",
"||",
"{",
"}",
"if",
"(",
"model",
".",
"routeOptions",
".",
"allowRead",
"!==",
"false",
")",
"{",
"this",
".",
"generateListEndpoint",
"(",
"server",
",",
"model",
",",
"options",
",",
"Log",
")",
"this",
".",
"generateFindEndpoint",
"(",
"server",
",",
"model",
",",
"options",
",",
"Log",
")",
"}",
"if",
"(",
"model",
".",
"routeOptions",
".",
"allowCreate",
"!==",
"false",
")",
"{",
"this",
".",
"generateCreateEndpoint",
"(",
"server",
",",
"model",
",",
"options",
",",
"Log",
")",
"}",
"if",
"(",
"model",
".",
"routeOptions",
".",
"allowUpdate",
"!==",
"false",
")",
"{",
"this",
".",
"generateUpdateEndpoint",
"(",
"server",
",",
"model",
",",
"options",
",",
"Log",
")",
"}",
"if",
"(",
"model",
".",
"routeOptions",
".",
"allowDelete",
"!==",
"false",
")",
"{",
"this",
".",
"generateDeleteOneEndpoint",
"(",
"server",
",",
"model",
",",
"options",
",",
"Log",
")",
"this",
".",
"generateDeleteManyEndpoint",
"(",
"server",
",",
"model",
",",
"options",
",",
"Log",
")",
"}",
"if",
"(",
"model",
".",
"routeOptions",
".",
"associations",
")",
"{",
"for",
"(",
"let",
"associationName",
"in",
"model",
".",
"routeOptions",
".",
"associations",
")",
"{",
"let",
"association",
"=",
"model",
".",
"routeOptions",
".",
"associations",
"[",
"associationName",
"]",
"if",
"(",
"association",
".",
"type",
"===",
"'MANY_MANY'",
"||",
"association",
".",
"type",
"===",
"'ONE_MANY'",
"||",
"association",
".",
"type",
"===",
"'_MANY'",
")",
"{",
"if",
"(",
"association",
".",
"allowAdd",
"!==",
"false",
")",
"{",
"this",
".",
"generateAssociationAddOneEndpoint",
"(",
"server",
",",
"model",
",",
"association",
",",
"options",
",",
"Log",
")",
"this",
".",
"generateAssociationAddManyEndpoint",
"(",
"server",
",",
"model",
",",
"association",
",",
"options",
",",
"Log",
")",
"}",
"if",
"(",
"association",
".",
"allowRemove",
"!==",
"false",
")",
"{",
"this",
".",
"generateAssociationRemoveOneEndpoint",
"(",
"server",
",",
"model",
",",
"association",
",",
"options",
",",
"Log",
")",
"this",
".",
"generateAssociationRemoveManyEndpoint",
"(",
"server",
",",
"model",
",",
"association",
",",
"options",
",",
"Log",
")",
"}",
"if",
"(",
"association",
".",
"allowRead",
"!==",
"false",
")",
"{",
"this",
".",
"generateAssociationGetAllEndpoint",
"(",
"server",
",",
"model",
",",
"association",
",",
"options",
",",
"Log",
")",
"}",
"}",
"}",
"}",
"if",
"(",
"model",
".",
"routeOptions",
"&&",
"model",
".",
"routeOptions",
".",
"extraEndpoints",
")",
"{",
"for",
"(",
"let",
"extraEndpointIndex",
"in",
"model",
".",
"routeOptions",
".",
"extraEndpoints",
")",
"{",
"let",
"extraEndpointFunction",
"=",
"model",
".",
"routeOptions",
".",
"extraEndpoints",
"[",
"extraEndpointIndex",
"]",
"extraEndpointFunction",
"(",
"server",
",",
"model",
",",
"options",
",",
"Log",
")",
"}",
"}",
"}",
"catch",
"(",
"error",
")",
"{",
"logger",
".",
"error",
"(",
"'Error:'",
",",
"error",
")",
"throw",
"error",
"}",
"}"
] |
Generates the restful API endpoints for a single model.
@param server: A Hapi server.
@param model: A mongoose model.
@param options: options object.
|
[
"Generates",
"the",
"restful",
"API",
"endpoints",
"for",
"a",
"single",
"model",
"."
] |
36110fd3cb2775b3b2068b18d775f1c87fbcef76
|
https://github.com/JKHeadley/rest-hapi/blob/36110fd3cb2775b3b2068b18d775f1c87fbcef76/utilities/rest-helper-factory.js#L39-L136
|
|
9,208
|
JKHeadley/rest-hapi
|
utilities/handler-helper.js
|
_list
|
function _list(model, query, Log) {
let request = { query: query }
return _listHandler(model, request, Log)
}
|
javascript
|
function _list(model, query, Log) {
let request = { query: query }
return _listHandler(model, request, Log)
}
|
[
"function",
"_list",
"(",
"model",
",",
"query",
",",
"Log",
")",
"{",
"let",
"request",
"=",
"{",
"query",
":",
"query",
"}",
"return",
"_listHandler",
"(",
"model",
",",
"request",
",",
"Log",
")",
"}"
] |
List function exposed as a mongoose wrapper.
@param model: A mongoose model.
@param query: rest-hapi query parameters to be converted to a mongoose query.
@param Log: A logging object.
@returns {object} A promise for the resulting model documents or the count of the query results.
@private
|
[
"List",
"function",
"exposed",
"as",
"a",
"mongoose",
"wrapper",
"."
] |
36110fd3cb2775b3b2068b18d775f1c87fbcef76
|
https://github.com/JKHeadley/rest-hapi/blob/36110fd3cb2775b3b2068b18d775f1c87fbcef76/utilities/handler-helper.js#L68-L71
|
9,209
|
JKHeadley/rest-hapi
|
utilities/handler-helper.js
|
_find
|
function _find(model, _id, query, Log) {
let request = { params: { _id: _id }, query: query }
return _findHandler(model, _id, request, Log)
}
|
javascript
|
function _find(model, _id, query, Log) {
let request = { params: { _id: _id }, query: query }
return _findHandler(model, _id, request, Log)
}
|
[
"function",
"_find",
"(",
"model",
",",
"_id",
",",
"query",
",",
"Log",
")",
"{",
"let",
"request",
"=",
"{",
"params",
":",
"{",
"_id",
":",
"_id",
"}",
",",
"query",
":",
"query",
"}",
"return",
"_findHandler",
"(",
"model",
",",
"_id",
",",
"request",
",",
"Log",
")",
"}"
] |
Find function exposed as a mongoose wrapper.
@param model: A mongoose model.
@param _id: The document id.
@param query: rest-hapi query parameters to be converted to a mongoose query.
@param Log: A logging object.
@returns {object} A promise for the resulting model document.
@private
|
[
"Find",
"function",
"exposed",
"as",
"a",
"mongoose",
"wrapper",
"."
] |
36110fd3cb2775b3b2068b18d775f1c87fbcef76
|
https://github.com/JKHeadley/rest-hapi/blob/36110fd3cb2775b3b2068b18d775f1c87fbcef76/utilities/handler-helper.js#L220-L223
|
9,210
|
JKHeadley/rest-hapi
|
utilities/handler-helper.js
|
_findHandler
|
async function _findHandler(model, _id, request, Log) {
try {
let query = Object.assign({}, request.query)
try {
if (
model.routeOptions &&
model.routeOptions.find &&
model.routeOptions.find.pre
) {
query = await model.routeOptions.find.pre(_id, query, request, Log)
}
} catch (err) {
handleError(err, 'There was a preprocessing error.', Boom.badRequest, Log)
}
let flatten = false
if (query.$flatten) {
flatten = true
}
delete query.$flatten
let mongooseQuery = model.findOne({ _id: _id })
mongooseQuery = QueryHelper.createMongooseQuery(
model,
query,
mongooseQuery,
Log
).lean()
let result = await mongooseQuery.exec()
if (result) {
let data = result
try {
if (
model.routeOptions &&
model.routeOptions.find &&
model.routeOptions.find.post
) {
data = await model.routeOptions.find.post(request, result, Log)
}
} catch (err) {
handleError(
err,
'There was a postprocessing error.',
Boom.badRequest,
Log
)
}
if (model.routeOptions) {
let associations = model.routeOptions.associations
for (let associationKey in associations) {
let association = associations[associationKey]
if (association.type === 'ONE_MANY' && data[associationKey]) {
// EXPL: we have to manually populate the return value for virtual (e.g. ONE_MANY) associations
result[associationKey] = data[associationKey]
}
if (association.type === 'MANY_MANY' && flatten === true) {
// EXPL: remove additional fields and return a flattened array
if (result[associationKey]) {
result[associationKey] = result[associationKey].map(object => {
object = object[association.model]
return object
})
}
}
}
}
if (config.enableSoftDelete && config.filterDeletedEmbeds) {
// EXPL: remove soft deleted documents from populated properties
filterDeletedEmbeds(result, {}, '', 0, Log)
}
Log.log('Result: %s', JSON.stringify(result))
return result
} else {
throw Boom.notFound('No resource was found with that id.')
}
} catch (err) {
handleError(err, null, null, Log)
}
}
|
javascript
|
async function _findHandler(model, _id, request, Log) {
try {
let query = Object.assign({}, request.query)
try {
if (
model.routeOptions &&
model.routeOptions.find &&
model.routeOptions.find.pre
) {
query = await model.routeOptions.find.pre(_id, query, request, Log)
}
} catch (err) {
handleError(err, 'There was a preprocessing error.', Boom.badRequest, Log)
}
let flatten = false
if (query.$flatten) {
flatten = true
}
delete query.$flatten
let mongooseQuery = model.findOne({ _id: _id })
mongooseQuery = QueryHelper.createMongooseQuery(
model,
query,
mongooseQuery,
Log
).lean()
let result = await mongooseQuery.exec()
if (result) {
let data = result
try {
if (
model.routeOptions &&
model.routeOptions.find &&
model.routeOptions.find.post
) {
data = await model.routeOptions.find.post(request, result, Log)
}
} catch (err) {
handleError(
err,
'There was a postprocessing error.',
Boom.badRequest,
Log
)
}
if (model.routeOptions) {
let associations = model.routeOptions.associations
for (let associationKey in associations) {
let association = associations[associationKey]
if (association.type === 'ONE_MANY' && data[associationKey]) {
// EXPL: we have to manually populate the return value for virtual (e.g. ONE_MANY) associations
result[associationKey] = data[associationKey]
}
if (association.type === 'MANY_MANY' && flatten === true) {
// EXPL: remove additional fields and return a flattened array
if (result[associationKey]) {
result[associationKey] = result[associationKey].map(object => {
object = object[association.model]
return object
})
}
}
}
}
if (config.enableSoftDelete && config.filterDeletedEmbeds) {
// EXPL: remove soft deleted documents from populated properties
filterDeletedEmbeds(result, {}, '', 0, Log)
}
Log.log('Result: %s', JSON.stringify(result))
return result
} else {
throw Boom.notFound('No resource was found with that id.')
}
} catch (err) {
handleError(err, null, null, Log)
}
}
|
[
"async",
"function",
"_findHandler",
"(",
"model",
",",
"_id",
",",
"request",
",",
"Log",
")",
"{",
"try",
"{",
"let",
"query",
"=",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"request",
".",
"query",
")",
"try",
"{",
"if",
"(",
"model",
".",
"routeOptions",
"&&",
"model",
".",
"routeOptions",
".",
"find",
"&&",
"model",
".",
"routeOptions",
".",
"find",
".",
"pre",
")",
"{",
"query",
"=",
"await",
"model",
".",
"routeOptions",
".",
"find",
".",
"pre",
"(",
"_id",
",",
"query",
",",
"request",
",",
"Log",
")",
"}",
"}",
"catch",
"(",
"err",
")",
"{",
"handleError",
"(",
"err",
",",
"'There was a preprocessing error.'",
",",
"Boom",
".",
"badRequest",
",",
"Log",
")",
"}",
"let",
"flatten",
"=",
"false",
"if",
"(",
"query",
".",
"$flatten",
")",
"{",
"flatten",
"=",
"true",
"}",
"delete",
"query",
".",
"$flatten",
"let",
"mongooseQuery",
"=",
"model",
".",
"findOne",
"(",
"{",
"_id",
":",
"_id",
"}",
")",
"mongooseQuery",
"=",
"QueryHelper",
".",
"createMongooseQuery",
"(",
"model",
",",
"query",
",",
"mongooseQuery",
",",
"Log",
")",
".",
"lean",
"(",
")",
"let",
"result",
"=",
"await",
"mongooseQuery",
".",
"exec",
"(",
")",
"if",
"(",
"result",
")",
"{",
"let",
"data",
"=",
"result",
"try",
"{",
"if",
"(",
"model",
".",
"routeOptions",
"&&",
"model",
".",
"routeOptions",
".",
"find",
"&&",
"model",
".",
"routeOptions",
".",
"find",
".",
"post",
")",
"{",
"data",
"=",
"await",
"model",
".",
"routeOptions",
".",
"find",
".",
"post",
"(",
"request",
",",
"result",
",",
"Log",
")",
"}",
"}",
"catch",
"(",
"err",
")",
"{",
"handleError",
"(",
"err",
",",
"'There was a postprocessing error.'",
",",
"Boom",
".",
"badRequest",
",",
"Log",
")",
"}",
"if",
"(",
"model",
".",
"routeOptions",
")",
"{",
"let",
"associations",
"=",
"model",
".",
"routeOptions",
".",
"associations",
"for",
"(",
"let",
"associationKey",
"in",
"associations",
")",
"{",
"let",
"association",
"=",
"associations",
"[",
"associationKey",
"]",
"if",
"(",
"association",
".",
"type",
"===",
"'ONE_MANY'",
"&&",
"data",
"[",
"associationKey",
"]",
")",
"{",
"// EXPL: we have to manually populate the return value for virtual (e.g. ONE_MANY) associations",
"result",
"[",
"associationKey",
"]",
"=",
"data",
"[",
"associationKey",
"]",
"}",
"if",
"(",
"association",
".",
"type",
"===",
"'MANY_MANY'",
"&&",
"flatten",
"===",
"true",
")",
"{",
"// EXPL: remove additional fields and return a flattened array",
"if",
"(",
"result",
"[",
"associationKey",
"]",
")",
"{",
"result",
"[",
"associationKey",
"]",
"=",
"result",
"[",
"associationKey",
"]",
".",
"map",
"(",
"object",
"=>",
"{",
"object",
"=",
"object",
"[",
"association",
".",
"model",
"]",
"return",
"object",
"}",
")",
"}",
"}",
"}",
"}",
"if",
"(",
"config",
".",
"enableSoftDelete",
"&&",
"config",
".",
"filterDeletedEmbeds",
")",
"{",
"// EXPL: remove soft deleted documents from populated properties",
"filterDeletedEmbeds",
"(",
"result",
",",
"{",
"}",
",",
"''",
",",
"0",
",",
"Log",
")",
"}",
"Log",
".",
"log",
"(",
"'Result: %s'",
",",
"JSON",
".",
"stringify",
"(",
"result",
")",
")",
"return",
"result",
"}",
"else",
"{",
"throw",
"Boom",
".",
"notFound",
"(",
"'No resource was found with that id.'",
")",
"}",
"}",
"catch",
"(",
"err",
")",
"{",
"handleError",
"(",
"err",
",",
"null",
",",
"null",
",",
"Log",
")",
"}",
"}"
] |
Finds a model document.
@param model: A mongoose model.
@param _id: The document id.
@param request: The Hapi request object, or a container for the wrapper query.
@param Log: A logging object.
@returns {object} A promise for the resulting model document.
@private
|
[
"Finds",
"a",
"model",
"document",
"."
] |
36110fd3cb2775b3b2068b18d775f1c87fbcef76
|
https://github.com/JKHeadley/rest-hapi/blob/36110fd3cb2775b3b2068b18d775f1c87fbcef76/utilities/handler-helper.js#L233-L313
|
9,211
|
JKHeadley/rest-hapi
|
utilities/handler-helper.js
|
_create
|
function _create(model, payload, Log) {
let request = { payload: payload }
return _createHandler(model, request, Log)
}
|
javascript
|
function _create(model, payload, Log) {
let request = { payload: payload }
return _createHandler(model, request, Log)
}
|
[
"function",
"_create",
"(",
"model",
",",
"payload",
",",
"Log",
")",
"{",
"let",
"request",
"=",
"{",
"payload",
":",
"payload",
"}",
"return",
"_createHandler",
"(",
"model",
",",
"request",
",",
"Log",
")",
"}"
] |
Create function exposed as a mongoose wrapper.
@param model: A mongoose model.
@param payload: Data used to create the model document/s.
@param Log: A logging object.
@returns {object} A promise for the resulting model document/s.
@private
|
[
"Create",
"function",
"exposed",
"as",
"a",
"mongoose",
"wrapper",
"."
] |
36110fd3cb2775b3b2068b18d775f1c87fbcef76
|
https://github.com/JKHeadley/rest-hapi/blob/36110fd3cb2775b3b2068b18d775f1c87fbcef76/utilities/handler-helper.js#L323-L326
|
9,212
|
JKHeadley/rest-hapi
|
utilities/handler-helper.js
|
_update
|
function _update(model, _id, payload, Log) {
let request = { params: { _id: _id }, payload: payload }
return _updateHandler(model, _id, request, Log)
}
|
javascript
|
function _update(model, _id, payload, Log) {
let request = { params: { _id: _id }, payload: payload }
return _updateHandler(model, _id, request, Log)
}
|
[
"function",
"_update",
"(",
"model",
",",
"_id",
",",
"payload",
",",
"Log",
")",
"{",
"let",
"request",
"=",
"{",
"params",
":",
"{",
"_id",
":",
"_id",
"}",
",",
"payload",
":",
"payload",
"}",
"return",
"_updateHandler",
"(",
"model",
",",
"_id",
",",
"request",
",",
"Log",
")",
"}"
] |
Update function exposed as a mongoose wrapper.
@param model: A mongoose model.
@param _id: The document id.
@param payload: Data used to update the model document.
@param Log: A logging object.
@returns {object} A promise for the resulting model document.
@private
|
[
"Update",
"function",
"exposed",
"as",
"a",
"mongoose",
"wrapper",
"."
] |
36110fd3cb2775b3b2068b18d775f1c87fbcef76
|
https://github.com/JKHeadley/rest-hapi/blob/36110fd3cb2775b3b2068b18d775f1c87fbcef76/utilities/handler-helper.js#L442-L445
|
9,213
|
JKHeadley/rest-hapi
|
utilities/handler-helper.js
|
_updateHandler
|
async function _updateHandler(model, _id, request, Log) {
let payload = Object.assign({}, request.payload)
try {
try {
if (
model.routeOptions &&
model.routeOptions.update &&
model.routeOptions.update.pre
) {
payload = await model.routeOptions.update.pre(
_id,
payload,
request,
Log
)
}
} catch (err) {
handleError(
err,
'There was a preprocessing error updating the resource.',
Boom.badRequest,
Log
)
}
if (config.enableUpdatedAt) {
payload.updatedAt = new Date()
}
let result
try {
result = await model.findByIdAndUpdate(_id, payload, {
runValidators: config.enableMongooseRunValidators
})
} catch (err) {
Log.error(err)
if (err.code === 11000) {
throw Boom.conflict('There was a duplicate key error.')
} else {
throw Boom.badImplementation(
'There was an error updating the resource.'
)
}
}
if (result) {
let attributes = QueryHelper.createAttributesFilter({}, model, Log)
result = await model.findOne({ _id: result._id }, attributes).lean()
try {
if (
model.routeOptions &&
model.routeOptions.update &&
model.routeOptions.update.post
) {
result = await model.routeOptions.update.post(request, result, Log)
}
} catch (err) {
handleError(
err,
'There was a postprocessing error updating the resource.',
Boom.badRequest,
Log
)
}
return result
} else {
throw Boom.notFound('No resource was found with that id.')
}
} catch (err) {
handleError(err, null, null, Log)
}
}
|
javascript
|
async function _updateHandler(model, _id, request, Log) {
let payload = Object.assign({}, request.payload)
try {
try {
if (
model.routeOptions &&
model.routeOptions.update &&
model.routeOptions.update.pre
) {
payload = await model.routeOptions.update.pre(
_id,
payload,
request,
Log
)
}
} catch (err) {
handleError(
err,
'There was a preprocessing error updating the resource.',
Boom.badRequest,
Log
)
}
if (config.enableUpdatedAt) {
payload.updatedAt = new Date()
}
let result
try {
result = await model.findByIdAndUpdate(_id, payload, {
runValidators: config.enableMongooseRunValidators
})
} catch (err) {
Log.error(err)
if (err.code === 11000) {
throw Boom.conflict('There was a duplicate key error.')
} else {
throw Boom.badImplementation(
'There was an error updating the resource.'
)
}
}
if (result) {
let attributes = QueryHelper.createAttributesFilter({}, model, Log)
result = await model.findOne({ _id: result._id }, attributes).lean()
try {
if (
model.routeOptions &&
model.routeOptions.update &&
model.routeOptions.update.post
) {
result = await model.routeOptions.update.post(request, result, Log)
}
} catch (err) {
handleError(
err,
'There was a postprocessing error updating the resource.',
Boom.badRequest,
Log
)
}
return result
} else {
throw Boom.notFound('No resource was found with that id.')
}
} catch (err) {
handleError(err, null, null, Log)
}
}
|
[
"async",
"function",
"_updateHandler",
"(",
"model",
",",
"_id",
",",
"request",
",",
"Log",
")",
"{",
"let",
"payload",
"=",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"request",
".",
"payload",
")",
"try",
"{",
"try",
"{",
"if",
"(",
"model",
".",
"routeOptions",
"&&",
"model",
".",
"routeOptions",
".",
"update",
"&&",
"model",
".",
"routeOptions",
".",
"update",
".",
"pre",
")",
"{",
"payload",
"=",
"await",
"model",
".",
"routeOptions",
".",
"update",
".",
"pre",
"(",
"_id",
",",
"payload",
",",
"request",
",",
"Log",
")",
"}",
"}",
"catch",
"(",
"err",
")",
"{",
"handleError",
"(",
"err",
",",
"'There was a preprocessing error updating the resource.'",
",",
"Boom",
".",
"badRequest",
",",
"Log",
")",
"}",
"if",
"(",
"config",
".",
"enableUpdatedAt",
")",
"{",
"payload",
".",
"updatedAt",
"=",
"new",
"Date",
"(",
")",
"}",
"let",
"result",
"try",
"{",
"result",
"=",
"await",
"model",
".",
"findByIdAndUpdate",
"(",
"_id",
",",
"payload",
",",
"{",
"runValidators",
":",
"config",
".",
"enableMongooseRunValidators",
"}",
")",
"}",
"catch",
"(",
"err",
")",
"{",
"Log",
".",
"error",
"(",
"err",
")",
"if",
"(",
"err",
".",
"code",
"===",
"11000",
")",
"{",
"throw",
"Boom",
".",
"conflict",
"(",
"'There was a duplicate key error.'",
")",
"}",
"else",
"{",
"throw",
"Boom",
".",
"badImplementation",
"(",
"'There was an error updating the resource.'",
")",
"}",
"}",
"if",
"(",
"result",
")",
"{",
"let",
"attributes",
"=",
"QueryHelper",
".",
"createAttributesFilter",
"(",
"{",
"}",
",",
"model",
",",
"Log",
")",
"result",
"=",
"await",
"model",
".",
"findOne",
"(",
"{",
"_id",
":",
"result",
".",
"_id",
"}",
",",
"attributes",
")",
".",
"lean",
"(",
")",
"try",
"{",
"if",
"(",
"model",
".",
"routeOptions",
"&&",
"model",
".",
"routeOptions",
".",
"update",
"&&",
"model",
".",
"routeOptions",
".",
"update",
".",
"post",
")",
"{",
"result",
"=",
"await",
"model",
".",
"routeOptions",
".",
"update",
".",
"post",
"(",
"request",
",",
"result",
",",
"Log",
")",
"}",
"}",
"catch",
"(",
"err",
")",
"{",
"handleError",
"(",
"err",
",",
"'There was a postprocessing error updating the resource.'",
",",
"Boom",
".",
"badRequest",
",",
"Log",
")",
"}",
"return",
"result",
"}",
"else",
"{",
"throw",
"Boom",
".",
"notFound",
"(",
"'No resource was found with that id.'",
")",
"}",
"}",
"catch",
"(",
"err",
")",
"{",
"handleError",
"(",
"err",
",",
"null",
",",
"null",
",",
"Log",
")",
"}",
"}"
] |
Updates a model document.
@param model: A mongoose model.
@param _id: The document id.
@param request: The Hapi request object, or a container for the wrapper payload.
@param Log: A logging object.
@returns {object} A promise for the resulting model document.
@private
|
[
"Updates",
"a",
"model",
"document",
"."
] |
36110fd3cb2775b3b2068b18d775f1c87fbcef76
|
https://github.com/JKHeadley/rest-hapi/blob/36110fd3cb2775b3b2068b18d775f1c87fbcef76/utilities/handler-helper.js#L455-L526
|
9,214
|
JKHeadley/rest-hapi
|
utilities/handler-helper.js
|
_deleteOne
|
function _deleteOne(model, _id, hardDelete, Log) {
let request = { params: { _id: _id } }
return _deleteOneHandler(model, _id, hardDelete, request, Log)
}
|
javascript
|
function _deleteOne(model, _id, hardDelete, Log) {
let request = { params: { _id: _id } }
return _deleteOneHandler(model, _id, hardDelete, request, Log)
}
|
[
"function",
"_deleteOne",
"(",
"model",
",",
"_id",
",",
"hardDelete",
",",
"Log",
")",
"{",
"let",
"request",
"=",
"{",
"params",
":",
"{",
"_id",
":",
"_id",
"}",
"}",
"return",
"_deleteOneHandler",
"(",
"model",
",",
"_id",
",",
"hardDelete",
",",
"request",
",",
"Log",
")",
"}"
] |
DeleteOne function exposed as a mongoose wrapper.
@param model: A mongoose model.
@param _id: The document id.
@param hardDelete: Flag used to determine a soft or hard delete.
@param Log: A logging object.
@returns {object} A promise returning true if the delete succeeds.
@private
|
[
"DeleteOne",
"function",
"exposed",
"as",
"a",
"mongoose",
"wrapper",
"."
] |
36110fd3cb2775b3b2068b18d775f1c87fbcef76
|
https://github.com/JKHeadley/rest-hapi/blob/36110fd3cb2775b3b2068b18d775f1c87fbcef76/utilities/handler-helper.js#L537-L540
|
9,215
|
JKHeadley/rest-hapi
|
utilities/handler-helper.js
|
_deleteOneHandler
|
async function _deleteOneHandler(model, _id, hardDelete, request, Log) {
try {
try {
if (
model.routeOptions &&
model.routeOptions.delete &&
model.routeOptions.delete.pre
) {
await model.routeOptions.delete.pre(_id, hardDelete, request, Log)
}
} catch (err) {
handleError(
err,
'There was a preprocessing error deleting the resource.',
Boom.badRequest,
Log
)
}
let deleted
try {
if (config.enableSoftDelete && !hardDelete) {
let payload = { isDeleted: true }
if (config.enableDeletedAt) {
payload.deletedAt = new Date()
}
if (config.enableDeletedBy && config.enableSoftDelete) {
let deletedBy =
request.payload.deletedBy || request.payload[0].deletedBy
if (deletedBy) {
payload.deletedBy = deletedBy
}
}
deleted = await model.findByIdAndUpdate(_id, payload, {
new: true,
runValidators: config.enableMongooseRunValidators
})
} else {
deleted = await model.findByIdAndRemove(_id)
}
} catch (err) {
handleError(
err,
'There was an error deleting the resource.',
Boom.badImplementation,
Log
)
}
// TODO: clean up associations/set rules for ON DELETE CASCADE/etc.
if (deleted) {
// TODO: add eventLogs
try {
if (
model.routeOptions &&
model.routeOptions.delete &&
model.routeOptions.delete.post
) {
await model.routeOptions.delete.post(
hardDelete,
deleted,
request,
Log
)
}
} catch (err) {
handleError(
err,
'There was a postprocessing error deleting the resource.',
Boom.badRequest,
Log
)
}
return true
} else {
throw Boom.notFound('No resource was found with that id.')
}
} catch (err) {
handleError(err, null, null, Log)
}
}
|
javascript
|
async function _deleteOneHandler(model, _id, hardDelete, request, Log) {
try {
try {
if (
model.routeOptions &&
model.routeOptions.delete &&
model.routeOptions.delete.pre
) {
await model.routeOptions.delete.pre(_id, hardDelete, request, Log)
}
} catch (err) {
handleError(
err,
'There was a preprocessing error deleting the resource.',
Boom.badRequest,
Log
)
}
let deleted
try {
if (config.enableSoftDelete && !hardDelete) {
let payload = { isDeleted: true }
if (config.enableDeletedAt) {
payload.deletedAt = new Date()
}
if (config.enableDeletedBy && config.enableSoftDelete) {
let deletedBy =
request.payload.deletedBy || request.payload[0].deletedBy
if (deletedBy) {
payload.deletedBy = deletedBy
}
}
deleted = await model.findByIdAndUpdate(_id, payload, {
new: true,
runValidators: config.enableMongooseRunValidators
})
} else {
deleted = await model.findByIdAndRemove(_id)
}
} catch (err) {
handleError(
err,
'There was an error deleting the resource.',
Boom.badImplementation,
Log
)
}
// TODO: clean up associations/set rules for ON DELETE CASCADE/etc.
if (deleted) {
// TODO: add eventLogs
try {
if (
model.routeOptions &&
model.routeOptions.delete &&
model.routeOptions.delete.post
) {
await model.routeOptions.delete.post(
hardDelete,
deleted,
request,
Log
)
}
} catch (err) {
handleError(
err,
'There was a postprocessing error deleting the resource.',
Boom.badRequest,
Log
)
}
return true
} else {
throw Boom.notFound('No resource was found with that id.')
}
} catch (err) {
handleError(err, null, null, Log)
}
}
|
[
"async",
"function",
"_deleteOneHandler",
"(",
"model",
",",
"_id",
",",
"hardDelete",
",",
"request",
",",
"Log",
")",
"{",
"try",
"{",
"try",
"{",
"if",
"(",
"model",
".",
"routeOptions",
"&&",
"model",
".",
"routeOptions",
".",
"delete",
"&&",
"model",
".",
"routeOptions",
".",
"delete",
".",
"pre",
")",
"{",
"await",
"model",
".",
"routeOptions",
".",
"delete",
".",
"pre",
"(",
"_id",
",",
"hardDelete",
",",
"request",
",",
"Log",
")",
"}",
"}",
"catch",
"(",
"err",
")",
"{",
"handleError",
"(",
"err",
",",
"'There was a preprocessing error deleting the resource.'",
",",
"Boom",
".",
"badRequest",
",",
"Log",
")",
"}",
"let",
"deleted",
"try",
"{",
"if",
"(",
"config",
".",
"enableSoftDelete",
"&&",
"!",
"hardDelete",
")",
"{",
"let",
"payload",
"=",
"{",
"isDeleted",
":",
"true",
"}",
"if",
"(",
"config",
".",
"enableDeletedAt",
")",
"{",
"payload",
".",
"deletedAt",
"=",
"new",
"Date",
"(",
")",
"}",
"if",
"(",
"config",
".",
"enableDeletedBy",
"&&",
"config",
".",
"enableSoftDelete",
")",
"{",
"let",
"deletedBy",
"=",
"request",
".",
"payload",
".",
"deletedBy",
"||",
"request",
".",
"payload",
"[",
"0",
"]",
".",
"deletedBy",
"if",
"(",
"deletedBy",
")",
"{",
"payload",
".",
"deletedBy",
"=",
"deletedBy",
"}",
"}",
"deleted",
"=",
"await",
"model",
".",
"findByIdAndUpdate",
"(",
"_id",
",",
"payload",
",",
"{",
"new",
":",
"true",
",",
"runValidators",
":",
"config",
".",
"enableMongooseRunValidators",
"}",
")",
"}",
"else",
"{",
"deleted",
"=",
"await",
"model",
".",
"findByIdAndRemove",
"(",
"_id",
")",
"}",
"}",
"catch",
"(",
"err",
")",
"{",
"handleError",
"(",
"err",
",",
"'There was an error deleting the resource.'",
",",
"Boom",
".",
"badImplementation",
",",
"Log",
")",
"}",
"// TODO: clean up associations/set rules for ON DELETE CASCADE/etc.",
"if",
"(",
"deleted",
")",
"{",
"// TODO: add eventLogs",
"try",
"{",
"if",
"(",
"model",
".",
"routeOptions",
"&&",
"model",
".",
"routeOptions",
".",
"delete",
"&&",
"model",
".",
"routeOptions",
".",
"delete",
".",
"post",
")",
"{",
"await",
"model",
".",
"routeOptions",
".",
"delete",
".",
"post",
"(",
"hardDelete",
",",
"deleted",
",",
"request",
",",
"Log",
")",
"}",
"}",
"catch",
"(",
"err",
")",
"{",
"handleError",
"(",
"err",
",",
"'There was a postprocessing error deleting the resource.'",
",",
"Boom",
".",
"badRequest",
",",
"Log",
")",
"}",
"return",
"true",
"}",
"else",
"{",
"throw",
"Boom",
".",
"notFound",
"(",
"'No resource was found with that id.'",
")",
"}",
"}",
"catch",
"(",
"err",
")",
"{",
"handleError",
"(",
"err",
",",
"null",
",",
"null",
",",
"Log",
")",
"}",
"}"
] |
Deletes a model document
@param model: A mongoose model.
@param _id: The document id.
@param hardDelete: Flag used to determine a soft or hard delete.
@param request: The Hapi request object.
@param Log: A logging object.
@returns {object} A promise returning true if the delete succeeds.
@private
TODO: only update "deleteAt" the first time a document is deleted
|
[
"Deletes",
"a",
"model",
"document"
] |
36110fd3cb2775b3b2068b18d775f1c87fbcef76
|
https://github.com/JKHeadley/rest-hapi/blob/36110fd3cb2775b3b2068b18d775f1c87fbcef76/utilities/handler-helper.js#L552-L632
|
9,216
|
JKHeadley/rest-hapi
|
utilities/handler-helper.js
|
_deleteMany
|
function _deleteMany(model, payload, Log) {
let request = { payload: payload }
return _deleteManyHandler(model, request, Log)
}
|
javascript
|
function _deleteMany(model, payload, Log) {
let request = { payload: payload }
return _deleteManyHandler(model, request, Log)
}
|
[
"function",
"_deleteMany",
"(",
"model",
",",
"payload",
",",
"Log",
")",
"{",
"let",
"request",
"=",
"{",
"payload",
":",
"payload",
"}",
"return",
"_deleteManyHandler",
"(",
"model",
",",
"request",
",",
"Log",
")",
"}"
] |
DeleteMany function exposed as a mongoose wrapper.
@param model: A mongoose model.
@param payload: Either an array of ids or an array of objects containing an id and a "hardDelete" flag.
@param Log: A logging object.
@returns {object} A promise returning true if the delete succeeds.
@private
|
[
"DeleteMany",
"function",
"exposed",
"as",
"a",
"mongoose",
"wrapper",
"."
] |
36110fd3cb2775b3b2068b18d775f1c87fbcef76
|
https://github.com/JKHeadley/rest-hapi/blob/36110fd3cb2775b3b2068b18d775f1c87fbcef76/utilities/handler-helper.js#L642-L645
|
9,217
|
JKHeadley/rest-hapi
|
utilities/handler-helper.js
|
_deleteManyHandler
|
async function _deleteManyHandler(model, request, Log) {
try {
// EXPL: make a copy of the payload so that request.payload remains unchanged
let payload = request.payload.map(item => {
return _.isObject(item) ? _.assignIn({}, item) : item
})
let promises = []
for (let arg of payload) {
if (JoiMongooseHelper.isObjectId(arg)) {
promises.push(_deleteOneHandler(model, arg, false, request, Log))
} else {
promises.push(
_deleteOneHandler(model, arg._id, arg.hardDelete, request, Log)
)
}
}
await Promise.all(promises)
return true
} catch (err) {
handleError(err, null, null, Log)
}
}
|
javascript
|
async function _deleteManyHandler(model, request, Log) {
try {
// EXPL: make a copy of the payload so that request.payload remains unchanged
let payload = request.payload.map(item => {
return _.isObject(item) ? _.assignIn({}, item) : item
})
let promises = []
for (let arg of payload) {
if (JoiMongooseHelper.isObjectId(arg)) {
promises.push(_deleteOneHandler(model, arg, false, request, Log))
} else {
promises.push(
_deleteOneHandler(model, arg._id, arg.hardDelete, request, Log)
)
}
}
await Promise.all(promises)
return true
} catch (err) {
handleError(err, null, null, Log)
}
}
|
[
"async",
"function",
"_deleteManyHandler",
"(",
"model",
",",
"request",
",",
"Log",
")",
"{",
"try",
"{",
"// EXPL: make a copy of the payload so that request.payload remains unchanged",
"let",
"payload",
"=",
"request",
".",
"payload",
".",
"map",
"(",
"item",
"=>",
"{",
"return",
"_",
".",
"isObject",
"(",
"item",
")",
"?",
"_",
".",
"assignIn",
"(",
"{",
"}",
",",
"item",
")",
":",
"item",
"}",
")",
"let",
"promises",
"=",
"[",
"]",
"for",
"(",
"let",
"arg",
"of",
"payload",
")",
"{",
"if",
"(",
"JoiMongooseHelper",
".",
"isObjectId",
"(",
"arg",
")",
")",
"{",
"promises",
".",
"push",
"(",
"_deleteOneHandler",
"(",
"model",
",",
"arg",
",",
"false",
",",
"request",
",",
"Log",
")",
")",
"}",
"else",
"{",
"promises",
".",
"push",
"(",
"_deleteOneHandler",
"(",
"model",
",",
"arg",
".",
"_id",
",",
"arg",
".",
"hardDelete",
",",
"request",
",",
"Log",
")",
")",
"}",
"}",
"await",
"Promise",
".",
"all",
"(",
"promises",
")",
"return",
"true",
"}",
"catch",
"(",
"err",
")",
"{",
"handleError",
"(",
"err",
",",
"null",
",",
"null",
",",
"Log",
")",
"}",
"}"
] |
Deletes multiple documents.
@param model: A mongoose model.
@param request: The Hapi request object, or a container for the wrapper payload.
@param Log: A logging object.
@returns {object} A promise returning true if the delete succeeds.
@private
TODO: prevent Promise.all from catching first error and returning early. Catch individual errors and return a list TODO(cont) of ids that failed
|
[
"Deletes",
"multiple",
"documents",
"."
] |
36110fd3cb2775b3b2068b18d775f1c87fbcef76
|
https://github.com/JKHeadley/rest-hapi/blob/36110fd3cb2775b3b2068b18d775f1c87fbcef76/utilities/handler-helper.js#L656-L678
|
9,218
|
JKHeadley/rest-hapi
|
utilities/handler-helper.js
|
_addOne
|
function _addOne(
ownerModel,
ownerId,
childModel,
childId,
associationName,
payload,
Log
) {
let request = {
params: { ownerId: ownerId, childId: childId },
payload: payload
}
return _addOneHandler(
ownerModel,
ownerId,
childModel,
childId,
associationName,
request,
Log
)
}
|
javascript
|
function _addOne(
ownerModel,
ownerId,
childModel,
childId,
associationName,
payload,
Log
) {
let request = {
params: { ownerId: ownerId, childId: childId },
payload: payload
}
return _addOneHandler(
ownerModel,
ownerId,
childModel,
childId,
associationName,
request,
Log
)
}
|
[
"function",
"_addOne",
"(",
"ownerModel",
",",
"ownerId",
",",
"childModel",
",",
"childId",
",",
"associationName",
",",
"payload",
",",
"Log",
")",
"{",
"let",
"request",
"=",
"{",
"params",
":",
"{",
"ownerId",
":",
"ownerId",
",",
"childId",
":",
"childId",
"}",
",",
"payload",
":",
"payload",
"}",
"return",
"_addOneHandler",
"(",
"ownerModel",
",",
"ownerId",
",",
"childModel",
",",
"childId",
",",
"associationName",
",",
"request",
",",
"Log",
")",
"}"
] |
AddOne function exposed as a mongoose wrapper.
@param ownerModel: The model that is being added to.
@param ownerId: The id of the owner document.
@param childModel: The model that is being added.
@param childId: The id of the child document.
@param associationName: The name of the association from the ownerModel's perspective.
@param payload: An object containing an extra linking-model fields.
@param Log: A logging object
@returns {object} A promise returning true if the add succeeds.
@private
|
[
"AddOne",
"function",
"exposed",
"as",
"a",
"mongoose",
"wrapper",
"."
] |
36110fd3cb2775b3b2068b18d775f1c87fbcef76
|
https://github.com/JKHeadley/rest-hapi/blob/36110fd3cb2775b3b2068b18d775f1c87fbcef76/utilities/handler-helper.js#L692-L714
|
9,219
|
JKHeadley/rest-hapi
|
utilities/handler-helper.js
|
_addOneHandler
|
async function _addOneHandler(
ownerModel,
ownerId,
childModel,
childId,
associationName,
request,
Log
) {
try {
let ownerObject = await ownerModel
.findOne({ _id: ownerId })
.select(associationName)
let payload = Object.assign({}, request.payload)
if (ownerObject) {
if (!payload) {
payload = {}
}
payload.childId = childId
payload = [payload]
try {
if (
ownerModel.routeOptions &&
ownerModel.routeOptions.add &&
ownerModel.routeOptions.add[associationName] &&
ownerModel.routeOptions.add[associationName].pre
) {
payload = await ownerModel.routeOptions.add[associationName].pre(
payload,
request,
Log
)
}
} catch (err) {
handleError(
err,
'There was a preprocessing error while setting the association.',
Boom.badRequest,
Log
)
}
try {
await _setAssociation(
ownerModel,
ownerObject,
childModel,
childId,
associationName,
payload,
Log
)
} catch (err) {
handleError(
err,
'There was a database error while setting the association.',
Boom.badImplementation,
Log
)
}
return true
} else {
throw Boom.notFound('No resource was found with that id.')
}
} catch (err) {
handleError(err, null, null, Log)
}
}
|
javascript
|
async function _addOneHandler(
ownerModel,
ownerId,
childModel,
childId,
associationName,
request,
Log
) {
try {
let ownerObject = await ownerModel
.findOne({ _id: ownerId })
.select(associationName)
let payload = Object.assign({}, request.payload)
if (ownerObject) {
if (!payload) {
payload = {}
}
payload.childId = childId
payload = [payload]
try {
if (
ownerModel.routeOptions &&
ownerModel.routeOptions.add &&
ownerModel.routeOptions.add[associationName] &&
ownerModel.routeOptions.add[associationName].pre
) {
payload = await ownerModel.routeOptions.add[associationName].pre(
payload,
request,
Log
)
}
} catch (err) {
handleError(
err,
'There was a preprocessing error while setting the association.',
Boom.badRequest,
Log
)
}
try {
await _setAssociation(
ownerModel,
ownerObject,
childModel,
childId,
associationName,
payload,
Log
)
} catch (err) {
handleError(
err,
'There was a database error while setting the association.',
Boom.badImplementation,
Log
)
}
return true
} else {
throw Boom.notFound('No resource was found with that id.')
}
} catch (err) {
handleError(err, null, null, Log)
}
}
|
[
"async",
"function",
"_addOneHandler",
"(",
"ownerModel",
",",
"ownerId",
",",
"childModel",
",",
"childId",
",",
"associationName",
",",
"request",
",",
"Log",
")",
"{",
"try",
"{",
"let",
"ownerObject",
"=",
"await",
"ownerModel",
".",
"findOne",
"(",
"{",
"_id",
":",
"ownerId",
"}",
")",
".",
"select",
"(",
"associationName",
")",
"let",
"payload",
"=",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"request",
".",
"payload",
")",
"if",
"(",
"ownerObject",
")",
"{",
"if",
"(",
"!",
"payload",
")",
"{",
"payload",
"=",
"{",
"}",
"}",
"payload",
".",
"childId",
"=",
"childId",
"payload",
"=",
"[",
"payload",
"]",
"try",
"{",
"if",
"(",
"ownerModel",
".",
"routeOptions",
"&&",
"ownerModel",
".",
"routeOptions",
".",
"add",
"&&",
"ownerModel",
".",
"routeOptions",
".",
"add",
"[",
"associationName",
"]",
"&&",
"ownerModel",
".",
"routeOptions",
".",
"add",
"[",
"associationName",
"]",
".",
"pre",
")",
"{",
"payload",
"=",
"await",
"ownerModel",
".",
"routeOptions",
".",
"add",
"[",
"associationName",
"]",
".",
"pre",
"(",
"payload",
",",
"request",
",",
"Log",
")",
"}",
"}",
"catch",
"(",
"err",
")",
"{",
"handleError",
"(",
"err",
",",
"'There was a preprocessing error while setting the association.'",
",",
"Boom",
".",
"badRequest",
",",
"Log",
")",
"}",
"try",
"{",
"await",
"_setAssociation",
"(",
"ownerModel",
",",
"ownerObject",
",",
"childModel",
",",
"childId",
",",
"associationName",
",",
"payload",
",",
"Log",
")",
"}",
"catch",
"(",
"err",
")",
"{",
"handleError",
"(",
"err",
",",
"'There was a database error while setting the association.'",
",",
"Boom",
".",
"badImplementation",
",",
"Log",
")",
"}",
"return",
"true",
"}",
"else",
"{",
"throw",
"Boom",
".",
"notFound",
"(",
"'No resource was found with that id.'",
")",
"}",
"}",
"catch",
"(",
"err",
")",
"{",
"handleError",
"(",
"err",
",",
"null",
",",
"null",
",",
"Log",
")",
"}",
"}"
] |
Adds an association to a document
@param ownerModel: The model that is being added to.
@param ownerId: The id of the owner document.
@param childModel: The model that is being added.
@param childId: The id of the child document.
@param associationName: The name of the association from the ownerModel's perspective.
@param request: The Hapi request object, or a container for the wrapper payload.
@param Log: A logging object
@returns {object} A promise returning true if the add succeeds.
@private
|
[
"Adds",
"an",
"association",
"to",
"a",
"document"
] |
36110fd3cb2775b3b2068b18d775f1c87fbcef76
|
https://github.com/JKHeadley/rest-hapi/blob/36110fd3cb2775b3b2068b18d775f1c87fbcef76/utilities/handler-helper.js#L727-L795
|
9,220
|
JKHeadley/rest-hapi
|
utilities/handler-helper.js
|
_removeOne
|
function _removeOne(
ownerModel,
ownerId,
childModel,
childId,
associationName,
Log
) {
let request = { params: { ownerId: ownerId, childId: childId } }
return _removeOneHandler(
ownerModel,
ownerId,
childModel,
childId,
associationName,
request,
Log
)
}
|
javascript
|
function _removeOne(
ownerModel,
ownerId,
childModel,
childId,
associationName,
Log
) {
let request = { params: { ownerId: ownerId, childId: childId } }
return _removeOneHandler(
ownerModel,
ownerId,
childModel,
childId,
associationName,
request,
Log
)
}
|
[
"function",
"_removeOne",
"(",
"ownerModel",
",",
"ownerId",
",",
"childModel",
",",
"childId",
",",
"associationName",
",",
"Log",
")",
"{",
"let",
"request",
"=",
"{",
"params",
":",
"{",
"ownerId",
":",
"ownerId",
",",
"childId",
":",
"childId",
"}",
"}",
"return",
"_removeOneHandler",
"(",
"ownerModel",
",",
"ownerId",
",",
"childModel",
",",
"childId",
",",
"associationName",
",",
"request",
",",
"Log",
")",
"}"
] |
RemoveOne function exposed as a mongoose wrapper.
@param ownerModel: The model that is being removed from.
@param ownerId: The id of the owner document.
@param childModel: The model that is being removed.
@param childId: The id of the child document.
@param associationName: The name of the association from the ownerModel's perspective.
@param Log: A logging object
@returns {object} A promise returning true if the remove succeeds.
@private
|
[
"RemoveOne",
"function",
"exposed",
"as",
"a",
"mongoose",
"wrapper",
"."
] |
36110fd3cb2775b3b2068b18d775f1c87fbcef76
|
https://github.com/JKHeadley/rest-hapi/blob/36110fd3cb2775b3b2068b18d775f1c87fbcef76/utilities/handler-helper.js#L808-L826
|
9,221
|
JKHeadley/rest-hapi
|
utilities/handler-helper.js
|
_removeOneHandler
|
async function _removeOneHandler(
ownerModel,
ownerId,
childModel,
childId,
associationName,
request,
Log
) {
try {
let ownerObject = await ownerModel
.findOne({ _id: ownerId })
.select(associationName)
if (ownerObject) {
try {
if (
ownerModel.routeOptions &&
ownerModel.routeOptions.remove &&
ownerModel.routeOptions.remove[associationName] &&
ownerModel.routeOptions.remove[associationName].pre
) {
await ownerModel.routeOptions.remove[associationName].pre(
{},
request,
Log
)
}
} catch (err) {
handleError(
err,
'There was a preprocessing error while removing the association.',
Boom.badRequest,
Log
)
}
try {
await _removeAssociation(
ownerModel,
ownerObject,
childModel,
childId,
associationName,
Log
)
} catch (err) {
handleError(
err,
'There was a database error while removing the association.',
Boom.badImplementation,
Log
)
}
return true
} else {
throw Boom.notFound('No resource was found with that id.')
}
} catch (err) {
handleError(err, null, null, Log)
}
}
|
javascript
|
async function _removeOneHandler(
ownerModel,
ownerId,
childModel,
childId,
associationName,
request,
Log
) {
try {
let ownerObject = await ownerModel
.findOne({ _id: ownerId })
.select(associationName)
if (ownerObject) {
try {
if (
ownerModel.routeOptions &&
ownerModel.routeOptions.remove &&
ownerModel.routeOptions.remove[associationName] &&
ownerModel.routeOptions.remove[associationName].pre
) {
await ownerModel.routeOptions.remove[associationName].pre(
{},
request,
Log
)
}
} catch (err) {
handleError(
err,
'There was a preprocessing error while removing the association.',
Boom.badRequest,
Log
)
}
try {
await _removeAssociation(
ownerModel,
ownerObject,
childModel,
childId,
associationName,
Log
)
} catch (err) {
handleError(
err,
'There was a database error while removing the association.',
Boom.badImplementation,
Log
)
}
return true
} else {
throw Boom.notFound('No resource was found with that id.')
}
} catch (err) {
handleError(err, null, null, Log)
}
}
|
[
"async",
"function",
"_removeOneHandler",
"(",
"ownerModel",
",",
"ownerId",
",",
"childModel",
",",
"childId",
",",
"associationName",
",",
"request",
",",
"Log",
")",
"{",
"try",
"{",
"let",
"ownerObject",
"=",
"await",
"ownerModel",
".",
"findOne",
"(",
"{",
"_id",
":",
"ownerId",
"}",
")",
".",
"select",
"(",
"associationName",
")",
"if",
"(",
"ownerObject",
")",
"{",
"try",
"{",
"if",
"(",
"ownerModel",
".",
"routeOptions",
"&&",
"ownerModel",
".",
"routeOptions",
".",
"remove",
"&&",
"ownerModel",
".",
"routeOptions",
".",
"remove",
"[",
"associationName",
"]",
"&&",
"ownerModel",
".",
"routeOptions",
".",
"remove",
"[",
"associationName",
"]",
".",
"pre",
")",
"{",
"await",
"ownerModel",
".",
"routeOptions",
".",
"remove",
"[",
"associationName",
"]",
".",
"pre",
"(",
"{",
"}",
",",
"request",
",",
"Log",
")",
"}",
"}",
"catch",
"(",
"err",
")",
"{",
"handleError",
"(",
"err",
",",
"'There was a preprocessing error while removing the association.'",
",",
"Boom",
".",
"badRequest",
",",
"Log",
")",
"}",
"try",
"{",
"await",
"_removeAssociation",
"(",
"ownerModel",
",",
"ownerObject",
",",
"childModel",
",",
"childId",
",",
"associationName",
",",
"Log",
")",
"}",
"catch",
"(",
"err",
")",
"{",
"handleError",
"(",
"err",
",",
"'There was a database error while removing the association.'",
",",
"Boom",
".",
"badImplementation",
",",
"Log",
")",
"}",
"return",
"true",
"}",
"else",
"{",
"throw",
"Boom",
".",
"notFound",
"(",
"'No resource was found with that id.'",
")",
"}",
"}",
"catch",
"(",
"err",
")",
"{",
"handleError",
"(",
"err",
",",
"null",
",",
"null",
",",
"Log",
")",
"}",
"}"
] |
Removes an association to a document
@param ownerModel: The model that is being removed from.
@param ownerId: The id of the owner document.
@param childModel: The model that is being removed.
@param childId: The id of the child document.
@param associationName: The name of the association from the ownerModel's perspective.
@param request: The Hapi request object.
@param Log: A logging object
@returns {object} A promise returning true if the remove succeeds.
@private
|
[
"Removes",
"an",
"association",
"to",
"a",
"document"
] |
36110fd3cb2775b3b2068b18d775f1c87fbcef76
|
https://github.com/JKHeadley/rest-hapi/blob/36110fd3cb2775b3b2068b18d775f1c87fbcef76/utilities/handler-helper.js#L839-L899
|
9,222
|
JKHeadley/rest-hapi
|
utilities/handler-helper.js
|
_addMany
|
function _addMany(
ownerModel,
ownerId,
childModel,
associationName,
payload,
Log
) {
let request = { params: { ownerId: ownerId }, payload: payload }
return _addManyHandler(
ownerModel,
ownerId,
childModel,
associationName,
request,
Log
)
}
|
javascript
|
function _addMany(
ownerModel,
ownerId,
childModel,
associationName,
payload,
Log
) {
let request = { params: { ownerId: ownerId }, payload: payload }
return _addManyHandler(
ownerModel,
ownerId,
childModel,
associationName,
request,
Log
)
}
|
[
"function",
"_addMany",
"(",
"ownerModel",
",",
"ownerId",
",",
"childModel",
",",
"associationName",
",",
"payload",
",",
"Log",
")",
"{",
"let",
"request",
"=",
"{",
"params",
":",
"{",
"ownerId",
":",
"ownerId",
"}",
",",
"payload",
":",
"payload",
"}",
"return",
"_addManyHandler",
"(",
"ownerModel",
",",
"ownerId",
",",
"childModel",
",",
"associationName",
",",
"request",
",",
"Log",
")",
"}"
] |
AddMany function exposed as a mongoose wrapper.
@param ownerModel: The model that is being added to.
@param ownerId: The id of the owner document.
@param childModel: The model that is being added.
@param associationName: The name of the association from the ownerModel's perspective.
@param payload: Either a list of id's or a list of id's along with extra linking-model fields.
@param Log: A logging object
@returns {object} A promise returning true if the add succeeds.
@private
|
[
"AddMany",
"function",
"exposed",
"as",
"a",
"mongoose",
"wrapper",
"."
] |
36110fd3cb2775b3b2068b18d775f1c87fbcef76
|
https://github.com/JKHeadley/rest-hapi/blob/36110fd3cb2775b3b2068b18d775f1c87fbcef76/utilities/handler-helper.js#L912-L929
|
9,223
|
JKHeadley/rest-hapi
|
utilities/handler-helper.js
|
_addManyHandler
|
async function _addManyHandler(
ownerModel,
ownerId,
childModel,
associationName,
request,
Log
) {
try {
// EXPL: make a copy of the payload so that request.payload remains unchanged
let payload = request.payload.map(item => {
return _.isObject(item) ? _.assignIn({}, item) : item
})
if (_.isEmpty(request.payload)) {
throw Boom.badRequest('Payload is empty.')
}
let ownerObject = await ownerModel
.findOne({ _id: ownerId })
.select(associationName)
if (ownerObject) {
try {
if (
ownerModel.routeOptions &&
ownerModel.routeOptions.add &&
ownerModel.routeOptions.add[associationName] &&
ownerModel.routeOptions.add[associationName].pre
) {
payload = await ownerModel.routeOptions.add[associationName].pre(
payload,
request,
Log
)
}
} catch (err) {
handleError(
err,
'There was a preprocessing error while setting the association.',
Boom.badRequest,
Log
)
}
let childIds = []
// EXPL: the payload is an array of Ids
if (
typeof payload[0] === 'string' ||
payload[0] instanceof String ||
payload[0]._bsontype === 'ObjectID'
) {
childIds = payload
} else {
// EXPL: the payload contains extra fields
childIds = payload.map(object => {
return object.childId
})
}
for (let childId of childIds) {
try {
await _setAssociation(
ownerModel,
ownerObject,
childModel,
childId,
associationName,
payload,
Log
)
} catch (err) {
handleError(
err,
'There was an internal error while setting the associations.',
Boom.badImplementation,
Log
)
}
}
return true
} else {
throw Boom.notFound('No owner resource was found with that id.')
}
} catch (err) {
handleError(err, null, null, Log)
}
}
|
javascript
|
async function _addManyHandler(
ownerModel,
ownerId,
childModel,
associationName,
request,
Log
) {
try {
// EXPL: make a copy of the payload so that request.payload remains unchanged
let payload = request.payload.map(item => {
return _.isObject(item) ? _.assignIn({}, item) : item
})
if (_.isEmpty(request.payload)) {
throw Boom.badRequest('Payload is empty.')
}
let ownerObject = await ownerModel
.findOne({ _id: ownerId })
.select(associationName)
if (ownerObject) {
try {
if (
ownerModel.routeOptions &&
ownerModel.routeOptions.add &&
ownerModel.routeOptions.add[associationName] &&
ownerModel.routeOptions.add[associationName].pre
) {
payload = await ownerModel.routeOptions.add[associationName].pre(
payload,
request,
Log
)
}
} catch (err) {
handleError(
err,
'There was a preprocessing error while setting the association.',
Boom.badRequest,
Log
)
}
let childIds = []
// EXPL: the payload is an array of Ids
if (
typeof payload[0] === 'string' ||
payload[0] instanceof String ||
payload[0]._bsontype === 'ObjectID'
) {
childIds = payload
} else {
// EXPL: the payload contains extra fields
childIds = payload.map(object => {
return object.childId
})
}
for (let childId of childIds) {
try {
await _setAssociation(
ownerModel,
ownerObject,
childModel,
childId,
associationName,
payload,
Log
)
} catch (err) {
handleError(
err,
'There was an internal error while setting the associations.',
Boom.badImplementation,
Log
)
}
}
return true
} else {
throw Boom.notFound('No owner resource was found with that id.')
}
} catch (err) {
handleError(err, null, null, Log)
}
}
|
[
"async",
"function",
"_addManyHandler",
"(",
"ownerModel",
",",
"ownerId",
",",
"childModel",
",",
"associationName",
",",
"request",
",",
"Log",
")",
"{",
"try",
"{",
"// EXPL: make a copy of the payload so that request.payload remains unchanged",
"let",
"payload",
"=",
"request",
".",
"payload",
".",
"map",
"(",
"item",
"=>",
"{",
"return",
"_",
".",
"isObject",
"(",
"item",
")",
"?",
"_",
".",
"assignIn",
"(",
"{",
"}",
",",
"item",
")",
":",
"item",
"}",
")",
"if",
"(",
"_",
".",
"isEmpty",
"(",
"request",
".",
"payload",
")",
")",
"{",
"throw",
"Boom",
".",
"badRequest",
"(",
"'Payload is empty.'",
")",
"}",
"let",
"ownerObject",
"=",
"await",
"ownerModel",
".",
"findOne",
"(",
"{",
"_id",
":",
"ownerId",
"}",
")",
".",
"select",
"(",
"associationName",
")",
"if",
"(",
"ownerObject",
")",
"{",
"try",
"{",
"if",
"(",
"ownerModel",
".",
"routeOptions",
"&&",
"ownerModel",
".",
"routeOptions",
".",
"add",
"&&",
"ownerModel",
".",
"routeOptions",
".",
"add",
"[",
"associationName",
"]",
"&&",
"ownerModel",
".",
"routeOptions",
".",
"add",
"[",
"associationName",
"]",
".",
"pre",
")",
"{",
"payload",
"=",
"await",
"ownerModel",
".",
"routeOptions",
".",
"add",
"[",
"associationName",
"]",
".",
"pre",
"(",
"payload",
",",
"request",
",",
"Log",
")",
"}",
"}",
"catch",
"(",
"err",
")",
"{",
"handleError",
"(",
"err",
",",
"'There was a preprocessing error while setting the association.'",
",",
"Boom",
".",
"badRequest",
",",
"Log",
")",
"}",
"let",
"childIds",
"=",
"[",
"]",
"// EXPL: the payload is an array of Ids",
"if",
"(",
"typeof",
"payload",
"[",
"0",
"]",
"===",
"'string'",
"||",
"payload",
"[",
"0",
"]",
"instanceof",
"String",
"||",
"payload",
"[",
"0",
"]",
".",
"_bsontype",
"===",
"'ObjectID'",
")",
"{",
"childIds",
"=",
"payload",
"}",
"else",
"{",
"// EXPL: the payload contains extra fields",
"childIds",
"=",
"payload",
".",
"map",
"(",
"object",
"=>",
"{",
"return",
"object",
".",
"childId",
"}",
")",
"}",
"for",
"(",
"let",
"childId",
"of",
"childIds",
")",
"{",
"try",
"{",
"await",
"_setAssociation",
"(",
"ownerModel",
",",
"ownerObject",
",",
"childModel",
",",
"childId",
",",
"associationName",
",",
"payload",
",",
"Log",
")",
"}",
"catch",
"(",
"err",
")",
"{",
"handleError",
"(",
"err",
",",
"'There was an internal error while setting the associations.'",
",",
"Boom",
".",
"badImplementation",
",",
"Log",
")",
"}",
"}",
"return",
"true",
"}",
"else",
"{",
"throw",
"Boom",
".",
"notFound",
"(",
"'No owner resource was found with that id.'",
")",
"}",
"}",
"catch",
"(",
"err",
")",
"{",
"handleError",
"(",
"err",
",",
"null",
",",
"null",
",",
"Log",
")",
"}",
"}"
] |
Adds multiple associations to a document.
@param ownerModel: The model that is being added to.
@param ownerId: The id of the owner document.
@param childModel: The model that is being added.
@param associationName: The name of the association from the ownerModel's perspective.
@param request: The Hapi request object, or a container for the wrapper payload.
@param Log: A logging object
@returns {object} A promise returning true if the add succeeds.
@private
|
[
"Adds",
"multiple",
"associations",
"to",
"a",
"document",
"."
] |
36110fd3cb2775b3b2068b18d775f1c87fbcef76
|
https://github.com/JKHeadley/rest-hapi/blob/36110fd3cb2775b3b2068b18d775f1c87fbcef76/utilities/handler-helper.js#L941-L1026
|
9,224
|
JKHeadley/rest-hapi
|
utilities/handler-helper.js
|
_removeMany
|
function _removeMany(
ownerModel,
ownerId,
childModel,
associationName,
payload,
Log
) {
let request = { params: { ownerId: ownerId }, payload: payload }
return _removeManyHandler(
ownerModel,
ownerId,
childModel,
associationName,
request,
Log
)
}
|
javascript
|
function _removeMany(
ownerModel,
ownerId,
childModel,
associationName,
payload,
Log
) {
let request = { params: { ownerId: ownerId }, payload: payload }
return _removeManyHandler(
ownerModel,
ownerId,
childModel,
associationName,
request,
Log
)
}
|
[
"function",
"_removeMany",
"(",
"ownerModel",
",",
"ownerId",
",",
"childModel",
",",
"associationName",
",",
"payload",
",",
"Log",
")",
"{",
"let",
"request",
"=",
"{",
"params",
":",
"{",
"ownerId",
":",
"ownerId",
"}",
",",
"payload",
":",
"payload",
"}",
"return",
"_removeManyHandler",
"(",
"ownerModel",
",",
"ownerId",
",",
"childModel",
",",
"associationName",
",",
"request",
",",
"Log",
")",
"}"
] |
RemoveMany function exposed as a mongoose wrapper.
@param ownerModel: The model that is being removed from.
@param ownerId: The id of the owner document.
@param childModel: The model that is being removed.
@param associationName: The name of the association from the ownerModel's perspective.
@param payload: A list of ids
@param Log: A logging object
@returns {object} A promise returning true if the remove succeeds.
@private
|
[
"RemoveMany",
"function",
"exposed",
"as",
"a",
"mongoose",
"wrapper",
"."
] |
36110fd3cb2775b3b2068b18d775f1c87fbcef76
|
https://github.com/JKHeadley/rest-hapi/blob/36110fd3cb2775b3b2068b18d775f1c87fbcef76/utilities/handler-helper.js#L1039-L1056
|
9,225
|
JKHeadley/rest-hapi
|
utilities/handler-helper.js
|
_removeManyHandler
|
async function _removeManyHandler(
ownerModel,
ownerId,
childModel,
associationName,
request,
Log
) {
try {
// EXPL: make a copy of the payload so that request.payload remains unchanged
let payload = request.payload.map(item => {
return _.isObject(item) ? _.assignIn({}, item) : item
})
if (_.isEmpty(request.payload)) {
throw Boom.badRequest('Payload is empty.')
}
let ownerObject = await ownerModel
.findOne({ _id: ownerId })
.select(associationName)
if (ownerObject) {
try {
if (
ownerModel.routeOptions &&
ownerModel.routeOptions.remove &&
ownerModel.routeOptions.remove[associationName] &&
ownerModel.routeOptions.remove[associationName].pre
) {
payload = await ownerModel.routeOptions.remove[associationName].pre(
payload,
request,
Log
)
}
} catch (err) {
handleError(
err,
'There was a preprocessing error while removing the association.',
Boom.badRequest,
Log
)
}
for (let childId of payload) {
try {
await _removeAssociation(
ownerModel,
ownerObject,
childModel,
childId,
associationName,
Log
)
} catch (err) {
handleError(
err,
'There was an internal error while removing the associations.',
Boom.badImplementation,
Log
)
}
}
return true
} else {
throw Boom.notFound('No owner resource was found with that id.')
}
} catch (err) {
handleError(err, null, null, Log)
}
}
|
javascript
|
async function _removeManyHandler(
ownerModel,
ownerId,
childModel,
associationName,
request,
Log
) {
try {
// EXPL: make a copy of the payload so that request.payload remains unchanged
let payload = request.payload.map(item => {
return _.isObject(item) ? _.assignIn({}, item) : item
})
if (_.isEmpty(request.payload)) {
throw Boom.badRequest('Payload is empty.')
}
let ownerObject = await ownerModel
.findOne({ _id: ownerId })
.select(associationName)
if (ownerObject) {
try {
if (
ownerModel.routeOptions &&
ownerModel.routeOptions.remove &&
ownerModel.routeOptions.remove[associationName] &&
ownerModel.routeOptions.remove[associationName].pre
) {
payload = await ownerModel.routeOptions.remove[associationName].pre(
payload,
request,
Log
)
}
} catch (err) {
handleError(
err,
'There was a preprocessing error while removing the association.',
Boom.badRequest,
Log
)
}
for (let childId of payload) {
try {
await _removeAssociation(
ownerModel,
ownerObject,
childModel,
childId,
associationName,
Log
)
} catch (err) {
handleError(
err,
'There was an internal error while removing the associations.',
Boom.badImplementation,
Log
)
}
}
return true
} else {
throw Boom.notFound('No owner resource was found with that id.')
}
} catch (err) {
handleError(err, null, null, Log)
}
}
|
[
"async",
"function",
"_removeManyHandler",
"(",
"ownerModel",
",",
"ownerId",
",",
"childModel",
",",
"associationName",
",",
"request",
",",
"Log",
")",
"{",
"try",
"{",
"// EXPL: make a copy of the payload so that request.payload remains unchanged",
"let",
"payload",
"=",
"request",
".",
"payload",
".",
"map",
"(",
"item",
"=>",
"{",
"return",
"_",
".",
"isObject",
"(",
"item",
")",
"?",
"_",
".",
"assignIn",
"(",
"{",
"}",
",",
"item",
")",
":",
"item",
"}",
")",
"if",
"(",
"_",
".",
"isEmpty",
"(",
"request",
".",
"payload",
")",
")",
"{",
"throw",
"Boom",
".",
"badRequest",
"(",
"'Payload is empty.'",
")",
"}",
"let",
"ownerObject",
"=",
"await",
"ownerModel",
".",
"findOne",
"(",
"{",
"_id",
":",
"ownerId",
"}",
")",
".",
"select",
"(",
"associationName",
")",
"if",
"(",
"ownerObject",
")",
"{",
"try",
"{",
"if",
"(",
"ownerModel",
".",
"routeOptions",
"&&",
"ownerModel",
".",
"routeOptions",
".",
"remove",
"&&",
"ownerModel",
".",
"routeOptions",
".",
"remove",
"[",
"associationName",
"]",
"&&",
"ownerModel",
".",
"routeOptions",
".",
"remove",
"[",
"associationName",
"]",
".",
"pre",
")",
"{",
"payload",
"=",
"await",
"ownerModel",
".",
"routeOptions",
".",
"remove",
"[",
"associationName",
"]",
".",
"pre",
"(",
"payload",
",",
"request",
",",
"Log",
")",
"}",
"}",
"catch",
"(",
"err",
")",
"{",
"handleError",
"(",
"err",
",",
"'There was a preprocessing error while removing the association.'",
",",
"Boom",
".",
"badRequest",
",",
"Log",
")",
"}",
"for",
"(",
"let",
"childId",
"of",
"payload",
")",
"{",
"try",
"{",
"await",
"_removeAssociation",
"(",
"ownerModel",
",",
"ownerObject",
",",
"childModel",
",",
"childId",
",",
"associationName",
",",
"Log",
")",
"}",
"catch",
"(",
"err",
")",
"{",
"handleError",
"(",
"err",
",",
"'There was an internal error while removing the associations.'",
",",
"Boom",
".",
"badImplementation",
",",
"Log",
")",
"}",
"}",
"return",
"true",
"}",
"else",
"{",
"throw",
"Boom",
".",
"notFound",
"(",
"'No owner resource was found with that id.'",
")",
"}",
"}",
"catch",
"(",
"err",
")",
"{",
"handleError",
"(",
"err",
",",
"null",
",",
"null",
",",
"Log",
")",
"}",
"}"
] |
Removes multiple associations from a document
@param ownerModel: The model that is being removed from.
@param ownerId: The id of the owner document.
@param childModel: The model that is being removed.
@param associationName: The name of the association from the ownerModel's perspective.
@param request: The Hapi request object, or a container for the wrapper payload.
@param Log: A logging object
@returns {object} A promise returning true if the remove succeeds.
@private
|
[
"Removes",
"multiple",
"associations",
"from",
"a",
"document"
] |
36110fd3cb2775b3b2068b18d775f1c87fbcef76
|
https://github.com/JKHeadley/rest-hapi/blob/36110fd3cb2775b3b2068b18d775f1c87fbcef76/utilities/handler-helper.js#L1068-L1136
|
9,226
|
JKHeadley/rest-hapi
|
utilities/handler-helper.js
|
_getAll
|
function _getAll(ownerModel, ownerId, childModel, associationName, query, Log) {
let request = { params: { ownerId: ownerId }, query: query }
return _getAllHandler(
ownerModel,
ownerId,
childModel,
associationName,
request,
Log
)
}
|
javascript
|
function _getAll(ownerModel, ownerId, childModel, associationName, query, Log) {
let request = { params: { ownerId: ownerId }, query: query }
return _getAllHandler(
ownerModel,
ownerId,
childModel,
associationName,
request,
Log
)
}
|
[
"function",
"_getAll",
"(",
"ownerModel",
",",
"ownerId",
",",
"childModel",
",",
"associationName",
",",
"query",
",",
"Log",
")",
"{",
"let",
"request",
"=",
"{",
"params",
":",
"{",
"ownerId",
":",
"ownerId",
"}",
",",
"query",
":",
"query",
"}",
"return",
"_getAllHandler",
"(",
"ownerModel",
",",
"ownerId",
",",
"childModel",
",",
"associationName",
",",
"request",
",",
"Log",
")",
"}"
] |
GetAll function exposed as a mongoose wrapper.
@param ownerModel: The model that is being added to.
@param ownerId: The id of the owner document.
@param childModel: The model that is being added.
@param associationName: The name of the association from the ownerModel's perspective.
@param query: rest-hapi query parameters to be converted to a mongoose query.
@param Log: A logging object
@returns {object} A promise for the resulting model documents or the count of the query results.
@private
|
[
"GetAll",
"function",
"exposed",
"as",
"a",
"mongoose",
"wrapper",
"."
] |
36110fd3cb2775b3b2068b18d775f1c87fbcef76
|
https://github.com/JKHeadley/rest-hapi/blob/36110fd3cb2775b3b2068b18d775f1c87fbcef76/utilities/handler-helper.js#L1149-L1159
|
9,227
|
JKHeadley/rest-hapi
|
utilities/handler-helper.js
|
filterDeletedEmbeds
|
function filterDeletedEmbeds(result, parent, parentkey, depth, Log) {
if (_.isArray(result)) {
result = result.filter(function(obj) {
let keep = filterDeletedEmbeds(obj, result, parentkey, depth + 1, Log)
// Log.log("KEEP:", keep);
return keep
})
// Log.log("UPDATED:", parentkey);
// Log.note("AFTER:", result);
parent[parentkey] = result
} else {
for (let key in result) {
// Log.debug("KEY:", key);
// Log.debug("VALUE:", result[key]);
if (_.isArray(result[key])) {
// Log.log("JUMPING IN ARRAY");
filterDeletedEmbeds(result[key], result, key, depth + 1, Log)
} else if (_.isObject(result[key]) && result[key]._id) {
// Log.log("JUMPING IN OBJECT");
let keep = filterDeletedEmbeds(result[key], result, key, depth + 1, Log)
if (!keep) {
return false
}
} else if (key === 'isDeleted' && result[key] === true && depth > 0) {
// Log.log("DELETED", depth);
return false
}
}
// Log.log("JUMPING OUT");
return true
}
}
|
javascript
|
function filterDeletedEmbeds(result, parent, parentkey, depth, Log) {
if (_.isArray(result)) {
result = result.filter(function(obj) {
let keep = filterDeletedEmbeds(obj, result, parentkey, depth + 1, Log)
// Log.log("KEEP:", keep);
return keep
})
// Log.log("UPDATED:", parentkey);
// Log.note("AFTER:", result);
parent[parentkey] = result
} else {
for (let key in result) {
// Log.debug("KEY:", key);
// Log.debug("VALUE:", result[key]);
if (_.isArray(result[key])) {
// Log.log("JUMPING IN ARRAY");
filterDeletedEmbeds(result[key], result, key, depth + 1, Log)
} else if (_.isObject(result[key]) && result[key]._id) {
// Log.log("JUMPING IN OBJECT");
let keep = filterDeletedEmbeds(result[key], result, key, depth + 1, Log)
if (!keep) {
return false
}
} else if (key === 'isDeleted' && result[key] === true && depth > 0) {
// Log.log("DELETED", depth);
return false
}
}
// Log.log("JUMPING OUT");
return true
}
}
|
[
"function",
"filterDeletedEmbeds",
"(",
"result",
",",
"parent",
",",
"parentkey",
",",
"depth",
",",
"Log",
")",
"{",
"if",
"(",
"_",
".",
"isArray",
"(",
"result",
")",
")",
"{",
"result",
"=",
"result",
".",
"filter",
"(",
"function",
"(",
"obj",
")",
"{",
"let",
"keep",
"=",
"filterDeletedEmbeds",
"(",
"obj",
",",
"result",
",",
"parentkey",
",",
"depth",
"+",
"1",
",",
"Log",
")",
"// Log.log(\"KEEP:\", keep);",
"return",
"keep",
"}",
")",
"// Log.log(\"UPDATED:\", parentkey);",
"// Log.note(\"AFTER:\", result);",
"parent",
"[",
"parentkey",
"]",
"=",
"result",
"}",
"else",
"{",
"for",
"(",
"let",
"key",
"in",
"result",
")",
"{",
"// Log.debug(\"KEY:\", key);",
"// Log.debug(\"VALUE:\", result[key]);",
"if",
"(",
"_",
".",
"isArray",
"(",
"result",
"[",
"key",
"]",
")",
")",
"{",
"// Log.log(\"JUMPING IN ARRAY\");",
"filterDeletedEmbeds",
"(",
"result",
"[",
"key",
"]",
",",
"result",
",",
"key",
",",
"depth",
"+",
"1",
",",
"Log",
")",
"}",
"else",
"if",
"(",
"_",
".",
"isObject",
"(",
"result",
"[",
"key",
"]",
")",
"&&",
"result",
"[",
"key",
"]",
".",
"_id",
")",
"{",
"// Log.log(\"JUMPING IN OBJECT\");",
"let",
"keep",
"=",
"filterDeletedEmbeds",
"(",
"result",
"[",
"key",
"]",
",",
"result",
",",
"key",
",",
"depth",
"+",
"1",
",",
"Log",
")",
"if",
"(",
"!",
"keep",
")",
"{",
"return",
"false",
"}",
"}",
"else",
"if",
"(",
"key",
"===",
"'isDeleted'",
"&&",
"result",
"[",
"key",
"]",
"===",
"true",
"&&",
"depth",
">",
"0",
")",
"{",
"// Log.log(\"DELETED\", depth);",
"return",
"false",
"}",
"}",
"// Log.log(\"JUMPING OUT\");",
"return",
"true",
"}",
"}"
] |
This function is called after embedded associations have been populated so that any associations
that have been soft deleted are removed.
@param result: the object that is being inspected
@param parent: the parent of the result object
@param parentkey: the parents key for the result object
@param depth: the current recursion depth
@param Log: a logging object
@returns {boolean}: returns false if the result object should be removed from the parent
@private
|
[
"This",
"function",
"is",
"called",
"after",
"embedded",
"associations",
"have",
"been",
"populated",
"so",
"that",
"any",
"associations",
"that",
"have",
"been",
"soft",
"deleted",
"are",
"removed",
"."
] |
36110fd3cb2775b3b2068b18d775f1c87fbcef76
|
https://github.com/JKHeadley/rest-hapi/blob/36110fd3cb2775b3b2068b18d775f1c87fbcef76/utilities/handler-helper.js#L1640-L1671
|
9,228
|
JKHeadley/rest-hapi
|
utilities/validation-helper.js
|
function(model, logger) {
assert(
model.schema,
"model not mongoose format. 'schema' property required."
)
assert(
model.schema.paths,
"model not mongoose format. 'schema.paths' property required."
)
assert(
model.schema.tree,
"model not mongoose format. 'schema.tree' property required."
)
let fields = model.schema.paths
let fieldNames = Object.keys(fields)
assert(
model.routeOptions,
"model not mongoose format. 'routeOptions' property required."
)
for (let i = 0; i < fieldNames.length; i++) {
let fieldName = fieldNames[i]
assert(
fields[fieldName].options,
"field not mongoose format. 'options' parameter required."
)
}
return true
}
|
javascript
|
function(model, logger) {
assert(
model.schema,
"model not mongoose format. 'schema' property required."
)
assert(
model.schema.paths,
"model not mongoose format. 'schema.paths' property required."
)
assert(
model.schema.tree,
"model not mongoose format. 'schema.tree' property required."
)
let fields = model.schema.paths
let fieldNames = Object.keys(fields)
assert(
model.routeOptions,
"model not mongoose format. 'routeOptions' property required."
)
for (let i = 0; i < fieldNames.length; i++) {
let fieldName = fieldNames[i]
assert(
fields[fieldName].options,
"field not mongoose format. 'options' parameter required."
)
}
return true
}
|
[
"function",
"(",
"model",
",",
"logger",
")",
"{",
"assert",
"(",
"model",
".",
"schema",
",",
"\"model not mongoose format. 'schema' property required.\"",
")",
"assert",
"(",
"model",
".",
"schema",
".",
"paths",
",",
"\"model not mongoose format. 'schema.paths' property required.\"",
")",
"assert",
"(",
"model",
".",
"schema",
".",
"tree",
",",
"\"model not mongoose format. 'schema.tree' property required.\"",
")",
"let",
"fields",
"=",
"model",
".",
"schema",
".",
"paths",
"let",
"fieldNames",
"=",
"Object",
".",
"keys",
"(",
"fields",
")",
"assert",
"(",
"model",
".",
"routeOptions",
",",
"\"model not mongoose format. 'routeOptions' property required.\"",
")",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"fieldNames",
".",
"length",
";",
"i",
"++",
")",
"{",
"let",
"fieldName",
"=",
"fieldNames",
"[",
"i",
"]",
"assert",
"(",
"fields",
"[",
"fieldName",
"]",
".",
"options",
",",
"\"field not mongoose format. 'options' parameter required.\"",
")",
"}",
"return",
"true",
"}"
] |
Assert that a given model follows the mongoose model format.
@param model
@param logger
@returns {boolean}
|
[
"Assert",
"that",
"a",
"given",
"model",
"follows",
"the",
"mongoose",
"model",
"format",
"."
] |
36110fd3cb2775b3b2068b18d775f1c87fbcef76
|
https://github.com/JKHeadley/rest-hapi/blob/36110fd3cb2775b3b2068b18d775f1c87fbcef76/utilities/validation-helper.js#L12-L43
|
|
9,229
|
JKHeadley/rest-hapi
|
seed/user.model.js
|
function(server, model, options, logger) {
const Log = logger.bind('Password Update')
let Boom = require('boom')
let collectionName = model.collectionDisplayName || model.modelName
Log.note('Generating Password Update endpoint for ' + collectionName)
let handler = async function(request, h) {
try {
let hashedPassword = model.generatePasswordHash(
request.payload.password
)
await model.findByIdAndUpdate(request.params._id, {
password: hashedPassword
})
return h.response('Password updated.').code(200)
} catch (err) {
Log.error(err)
throw Boom.badImplementation(err)
}
}
server.route({
method: 'PUT',
path: '/user/{_id}/password',
config: {
handler: handler,
auth: null,
description: "Update a user's password.",
tags: ['api', 'User', 'Password'],
validate: {
params: {
_id: RestHapi.joiHelper.joiObjectId().required()
},
payload: {
password: Joi.string()
.required()
.description("The user's new password")
}
},
plugins: {
'hapi-swagger': {
responseMessages: [
{ code: 200, message: 'Success' },
{ code: 400, message: 'Bad Request' },
{ code: 404, message: 'Not Found' },
{ code: 500, message: 'Internal Server Error' }
]
}
}
}
})
}
|
javascript
|
function(server, model, options, logger) {
const Log = logger.bind('Password Update')
let Boom = require('boom')
let collectionName = model.collectionDisplayName || model.modelName
Log.note('Generating Password Update endpoint for ' + collectionName)
let handler = async function(request, h) {
try {
let hashedPassword = model.generatePasswordHash(
request.payload.password
)
await model.findByIdAndUpdate(request.params._id, {
password: hashedPassword
})
return h.response('Password updated.').code(200)
} catch (err) {
Log.error(err)
throw Boom.badImplementation(err)
}
}
server.route({
method: 'PUT',
path: '/user/{_id}/password',
config: {
handler: handler,
auth: null,
description: "Update a user's password.",
tags: ['api', 'User', 'Password'],
validate: {
params: {
_id: RestHapi.joiHelper.joiObjectId().required()
},
payload: {
password: Joi.string()
.required()
.description("The user's new password")
}
},
plugins: {
'hapi-swagger': {
responseMessages: [
{ code: 200, message: 'Success' },
{ code: 400, message: 'Bad Request' },
{ code: 404, message: 'Not Found' },
{ code: 500, message: 'Internal Server Error' }
]
}
}
}
})
}
|
[
"function",
"(",
"server",
",",
"model",
",",
"options",
",",
"logger",
")",
"{",
"const",
"Log",
"=",
"logger",
".",
"bind",
"(",
"'Password Update'",
")",
"let",
"Boom",
"=",
"require",
"(",
"'boom'",
")",
"let",
"collectionName",
"=",
"model",
".",
"collectionDisplayName",
"||",
"model",
".",
"modelName",
"Log",
".",
"note",
"(",
"'Generating Password Update endpoint for '",
"+",
"collectionName",
")",
"let",
"handler",
"=",
"async",
"function",
"(",
"request",
",",
"h",
")",
"{",
"try",
"{",
"let",
"hashedPassword",
"=",
"model",
".",
"generatePasswordHash",
"(",
"request",
".",
"payload",
".",
"password",
")",
"await",
"model",
".",
"findByIdAndUpdate",
"(",
"request",
".",
"params",
".",
"_id",
",",
"{",
"password",
":",
"hashedPassword",
"}",
")",
"return",
"h",
".",
"response",
"(",
"'Password updated.'",
")",
".",
"code",
"(",
"200",
")",
"}",
"catch",
"(",
"err",
")",
"{",
"Log",
".",
"error",
"(",
"err",
")",
"throw",
"Boom",
".",
"badImplementation",
"(",
"err",
")",
"}",
"}",
"server",
".",
"route",
"(",
"{",
"method",
":",
"'PUT'",
",",
"path",
":",
"'/user/{_id}/password'",
",",
"config",
":",
"{",
"handler",
":",
"handler",
",",
"auth",
":",
"null",
",",
"description",
":",
"\"Update a user's password.\"",
",",
"tags",
":",
"[",
"'api'",
",",
"'User'",
",",
"'Password'",
"]",
",",
"validate",
":",
"{",
"params",
":",
"{",
"_id",
":",
"RestHapi",
".",
"joiHelper",
".",
"joiObjectId",
"(",
")",
".",
"required",
"(",
")",
"}",
",",
"payload",
":",
"{",
"password",
":",
"Joi",
".",
"string",
"(",
")",
".",
"required",
"(",
")",
".",
"description",
"(",
"\"The user's new password\"",
")",
"}",
"}",
",",
"plugins",
":",
"{",
"'hapi-swagger'",
":",
"{",
"responseMessages",
":",
"[",
"{",
"code",
":",
"200",
",",
"message",
":",
"'Success'",
"}",
",",
"{",
"code",
":",
"400",
",",
"message",
":",
"'Bad Request'",
"}",
",",
"{",
"code",
":",
"404",
",",
"message",
":",
"'Not Found'",
"}",
",",
"{",
"code",
":",
"500",
",",
"message",
":",
"'Internal Server Error'",
"}",
"]",
"}",
"}",
"}",
"}",
")",
"}"
] |
Password Update Endpoint
|
[
"Password",
"Update",
"Endpoint"
] |
36110fd3cb2775b3b2068b18d775f1c87fbcef76
|
https://github.com/JKHeadley/rest-hapi/blob/36110fd3cb2775b3b2068b18d775f1c87fbcef76/seed/user.model.js#L57-L112
|
|
9,230
|
JKHeadley/rest-hapi
|
rest-hapi.js
|
getLogger
|
function getLogger(label) {
let config = defaultConfig
extend(true, config, module.exports.config)
let rootLogger = logging.getLogger(chalk.gray(label))
rootLogger.logLevel = config.loglevel
return rootLogger
}
|
javascript
|
function getLogger(label) {
let config = defaultConfig
extend(true, config, module.exports.config)
let rootLogger = logging.getLogger(chalk.gray(label))
rootLogger.logLevel = config.loglevel
return rootLogger
}
|
[
"function",
"getLogger",
"(",
"label",
")",
"{",
"let",
"config",
"=",
"defaultConfig",
"extend",
"(",
"true",
",",
"config",
",",
"module",
".",
"exports",
".",
"config",
")",
"let",
"rootLogger",
"=",
"logging",
".",
"getLogger",
"(",
"chalk",
".",
"gray",
"(",
"label",
")",
")",
"rootLogger",
".",
"logLevel",
"=",
"config",
".",
"loglevel",
"return",
"rootLogger",
"}"
] |
Get a new Log object with a root label.
@param label: The root label for the Log.
@returns {*}
|
[
"Get",
"a",
"new",
"Log",
"object",
"with",
"a",
"root",
"label",
"."
] |
36110fd3cb2775b3b2068b18d775f1c87fbcef76
|
https://github.com/JKHeadley/rest-hapi/blob/36110fd3cb2775b3b2068b18d775f1c87fbcef76/rest-hapi.js#L132-L142
|
9,231
|
JKHeadley/rest-hapi
|
rest-hapi.js
|
mongooseInit
|
function mongooseInit(mongoose, logger, config) {
const Log = logger.bind('mongoose-init')
mongoose.Promise = Promise
logUtil.logActionStart(
Log,
'Connecting to Database',
_.omit(config.mongo, ['pass'])
)
mongoose.connect(config.mongo.URI)
globals.mongoose = mongoose
Log.log('mongoose connected')
return mongoose
}
|
javascript
|
function mongooseInit(mongoose, logger, config) {
const Log = logger.bind('mongoose-init')
mongoose.Promise = Promise
logUtil.logActionStart(
Log,
'Connecting to Database',
_.omit(config.mongo, ['pass'])
)
mongoose.connect(config.mongo.URI)
globals.mongoose = mongoose
Log.log('mongoose connected')
return mongoose
}
|
[
"function",
"mongooseInit",
"(",
"mongoose",
",",
"logger",
",",
"config",
")",
"{",
"const",
"Log",
"=",
"logger",
".",
"bind",
"(",
"'mongoose-init'",
")",
"mongoose",
".",
"Promise",
"=",
"Promise",
"logUtil",
".",
"logActionStart",
"(",
"Log",
",",
"'Connecting to Database'",
",",
"_",
".",
"omit",
"(",
"config",
".",
"mongo",
",",
"[",
"'pass'",
"]",
")",
")",
"mongoose",
".",
"connect",
"(",
"config",
".",
"mongo",
".",
"URI",
")",
"globals",
".",
"mongoose",
"=",
"mongoose",
"Log",
".",
"log",
"(",
"'mongoose connected'",
")",
"return",
"mongoose",
"}"
] |
Connect mongoose and add to globals.
@param mongoose
@param logger
@param config
@returns {*}
|
[
"Connect",
"mongoose",
"and",
"add",
"to",
"globals",
"."
] |
36110fd3cb2775b3b2068b18d775f1c87fbcef76
|
https://github.com/JKHeadley/rest-hapi/blob/36110fd3cb2775b3b2068b18d775f1c87fbcef76/rest-hapi.js#L151-L169
|
9,232
|
JKHeadley/rest-hapi
|
rest-hapi.js
|
registerMrHorse
|
async function registerMrHorse(server, logger, config) {
const Log = logger.bind('register-MrHorse')
let policyPath = ''
if (config.enablePolicies) {
if (config.absolutePolicyPath === true) {
policyPath = config.policyPath
} else {
policyPath = __dirname.replace(
'node_modules/rest-hapi',
config.policyPath
)
}
} else {
policyPath = path.join(__dirname, '/policies')
}
await server.register([
{
plugin: Mrhorse,
options: {
policyDirectory: policyPath
}
}
])
if (config.enablePolicies) {
await server.plugins.mrhorse.loadPolicies(server, {
policyDirectory: path.join(__dirname, '/policies')
})
}
Log.info('MrHorse plugin registered')
}
|
javascript
|
async function registerMrHorse(server, logger, config) {
const Log = logger.bind('register-MrHorse')
let policyPath = ''
if (config.enablePolicies) {
if (config.absolutePolicyPath === true) {
policyPath = config.policyPath
} else {
policyPath = __dirname.replace(
'node_modules/rest-hapi',
config.policyPath
)
}
} else {
policyPath = path.join(__dirname, '/policies')
}
await server.register([
{
plugin: Mrhorse,
options: {
policyDirectory: policyPath
}
}
])
if (config.enablePolicies) {
await server.plugins.mrhorse.loadPolicies(server, {
policyDirectory: path.join(__dirname, '/policies')
})
}
Log.info('MrHorse plugin registered')
}
|
[
"async",
"function",
"registerMrHorse",
"(",
"server",
",",
"logger",
",",
"config",
")",
"{",
"const",
"Log",
"=",
"logger",
".",
"bind",
"(",
"'register-MrHorse'",
")",
"let",
"policyPath",
"=",
"''",
"if",
"(",
"config",
".",
"enablePolicies",
")",
"{",
"if",
"(",
"config",
".",
"absolutePolicyPath",
"===",
"true",
")",
"{",
"policyPath",
"=",
"config",
".",
"policyPath",
"}",
"else",
"{",
"policyPath",
"=",
"__dirname",
".",
"replace",
"(",
"'node_modules/rest-hapi'",
",",
"config",
".",
"policyPath",
")",
"}",
"}",
"else",
"{",
"policyPath",
"=",
"path",
".",
"join",
"(",
"__dirname",
",",
"'/policies'",
")",
"}",
"await",
"server",
".",
"register",
"(",
"[",
"{",
"plugin",
":",
"Mrhorse",
",",
"options",
":",
"{",
"policyDirectory",
":",
"policyPath",
"}",
"}",
"]",
")",
"if",
"(",
"config",
".",
"enablePolicies",
")",
"{",
"await",
"server",
".",
"plugins",
".",
"mrhorse",
".",
"loadPolicies",
"(",
"server",
",",
"{",
"policyDirectory",
":",
"path",
".",
"join",
"(",
"__dirname",
",",
"'/policies'",
")",
"}",
")",
"}",
"Log",
".",
"info",
"(",
"'MrHorse plugin registered'",
")",
"}"
] |
Register and configure the mrhorse plugin.
@param server
@param logger
@param config
@returns {Promise<void>}
|
[
"Register",
"and",
"configure",
"the",
"mrhorse",
"plugin",
"."
] |
36110fd3cb2775b3b2068b18d775f1c87fbcef76
|
https://github.com/JKHeadley/rest-hapi/blob/36110fd3cb2775b3b2068b18d775f1c87fbcef76/rest-hapi.js#L178-L211
|
9,233
|
JKHeadley/rest-hapi
|
rest-hapi.js
|
registerHapiSwagger
|
async function registerHapiSwagger(server, logger, config) {
const Log = logger.bind('register-hapi-swagger')
let swaggerOptions = {
documentationPath: '/',
host: config.swaggerHost,
expanded: config.docExpansion,
swaggerUI: config.enableSwaggerUI,
documentationPage: config.enableSwaggerUI,
schemes: config.enableSwaggerHttps ? ['https'] : ['http']
}
// if swagger config is defined, use that
if (config.swaggerOptions) {
swaggerOptions = { ...swaggerOptions, ...config.swaggerOptions }
}
// override some options for safety
if (!swaggerOptions.info) {
swaggerOptions.info = {}
}
swaggerOptions.info.title = config.appTitle
swaggerOptions.info.version = config.version
swaggerOptions.reuseDefinitions = false
await server.register([
Inert,
Vision,
{ plugin: HapiSwagger, options: swaggerOptions }
])
Log.info('hapi-swagger plugin registered')
}
|
javascript
|
async function registerHapiSwagger(server, logger, config) {
const Log = logger.bind('register-hapi-swagger')
let swaggerOptions = {
documentationPath: '/',
host: config.swaggerHost,
expanded: config.docExpansion,
swaggerUI: config.enableSwaggerUI,
documentationPage: config.enableSwaggerUI,
schemes: config.enableSwaggerHttps ? ['https'] : ['http']
}
// if swagger config is defined, use that
if (config.swaggerOptions) {
swaggerOptions = { ...swaggerOptions, ...config.swaggerOptions }
}
// override some options for safety
if (!swaggerOptions.info) {
swaggerOptions.info = {}
}
swaggerOptions.info.title = config.appTitle
swaggerOptions.info.version = config.version
swaggerOptions.reuseDefinitions = false
await server.register([
Inert,
Vision,
{ plugin: HapiSwagger, options: swaggerOptions }
])
Log.info('hapi-swagger plugin registered')
}
|
[
"async",
"function",
"registerHapiSwagger",
"(",
"server",
",",
"logger",
",",
"config",
")",
"{",
"const",
"Log",
"=",
"logger",
".",
"bind",
"(",
"'register-hapi-swagger'",
")",
"let",
"swaggerOptions",
"=",
"{",
"documentationPath",
":",
"'/'",
",",
"host",
":",
"config",
".",
"swaggerHost",
",",
"expanded",
":",
"config",
".",
"docExpansion",
",",
"swaggerUI",
":",
"config",
".",
"enableSwaggerUI",
",",
"documentationPage",
":",
"config",
".",
"enableSwaggerUI",
",",
"schemes",
":",
"config",
".",
"enableSwaggerHttps",
"?",
"[",
"'https'",
"]",
":",
"[",
"'http'",
"]",
"}",
"// if swagger config is defined, use that",
"if",
"(",
"config",
".",
"swaggerOptions",
")",
"{",
"swaggerOptions",
"=",
"{",
"...",
"swaggerOptions",
",",
"...",
"config",
".",
"swaggerOptions",
"}",
"}",
"// override some options for safety",
"if",
"(",
"!",
"swaggerOptions",
".",
"info",
")",
"{",
"swaggerOptions",
".",
"info",
"=",
"{",
"}",
"}",
"swaggerOptions",
".",
"info",
".",
"title",
"=",
"config",
".",
"appTitle",
"swaggerOptions",
".",
"info",
".",
"version",
"=",
"config",
".",
"version",
"swaggerOptions",
".",
"reuseDefinitions",
"=",
"false",
"await",
"server",
".",
"register",
"(",
"[",
"Inert",
",",
"Vision",
",",
"{",
"plugin",
":",
"HapiSwagger",
",",
"options",
":",
"swaggerOptions",
"}",
"]",
")",
"Log",
".",
"info",
"(",
"'hapi-swagger plugin registered'",
")",
"}"
] |
Register and configure the hapi-swagger plugin.
@param server
@param logger
@param config
@returns {Promise<void>}
|
[
"Register",
"and",
"configure",
"the",
"hapi",
"-",
"swagger",
"plugin",
"."
] |
36110fd3cb2775b3b2068b18d775f1c87fbcef76
|
https://github.com/JKHeadley/rest-hapi/blob/36110fd3cb2775b3b2068b18d775f1c87fbcef76/rest-hapi.js#L220-L253
|
9,234
|
JKHeadley/rest-hapi
|
utilities/query-helper.js
|
function(model, query, mongooseQuery, logger) {
// This line has to come first
validationHelper.validateModel(model, logger)
const Log = logger.bind()
// (email == 'test@user.com' && (firstName == 'test2@user.com' || firstName == 'test4@user.com')) && (age < 15 || age > 30)
// LITERAL
// {
// and: {
// email: {
// equal: 'test@user.com',
// },
// or: {
// firstName: {
// equal: ['test2@user.com', 'test4@user.com']
// }
// },
// age: {
// gt: '15',
// lt: '30'
// }
// }
// {
// and[email][equal]=test@user.com&and[or][firstName][equal]=test2@user.com&and[or][firstName][equal]=test4@user.com&and[age][gt]=15
// ABBREVIATED
// {
// email:'test@user.com',
// firstName: ['test2@user.com', 'test4@user.com'],
// age: {
// $or: {
// $gt: '15',
// $lt: '30'
// }
// }
// }
// [email]=test@user.com&[firstName]=test2@user.com&[firstName]=test4@user.com&[age][gt]=15&[age][lt]=30
delete query[''] // EXPL: hack due to bug in hapi-swagger-docs
delete query.$count
mongooseQuery = this.setExclude(query, mongooseQuery, Log)
let attributesFilter = this.createAttributesFilter(query, model, Log)
if (attributesFilter === '') {
attributesFilter = '_id'
}
let result = this.populateEmbeddedDocs(
query,
mongooseQuery,
attributesFilter,
model.routeOptions.associations,
model,
Log
)
mongooseQuery = result.mongooseQuery
attributesFilter = result.attributesFilter
mongooseQuery = this.setSort(query, mongooseQuery, Log)
mongooseQuery.select(attributesFilter)
if (typeof query.$where === 'string') {
query.$where = JSON.parse(query.$where)
}
if (query.$where) {
mongooseQuery.where(query.$where)
delete query.$where
}
// EXPL: Support single (string) inputs or multiple "or'd" inputs (arrays) for field queries
for (let fieldQueryKey in query) {
let fieldQuery = query[fieldQueryKey]
if (!Array.isArray(fieldQuery)) {
fieldQuery = tryParseJSON(query[fieldQueryKey])
}
if (
fieldQuery &&
Array.isArray(fieldQuery) &&
fieldQueryKey !== '$searchFields'
) {
query[fieldQueryKey] = { $in: fieldQuery } // EXPL: "or" the inputs
}
}
// EXPL: handle full text search
if (query.$text) {
query.$text = { $search: query.$text }
}
// EXPL: handle regex search
this.setTermSearch(query, model, Log)
let whereQuery = _.extend({}, query)
// EXPL: delete pagination parameters
delete whereQuery.$limit
delete whereQuery.$skip
delete whereQuery.$page
mongooseQuery.where(whereQuery)
return mongooseQuery
}
|
javascript
|
function(model, query, mongooseQuery, logger) {
// This line has to come first
validationHelper.validateModel(model, logger)
const Log = logger.bind()
// (email == 'test@user.com' && (firstName == 'test2@user.com' || firstName == 'test4@user.com')) && (age < 15 || age > 30)
// LITERAL
// {
// and: {
// email: {
// equal: 'test@user.com',
// },
// or: {
// firstName: {
// equal: ['test2@user.com', 'test4@user.com']
// }
// },
// age: {
// gt: '15',
// lt: '30'
// }
// }
// {
// and[email][equal]=test@user.com&and[or][firstName][equal]=test2@user.com&and[or][firstName][equal]=test4@user.com&and[age][gt]=15
// ABBREVIATED
// {
// email:'test@user.com',
// firstName: ['test2@user.com', 'test4@user.com'],
// age: {
// $or: {
// $gt: '15',
// $lt: '30'
// }
// }
// }
// [email]=test@user.com&[firstName]=test2@user.com&[firstName]=test4@user.com&[age][gt]=15&[age][lt]=30
delete query[''] // EXPL: hack due to bug in hapi-swagger-docs
delete query.$count
mongooseQuery = this.setExclude(query, mongooseQuery, Log)
let attributesFilter = this.createAttributesFilter(query, model, Log)
if (attributesFilter === '') {
attributesFilter = '_id'
}
let result = this.populateEmbeddedDocs(
query,
mongooseQuery,
attributesFilter,
model.routeOptions.associations,
model,
Log
)
mongooseQuery = result.mongooseQuery
attributesFilter = result.attributesFilter
mongooseQuery = this.setSort(query, mongooseQuery, Log)
mongooseQuery.select(attributesFilter)
if (typeof query.$where === 'string') {
query.$where = JSON.parse(query.$where)
}
if (query.$where) {
mongooseQuery.where(query.$where)
delete query.$where
}
// EXPL: Support single (string) inputs or multiple "or'd" inputs (arrays) for field queries
for (let fieldQueryKey in query) {
let fieldQuery = query[fieldQueryKey]
if (!Array.isArray(fieldQuery)) {
fieldQuery = tryParseJSON(query[fieldQueryKey])
}
if (
fieldQuery &&
Array.isArray(fieldQuery) &&
fieldQueryKey !== '$searchFields'
) {
query[fieldQueryKey] = { $in: fieldQuery } // EXPL: "or" the inputs
}
}
// EXPL: handle full text search
if (query.$text) {
query.$text = { $search: query.$text }
}
// EXPL: handle regex search
this.setTermSearch(query, model, Log)
let whereQuery = _.extend({}, query)
// EXPL: delete pagination parameters
delete whereQuery.$limit
delete whereQuery.$skip
delete whereQuery.$page
mongooseQuery.where(whereQuery)
return mongooseQuery
}
|
[
"function",
"(",
"model",
",",
"query",
",",
"mongooseQuery",
",",
"logger",
")",
"{",
"// This line has to come first",
"validationHelper",
".",
"validateModel",
"(",
"model",
",",
"logger",
")",
"const",
"Log",
"=",
"logger",
".",
"bind",
"(",
")",
"// (email == 'test@user.com' && (firstName == 'test2@user.com' || firstName == 'test4@user.com')) && (age < 15 || age > 30)",
"// LITERAL",
"// {",
"// and: {",
"// email: {",
"// equal: 'test@user.com',",
"// },",
"// or: {",
"// firstName: {",
"// equal: ['test2@user.com', 'test4@user.com']",
"// }",
"// },",
"// age: {",
"// gt: '15',",
"// lt: '30'",
"// }",
"// }",
"// {",
"// and[email][equal]=test@user.com&and[or][firstName][equal]=test2@user.com&and[or][firstName][equal]=test4@user.com&and[age][gt]=15",
"// ABBREVIATED",
"// {",
"// email:'test@user.com',",
"// firstName: ['test2@user.com', 'test4@user.com'],",
"// age: {",
"// $or: {",
"// $gt: '15',",
"// $lt: '30'",
"// }",
"// }",
"// }",
"// [email]=test@user.com&[firstName]=test2@user.com&[firstName]=test4@user.com&[age][gt]=15&[age][lt]=30",
"delete",
"query",
"[",
"''",
"]",
"// EXPL: hack due to bug in hapi-swagger-docs",
"delete",
"query",
".",
"$count",
"mongooseQuery",
"=",
"this",
".",
"setExclude",
"(",
"query",
",",
"mongooseQuery",
",",
"Log",
")",
"let",
"attributesFilter",
"=",
"this",
".",
"createAttributesFilter",
"(",
"query",
",",
"model",
",",
"Log",
")",
"if",
"(",
"attributesFilter",
"===",
"''",
")",
"{",
"attributesFilter",
"=",
"'_id'",
"}",
"let",
"result",
"=",
"this",
".",
"populateEmbeddedDocs",
"(",
"query",
",",
"mongooseQuery",
",",
"attributesFilter",
",",
"model",
".",
"routeOptions",
".",
"associations",
",",
"model",
",",
"Log",
")",
"mongooseQuery",
"=",
"result",
".",
"mongooseQuery",
"attributesFilter",
"=",
"result",
".",
"attributesFilter",
"mongooseQuery",
"=",
"this",
".",
"setSort",
"(",
"query",
",",
"mongooseQuery",
",",
"Log",
")",
"mongooseQuery",
".",
"select",
"(",
"attributesFilter",
")",
"if",
"(",
"typeof",
"query",
".",
"$where",
"===",
"'string'",
")",
"{",
"query",
".",
"$where",
"=",
"JSON",
".",
"parse",
"(",
"query",
".",
"$where",
")",
"}",
"if",
"(",
"query",
".",
"$where",
")",
"{",
"mongooseQuery",
".",
"where",
"(",
"query",
".",
"$where",
")",
"delete",
"query",
".",
"$where",
"}",
"// EXPL: Support single (string) inputs or multiple \"or'd\" inputs (arrays) for field queries",
"for",
"(",
"let",
"fieldQueryKey",
"in",
"query",
")",
"{",
"let",
"fieldQuery",
"=",
"query",
"[",
"fieldQueryKey",
"]",
"if",
"(",
"!",
"Array",
".",
"isArray",
"(",
"fieldQuery",
")",
")",
"{",
"fieldQuery",
"=",
"tryParseJSON",
"(",
"query",
"[",
"fieldQueryKey",
"]",
")",
"}",
"if",
"(",
"fieldQuery",
"&&",
"Array",
".",
"isArray",
"(",
"fieldQuery",
")",
"&&",
"fieldQueryKey",
"!==",
"'$searchFields'",
")",
"{",
"query",
"[",
"fieldQueryKey",
"]",
"=",
"{",
"$in",
":",
"fieldQuery",
"}",
"// EXPL: \"or\" the inputs",
"}",
"}",
"// EXPL: handle full text search",
"if",
"(",
"query",
".",
"$text",
")",
"{",
"query",
".",
"$text",
"=",
"{",
"$search",
":",
"query",
".",
"$text",
"}",
"}",
"// EXPL: handle regex search",
"this",
".",
"setTermSearch",
"(",
"query",
",",
"model",
",",
"Log",
")",
"let",
"whereQuery",
"=",
"_",
".",
"extend",
"(",
"{",
"}",
",",
"query",
")",
"// EXPL: delete pagination parameters",
"delete",
"whereQuery",
".",
"$limit",
"delete",
"whereQuery",
".",
"$skip",
"delete",
"whereQuery",
".",
"$page",
"mongooseQuery",
".",
"where",
"(",
"whereQuery",
")",
"return",
"mongooseQuery",
"}"
] |
Create a mongoose query based off of the request query
@param model: A mongoose model object.
@param query: The incoming request query.
@param mongooseQuery: A mongoose query.
@param logger: A logging object.
@returns {*}: A modified mongoose query.
|
[
"Create",
"a",
"mongoose",
"query",
"based",
"off",
"of",
"the",
"request",
"query"
] |
36110fd3cb2775b3b2068b18d775f1c87fbcef76
|
https://github.com/JKHeadley/rest-hapi/blob/36110fd3cb2775b3b2068b18d775f1c87fbcef76/utilities/query-helper.js#L41-L144
|
|
9,235
|
JKHeadley/rest-hapi
|
utilities/query-helper.js
|
function(model, logger) {
// This line has to come first
validationHelper.validateModel(model, logger)
let readableFields = []
let fields = model.schema.paths
for (let fieldName in fields) {
let field = fields[fieldName].options
if (!field.exclude && fieldName !== '__v') {
readableFields.push(fieldName)
}
}
return readableFields
}
|
javascript
|
function(model, logger) {
// This line has to come first
validationHelper.validateModel(model, logger)
let readableFields = []
let fields = model.schema.paths
for (let fieldName in fields) {
let field = fields[fieldName].options
if (!field.exclude && fieldName !== '__v') {
readableFields.push(fieldName)
}
}
return readableFields
}
|
[
"function",
"(",
"model",
",",
"logger",
")",
"{",
"// This line has to come first",
"validationHelper",
".",
"validateModel",
"(",
"model",
",",
"logger",
")",
"let",
"readableFields",
"=",
"[",
"]",
"let",
"fields",
"=",
"model",
".",
"schema",
".",
"paths",
"for",
"(",
"let",
"fieldName",
"in",
"fields",
")",
"{",
"let",
"field",
"=",
"fields",
"[",
"fieldName",
"]",
".",
"options",
"if",
"(",
"!",
"field",
".",
"exclude",
"&&",
"fieldName",
"!==",
"'__v'",
")",
"{",
"readableFields",
".",
"push",
"(",
"fieldName",
")",
"}",
"}",
"return",
"readableFields",
"}"
] |
Get a list of fields that can be returned as part of a query result.
@param model: A mongoose model object.
@param logger: A logging object.
@returns {Array}: A list of fields.
|
[
"Get",
"a",
"list",
"of",
"fields",
"that",
"can",
"be",
"returned",
"as",
"part",
"of",
"a",
"query",
"result",
"."
] |
36110fd3cb2775b3b2068b18d775f1c87fbcef76
|
https://github.com/JKHeadley/rest-hapi/blob/36110fd3cb2775b3b2068b18d775f1c87fbcef76/utilities/query-helper.js#L152-L168
|
|
9,236
|
JKHeadley/rest-hapi
|
utilities/query-helper.js
|
function(model, logger) {
// This line has to come first
validationHelper.validateModel(model, logger)
const Log = logger.bind()
let sortableFields = this.getReadableFields(model, Log)
for (let i = sortableFields.length - 1; i >= 0; i--) {
let descendingField = '-' + sortableFields[i]
sortableFields.splice(i, 0, descendingField)
}
return sortableFields
}
|
javascript
|
function(model, logger) {
// This line has to come first
validationHelper.validateModel(model, logger)
const Log = logger.bind()
let sortableFields = this.getReadableFields(model, Log)
for (let i = sortableFields.length - 1; i >= 0; i--) {
let descendingField = '-' + sortableFields[i]
sortableFields.splice(i, 0, descendingField)
}
return sortableFields
}
|
[
"function",
"(",
"model",
",",
"logger",
")",
"{",
"// This line has to come first",
"validationHelper",
".",
"validateModel",
"(",
"model",
",",
"logger",
")",
"const",
"Log",
"=",
"logger",
".",
"bind",
"(",
")",
"let",
"sortableFields",
"=",
"this",
".",
"getReadableFields",
"(",
"model",
",",
"Log",
")",
"for",
"(",
"let",
"i",
"=",
"sortableFields",
".",
"length",
"-",
"1",
";",
"i",
">=",
"0",
";",
"i",
"--",
")",
"{",
"let",
"descendingField",
"=",
"'-'",
"+",
"sortableFields",
"[",
"i",
"]",
"sortableFields",
".",
"splice",
"(",
"i",
",",
"0",
",",
"descendingField",
")",
"}",
"return",
"sortableFields",
"}"
] |
Get a list of valid query sort inputs.
@param model: A mongoose model object.
@param logger: A logging object.
@returns {Array}: A list of fields.
|
[
"Get",
"a",
"list",
"of",
"valid",
"query",
"sort",
"inputs",
"."
] |
36110fd3cb2775b3b2068b18d775f1c87fbcef76
|
https://github.com/JKHeadley/rest-hapi/blob/36110fd3cb2775b3b2068b18d775f1c87fbcef76/utilities/query-helper.js#L176-L189
|
|
9,237
|
JKHeadley/rest-hapi
|
utilities/query-helper.js
|
function(model, logger) {
// This line has to come first
validationHelper.validateModel(model, logger)
let queryableFields = []
let fields = model.schema.paths
let fieldNames = Object.keys(fields)
let associations = model.routeOptions
? model.routeOptions.associations
: null
for (let i = 0; i < fieldNames.length; i++) {
let fieldName = fieldNames[i]
if (fields[fieldName] && fieldName !== '__v' && fieldName !== '__t') {
let field = fields[fieldName].options
let association = associations
? associations[fields[fieldName].path] || {}
: {}
// EXPL: by default we don't include MANY_MANY array references
if (
field.queryable !== false &&
!field.exclude &&
association.type !== 'MANY_MANY'
) {
queryableFields.push(fieldName)
}
}
}
return queryableFields
}
|
javascript
|
function(model, logger) {
// This line has to come first
validationHelper.validateModel(model, logger)
let queryableFields = []
let fields = model.schema.paths
let fieldNames = Object.keys(fields)
let associations = model.routeOptions
? model.routeOptions.associations
: null
for (let i = 0; i < fieldNames.length; i++) {
let fieldName = fieldNames[i]
if (fields[fieldName] && fieldName !== '__v' && fieldName !== '__t') {
let field = fields[fieldName].options
let association = associations
? associations[fields[fieldName].path] || {}
: {}
// EXPL: by default we don't include MANY_MANY array references
if (
field.queryable !== false &&
!field.exclude &&
association.type !== 'MANY_MANY'
) {
queryableFields.push(fieldName)
}
}
}
return queryableFields
}
|
[
"function",
"(",
"model",
",",
"logger",
")",
"{",
"// This line has to come first",
"validationHelper",
".",
"validateModel",
"(",
"model",
",",
"logger",
")",
"let",
"queryableFields",
"=",
"[",
"]",
"let",
"fields",
"=",
"model",
".",
"schema",
".",
"paths",
"let",
"fieldNames",
"=",
"Object",
".",
"keys",
"(",
"fields",
")",
"let",
"associations",
"=",
"model",
".",
"routeOptions",
"?",
"model",
".",
"routeOptions",
".",
"associations",
":",
"null",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"fieldNames",
".",
"length",
";",
"i",
"++",
")",
"{",
"let",
"fieldName",
"=",
"fieldNames",
"[",
"i",
"]",
"if",
"(",
"fields",
"[",
"fieldName",
"]",
"&&",
"fieldName",
"!==",
"'__v'",
"&&",
"fieldName",
"!==",
"'__t'",
")",
"{",
"let",
"field",
"=",
"fields",
"[",
"fieldName",
"]",
".",
"options",
"let",
"association",
"=",
"associations",
"?",
"associations",
"[",
"fields",
"[",
"fieldName",
"]",
".",
"path",
"]",
"||",
"{",
"}",
":",
"{",
"}",
"// EXPL: by default we don't include MANY_MANY array references",
"if",
"(",
"field",
".",
"queryable",
"!==",
"false",
"&&",
"!",
"field",
".",
"exclude",
"&&",
"association",
".",
"type",
"!==",
"'MANY_MANY'",
")",
"{",
"queryableFields",
".",
"push",
"(",
"fieldName",
")",
"}",
"}",
"}",
"return",
"queryableFields",
"}"
] |
Get a list of fields that can be queried against.
@param model: A mongoose model object.
@param logger: A logging object.
@returns {Array}: A list of fields.
|
[
"Get",
"a",
"list",
"of",
"fields",
"that",
"can",
"be",
"queried",
"against",
"."
] |
36110fd3cb2775b3b2068b18d775f1c87fbcef76
|
https://github.com/JKHeadley/rest-hapi/blob/36110fd3cb2775b3b2068b18d775f1c87fbcef76/utilities/query-helper.js#L197-L230
|
|
9,238
|
JKHeadley/rest-hapi
|
utilities/query-helper.js
|
function(query, mongooseQuery, logger) {
const Log = logger.bind()
if (query.$page) {
mongooseQuery = this.setPage(query, mongooseQuery, Log)
} else {
mongooseQuery = this.setSkip(query, mongooseQuery, Log)
}
mongooseQuery = this.setLimit(query, mongooseQuery, Log)
return mongooseQuery
}
|
javascript
|
function(query, mongooseQuery, logger) {
const Log = logger.bind()
if (query.$page) {
mongooseQuery = this.setPage(query, mongooseQuery, Log)
} else {
mongooseQuery = this.setSkip(query, mongooseQuery, Log)
}
mongooseQuery = this.setLimit(query, mongooseQuery, Log)
return mongooseQuery
}
|
[
"function",
"(",
"query",
",",
"mongooseQuery",
",",
"logger",
")",
"{",
"const",
"Log",
"=",
"logger",
".",
"bind",
"(",
")",
"if",
"(",
"query",
".",
"$page",
")",
"{",
"mongooseQuery",
"=",
"this",
".",
"setPage",
"(",
"query",
",",
"mongooseQuery",
",",
"Log",
")",
"}",
"else",
"{",
"mongooseQuery",
"=",
"this",
".",
"setSkip",
"(",
"query",
",",
"mongooseQuery",
",",
"Log",
")",
"}",
"mongooseQuery",
"=",
"this",
".",
"setLimit",
"(",
"query",
",",
"mongooseQuery",
",",
"Log",
")",
"return",
"mongooseQuery",
"}"
] |
Handle pagination for the query if needed.
@param query: The incoming request query.
@param mongooseQuery: A mongoose query.
@param logger: A logging object.
@returns {*}: The updated mongoose query.
|
[
"Handle",
"pagination",
"for",
"the",
"query",
"if",
"needed",
"."
] |
36110fd3cb2775b3b2068b18d775f1c87fbcef76
|
https://github.com/JKHeadley/rest-hapi/blob/36110fd3cb2775b3b2068b18d775f1c87fbcef76/utilities/query-helper.js#L257-L268
|
|
9,239
|
JKHeadley/rest-hapi
|
utilities/query-helper.js
|
function(query, mongooseQuery, logger) {
if (query.$exclude) {
if (!Array.isArray(query.$exclude)) {
query.$exclude = query.$exclude.split(',')
}
mongooseQuery.where({ _id: { $nin: query.$exclude } })
delete query.$exclude
}
return mongooseQuery
}
|
javascript
|
function(query, mongooseQuery, logger) {
if (query.$exclude) {
if (!Array.isArray(query.$exclude)) {
query.$exclude = query.$exclude.split(',')
}
mongooseQuery.where({ _id: { $nin: query.$exclude } })
delete query.$exclude
}
return mongooseQuery
}
|
[
"function",
"(",
"query",
",",
"mongooseQuery",
",",
"logger",
")",
"{",
"if",
"(",
"query",
".",
"$exclude",
")",
"{",
"if",
"(",
"!",
"Array",
".",
"isArray",
"(",
"query",
".",
"$exclude",
")",
")",
"{",
"query",
".",
"$exclude",
"=",
"query",
".",
"$exclude",
".",
"split",
"(",
"','",
")",
"}",
"mongooseQuery",
".",
"where",
"(",
"{",
"_id",
":",
"{",
"$nin",
":",
"query",
".",
"$exclude",
"}",
"}",
")",
"delete",
"query",
".",
"$exclude",
"}",
"return",
"mongooseQuery",
"}"
] |
Set the list of objectIds to exclude.
@param query: The incoming request query.
@param mongooseQuery: A mongoose query.
@param logger: A logging object.
@returns {*}: The updated mongoose query.
|
[
"Set",
"the",
"list",
"of",
"objectIds",
"to",
"exclude",
"."
] |
36110fd3cb2775b3b2068b18d775f1c87fbcef76
|
https://github.com/JKHeadley/rest-hapi/blob/36110fd3cb2775b3b2068b18d775f1c87fbcef76/utilities/query-helper.js#L320-L330
|
|
9,240
|
JKHeadley/rest-hapi
|
utilities/query-helper.js
|
function(query, model, logger) {
const Log = logger.bind()
if (query.$term) {
query.$or = [] // TODO: allow option to choose ANDing or ORing of searchFields/queryableFields
let queryableFields = this.getQueryableFields(model, Log)
let stringFields = this.getStringFields(model, Log)
// EXPL: we can only search fields that are a string type
queryableFields = queryableFields.filter(function(field) {
return stringFields.indexOf(field) > -1
})
// EXPL: search only specified fields if included
if (query.$searchFields) {
if (!Array.isArray(query.$searchFields)) {
query.$searchFields = query.$searchFields.split(',')
}
// EXPL: we can only search fields that are a string type
query.$searchFields = query.$searchFields.filter(function(field) {
return stringFields.indexOf(field) > -1
})
query.$searchFields.forEach(function(field) {
let obj = {}
obj[field] = new RegExp(query.$term, 'i')
query.$or.push(obj)
})
} else {
queryableFields.forEach(function(field) {
let obj = {}
obj[field] = new RegExp(query.$term, 'i')
query.$or.push(obj)
})
}
}
delete query.$searchFields
delete query.$term
}
|
javascript
|
function(query, model, logger) {
const Log = logger.bind()
if (query.$term) {
query.$or = [] // TODO: allow option to choose ANDing or ORing of searchFields/queryableFields
let queryableFields = this.getQueryableFields(model, Log)
let stringFields = this.getStringFields(model, Log)
// EXPL: we can only search fields that are a string type
queryableFields = queryableFields.filter(function(field) {
return stringFields.indexOf(field) > -1
})
// EXPL: search only specified fields if included
if (query.$searchFields) {
if (!Array.isArray(query.$searchFields)) {
query.$searchFields = query.$searchFields.split(',')
}
// EXPL: we can only search fields that are a string type
query.$searchFields = query.$searchFields.filter(function(field) {
return stringFields.indexOf(field) > -1
})
query.$searchFields.forEach(function(field) {
let obj = {}
obj[field] = new RegExp(query.$term, 'i')
query.$or.push(obj)
})
} else {
queryableFields.forEach(function(field) {
let obj = {}
obj[field] = new RegExp(query.$term, 'i')
query.$or.push(obj)
})
}
}
delete query.$searchFields
delete query.$term
}
|
[
"function",
"(",
"query",
",",
"model",
",",
"logger",
")",
"{",
"const",
"Log",
"=",
"logger",
".",
"bind",
"(",
")",
"if",
"(",
"query",
".",
"$term",
")",
"{",
"query",
".",
"$or",
"=",
"[",
"]",
"// TODO: allow option to choose ANDing or ORing of searchFields/queryableFields",
"let",
"queryableFields",
"=",
"this",
".",
"getQueryableFields",
"(",
"model",
",",
"Log",
")",
"let",
"stringFields",
"=",
"this",
".",
"getStringFields",
"(",
"model",
",",
"Log",
")",
"// EXPL: we can only search fields that are a string type",
"queryableFields",
"=",
"queryableFields",
".",
"filter",
"(",
"function",
"(",
"field",
")",
"{",
"return",
"stringFields",
".",
"indexOf",
"(",
"field",
")",
">",
"-",
"1",
"}",
")",
"// EXPL: search only specified fields if included",
"if",
"(",
"query",
".",
"$searchFields",
")",
"{",
"if",
"(",
"!",
"Array",
".",
"isArray",
"(",
"query",
".",
"$searchFields",
")",
")",
"{",
"query",
".",
"$searchFields",
"=",
"query",
".",
"$searchFields",
".",
"split",
"(",
"','",
")",
"}",
"// EXPL: we can only search fields that are a string type",
"query",
".",
"$searchFields",
"=",
"query",
".",
"$searchFields",
".",
"filter",
"(",
"function",
"(",
"field",
")",
"{",
"return",
"stringFields",
".",
"indexOf",
"(",
"field",
")",
">",
"-",
"1",
"}",
")",
"query",
".",
"$searchFields",
".",
"forEach",
"(",
"function",
"(",
"field",
")",
"{",
"let",
"obj",
"=",
"{",
"}",
"obj",
"[",
"field",
"]",
"=",
"new",
"RegExp",
"(",
"query",
".",
"$term",
",",
"'i'",
")",
"query",
".",
"$or",
".",
"push",
"(",
"obj",
")",
"}",
")",
"}",
"else",
"{",
"queryableFields",
".",
"forEach",
"(",
"function",
"(",
"field",
")",
"{",
"let",
"obj",
"=",
"{",
"}",
"obj",
"[",
"field",
"]",
"=",
"new",
"RegExp",
"(",
"query",
".",
"$term",
",",
"'i'",
")",
"query",
".",
"$or",
".",
"push",
"(",
"obj",
")",
"}",
")",
"}",
"}",
"delete",
"query",
".",
"$searchFields",
"delete",
"query",
".",
"$term",
"}"
] |
Perform a regex search on the models immediate fields
@param query:The incoming request query.
@param model: A mongoose model object
@param logger: A logging object
|
[
"Perform",
"a",
"regex",
"search",
"on",
"the",
"models",
"immediate",
"fields"
] |
36110fd3cb2775b3b2068b18d775f1c87fbcef76
|
https://github.com/JKHeadley/rest-hapi/blob/36110fd3cb2775b3b2068b18d775f1c87fbcef76/utilities/query-helper.js#L338-L377
|
|
9,241
|
JKHeadley/rest-hapi
|
utilities/query-helper.js
|
function(query, mongooseQuery, logger) {
if (query.$sort) {
if (Array.isArray(query.$sort)) {
query.$sort = query.$sort.join(' ')
}
mongooseQuery.sort(query.$sort)
delete query.$sort
}
return mongooseQuery
}
|
javascript
|
function(query, mongooseQuery, logger) {
if (query.$sort) {
if (Array.isArray(query.$sort)) {
query.$sort = query.$sort.join(' ')
}
mongooseQuery.sort(query.$sort)
delete query.$sort
}
return mongooseQuery
}
|
[
"function",
"(",
"query",
",",
"mongooseQuery",
",",
"logger",
")",
"{",
"if",
"(",
"query",
".",
"$sort",
")",
"{",
"if",
"(",
"Array",
".",
"isArray",
"(",
"query",
".",
"$sort",
")",
")",
"{",
"query",
".",
"$sort",
"=",
"query",
".",
"$sort",
".",
"join",
"(",
"' '",
")",
"}",
"mongooseQuery",
".",
"sort",
"(",
"query",
".",
"$sort",
")",
"delete",
"query",
".",
"$sort",
"}",
"return",
"mongooseQuery",
"}"
] |
Set the sort priority for the mongoose query.
@param query: The incoming request query.
@param mongooseQuery: A mongoose query.
@param logger: A logging object.
@returns {*}: The updated mongoose query.
|
[
"Set",
"the",
"sort",
"priority",
"for",
"the",
"mongoose",
"query",
"."
] |
36110fd3cb2775b3b2068b18d775f1c87fbcef76
|
https://github.com/JKHeadley/rest-hapi/blob/36110fd3cb2775b3b2068b18d775f1c87fbcef76/utilities/query-helper.js#L435-L444
|
|
9,242
|
JKHeadley/rest-hapi
|
utilities/query-helper.js
|
getReference
|
function getReference(model, embed, logger) {
let property = model.schema.obj[embed]
while (_.isArray(property)) {
property = property[0]
}
if (property && property.ref) {
return {
model: property.ref,
include: { model: globals.mongoose.model(property.ref), as: embed }
}
} else {
return null
}
}
|
javascript
|
function getReference(model, embed, logger) {
let property = model.schema.obj[embed]
while (_.isArray(property)) {
property = property[0]
}
if (property && property.ref) {
return {
model: property.ref,
include: { model: globals.mongoose.model(property.ref), as: embed }
}
} else {
return null
}
}
|
[
"function",
"getReference",
"(",
"model",
",",
"embed",
",",
"logger",
")",
"{",
"let",
"property",
"=",
"model",
".",
"schema",
".",
"obj",
"[",
"embed",
"]",
"while",
"(",
"_",
".",
"isArray",
"(",
"property",
")",
")",
"{",
"property",
"=",
"property",
"[",
"0",
"]",
"}",
"if",
"(",
"property",
"&&",
"property",
".",
"ref",
")",
"{",
"return",
"{",
"model",
":",
"property",
".",
"ref",
",",
"include",
":",
"{",
"model",
":",
"globals",
".",
"mongoose",
".",
"model",
"(",
"property",
".",
"ref",
")",
",",
"as",
":",
"embed",
"}",
"}",
"}",
"else",
"{",
"return",
"null",
"}",
"}"
] |
Creates an association object from a model property if the property is a reference id
@param model
@param embed
@param logger
@returns {*} The association object or null if no reference is found
|
[
"Creates",
"an",
"association",
"object",
"from",
"a",
"model",
"property",
"if",
"the",
"property",
"is",
"a",
"reference",
"id"
] |
36110fd3cb2775b3b2068b18d775f1c87fbcef76
|
https://github.com/JKHeadley/rest-hapi/blob/36110fd3cb2775b3b2068b18d775f1c87fbcef76/utilities/query-helper.js#L638-L651
|
9,243
|
JKHeadley/rest-hapi
|
utilities/auth-helper.js
|
function(model, type, logger) {
let routeScope = model.routeOptions.routeScope || {}
let rootScope = routeScope.rootScope
let scope = []
let additionalScope = null
switch (type) {
case 'create':
additionalScope = routeScope.createScope
break
case 'read':
additionalScope = routeScope.readScope
break
case 'update':
additionalScope = routeScope.updateScope
break
case 'delete':
additionalScope = routeScope.deleteScope
break
case 'associate':
additionalScope = routeScope.associateScope
break
default:
if (routeScope[type]) {
scope = routeScope[type]
if (!_.isArray(scope)) {
scope = [scope]
}
}
return scope
}
if (rootScope && _.isArray(rootScope)) {
scope = scope.concat(rootScope)
} else if (rootScope) {
scope.push(rootScope)
}
if (additionalScope && _.isArray(additionalScope)) {
scope = scope.concat(additionalScope)
} else if (additionalScope) {
scope.push(additionalScope)
}
return scope
}
|
javascript
|
function(model, type, logger) {
let routeScope = model.routeOptions.routeScope || {}
let rootScope = routeScope.rootScope
let scope = []
let additionalScope = null
switch (type) {
case 'create':
additionalScope = routeScope.createScope
break
case 'read':
additionalScope = routeScope.readScope
break
case 'update':
additionalScope = routeScope.updateScope
break
case 'delete':
additionalScope = routeScope.deleteScope
break
case 'associate':
additionalScope = routeScope.associateScope
break
default:
if (routeScope[type]) {
scope = routeScope[type]
if (!_.isArray(scope)) {
scope = [scope]
}
}
return scope
}
if (rootScope && _.isArray(rootScope)) {
scope = scope.concat(rootScope)
} else if (rootScope) {
scope.push(rootScope)
}
if (additionalScope && _.isArray(additionalScope)) {
scope = scope.concat(additionalScope)
} else if (additionalScope) {
scope.push(additionalScope)
}
return scope
}
|
[
"function",
"(",
"model",
",",
"type",
",",
"logger",
")",
"{",
"let",
"routeScope",
"=",
"model",
".",
"routeOptions",
".",
"routeScope",
"||",
"{",
"}",
"let",
"rootScope",
"=",
"routeScope",
".",
"rootScope",
"let",
"scope",
"=",
"[",
"]",
"let",
"additionalScope",
"=",
"null",
"switch",
"(",
"type",
")",
"{",
"case",
"'create'",
":",
"additionalScope",
"=",
"routeScope",
".",
"createScope",
"break",
"case",
"'read'",
":",
"additionalScope",
"=",
"routeScope",
".",
"readScope",
"break",
"case",
"'update'",
":",
"additionalScope",
"=",
"routeScope",
".",
"updateScope",
"break",
"case",
"'delete'",
":",
"additionalScope",
"=",
"routeScope",
".",
"deleteScope",
"break",
"case",
"'associate'",
":",
"additionalScope",
"=",
"routeScope",
".",
"associateScope",
"break",
"default",
":",
"if",
"(",
"routeScope",
"[",
"type",
"]",
")",
"{",
"scope",
"=",
"routeScope",
"[",
"type",
"]",
"if",
"(",
"!",
"_",
".",
"isArray",
"(",
"scope",
")",
")",
"{",
"scope",
"=",
"[",
"scope",
"]",
"}",
"}",
"return",
"scope",
"}",
"if",
"(",
"rootScope",
"&&",
"_",
".",
"isArray",
"(",
"rootScope",
")",
")",
"{",
"scope",
"=",
"scope",
".",
"concat",
"(",
"rootScope",
")",
"}",
"else",
"if",
"(",
"rootScope",
")",
"{",
"scope",
".",
"push",
"(",
"rootScope",
")",
"}",
"if",
"(",
"additionalScope",
"&&",
"_",
".",
"isArray",
"(",
"additionalScope",
")",
")",
"{",
"scope",
"=",
"scope",
".",
"concat",
"(",
"additionalScope",
")",
"}",
"else",
"if",
"(",
"additionalScope",
")",
"{",
"scope",
".",
"push",
"(",
"additionalScope",
")",
"}",
"return",
"scope",
"}"
] |
Generates the proper scope for an endpoint based on the model routeOptions
@param model: A mongoose model
@param type: The scope CRUD type. Valid values are 'create', 'read', 'update', 'delete', and 'associate'.
@param logger: A logging object
@returns {Array}: A list of authorization scopes for the endpoint.
|
[
"Generates",
"the",
"proper",
"scope",
"for",
"an",
"endpoint",
"based",
"on",
"the",
"model",
"routeOptions"
] |
36110fd3cb2775b3b2068b18d775f1c87fbcef76
|
https://github.com/JKHeadley/rest-hapi/blob/36110fd3cb2775b3b2068b18d775f1c87fbcef76/utilities/auth-helper.js#L13-L59
|
|
9,244
|
textlint/textlint
|
packages/textlint/bin/textlint.js
|
showError
|
function showError(error) {
console.error(logSymbols.error, "Error");
console.error(`${error.message}\n`);
console.error(logSymbols.error, "Stack trace");
console.error(error.stack);
}
|
javascript
|
function showError(error) {
console.error(logSymbols.error, "Error");
console.error(`${error.message}\n`);
console.error(logSymbols.error, "Stack trace");
console.error(error.stack);
}
|
[
"function",
"showError",
"(",
"error",
")",
"{",
"console",
".",
"error",
"(",
"logSymbols",
".",
"error",
",",
"\"Error\"",
")",
";",
"console",
".",
"error",
"(",
"`",
"${",
"error",
".",
"message",
"}",
"\\n",
"`",
")",
";",
"console",
".",
"error",
"(",
"logSymbols",
".",
"error",
",",
"\"Stack trace\"",
")",
";",
"console",
".",
"error",
"(",
"error",
".",
"stack",
")",
";",
"}"
] |
show error message for user
@param {Error} error
|
[
"show",
"error",
"message",
"for",
"user"
] |
61ebd75dac6804827aad9b4268867c60e328e566
|
https://github.com/textlint/textlint/blob/61ebd75dac6804827aad9b4268867c60e328e566/packages/textlint/bin/textlint.js#L22-L27
|
9,245
|
textlint/textlint
|
packages/@textlint/markdown-to-ast/src/markdown-parser.js
|
parse
|
function parse(text) {
const ast = remark.parse(text);
const src = new StructuredSource(text);
traverse(ast).forEach(function(node) {
// eslint-disable-next-line no-invalid-this
if (this.notLeaf) {
if (node.type) {
const replacedType = SyntaxMap[node.type];
if (!replacedType) {
debug(`replacedType : ${replacedType} , node.type: ${node.type}`);
} else {
node.type = replacedType;
}
}
// map `range`, `loc` and `raw` to node
if (node.position) {
const position = node.position;
const positionCompensated = {
start: { line: position.start.line, column: position.start.column - 1 },
end: { line: position.end.line, column: position.end.column - 1 }
};
const range = src.locationToRange(positionCompensated);
node.loc = positionCompensated;
node.range = range;
node.raw = text.slice(range[0], range[1]);
// Compatible for https://github.com/wooorm/unist, but hidden
Object.defineProperty(node, "position", {
enumerable: false,
configurable: false,
writable: false,
value: position
});
}
}
});
return ast;
}
|
javascript
|
function parse(text) {
const ast = remark.parse(text);
const src = new StructuredSource(text);
traverse(ast).forEach(function(node) {
// eslint-disable-next-line no-invalid-this
if (this.notLeaf) {
if (node.type) {
const replacedType = SyntaxMap[node.type];
if (!replacedType) {
debug(`replacedType : ${replacedType} , node.type: ${node.type}`);
} else {
node.type = replacedType;
}
}
// map `range`, `loc` and `raw` to node
if (node.position) {
const position = node.position;
const positionCompensated = {
start: { line: position.start.line, column: position.start.column - 1 },
end: { line: position.end.line, column: position.end.column - 1 }
};
const range = src.locationToRange(positionCompensated);
node.loc = positionCompensated;
node.range = range;
node.raw = text.slice(range[0], range[1]);
// Compatible for https://github.com/wooorm/unist, but hidden
Object.defineProperty(node, "position", {
enumerable: false,
configurable: false,
writable: false,
value: position
});
}
}
});
return ast;
}
|
[
"function",
"parse",
"(",
"text",
")",
"{",
"const",
"ast",
"=",
"remark",
".",
"parse",
"(",
"text",
")",
";",
"const",
"src",
"=",
"new",
"StructuredSource",
"(",
"text",
")",
";",
"traverse",
"(",
"ast",
")",
".",
"forEach",
"(",
"function",
"(",
"node",
")",
"{",
"// eslint-disable-next-line no-invalid-this",
"if",
"(",
"this",
".",
"notLeaf",
")",
"{",
"if",
"(",
"node",
".",
"type",
")",
"{",
"const",
"replacedType",
"=",
"SyntaxMap",
"[",
"node",
".",
"type",
"]",
";",
"if",
"(",
"!",
"replacedType",
")",
"{",
"debug",
"(",
"`",
"${",
"replacedType",
"}",
"${",
"node",
".",
"type",
"}",
"`",
")",
";",
"}",
"else",
"{",
"node",
".",
"type",
"=",
"replacedType",
";",
"}",
"}",
"// map `range`, `loc` and `raw` to node",
"if",
"(",
"node",
".",
"position",
")",
"{",
"const",
"position",
"=",
"node",
".",
"position",
";",
"const",
"positionCompensated",
"=",
"{",
"start",
":",
"{",
"line",
":",
"position",
".",
"start",
".",
"line",
",",
"column",
":",
"position",
".",
"start",
".",
"column",
"-",
"1",
"}",
",",
"end",
":",
"{",
"line",
":",
"position",
".",
"end",
".",
"line",
",",
"column",
":",
"position",
".",
"end",
".",
"column",
"-",
"1",
"}",
"}",
";",
"const",
"range",
"=",
"src",
".",
"locationToRange",
"(",
"positionCompensated",
")",
";",
"node",
".",
"loc",
"=",
"positionCompensated",
";",
"node",
".",
"range",
"=",
"range",
";",
"node",
".",
"raw",
"=",
"text",
".",
"slice",
"(",
"range",
"[",
"0",
"]",
",",
"range",
"[",
"1",
"]",
")",
";",
"// Compatible for https://github.com/wooorm/unist, but hidden",
"Object",
".",
"defineProperty",
"(",
"node",
",",
"\"position\"",
",",
"{",
"enumerable",
":",
"false",
",",
"configurable",
":",
"false",
",",
"writable",
":",
"false",
",",
"value",
":",
"position",
"}",
")",
";",
"}",
"}",
"}",
")",
";",
"return",
"ast",
";",
"}"
] |
parse markdown text and return ast mapped location info.
@param {string} text
@returns {TxtNode}
|
[
"parse",
"markdown",
"text",
"and",
"return",
"ast",
"mapped",
"location",
"info",
"."
] |
61ebd75dac6804827aad9b4268867c60e328e566
|
https://github.com/textlint/textlint/blob/61ebd75dac6804827aad9b4268867c60e328e566/packages/@textlint/markdown-to-ast/src/markdown-parser.js#L19-L55
|
9,246
|
textlint/textlint
|
packages/@textlint/text-to-ast/src/plaintext-parser.js
|
createParagraph
|
function createParagraph(nodes) {
const firstNode = nodes[0];
const lastNode = nodes[nodes.length - 1];
return {
type: Syntax.Paragraph,
raw: nodes
.map(function(node) {
return node.raw;
})
.join(""),
range: [firstNode.range[0], lastNode.range[1]],
loc: {
start: {
line: firstNode.loc.start.line,
column: firstNode.loc.start.column
},
end: {
line: lastNode.loc.end.line,
column: lastNode.loc.end.column
}
},
children: nodes
};
}
|
javascript
|
function createParagraph(nodes) {
const firstNode = nodes[0];
const lastNode = nodes[nodes.length - 1];
return {
type: Syntax.Paragraph,
raw: nodes
.map(function(node) {
return node.raw;
})
.join(""),
range: [firstNode.range[0], lastNode.range[1]],
loc: {
start: {
line: firstNode.loc.start.line,
column: firstNode.loc.start.column
},
end: {
line: lastNode.loc.end.line,
column: lastNode.loc.end.column
}
},
children: nodes
};
}
|
[
"function",
"createParagraph",
"(",
"nodes",
")",
"{",
"const",
"firstNode",
"=",
"nodes",
"[",
"0",
"]",
";",
"const",
"lastNode",
"=",
"nodes",
"[",
"nodes",
".",
"length",
"-",
"1",
"]",
";",
"return",
"{",
"type",
":",
"Syntax",
".",
"Paragraph",
",",
"raw",
":",
"nodes",
".",
"map",
"(",
"function",
"(",
"node",
")",
"{",
"return",
"node",
".",
"raw",
";",
"}",
")",
".",
"join",
"(",
"\"\"",
")",
",",
"range",
":",
"[",
"firstNode",
".",
"range",
"[",
"0",
"]",
",",
"lastNode",
".",
"range",
"[",
"1",
"]",
"]",
",",
"loc",
":",
"{",
"start",
":",
"{",
"line",
":",
"firstNode",
".",
"loc",
".",
"start",
".",
"line",
",",
"column",
":",
"firstNode",
".",
"loc",
".",
"start",
".",
"column",
"}",
",",
"end",
":",
"{",
"line",
":",
"lastNode",
".",
"loc",
".",
"end",
".",
"line",
",",
"column",
":",
"lastNode",
".",
"loc",
".",
"end",
".",
"column",
"}",
"}",
",",
"children",
":",
"nodes",
"}",
";",
"}"
] |
create paragraph node from TxtNodes
@param {[TxtNode]} nodes
@returns {TxtNode} Paragraph node
|
[
"create",
"paragraph",
"node",
"from",
"TxtNodes"
] |
61ebd75dac6804827aad9b4268867c60e328e566
|
https://github.com/textlint/textlint/blob/61ebd75dac6804827aad9b4268867c60e328e566/packages/@textlint/text-to-ast/src/plaintext-parser.js#L72-L95
|
9,247
|
textlint/textlint
|
packages/@textlint/text-to-ast/src/plaintext-parser.js
|
parse
|
function parse(text) {
const textLineByLine = text.split(LINEBREAKE_MARK);
// it should be alternately Str and Break
let startIndex = 0;
const lastLineIndex = textLineByLine.length - 1;
const isLasEmptytLine = (line, index) => {
return index === lastLineIndex && line === "";
};
const isEmptyLine = (line, index) => {
return index !== lastLineIndex && line === "";
};
const children = textLineByLine.reduce(function(result, currentLine, index) {
const lineNumber = index + 1;
if (isLasEmptytLine(currentLine, index)) {
return result;
}
// \n
if (isEmptyLine(currentLine, index)) {
const emptyBreakNode = createBRNode(lineNumber, startIndex);
startIndex += emptyBreakNode.raw.length;
result.push(emptyBreakNode);
return result;
}
// (Paragraph > Str) -> Br?
const strNode = parseLine(currentLine, lineNumber, startIndex);
const paragraph = createParagraph([strNode]);
startIndex += paragraph.raw.length;
result.push(paragraph);
if (index !== lastLineIndex) {
const breakNode = createEndedBRNode(paragraph);
startIndex += breakNode.raw.length;
result.push(breakNode);
}
return result;
}, []);
return {
type: Syntax.Document,
raw: text,
range: [0, text.length],
loc: {
start: {
line: 1,
column: 0
},
end: {
line: textLineByLine.length,
column: textLineByLine[textLineByLine.length - 1].length
}
},
children
};
}
|
javascript
|
function parse(text) {
const textLineByLine = text.split(LINEBREAKE_MARK);
// it should be alternately Str and Break
let startIndex = 0;
const lastLineIndex = textLineByLine.length - 1;
const isLasEmptytLine = (line, index) => {
return index === lastLineIndex && line === "";
};
const isEmptyLine = (line, index) => {
return index !== lastLineIndex && line === "";
};
const children = textLineByLine.reduce(function(result, currentLine, index) {
const lineNumber = index + 1;
if (isLasEmptytLine(currentLine, index)) {
return result;
}
// \n
if (isEmptyLine(currentLine, index)) {
const emptyBreakNode = createBRNode(lineNumber, startIndex);
startIndex += emptyBreakNode.raw.length;
result.push(emptyBreakNode);
return result;
}
// (Paragraph > Str) -> Br?
const strNode = parseLine(currentLine, lineNumber, startIndex);
const paragraph = createParagraph([strNode]);
startIndex += paragraph.raw.length;
result.push(paragraph);
if (index !== lastLineIndex) {
const breakNode = createEndedBRNode(paragraph);
startIndex += breakNode.raw.length;
result.push(breakNode);
}
return result;
}, []);
return {
type: Syntax.Document,
raw: text,
range: [0, text.length],
loc: {
start: {
line: 1,
column: 0
},
end: {
line: textLineByLine.length,
column: textLineByLine[textLineByLine.length - 1].length
}
},
children
};
}
|
[
"function",
"parse",
"(",
"text",
")",
"{",
"const",
"textLineByLine",
"=",
"text",
".",
"split",
"(",
"LINEBREAKE_MARK",
")",
";",
"// it should be alternately Str and Break",
"let",
"startIndex",
"=",
"0",
";",
"const",
"lastLineIndex",
"=",
"textLineByLine",
".",
"length",
"-",
"1",
";",
"const",
"isLasEmptytLine",
"=",
"(",
"line",
",",
"index",
")",
"=>",
"{",
"return",
"index",
"===",
"lastLineIndex",
"&&",
"line",
"===",
"\"\"",
";",
"}",
";",
"const",
"isEmptyLine",
"=",
"(",
"line",
",",
"index",
")",
"=>",
"{",
"return",
"index",
"!==",
"lastLineIndex",
"&&",
"line",
"===",
"\"\"",
";",
"}",
";",
"const",
"children",
"=",
"textLineByLine",
".",
"reduce",
"(",
"function",
"(",
"result",
",",
"currentLine",
",",
"index",
")",
"{",
"const",
"lineNumber",
"=",
"index",
"+",
"1",
";",
"if",
"(",
"isLasEmptytLine",
"(",
"currentLine",
",",
"index",
")",
")",
"{",
"return",
"result",
";",
"}",
"// \\n",
"if",
"(",
"isEmptyLine",
"(",
"currentLine",
",",
"index",
")",
")",
"{",
"const",
"emptyBreakNode",
"=",
"createBRNode",
"(",
"lineNumber",
",",
"startIndex",
")",
";",
"startIndex",
"+=",
"emptyBreakNode",
".",
"raw",
".",
"length",
";",
"result",
".",
"push",
"(",
"emptyBreakNode",
")",
";",
"return",
"result",
";",
"}",
"// (Paragraph > Str) -> Br?",
"const",
"strNode",
"=",
"parseLine",
"(",
"currentLine",
",",
"lineNumber",
",",
"startIndex",
")",
";",
"const",
"paragraph",
"=",
"createParagraph",
"(",
"[",
"strNode",
"]",
")",
";",
"startIndex",
"+=",
"paragraph",
".",
"raw",
".",
"length",
";",
"result",
".",
"push",
"(",
"paragraph",
")",
";",
"if",
"(",
"index",
"!==",
"lastLineIndex",
")",
"{",
"const",
"breakNode",
"=",
"createEndedBRNode",
"(",
"paragraph",
")",
";",
"startIndex",
"+=",
"breakNode",
".",
"raw",
".",
"length",
";",
"result",
".",
"push",
"(",
"breakNode",
")",
";",
"}",
"return",
"result",
";",
"}",
",",
"[",
"]",
")",
";",
"return",
"{",
"type",
":",
"Syntax",
".",
"Document",
",",
"raw",
":",
"text",
",",
"range",
":",
"[",
"0",
",",
"text",
".",
"length",
"]",
",",
"loc",
":",
"{",
"start",
":",
"{",
"line",
":",
"1",
",",
"column",
":",
"0",
"}",
",",
"end",
":",
"{",
"line",
":",
"textLineByLine",
".",
"length",
",",
"column",
":",
"textLineByLine",
"[",
"textLineByLine",
".",
"length",
"-",
"1",
"]",
".",
"length",
"}",
"}",
",",
"children",
"}",
";",
"}"
] |
parse text and return ast mapped location info.
@param {string} text
@returns {TxtNode}
|
[
"parse",
"text",
"and",
"return",
"ast",
"mapped",
"location",
"info",
"."
] |
61ebd75dac6804827aad9b4268867c60e328e566
|
https://github.com/textlint/textlint/blob/61ebd75dac6804827aad9b4268867c60e328e566/packages/@textlint/text-to-ast/src/plaintext-parser.js#L102-L154
|
9,248
|
textlint/textlint
|
examples/perf/perf.js
|
time
|
function time(cmd, runs, runNumber, results, cb) {
var start = process.hrtime();
exec(cmd, { silent: true }, function() {
var diff = process.hrtime(start),
actual = diff[0] * 1e3 + diff[1] / 1e6; // ms
results.push(actual);
echo("Performance Run #" + runNumber + ": %dms", actual);
if (runs > 1) {
time(cmd, runs - 1, runNumber + 1, results, cb);
} else {
return cb(results);
}
});
}
|
javascript
|
function time(cmd, runs, runNumber, results, cb) {
var start = process.hrtime();
exec(cmd, { silent: true }, function() {
var diff = process.hrtime(start),
actual = diff[0] * 1e3 + diff[1] / 1e6; // ms
results.push(actual);
echo("Performance Run #" + runNumber + ": %dms", actual);
if (runs > 1) {
time(cmd, runs - 1, runNumber + 1, results, cb);
} else {
return cb(results);
}
});
}
|
[
"function",
"time",
"(",
"cmd",
",",
"runs",
",",
"runNumber",
",",
"results",
",",
"cb",
")",
"{",
"var",
"start",
"=",
"process",
".",
"hrtime",
"(",
")",
";",
"exec",
"(",
"cmd",
",",
"{",
"silent",
":",
"true",
"}",
",",
"function",
"(",
")",
"{",
"var",
"diff",
"=",
"process",
".",
"hrtime",
"(",
"start",
")",
",",
"actual",
"=",
"diff",
"[",
"0",
"]",
"*",
"1e3",
"+",
"diff",
"[",
"1",
"]",
"/",
"1e6",
";",
"// ms",
"results",
".",
"push",
"(",
"actual",
")",
";",
"echo",
"(",
"\"Performance Run #\"",
"+",
"runNumber",
"+",
"\": %dms\"",
",",
"actual",
")",
";",
"if",
"(",
"runs",
">",
"1",
")",
"{",
"time",
"(",
"cmd",
",",
"runs",
"-",
"1",
",",
"runNumber",
"+",
"1",
",",
"results",
",",
"cb",
")",
";",
"}",
"else",
"{",
"return",
"cb",
"(",
"results",
")",
";",
"}",
"}",
")",
";",
"}"
] |
Calculates the time for each run for performance
@param {string} cmd cmd
@param {int} runs Total number of runs to do
@param {int} runNumber Current run number
@param {int[]} results Collection results from each run
@param {function} cb Function to call when everything is done
@returns {int[]} calls the cb with all the results
@private
|
[
"Calculates",
"the",
"time",
"for",
"each",
"run",
"for",
"performance"
] |
61ebd75dac6804827aad9b4268867c60e328e566
|
https://github.com/textlint/textlint/blob/61ebd75dac6804827aad9b4268867c60e328e566/examples/perf/perf.js#L22-L36
|
9,249
|
textlint/textlint
|
examples/rulesdir/rules/no-todo.js
|
getParents
|
function getParents(node) {
var result = [];
var parent = node.parent;
while (parent != null) {
result.push(parent);
parent = parent.parent;
}
return result;
}
|
javascript
|
function getParents(node) {
var result = [];
var parent = node.parent;
while (parent != null) {
result.push(parent);
parent = parent.parent;
}
return result;
}
|
[
"function",
"getParents",
"(",
"node",
")",
"{",
"var",
"result",
"=",
"[",
"]",
";",
"var",
"parent",
"=",
"node",
".",
"parent",
";",
"while",
"(",
"parent",
"!=",
"null",
")",
"{",
"result",
".",
"push",
"(",
"parent",
")",
";",
"parent",
"=",
"parent",
".",
"parent",
";",
"}",
"return",
"result",
";",
"}"
] |
Get parents of node.
The parent nodes are returned in order from the closest parent to the outer ones.
@param node
@returns {Array}
|
[
"Get",
"parents",
"of",
"node",
".",
"The",
"parent",
"nodes",
"are",
"returned",
"in",
"order",
"from",
"the",
"closest",
"parent",
"to",
"the",
"outer",
"ones",
"."
] |
61ebd75dac6804827aad9b4268867c60e328e566
|
https://github.com/textlint/textlint/blob/61ebd75dac6804827aad9b4268867c60e328e566/examples/rulesdir/rules/no-todo.js#L10-L18
|
9,250
|
textlint/textlint
|
examples/rulesdir/rules/no-todo.js
|
isNodeWrapped
|
function isNodeWrapped(node, types) {
var parents = getParents(node);
var parentsTypes = parents.map(function(parent) {
return parent.type;
});
return types.some(function(type) {
return parentsTypes.some(function(parentType) {
return parentType === type;
});
});
}
|
javascript
|
function isNodeWrapped(node, types) {
var parents = getParents(node);
var parentsTypes = parents.map(function(parent) {
return parent.type;
});
return types.some(function(type) {
return parentsTypes.some(function(parentType) {
return parentType === type;
});
});
}
|
[
"function",
"isNodeWrapped",
"(",
"node",
",",
"types",
")",
"{",
"var",
"parents",
"=",
"getParents",
"(",
"node",
")",
";",
"var",
"parentsTypes",
"=",
"parents",
".",
"map",
"(",
"function",
"(",
"parent",
")",
"{",
"return",
"parent",
".",
"type",
";",
"}",
")",
";",
"return",
"types",
".",
"some",
"(",
"function",
"(",
"type",
")",
"{",
"return",
"parentsTypes",
".",
"some",
"(",
"function",
"(",
"parentType",
")",
"{",
"return",
"parentType",
"===",
"type",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] |
Return true if `node` is wrapped any one of `types`.
@param {TxtNode} node is target node
@param {string[]} types are wrapped target node
@returns {boolean}
|
[
"Return",
"true",
"if",
"node",
"is",
"wrapped",
"any",
"one",
"of",
"types",
"."
] |
61ebd75dac6804827aad9b4268867c60e328e566
|
https://github.com/textlint/textlint/blob/61ebd75dac6804827aad9b4268867c60e328e566/examples/rulesdir/rules/no-todo.js#L25-L35
|
9,251
|
slanatech/swagger-stats
|
ui/plugins/cubism/cubism.v1.js
|
cubism_graphiteParse
|
function cubism_graphiteParse(text) {
var i = text.indexOf("|"),
meta = text.substring(0, i),
c = meta.lastIndexOf(","),
b = meta.lastIndexOf(",", c - 1),
a = meta.lastIndexOf(",", b - 1),
start = meta.substring(a + 1, b) * 1000,
step = meta.substring(c + 1) * 1000;
return text
.substring(i + 1)
.split(",")
.slice(1) // the first value is always None?
.map(function(d) { return +d; });
}
|
javascript
|
function cubism_graphiteParse(text) {
var i = text.indexOf("|"),
meta = text.substring(0, i),
c = meta.lastIndexOf(","),
b = meta.lastIndexOf(",", c - 1),
a = meta.lastIndexOf(",", b - 1),
start = meta.substring(a + 1, b) * 1000,
step = meta.substring(c + 1) * 1000;
return text
.substring(i + 1)
.split(",")
.slice(1) // the first value is always None?
.map(function(d) { return +d; });
}
|
[
"function",
"cubism_graphiteParse",
"(",
"text",
")",
"{",
"var",
"i",
"=",
"text",
".",
"indexOf",
"(",
"\"|\"",
")",
",",
"meta",
"=",
"text",
".",
"substring",
"(",
"0",
",",
"i",
")",
",",
"c",
"=",
"meta",
".",
"lastIndexOf",
"(",
"\",\"",
")",
",",
"b",
"=",
"meta",
".",
"lastIndexOf",
"(",
"\",\"",
",",
"c",
"-",
"1",
")",
",",
"a",
"=",
"meta",
".",
"lastIndexOf",
"(",
"\",\"",
",",
"b",
"-",
"1",
")",
",",
"start",
"=",
"meta",
".",
"substring",
"(",
"a",
"+",
"1",
",",
"b",
")",
"*",
"1000",
",",
"step",
"=",
"meta",
".",
"substring",
"(",
"c",
"+",
"1",
")",
"*",
"1000",
";",
"return",
"text",
".",
"substring",
"(",
"i",
"+",
"1",
")",
".",
"split",
"(",
"\",\"",
")",
".",
"slice",
"(",
"1",
")",
"// the first value is always None?",
".",
"map",
"(",
"function",
"(",
"d",
")",
"{",
"return",
"+",
"d",
";",
"}",
")",
";",
"}"
] |
Helper method for parsing graphite's raw format.
|
[
"Helper",
"method",
"for",
"parsing",
"graphite",
"s",
"raw",
"format",
"."
] |
94b99c98ae5fadad72c250d516333b603e9b0fc1
|
https://github.com/slanatech/swagger-stats/blob/94b99c98ae5fadad72c250d516333b603e9b0fc1/ui/plugins/cubism/cubism.v1.js#L428-L441
|
9,252
|
slanatech/swagger-stats
|
ui/plugins/cubism/cubism.v1.js
|
prepare
|
function prepare(start1, stop) {
var steps = Math.min(size, Math.round((start1 - start) / step));
if (!steps || fetching) return; // already fetched, or fetching!
fetching = true;
steps = Math.min(size, steps + cubism_metricOverlap);
var start0 = new Date(stop - steps * step);
request(start0, stop, step, function(error, data) {
fetching = false;
if (error) return console.warn(error);
var i = isFinite(start) ? Math.round((start0 - start) / step) : 0;
for (var j = 0, m = data.length; j < m; ++j) values[j + i] = data[j];
event.change.call(metric, start, stop);
});
}
|
javascript
|
function prepare(start1, stop) {
var steps = Math.min(size, Math.round((start1 - start) / step));
if (!steps || fetching) return; // already fetched, or fetching!
fetching = true;
steps = Math.min(size, steps + cubism_metricOverlap);
var start0 = new Date(stop - steps * step);
request(start0, stop, step, function(error, data) {
fetching = false;
if (error) return console.warn(error);
var i = isFinite(start) ? Math.round((start0 - start) / step) : 0;
for (var j = 0, m = data.length; j < m; ++j) values[j + i] = data[j];
event.change.call(metric, start, stop);
});
}
|
[
"function",
"prepare",
"(",
"start1",
",",
"stop",
")",
"{",
"var",
"steps",
"=",
"Math",
".",
"min",
"(",
"size",
",",
"Math",
".",
"round",
"(",
"(",
"start1",
"-",
"start",
")",
"/",
"step",
")",
")",
";",
"if",
"(",
"!",
"steps",
"||",
"fetching",
")",
"return",
";",
"// already fetched, or fetching!",
"fetching",
"=",
"true",
";",
"steps",
"=",
"Math",
".",
"min",
"(",
"size",
",",
"steps",
"+",
"cubism_metricOverlap",
")",
";",
"var",
"start0",
"=",
"new",
"Date",
"(",
"stop",
"-",
"steps",
"*",
"step",
")",
";",
"request",
"(",
"start0",
",",
"stop",
",",
"step",
",",
"function",
"(",
"error",
",",
"data",
")",
"{",
"fetching",
"=",
"false",
";",
"if",
"(",
"error",
")",
"return",
"console",
".",
"warn",
"(",
"error",
")",
";",
"var",
"i",
"=",
"isFinite",
"(",
"start",
")",
"?",
"Math",
".",
"round",
"(",
"(",
"start0",
"-",
"start",
")",
"/",
"step",
")",
":",
"0",
";",
"for",
"(",
"var",
"j",
"=",
"0",
",",
"m",
"=",
"data",
".",
"length",
";",
"j",
"<",
"m",
";",
"++",
"j",
")",
"values",
"[",
"j",
"+",
"i",
"]",
"=",
"data",
"[",
"j",
"]",
";",
"event",
".",
"change",
".",
"call",
"(",
"metric",
",",
"start",
",",
"stop",
")",
";",
"}",
")",
";",
"}"
] |
Prefetch new data into a temporary array.
|
[
"Prefetch",
"new",
"data",
"into",
"a",
"temporary",
"array",
"."
] |
94b99c98ae5fadad72c250d516333b603e9b0fc1
|
https://github.com/slanatech/swagger-stats/blob/94b99c98ae5fadad72c250d516333b603e9b0fc1/ui/plugins/cubism/cubism.v1.js#L593-L606
|
9,253
|
slanatech/swagger-stats
|
ui/plugins/cubism/cubism.v1.js
|
beforechange
|
function beforechange(start1, stop1) {
if (!isFinite(start)) start = start1;
values.splice(0, Math.max(0, Math.min(size, Math.round((start1 - start) / step))));
start = start1;
stop = stop1;
}
|
javascript
|
function beforechange(start1, stop1) {
if (!isFinite(start)) start = start1;
values.splice(0, Math.max(0, Math.min(size, Math.round((start1 - start) / step))));
start = start1;
stop = stop1;
}
|
[
"function",
"beforechange",
"(",
"start1",
",",
"stop1",
")",
"{",
"if",
"(",
"!",
"isFinite",
"(",
"start",
")",
")",
"start",
"=",
"start1",
";",
"values",
".",
"splice",
"(",
"0",
",",
"Math",
".",
"max",
"(",
"0",
",",
"Math",
".",
"min",
"(",
"size",
",",
"Math",
".",
"round",
"(",
"(",
"start1",
"-",
"start",
")",
"/",
"step",
")",
")",
")",
")",
";",
"start",
"=",
"start1",
";",
"stop",
"=",
"stop1",
";",
"}"
] |
When the context changes, switch to the new data, ready-or-not!
|
[
"When",
"the",
"context",
"changes",
"switch",
"to",
"the",
"new",
"data",
"ready",
"-",
"or",
"-",
"not!"
] |
94b99c98ae5fadad72c250d516333b603e9b0fc1
|
https://github.com/slanatech/swagger-stats/blob/94b99c98ae5fadad72c250d516333b603e9b0fc1/ui/plugins/cubism/cubism.v1.js#L609-L614
|
9,254
|
slanatech/swagger-stats
|
ui/plugins/cubism/cubism.v1.js
|
cubism_metricShift
|
function cubism_metricShift(request, offset) {
return function(start, stop, step, callback) {
request(new Date(+start + offset), new Date(+stop + offset), step, callback);
};
}
|
javascript
|
function cubism_metricShift(request, offset) {
return function(start, stop, step, callback) {
request(new Date(+start + offset), new Date(+stop + offset), step, callback);
};
}
|
[
"function",
"cubism_metricShift",
"(",
"request",
",",
"offset",
")",
"{",
"return",
"function",
"(",
"start",
",",
"stop",
",",
"step",
",",
"callback",
")",
"{",
"request",
"(",
"new",
"Date",
"(",
"+",
"start",
"+",
"offset",
")",
",",
"new",
"Date",
"(",
"+",
"stop",
"+",
"offset",
")",
",",
"step",
",",
"callback",
")",
";",
"}",
";",
"}"
] |
Wraps the specified request implementation, and shifts time by the given offset.
|
[
"Wraps",
"the",
"specified",
"request",
"implementation",
"and",
"shifts",
"time",
"by",
"the",
"given",
"offset",
"."
] |
94b99c98ae5fadad72c250d516333b603e9b0fc1
|
https://github.com/slanatech/swagger-stats/blob/94b99c98ae5fadad72c250d516333b603e9b0fc1/ui/plugins/cubism/cubism.v1.js#L665-L669
|
9,255
|
slanatech/swagger-stats
|
lib/swsInterface.js
|
expireSessionIDs
|
function expireSessionIDs(){
var tssec = Date.now();
var expired = [];
for(var sid in sessionIDs){
if(sessionIDs[sid] < (tssec + 500)){
expired.push(sid);
}
}
for(var i=0;i<expired.length;i++){
delete sessionIDs[expired[i]];
debug('Session ID expired: %s', expired[i]);
}
}
|
javascript
|
function expireSessionIDs(){
var tssec = Date.now();
var expired = [];
for(var sid in sessionIDs){
if(sessionIDs[sid] < (tssec + 500)){
expired.push(sid);
}
}
for(var i=0;i<expired.length;i++){
delete sessionIDs[expired[i]];
debug('Session ID expired: %s', expired[i]);
}
}
|
[
"function",
"expireSessionIDs",
"(",
")",
"{",
"var",
"tssec",
"=",
"Date",
".",
"now",
"(",
")",
";",
"var",
"expired",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"sid",
"in",
"sessionIDs",
")",
"{",
"if",
"(",
"sessionIDs",
"[",
"sid",
"]",
"<",
"(",
"tssec",
"+",
"500",
")",
")",
"{",
"expired",
".",
"push",
"(",
"sid",
")",
";",
"}",
"}",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"expired",
".",
"length",
";",
"i",
"++",
")",
"{",
"delete",
"sessionIDs",
"[",
"expired",
"[",
"i",
"]",
"]",
";",
"debug",
"(",
"'Session ID expired: %s'",
",",
"expired",
"[",
"i",
"]",
")",
";",
"}",
"}"
] |
If authentication is enabled, executed periodically and expires old session IDs
|
[
"If",
"authentication",
"is",
"enabled",
"executed",
"periodically",
"and",
"expires",
"old",
"session",
"IDs"
] |
94b99c98ae5fadad72c250d516333b603e9b0fc1
|
https://github.com/slanatech/swagger-stats/blob/94b99c98ae5fadad72c250d516333b603e9b0fc1/lib/swsInterface.js#L60-L72
|
9,256
|
slanatech/swagger-stats
|
lib/swsInterface.js
|
processOptions
|
function processOptions(options){
if(!options) return;
for(var op in swsUtil.supportedOptions){
if(op in options){
swsOptions[op] = options[op];
}
}
// update standard path
pathUI = swsOptions.uriPath+'/ui';
pathDist = swsOptions.uriPath+'/dist';
pathStats = swsOptions.uriPath+'/stats';
pathMetrics = swsOptions.uriPath+'/metrics';
pathLogout = swsOptions.uriPath+'/logout';
if( swsOptions.authentication ){
setInterval(expireSessionIDs,500);
}
}
|
javascript
|
function processOptions(options){
if(!options) return;
for(var op in swsUtil.supportedOptions){
if(op in options){
swsOptions[op] = options[op];
}
}
// update standard path
pathUI = swsOptions.uriPath+'/ui';
pathDist = swsOptions.uriPath+'/dist';
pathStats = swsOptions.uriPath+'/stats';
pathMetrics = swsOptions.uriPath+'/metrics';
pathLogout = swsOptions.uriPath+'/logout';
if( swsOptions.authentication ){
setInterval(expireSessionIDs,500);
}
}
|
[
"function",
"processOptions",
"(",
"options",
")",
"{",
"if",
"(",
"!",
"options",
")",
"return",
";",
"for",
"(",
"var",
"op",
"in",
"swsUtil",
".",
"supportedOptions",
")",
"{",
"if",
"(",
"op",
"in",
"options",
")",
"{",
"swsOptions",
"[",
"op",
"]",
"=",
"options",
"[",
"op",
"]",
";",
"}",
"}",
"// update standard path",
"pathUI",
"=",
"swsOptions",
".",
"uriPath",
"+",
"'/ui'",
";",
"pathDist",
"=",
"swsOptions",
".",
"uriPath",
"+",
"'/dist'",
";",
"pathStats",
"=",
"swsOptions",
".",
"uriPath",
"+",
"'/stats'",
";",
"pathMetrics",
"=",
"swsOptions",
".",
"uriPath",
"+",
"'/metrics'",
";",
"pathLogout",
"=",
"swsOptions",
".",
"uriPath",
"+",
"'/logout'",
";",
"if",
"(",
"swsOptions",
".",
"authentication",
")",
"{",
"setInterval",
"(",
"expireSessionIDs",
",",
"500",
")",
";",
"}",
"}"
] |
Override defaults if options are provided
|
[
"Override",
"defaults",
"if",
"options",
"are",
"provided"
] |
94b99c98ae5fadad72c250d516333b603e9b0fc1
|
https://github.com/slanatech/swagger-stats/blob/94b99c98ae5fadad72c250d516333b603e9b0fc1/lib/swsInterface.js#L104-L123
|
9,257
|
slanatech/swagger-stats
|
lib/swsInterface.js
|
function (options) {
processOptions(options);
processor = new swsProcessor();
processor.init(swsOptions);
return function trackingMiddleware(req, res, next) {
// Respond to requests handled by swagger-stats
// swagger-stats requests will not be counted in statistics
if(req.url.startsWith(pathStats)) {
return processGetStats(req, res);
}else if(req.url.startsWith(pathMetrics)){
return processGetMetrics(req,res);
}else if(req.url.startsWith(pathLogout)){
processLogout(req,res);
return;
}else if(req.url.startsWith(pathUI) ){
res.status(200).send(uiMarkup);
return;
}else if(req.url.startsWith(pathDist)) {
var fileName = req.url.replace(pathDist+'/','');
var qidx = fileName.indexOf('?');
if(qidx!=-1) fileName = fileName.substring(0,qidx);
var options = {
root: path.join(__dirname,'..','dist'),
dotfiles: 'deny'
// TODO Caching
};
res.sendFile(fileName, options, function (err) {
if (err) {
debug('unable to send file: %s',fileName);
}
});
return;
}
handleRequest(req, res);
return next();
};
}
|
javascript
|
function (options) {
processOptions(options);
processor = new swsProcessor();
processor.init(swsOptions);
return function trackingMiddleware(req, res, next) {
// Respond to requests handled by swagger-stats
// swagger-stats requests will not be counted in statistics
if(req.url.startsWith(pathStats)) {
return processGetStats(req, res);
}else if(req.url.startsWith(pathMetrics)){
return processGetMetrics(req,res);
}else if(req.url.startsWith(pathLogout)){
processLogout(req,res);
return;
}else if(req.url.startsWith(pathUI) ){
res.status(200).send(uiMarkup);
return;
}else if(req.url.startsWith(pathDist)) {
var fileName = req.url.replace(pathDist+'/','');
var qidx = fileName.indexOf('?');
if(qidx!=-1) fileName = fileName.substring(0,qidx);
var options = {
root: path.join(__dirname,'..','dist'),
dotfiles: 'deny'
// TODO Caching
};
res.sendFile(fileName, options, function (err) {
if (err) {
debug('unable to send file: %s',fileName);
}
});
return;
}
handleRequest(req, res);
return next();
};
}
|
[
"function",
"(",
"options",
")",
"{",
"processOptions",
"(",
"options",
")",
";",
"processor",
"=",
"new",
"swsProcessor",
"(",
")",
";",
"processor",
".",
"init",
"(",
"swsOptions",
")",
";",
"return",
"function",
"trackingMiddleware",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"// Respond to requests handled by swagger-stats",
"// swagger-stats requests will not be counted in statistics",
"if",
"(",
"req",
".",
"url",
".",
"startsWith",
"(",
"pathStats",
")",
")",
"{",
"return",
"processGetStats",
"(",
"req",
",",
"res",
")",
";",
"}",
"else",
"if",
"(",
"req",
".",
"url",
".",
"startsWith",
"(",
"pathMetrics",
")",
")",
"{",
"return",
"processGetMetrics",
"(",
"req",
",",
"res",
")",
";",
"}",
"else",
"if",
"(",
"req",
".",
"url",
".",
"startsWith",
"(",
"pathLogout",
")",
")",
"{",
"processLogout",
"(",
"req",
",",
"res",
")",
";",
"return",
";",
"}",
"else",
"if",
"(",
"req",
".",
"url",
".",
"startsWith",
"(",
"pathUI",
")",
")",
"{",
"res",
".",
"status",
"(",
"200",
")",
".",
"send",
"(",
"uiMarkup",
")",
";",
"return",
";",
"}",
"else",
"if",
"(",
"req",
".",
"url",
".",
"startsWith",
"(",
"pathDist",
")",
")",
"{",
"var",
"fileName",
"=",
"req",
".",
"url",
".",
"replace",
"(",
"pathDist",
"+",
"'/'",
",",
"''",
")",
";",
"var",
"qidx",
"=",
"fileName",
".",
"indexOf",
"(",
"'?'",
")",
";",
"if",
"(",
"qidx",
"!=",
"-",
"1",
")",
"fileName",
"=",
"fileName",
".",
"substring",
"(",
"0",
",",
"qidx",
")",
";",
"var",
"options",
"=",
"{",
"root",
":",
"path",
".",
"join",
"(",
"__dirname",
",",
"'..'",
",",
"'dist'",
")",
",",
"dotfiles",
":",
"'deny'",
"// TODO Caching",
"}",
";",
"res",
".",
"sendFile",
"(",
"fileName",
",",
"options",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"debug",
"(",
"'unable to send file: %s'",
",",
"fileName",
")",
";",
"}",
"}",
")",
";",
"return",
";",
"}",
"handleRequest",
"(",
"req",
",",
"res",
")",
";",
"return",
"next",
"(",
")",
";",
"}",
";",
"}"
] |
Initialize swagger-stats and return middleware to perform API Data collection
|
[
"Initialize",
"swagger",
"-",
"stats",
"and",
"return",
"middleware",
"to",
"perform",
"API",
"Data",
"collection"
] |
94b99c98ae5fadad72c250d516333b603e9b0fc1
|
https://github.com/slanatech/swagger-stats/blob/94b99c98ae5fadad72c250d516333b603e9b0fc1/lib/swsInterface.js#L326-L369
|
|
9,258
|
rajgoel/reveal.js-plugins
|
broadcast/RTCMultiConnection.js
|
getIPs
|
function getIPs(callback) {
if (typeof document === 'undefined' || typeof document.getElementById !== 'function') {
return;
}
var ipDuplicates = {};
//compatibility for firefox and chrome
var RTCPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
var useWebKit = !!window.webkitRTCPeerConnection;
// bypass naive webrtc blocking using an iframe
if (!RTCPeerConnection) {
var iframe = document.getElementById('iframe');
if (!iframe) {
//<iframe id="iframe" sandbox="allow-same-origin" style="display: none"></iframe>
throw 'NOTE: you need to have an iframe in the page right above the script tag.';
}
var win = iframe.contentWindow;
RTCPeerConnection = win.RTCPeerConnection || win.mozRTCPeerConnection || win.webkitRTCPeerConnection;
useWebKit = !!win.webkitRTCPeerConnection;
}
// if still no RTCPeerConnection then it is not supported by the browser so just return
if (!RTCPeerConnection) {
return;
}
//minimal requirements for data connection
var mediaConstraints = {
optional: [{
RtpDataChannels: true
}]
};
//firefox already has a default stun server in about:config
// media.peerconnection.default_iceservers =
// [{"url": "stun:stun.services.mozilla.com"}]
var servers;
//add same stun server for chrome
if (useWebKit) {
servers = {
iceServers: [{
urls: 'stun:stun.services.mozilla.com'
}]
};
if (typeof DetectRTC !== 'undefined' && DetectRTC.browser.isFirefox && DetectRTC.browser.version <= 38) {
servers[0] = {
url: servers[0].urls
};
}
}
//construct a new RTCPeerConnection
var pc = new RTCPeerConnection(servers, mediaConstraints);
function handleCandidate(candidate) {
//match just the IP address
var ipRegex = /([0-9]{1,3}(\.[0-9]{1,3}){3})/;
var match = ipRegex.exec(candidate);
if (!match) {
console.warn('Could not match IP address in', candidate);
return;
}
var ipAddress = match[1];
//remove duplicates
if (ipDuplicates[ipAddress] === undefined) {
callback(ipAddress);
}
ipDuplicates[ipAddress] = true;
}
//listen for candidate events
pc.onicecandidate = function(ice) {
//skip non-candidate events
if (ice.candidate) {
handleCandidate(ice.candidate.candidate);
}
};
//create a bogus data channel
pc.createDataChannel('');
//create an offer sdp
pc.createOffer(function(result) {
//trigger the stun server request
pc.setLocalDescription(result, function() {}, function() {});
}, function() {});
//wait for a while to let everything done
setTimeout(function() {
//read candidate info from local description
var lines = pc.localDescription.sdp.split('\n');
lines.forEach(function(line) {
if (line.indexOf('a=candidate:') === 0) {
handleCandidate(line);
}
});
}, 1000);
}
|
javascript
|
function getIPs(callback) {
if (typeof document === 'undefined' || typeof document.getElementById !== 'function') {
return;
}
var ipDuplicates = {};
//compatibility for firefox and chrome
var RTCPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
var useWebKit = !!window.webkitRTCPeerConnection;
// bypass naive webrtc blocking using an iframe
if (!RTCPeerConnection) {
var iframe = document.getElementById('iframe');
if (!iframe) {
//<iframe id="iframe" sandbox="allow-same-origin" style="display: none"></iframe>
throw 'NOTE: you need to have an iframe in the page right above the script tag.';
}
var win = iframe.contentWindow;
RTCPeerConnection = win.RTCPeerConnection || win.mozRTCPeerConnection || win.webkitRTCPeerConnection;
useWebKit = !!win.webkitRTCPeerConnection;
}
// if still no RTCPeerConnection then it is not supported by the browser so just return
if (!RTCPeerConnection) {
return;
}
//minimal requirements for data connection
var mediaConstraints = {
optional: [{
RtpDataChannels: true
}]
};
//firefox already has a default stun server in about:config
// media.peerconnection.default_iceservers =
// [{"url": "stun:stun.services.mozilla.com"}]
var servers;
//add same stun server for chrome
if (useWebKit) {
servers = {
iceServers: [{
urls: 'stun:stun.services.mozilla.com'
}]
};
if (typeof DetectRTC !== 'undefined' && DetectRTC.browser.isFirefox && DetectRTC.browser.version <= 38) {
servers[0] = {
url: servers[0].urls
};
}
}
//construct a new RTCPeerConnection
var pc = new RTCPeerConnection(servers, mediaConstraints);
function handleCandidate(candidate) {
//match just the IP address
var ipRegex = /([0-9]{1,3}(\.[0-9]{1,3}){3})/;
var match = ipRegex.exec(candidate);
if (!match) {
console.warn('Could not match IP address in', candidate);
return;
}
var ipAddress = match[1];
//remove duplicates
if (ipDuplicates[ipAddress] === undefined) {
callback(ipAddress);
}
ipDuplicates[ipAddress] = true;
}
//listen for candidate events
pc.onicecandidate = function(ice) {
//skip non-candidate events
if (ice.candidate) {
handleCandidate(ice.candidate.candidate);
}
};
//create a bogus data channel
pc.createDataChannel('');
//create an offer sdp
pc.createOffer(function(result) {
//trigger the stun server request
pc.setLocalDescription(result, function() {}, function() {});
}, function() {});
//wait for a while to let everything done
setTimeout(function() {
//read candidate info from local description
var lines = pc.localDescription.sdp.split('\n');
lines.forEach(function(line) {
if (line.indexOf('a=candidate:') === 0) {
handleCandidate(line);
}
});
}, 1000);
}
|
[
"function",
"getIPs",
"(",
"callback",
")",
"{",
"if",
"(",
"typeof",
"document",
"===",
"'undefined'",
"||",
"typeof",
"document",
".",
"getElementById",
"!==",
"'function'",
")",
"{",
"return",
";",
"}",
"var",
"ipDuplicates",
"=",
"{",
"}",
";",
"//compatibility for firefox and chrome",
"var",
"RTCPeerConnection",
"=",
"window",
".",
"RTCPeerConnection",
"||",
"window",
".",
"mozRTCPeerConnection",
"||",
"window",
".",
"webkitRTCPeerConnection",
";",
"var",
"useWebKit",
"=",
"!",
"!",
"window",
".",
"webkitRTCPeerConnection",
";",
"// bypass naive webrtc blocking using an iframe",
"if",
"(",
"!",
"RTCPeerConnection",
")",
"{",
"var",
"iframe",
"=",
"document",
".",
"getElementById",
"(",
"'iframe'",
")",
";",
"if",
"(",
"!",
"iframe",
")",
"{",
"//<iframe id=\"iframe\" sandbox=\"allow-same-origin\" style=\"display: none\"></iframe>",
"throw",
"'NOTE: you need to have an iframe in the page right above the script tag.'",
";",
"}",
"var",
"win",
"=",
"iframe",
".",
"contentWindow",
";",
"RTCPeerConnection",
"=",
"win",
".",
"RTCPeerConnection",
"||",
"win",
".",
"mozRTCPeerConnection",
"||",
"win",
".",
"webkitRTCPeerConnection",
";",
"useWebKit",
"=",
"!",
"!",
"win",
".",
"webkitRTCPeerConnection",
";",
"}",
"// if still no RTCPeerConnection then it is not supported by the browser so just return",
"if",
"(",
"!",
"RTCPeerConnection",
")",
"{",
"return",
";",
"}",
"//minimal requirements for data connection",
"var",
"mediaConstraints",
"=",
"{",
"optional",
":",
"[",
"{",
"RtpDataChannels",
":",
"true",
"}",
"]",
"}",
";",
"//firefox already has a default stun server in about:config",
"// media.peerconnection.default_iceservers =",
"// [{\"url\": \"stun:stun.services.mozilla.com\"}]",
"var",
"servers",
";",
"//add same stun server for chrome",
"if",
"(",
"useWebKit",
")",
"{",
"servers",
"=",
"{",
"iceServers",
":",
"[",
"{",
"urls",
":",
"'stun:stun.services.mozilla.com'",
"}",
"]",
"}",
";",
"if",
"(",
"typeof",
"DetectRTC",
"!==",
"'undefined'",
"&&",
"DetectRTC",
".",
"browser",
".",
"isFirefox",
"&&",
"DetectRTC",
".",
"browser",
".",
"version",
"<=",
"38",
")",
"{",
"servers",
"[",
"0",
"]",
"=",
"{",
"url",
":",
"servers",
"[",
"0",
"]",
".",
"urls",
"}",
";",
"}",
"}",
"//construct a new RTCPeerConnection",
"var",
"pc",
"=",
"new",
"RTCPeerConnection",
"(",
"servers",
",",
"mediaConstraints",
")",
";",
"function",
"handleCandidate",
"(",
"candidate",
")",
"{",
"//match just the IP address",
"var",
"ipRegex",
"=",
"/",
"([0-9]{1,3}(\\.[0-9]{1,3}){3})",
"/",
";",
"var",
"match",
"=",
"ipRegex",
".",
"exec",
"(",
"candidate",
")",
";",
"if",
"(",
"!",
"match",
")",
"{",
"console",
".",
"warn",
"(",
"'Could not match IP address in'",
",",
"candidate",
")",
";",
"return",
";",
"}",
"var",
"ipAddress",
"=",
"match",
"[",
"1",
"]",
";",
"//remove duplicates",
"if",
"(",
"ipDuplicates",
"[",
"ipAddress",
"]",
"===",
"undefined",
")",
"{",
"callback",
"(",
"ipAddress",
")",
";",
"}",
"ipDuplicates",
"[",
"ipAddress",
"]",
"=",
"true",
";",
"}",
"//listen for candidate events",
"pc",
".",
"onicecandidate",
"=",
"function",
"(",
"ice",
")",
"{",
"//skip non-candidate events",
"if",
"(",
"ice",
".",
"candidate",
")",
"{",
"handleCandidate",
"(",
"ice",
".",
"candidate",
".",
"candidate",
")",
";",
"}",
"}",
";",
"//create a bogus data channel",
"pc",
".",
"createDataChannel",
"(",
"''",
")",
";",
"//create an offer sdp",
"pc",
".",
"createOffer",
"(",
"function",
"(",
"result",
")",
"{",
"//trigger the stun server request",
"pc",
".",
"setLocalDescription",
"(",
"result",
",",
"function",
"(",
")",
"{",
"}",
",",
"function",
"(",
")",
"{",
"}",
")",
";",
"}",
",",
"function",
"(",
")",
"{",
"}",
")",
";",
"//wait for a while to let everything done",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"//read candidate info from local description",
"var",
"lines",
"=",
"pc",
".",
"localDescription",
".",
"sdp",
".",
"split",
"(",
"'\\n'",
")",
";",
"lines",
".",
"forEach",
"(",
"function",
"(",
"line",
")",
"{",
"if",
"(",
"line",
".",
"indexOf",
"(",
"'a=candidate:'",
")",
"===",
"0",
")",
"{",
"handleCandidate",
"(",
"line",
")",
";",
"}",
"}",
")",
";",
"}",
",",
"1000",
")",
";",
"}"
] |
get the IP addresses associated with an account
|
[
"get",
"the",
"IP",
"addresses",
"associated",
"with",
"an",
"account"
] |
240f37227f923076dbe9a8a24bce39655200f04b
|
https://github.com/rajgoel/reveal.js-plugins/blob/240f37227f923076dbe9a8a24bce39655200f04b/broadcast/RTCMultiConnection.js#L1423-L1529
|
9,259
|
rajgoel/reveal.js-plugins
|
spreadsheet/ruleJS.all.full.js
|
getObject
|
function getObject() {
return objectPool.pop() || {
'array': null,
'cache': null,
'criteria': null,
'false': false,
'index': 0,
'null': false,
'number': null,
'object': null,
'push': null,
'string': null,
'true': false,
'undefined': false,
'value': null
};
}
|
javascript
|
function getObject() {
return objectPool.pop() || {
'array': null,
'cache': null,
'criteria': null,
'false': false,
'index': 0,
'null': false,
'number': null,
'object': null,
'push': null,
'string': null,
'true': false,
'undefined': false,
'value': null
};
}
|
[
"function",
"getObject",
"(",
")",
"{",
"return",
"objectPool",
".",
"pop",
"(",
")",
"||",
"{",
"'array'",
":",
"null",
",",
"'cache'",
":",
"null",
",",
"'criteria'",
":",
"null",
",",
"'false'",
":",
"false",
",",
"'index'",
":",
"0",
",",
"'null'",
":",
"false",
",",
"'number'",
":",
"null",
",",
"'object'",
":",
"null",
",",
"'push'",
":",
"null",
",",
"'string'",
":",
"null",
",",
"'true'",
":",
"false",
",",
"'undefined'",
":",
"false",
",",
"'value'",
":",
"null",
"}",
";",
"}"
] |
Gets an object from the object pool or creates a new one if the pool is empty.
@private
@returns {Object} The object from the pool.
|
[
"Gets",
"an",
"object",
"from",
"the",
"object",
"pool",
"or",
"creates",
"a",
"new",
"one",
"if",
"the",
"pool",
"is",
"empty",
"."
] |
240f37227f923076dbe9a8a24bce39655200f04b
|
https://github.com/rajgoel/reveal.js-plugins/blob/240f37227f923076dbe9a8a24bce39655200f04b/spreadsheet/ruleJS.all.full.js#L345-L361
|
9,260
|
rajgoel/reveal.js-plugins
|
spreadsheet/ruleJS.all.full.js
|
releaseArray
|
function releaseArray(array) {
array.length = 0;
if (arrayPool.length < maxPoolSize) {
arrayPool.push(array);
}
}
|
javascript
|
function releaseArray(array) {
array.length = 0;
if (arrayPool.length < maxPoolSize) {
arrayPool.push(array);
}
}
|
[
"function",
"releaseArray",
"(",
"array",
")",
"{",
"array",
".",
"length",
"=",
"0",
";",
"if",
"(",
"arrayPool",
".",
"length",
"<",
"maxPoolSize",
")",
"{",
"arrayPool",
".",
"push",
"(",
"array",
")",
";",
"}",
"}"
] |
Releases the given array back to the array pool.
@private
@param {Array} [array] The array to release.
|
[
"Releases",
"the",
"given",
"array",
"back",
"to",
"the",
"array",
"pool",
"."
] |
240f37227f923076dbe9a8a24bce39655200f04b
|
https://github.com/rajgoel/reveal.js-plugins/blob/240f37227f923076dbe9a8a24bce39655200f04b/spreadsheet/ruleJS.all.full.js#L369-L374
|
9,261
|
rajgoel/reveal.js-plugins
|
spreadsheet/ruleJS.all.full.js
|
releaseObject
|
function releaseObject(object) {
var cache = object.cache;
if (cache) {
releaseObject(cache);
}
object.array = object.cache = object.criteria = object.object = object.number = object.string = object.value = null;
if (objectPool.length < maxPoolSize) {
objectPool.push(object);
}
}
|
javascript
|
function releaseObject(object) {
var cache = object.cache;
if (cache) {
releaseObject(cache);
}
object.array = object.cache = object.criteria = object.object = object.number = object.string = object.value = null;
if (objectPool.length < maxPoolSize) {
objectPool.push(object);
}
}
|
[
"function",
"releaseObject",
"(",
"object",
")",
"{",
"var",
"cache",
"=",
"object",
".",
"cache",
";",
"if",
"(",
"cache",
")",
"{",
"releaseObject",
"(",
"cache",
")",
";",
"}",
"object",
".",
"array",
"=",
"object",
".",
"cache",
"=",
"object",
".",
"criteria",
"=",
"object",
".",
"object",
"=",
"object",
".",
"number",
"=",
"object",
".",
"string",
"=",
"object",
".",
"value",
"=",
"null",
";",
"if",
"(",
"objectPool",
".",
"length",
"<",
"maxPoolSize",
")",
"{",
"objectPool",
".",
"push",
"(",
"object",
")",
";",
"}",
"}"
] |
Releases the given object back to the object pool.
@private
@param {Object} [object] The object to release.
|
[
"Releases",
"the",
"given",
"object",
"back",
"to",
"the",
"object",
"pool",
"."
] |
240f37227f923076dbe9a8a24bce39655200f04b
|
https://github.com/rajgoel/reveal.js-plugins/blob/240f37227f923076dbe9a8a24bce39655200f04b/spreadsheet/ruleJS.all.full.js#L382-L391
|
9,262
|
rajgoel/reveal.js-plugins
|
spreadsheet/ruleJS.all.full.js
|
create
|
function create(prototype, properties) {
var result = baseCreate(prototype);
return properties ? assign(result, properties) : result;
}
|
javascript
|
function create(prototype, properties) {
var result = baseCreate(prototype);
return properties ? assign(result, properties) : result;
}
|
[
"function",
"create",
"(",
"prototype",
",",
"properties",
")",
"{",
"var",
"result",
"=",
"baseCreate",
"(",
"prototype",
")",
";",
"return",
"properties",
"?",
"assign",
"(",
"result",
",",
"properties",
")",
":",
"result",
";",
"}"
] |
Creates an object that inherits from the given `prototype` object. If a
`properties` object is provided its own enumerable properties are assigned
to the created object.
@static
@memberOf _
@category Objects
@param {Object} prototype The object to inherit from.
@param {Object} [properties] The properties to assign to the object.
@returns {Object} Returns the new object.
@example
function Shape() {
this.x = 0;
this.y = 0;
}
function Circle() {
Shape.call(this);
}
Circle.prototype = _.create(Shape.prototype, { 'constructor': Circle });
var circle = new Circle;
circle instanceof Circle;
// => true
circle instanceof Shape;
// => true
|
[
"Creates",
"an",
"object",
"that",
"inherits",
"from",
"the",
"given",
"prototype",
"object",
".",
"If",
"a",
"properties",
"object",
"is",
"provided",
"its",
"own",
"enumerable",
"properties",
"are",
"assigned",
"to",
"the",
"created",
"object",
"."
] |
240f37227f923076dbe9a8a24bce39655200f04b
|
https://github.com/rajgoel/reveal.js-plugins/blob/240f37227f923076dbe9a8a24bce39655200f04b/spreadsheet/ruleJS.all.full.js#L1833-L1836
|
9,263
|
rajgoel/reveal.js-plugins
|
spreadsheet/ruleJS.all.full.js
|
memoize
|
function memoize(func, resolver) {
if (!isFunction(func)) {
throw new TypeError;
}
var memoized = function() {
var cache = memoized.cache,
key = resolver ? resolver.apply(this, arguments) : keyPrefix + arguments[0];
return hasOwnProperty.call(cache, key)
? cache[key]
: (cache[key] = func.apply(this, arguments));
}
memoized.cache = {};
return memoized;
}
|
javascript
|
function memoize(func, resolver) {
if (!isFunction(func)) {
throw new TypeError;
}
var memoized = function() {
var cache = memoized.cache,
key = resolver ? resolver.apply(this, arguments) : keyPrefix + arguments[0];
return hasOwnProperty.call(cache, key)
? cache[key]
: (cache[key] = func.apply(this, arguments));
}
memoized.cache = {};
return memoized;
}
|
[
"function",
"memoize",
"(",
"func",
",",
"resolver",
")",
"{",
"if",
"(",
"!",
"isFunction",
"(",
"func",
")",
")",
"{",
"throw",
"new",
"TypeError",
";",
"}",
"var",
"memoized",
"=",
"function",
"(",
")",
"{",
"var",
"cache",
"=",
"memoized",
".",
"cache",
",",
"key",
"=",
"resolver",
"?",
"resolver",
".",
"apply",
"(",
"this",
",",
"arguments",
")",
":",
"keyPrefix",
"+",
"arguments",
"[",
"0",
"]",
";",
"return",
"hasOwnProperty",
".",
"call",
"(",
"cache",
",",
"key",
")",
"?",
"cache",
"[",
"key",
"]",
":",
"(",
"cache",
"[",
"key",
"]",
"=",
"func",
".",
"apply",
"(",
"this",
",",
"arguments",
")",
")",
";",
"}",
"memoized",
".",
"cache",
"=",
"{",
"}",
";",
"return",
"memoized",
";",
"}"
] |
Creates a function that memoizes the result of `func`. If `resolver` is
provided it will be used to determine the cache key for storing the result
based on the arguments provided to the memoized function. By default, the
first argument provided to the memoized function is used as the cache key.
The `func` is executed with the `this` binding of the memoized function.
The result cache is exposed as the `cache` property on the memoized function.
@static
@memberOf _
@category Functions
@param {Function} func The function to have its output memoized.
@param {Function} [resolver] A function used to resolve the cache key.
@returns {Function} Returns the new memoizing function.
@example
var fibonacci = _.memoize(function(n) {
return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2);
});
fibonacci(9)
// => 34
var data = {
'fred': { 'name': 'fred', 'age': 40 },
'pebbles': { 'name': 'pebbles', 'age': 1 }
};
// modifying the result cache
var get = _.memoize(function(name) { return data[name]; }, _.identity);
get('pebbles');
// => { 'name': 'pebbles', 'age': 1 }
get.cache.pebbles.name = 'penelope';
get('pebbles');
// => { 'name': 'penelope', 'age': 1 }
|
[
"Creates",
"a",
"function",
"that",
"memoizes",
"the",
"result",
"of",
"func",
".",
"If",
"resolver",
"is",
"provided",
"it",
"will",
"be",
"used",
"to",
"determine",
"the",
"cache",
"key",
"for",
"storing",
"the",
"result",
"based",
"on",
"the",
"arguments",
"provided",
"to",
"the",
"memoized",
"function",
".",
"By",
"default",
"the",
"first",
"argument",
"provided",
"to",
"the",
"memoized",
"function",
"is",
"used",
"as",
"the",
"cache",
"key",
".",
"The",
"func",
"is",
"executed",
"with",
"the",
"this",
"binding",
"of",
"the",
"memoized",
"function",
".",
"The",
"result",
"cache",
"is",
"exposed",
"as",
"the",
"cache",
"property",
"on",
"the",
"memoized",
"function",
"."
] |
240f37227f923076dbe9a8a24bce39655200f04b
|
https://github.com/rajgoel/reveal.js-plugins/blob/240f37227f923076dbe9a8a24bce39655200f04b/spreadsheet/ruleJS.all.full.js#L5559-L5573
|
9,264
|
rajgoel/reveal.js-plugins
|
spreadsheet/ruleJS.all.full.js
|
boolMatch
|
function boolMatch(s, matchers) {
var i, matcher, down = s.toLowerCase();
matchers = [].concat(matchers);
for (i = 0; i < matchers.length; i += 1) {
matcher = matchers[i];
if (!matcher) continue;
if (matcher.test && matcher.test(s)) return true;
if (matcher.toLowerCase() === down) return true;
}
}
|
javascript
|
function boolMatch(s, matchers) {
var i, matcher, down = s.toLowerCase();
matchers = [].concat(matchers);
for (i = 0; i < matchers.length; i += 1) {
matcher = matchers[i];
if (!matcher) continue;
if (matcher.test && matcher.test(s)) return true;
if (matcher.toLowerCase() === down) return true;
}
}
|
[
"function",
"boolMatch",
"(",
"s",
",",
"matchers",
")",
"{",
"var",
"i",
",",
"matcher",
",",
"down",
"=",
"s",
".",
"toLowerCase",
"(",
")",
";",
"matchers",
"=",
"[",
"]",
".",
"concat",
"(",
"matchers",
")",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"matchers",
".",
"length",
";",
"i",
"+=",
"1",
")",
"{",
"matcher",
"=",
"matchers",
"[",
"i",
"]",
";",
"if",
"(",
"!",
"matcher",
")",
"continue",
";",
"if",
"(",
"matcher",
".",
"test",
"&&",
"matcher",
".",
"test",
"(",
"s",
")",
")",
"return",
"true",
";",
"if",
"(",
"matcher",
".",
"toLowerCase",
"(",
")",
"===",
"down",
")",
"return",
"true",
";",
"}",
"}"
] |
Helper for toBoolean
|
[
"Helper",
"for",
"toBoolean"
] |
240f37227f923076dbe9a8a24bce39655200f04b
|
https://github.com/rajgoel/reveal.js-plugins/blob/240f37227f923076dbe9a8a24bce39655200f04b/spreadsheet/ruleJS.all.full.js#L6831-L6840
|
9,265
|
rajgoel/reveal.js-plugins
|
spreadsheet/ruleJS.all.full.js
|
compareArrays
|
function compareArrays(array1, array2, dontConvert) {
var len = Math.min(array1.length, array2.length),
lengthDiff = Math.abs(array1.length - array2.length),
diffs = 0,
i;
for (i = 0; i < len; i++) {
if ((dontConvert && array1[i] !== array2[i]) ||
(!dontConvert && toInt(array1[i]) !== toInt(array2[i]))) {
diffs++;
}
}
return diffs + lengthDiff;
}
|
javascript
|
function compareArrays(array1, array2, dontConvert) {
var len = Math.min(array1.length, array2.length),
lengthDiff = Math.abs(array1.length - array2.length),
diffs = 0,
i;
for (i = 0; i < len; i++) {
if ((dontConvert && array1[i] !== array2[i]) ||
(!dontConvert && toInt(array1[i]) !== toInt(array2[i]))) {
diffs++;
}
}
return diffs + lengthDiff;
}
|
[
"function",
"compareArrays",
"(",
"array1",
",",
"array2",
",",
"dontConvert",
")",
"{",
"var",
"len",
"=",
"Math",
".",
"min",
"(",
"array1",
".",
"length",
",",
"array2",
".",
"length",
")",
",",
"lengthDiff",
"=",
"Math",
".",
"abs",
"(",
"array1",
".",
"length",
"-",
"array2",
".",
"length",
")",
",",
"diffs",
"=",
"0",
",",
"i",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"if",
"(",
"(",
"dontConvert",
"&&",
"array1",
"[",
"i",
"]",
"!==",
"array2",
"[",
"i",
"]",
")",
"||",
"(",
"!",
"dontConvert",
"&&",
"toInt",
"(",
"array1",
"[",
"i",
"]",
")",
"!==",
"toInt",
"(",
"array2",
"[",
"i",
"]",
")",
")",
")",
"{",
"diffs",
"++",
";",
"}",
"}",
"return",
"diffs",
"+",
"lengthDiff",
";",
"}"
] |
compare two arrays, return the number of differences
|
[
"compare",
"two",
"arrays",
"return",
"the",
"number",
"of",
"differences"
] |
240f37227f923076dbe9a8a24bce39655200f04b
|
https://github.com/rajgoel/reveal.js-plugins/blob/240f37227f923076dbe9a8a24bce39655200f04b/spreadsheet/ruleJS.all.full.js#L7885-L7897
|
9,266
|
rajgoel/reveal.js-plugins
|
spreadsheet/ruleJS.all.full.js
|
getLangDefinition
|
function getLangDefinition(key) {
var i = 0, j, lang, next, split,
get = function (k) {
if (!languages[k] && hasModule) {
try {
require('./lang/' + k);
} catch (e) { }
}
return languages[k];
};
if (!key) {
return moment.fn._lang;
}
if (!isArray(key)) {
//short-circuit everything else
lang = get(key);
if (lang) {
return lang;
}
key = [key];
}
//pick the language from the array
//try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each
//substring from most specific to least, but move to the next array item if it's a more specific variant than the current root
while (i < key.length) {
split = normalizeLanguage(key[i]).split('-');
j = split.length;
next = normalizeLanguage(key[i + 1]);
next = next ? next.split('-') : null;
while (j > 0) {
lang = get(split.slice(0, j).join('-'));
if (lang) {
return lang;
}
if (next && next.length >= j && compareArrays(split, next, true) >= j - 1) {
//the next array item is better than a shallower substring of this one
break;
}
j--;
}
i++;
}
return moment.fn._lang;
}
|
javascript
|
function getLangDefinition(key) {
var i = 0, j, lang, next, split,
get = function (k) {
if (!languages[k] && hasModule) {
try {
require('./lang/' + k);
} catch (e) { }
}
return languages[k];
};
if (!key) {
return moment.fn._lang;
}
if (!isArray(key)) {
//short-circuit everything else
lang = get(key);
if (lang) {
return lang;
}
key = [key];
}
//pick the language from the array
//try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each
//substring from most specific to least, but move to the next array item if it's a more specific variant than the current root
while (i < key.length) {
split = normalizeLanguage(key[i]).split('-');
j = split.length;
next = normalizeLanguage(key[i + 1]);
next = next ? next.split('-') : null;
while (j > 0) {
lang = get(split.slice(0, j).join('-'));
if (lang) {
return lang;
}
if (next && next.length >= j && compareArrays(split, next, true) >= j - 1) {
//the next array item is better than a shallower substring of this one
break;
}
j--;
}
i++;
}
return moment.fn._lang;
}
|
[
"function",
"getLangDefinition",
"(",
"key",
")",
"{",
"var",
"i",
"=",
"0",
",",
"j",
",",
"lang",
",",
"next",
",",
"split",
",",
"get",
"=",
"function",
"(",
"k",
")",
"{",
"if",
"(",
"!",
"languages",
"[",
"k",
"]",
"&&",
"hasModule",
")",
"{",
"try",
"{",
"require",
"(",
"'./lang/'",
"+",
"k",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"}",
"}",
"return",
"languages",
"[",
"k",
"]",
";",
"}",
";",
"if",
"(",
"!",
"key",
")",
"{",
"return",
"moment",
".",
"fn",
".",
"_lang",
";",
"}",
"if",
"(",
"!",
"isArray",
"(",
"key",
")",
")",
"{",
"//short-circuit everything else",
"lang",
"=",
"get",
"(",
"key",
")",
";",
"if",
"(",
"lang",
")",
"{",
"return",
"lang",
";",
"}",
"key",
"=",
"[",
"key",
"]",
";",
"}",
"//pick the language from the array",
"//try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each",
"//substring from most specific to least, but move to the next array item if it's a more specific variant than the current root",
"while",
"(",
"i",
"<",
"key",
".",
"length",
")",
"{",
"split",
"=",
"normalizeLanguage",
"(",
"key",
"[",
"i",
"]",
")",
".",
"split",
"(",
"'-'",
")",
";",
"j",
"=",
"split",
".",
"length",
";",
"next",
"=",
"normalizeLanguage",
"(",
"key",
"[",
"i",
"+",
"1",
"]",
")",
";",
"next",
"=",
"next",
"?",
"next",
".",
"split",
"(",
"'-'",
")",
":",
"null",
";",
"while",
"(",
"j",
">",
"0",
")",
"{",
"lang",
"=",
"get",
"(",
"split",
".",
"slice",
"(",
"0",
",",
"j",
")",
".",
"join",
"(",
"'-'",
")",
")",
";",
"if",
"(",
"lang",
")",
"{",
"return",
"lang",
";",
"}",
"if",
"(",
"next",
"&&",
"next",
".",
"length",
">=",
"j",
"&&",
"compareArrays",
"(",
"split",
",",
"next",
",",
"true",
")",
">=",
"j",
"-",
"1",
")",
"{",
"//the next array item is better than a shallower substring of this one",
"break",
";",
"}",
"j",
"--",
";",
"}",
"i",
"++",
";",
"}",
"return",
"moment",
".",
"fn",
".",
"_lang",
";",
"}"
] |
Determines which language definition to use and returns it. With no parameters, it will return the global language. If you pass in a language key, such as 'en', it will return the definition for 'en', so long as 'en' has already been loaded using moment.lang.
|
[
"Determines",
"which",
"language",
"definition",
"to",
"use",
"and",
"returns",
"it",
".",
"With",
"no",
"parameters",
"it",
"will",
"return",
"the",
"global",
"language",
".",
"If",
"you",
"pass",
"in",
"a",
"language",
"key",
"such",
"as",
"en",
"it",
"will",
"return",
"the",
"definition",
"for",
"en",
"so",
"long",
"as",
"en",
"has",
"already",
"been",
"loaded",
"using",
"moment",
".",
"lang",
"."
] |
240f37227f923076dbe9a8a24bce39655200f04b
|
https://github.com/rajgoel/reveal.js-plugins/blob/240f37227f923076dbe9a8a24bce39655200f04b/spreadsheet/ruleJS.all.full.js#L8267-L8313
|
9,267
|
rajgoel/reveal.js-plugins
|
spreadsheet/ruleJS.all.full.js
|
makeGetterAndSetter
|
function makeGetterAndSetter(name, key) {
moment.fn[name] = moment.fn[name + 's'] = function (input) {
var utc = this._isUTC ? 'UTC' : '';
if (input != null) {
this._d['set' + utc + key](input);
moment.updateOffset(this);
return this;
} else {
return this._d['get' + utc + key]();
}
};
}
|
javascript
|
function makeGetterAndSetter(name, key) {
moment.fn[name] = moment.fn[name + 's'] = function (input) {
var utc = this._isUTC ? 'UTC' : '';
if (input != null) {
this._d['set' + utc + key](input);
moment.updateOffset(this);
return this;
} else {
return this._d['get' + utc + key]();
}
};
}
|
[
"function",
"makeGetterAndSetter",
"(",
"name",
",",
"key",
")",
"{",
"moment",
".",
"fn",
"[",
"name",
"]",
"=",
"moment",
".",
"fn",
"[",
"name",
"+",
"'s'",
"]",
"=",
"function",
"(",
"input",
")",
"{",
"var",
"utc",
"=",
"this",
".",
"_isUTC",
"?",
"'UTC'",
":",
"''",
";",
"if",
"(",
"input",
"!=",
"null",
")",
"{",
"this",
".",
"_d",
"[",
"'set'",
"+",
"utc",
"+",
"key",
"]",
"(",
"input",
")",
";",
"moment",
".",
"updateOffset",
"(",
"this",
")",
";",
"return",
"this",
";",
"}",
"else",
"{",
"return",
"this",
".",
"_d",
"[",
"'get'",
"+",
"utc",
"+",
"key",
"]",
"(",
")",
";",
"}",
"}",
";",
"}"
] |
helper for adding shortcuts
|
[
"helper",
"for",
"adding",
"shortcuts"
] |
240f37227f923076dbe9a8a24bce39655200f04b
|
https://github.com/rajgoel/reveal.js-plugins/blob/240f37227f923076dbe9a8a24bce39655200f04b/spreadsheet/ruleJS.all.full.js#L9584-L9595
|
9,268
|
rajgoel/reveal.js-plugins
|
spreadsheet/ruleJS.all.full.js
|
unformatNumeral
|
function unformatNumeral (n, string) {
var stringOriginal = string,
thousandRegExp,
millionRegExp,
billionRegExp,
trillionRegExp,
suffixes = ['KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
bytesMultiplier = false,
power;
if (string.indexOf(':') > -1) {
n._value = unformatTime(string);
} else {
if (string === zeroFormat) {
n._value = 0;
} else {
if (languages[currentLanguage].delimiters.decimal !== '.') {
string = string.replace(/\./g,'').replace(languages[currentLanguage].delimiters.decimal, '.');
}
// see if abbreviations are there so that we can multiply to the correct number
thousandRegExp = new RegExp('[^a-zA-Z]' + languages[currentLanguage].abbreviations.thousand + '(?:\\)|(\\' + languages[currentLanguage].currency.symbol + ')?(?:\\))?)?$');
millionRegExp = new RegExp('[^a-zA-Z]' + languages[currentLanguage].abbreviations.million + '(?:\\)|(\\' + languages[currentLanguage].currency.symbol + ')?(?:\\))?)?$');
billionRegExp = new RegExp('[^a-zA-Z]' + languages[currentLanguage].abbreviations.billion + '(?:\\)|(\\' + languages[currentLanguage].currency.symbol + ')?(?:\\))?)?$');
trillionRegExp = new RegExp('[^a-zA-Z]' + languages[currentLanguage].abbreviations.trillion + '(?:\\)|(\\' + languages[currentLanguage].currency.symbol + ')?(?:\\))?)?$');
// see if bytes are there so that we can multiply to the correct number
for (power = 0; power <= suffixes.length; power++) {
bytesMultiplier = (string.indexOf(suffixes[power]) > -1) ? Math.pow(1024, power + 1) : false;
if (bytesMultiplier) {
break;
}
}
// do some math to create our number
n._value = ((bytesMultiplier) ? bytesMultiplier : 1) * ((stringOriginal.match(thousandRegExp)) ? Math.pow(10, 3) : 1) * ((stringOriginal.match(millionRegExp)) ? Math.pow(10, 6) : 1) * ((stringOriginal.match(billionRegExp)) ? Math.pow(10, 9) : 1) * ((stringOriginal.match(trillionRegExp)) ? Math.pow(10, 12) : 1) * ((string.indexOf('%') > -1) ? 0.01 : 1) * (((string.split('-').length + Math.min(string.split('(').length-1, string.split(')').length-1)) % 2)? 1: -1) * Number(string.replace(/[^0-9\.]+/g, ''));
// round if we are talking about bytes
n._value = (bytesMultiplier) ? Math.ceil(n._value) : n._value;
}
}
return n._value;
}
|
javascript
|
function unformatNumeral (n, string) {
var stringOriginal = string,
thousandRegExp,
millionRegExp,
billionRegExp,
trillionRegExp,
suffixes = ['KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
bytesMultiplier = false,
power;
if (string.indexOf(':') > -1) {
n._value = unformatTime(string);
} else {
if (string === zeroFormat) {
n._value = 0;
} else {
if (languages[currentLanguage].delimiters.decimal !== '.') {
string = string.replace(/\./g,'').replace(languages[currentLanguage].delimiters.decimal, '.');
}
// see if abbreviations are there so that we can multiply to the correct number
thousandRegExp = new RegExp('[^a-zA-Z]' + languages[currentLanguage].abbreviations.thousand + '(?:\\)|(\\' + languages[currentLanguage].currency.symbol + ')?(?:\\))?)?$');
millionRegExp = new RegExp('[^a-zA-Z]' + languages[currentLanguage].abbreviations.million + '(?:\\)|(\\' + languages[currentLanguage].currency.symbol + ')?(?:\\))?)?$');
billionRegExp = new RegExp('[^a-zA-Z]' + languages[currentLanguage].abbreviations.billion + '(?:\\)|(\\' + languages[currentLanguage].currency.symbol + ')?(?:\\))?)?$');
trillionRegExp = new RegExp('[^a-zA-Z]' + languages[currentLanguage].abbreviations.trillion + '(?:\\)|(\\' + languages[currentLanguage].currency.symbol + ')?(?:\\))?)?$');
// see if bytes are there so that we can multiply to the correct number
for (power = 0; power <= suffixes.length; power++) {
bytesMultiplier = (string.indexOf(suffixes[power]) > -1) ? Math.pow(1024, power + 1) : false;
if (bytesMultiplier) {
break;
}
}
// do some math to create our number
n._value = ((bytesMultiplier) ? bytesMultiplier : 1) * ((stringOriginal.match(thousandRegExp)) ? Math.pow(10, 3) : 1) * ((stringOriginal.match(millionRegExp)) ? Math.pow(10, 6) : 1) * ((stringOriginal.match(billionRegExp)) ? Math.pow(10, 9) : 1) * ((stringOriginal.match(trillionRegExp)) ? Math.pow(10, 12) : 1) * ((string.indexOf('%') > -1) ? 0.01 : 1) * (((string.split('-').length + Math.min(string.split('(').length-1, string.split(')').length-1)) % 2)? 1: -1) * Number(string.replace(/[^0-9\.]+/g, ''));
// round if we are talking about bytes
n._value = (bytesMultiplier) ? Math.ceil(n._value) : n._value;
}
}
return n._value;
}
|
[
"function",
"unformatNumeral",
"(",
"n",
",",
"string",
")",
"{",
"var",
"stringOriginal",
"=",
"string",
",",
"thousandRegExp",
",",
"millionRegExp",
",",
"billionRegExp",
",",
"trillionRegExp",
",",
"suffixes",
"=",
"[",
"'KB'",
",",
"'MB'",
",",
"'GB'",
",",
"'TB'",
",",
"'PB'",
",",
"'EB'",
",",
"'ZB'",
",",
"'YB'",
"]",
",",
"bytesMultiplier",
"=",
"false",
",",
"power",
";",
"if",
"(",
"string",
".",
"indexOf",
"(",
"':'",
")",
">",
"-",
"1",
")",
"{",
"n",
".",
"_value",
"=",
"unformatTime",
"(",
"string",
")",
";",
"}",
"else",
"{",
"if",
"(",
"string",
"===",
"zeroFormat",
")",
"{",
"n",
".",
"_value",
"=",
"0",
";",
"}",
"else",
"{",
"if",
"(",
"languages",
"[",
"currentLanguage",
"]",
".",
"delimiters",
".",
"decimal",
"!==",
"'.'",
")",
"{",
"string",
"=",
"string",
".",
"replace",
"(",
"/",
"\\.",
"/",
"g",
",",
"''",
")",
".",
"replace",
"(",
"languages",
"[",
"currentLanguage",
"]",
".",
"delimiters",
".",
"decimal",
",",
"'.'",
")",
";",
"}",
"// see if abbreviations are there so that we can multiply to the correct number",
"thousandRegExp",
"=",
"new",
"RegExp",
"(",
"'[^a-zA-Z]'",
"+",
"languages",
"[",
"currentLanguage",
"]",
".",
"abbreviations",
".",
"thousand",
"+",
"'(?:\\\\)|(\\\\'",
"+",
"languages",
"[",
"currentLanguage",
"]",
".",
"currency",
".",
"symbol",
"+",
"')?(?:\\\\))?)?$'",
")",
";",
"millionRegExp",
"=",
"new",
"RegExp",
"(",
"'[^a-zA-Z]'",
"+",
"languages",
"[",
"currentLanguage",
"]",
".",
"abbreviations",
".",
"million",
"+",
"'(?:\\\\)|(\\\\'",
"+",
"languages",
"[",
"currentLanguage",
"]",
".",
"currency",
".",
"symbol",
"+",
"')?(?:\\\\))?)?$'",
")",
";",
"billionRegExp",
"=",
"new",
"RegExp",
"(",
"'[^a-zA-Z]'",
"+",
"languages",
"[",
"currentLanguage",
"]",
".",
"abbreviations",
".",
"billion",
"+",
"'(?:\\\\)|(\\\\'",
"+",
"languages",
"[",
"currentLanguage",
"]",
".",
"currency",
".",
"symbol",
"+",
"')?(?:\\\\))?)?$'",
")",
";",
"trillionRegExp",
"=",
"new",
"RegExp",
"(",
"'[^a-zA-Z]'",
"+",
"languages",
"[",
"currentLanguage",
"]",
".",
"abbreviations",
".",
"trillion",
"+",
"'(?:\\\\)|(\\\\'",
"+",
"languages",
"[",
"currentLanguage",
"]",
".",
"currency",
".",
"symbol",
"+",
"')?(?:\\\\))?)?$'",
")",
";",
"// see if bytes are there so that we can multiply to the correct number",
"for",
"(",
"power",
"=",
"0",
";",
"power",
"<=",
"suffixes",
".",
"length",
";",
"power",
"++",
")",
"{",
"bytesMultiplier",
"=",
"(",
"string",
".",
"indexOf",
"(",
"suffixes",
"[",
"power",
"]",
")",
">",
"-",
"1",
")",
"?",
"Math",
".",
"pow",
"(",
"1024",
",",
"power",
"+",
"1",
")",
":",
"false",
";",
"if",
"(",
"bytesMultiplier",
")",
"{",
"break",
";",
"}",
"}",
"// do some math to create our number",
"n",
".",
"_value",
"=",
"(",
"(",
"bytesMultiplier",
")",
"?",
"bytesMultiplier",
":",
"1",
")",
"*",
"(",
"(",
"stringOriginal",
".",
"match",
"(",
"thousandRegExp",
")",
")",
"?",
"Math",
".",
"pow",
"(",
"10",
",",
"3",
")",
":",
"1",
")",
"*",
"(",
"(",
"stringOriginal",
".",
"match",
"(",
"millionRegExp",
")",
")",
"?",
"Math",
".",
"pow",
"(",
"10",
",",
"6",
")",
":",
"1",
")",
"*",
"(",
"(",
"stringOriginal",
".",
"match",
"(",
"billionRegExp",
")",
")",
"?",
"Math",
".",
"pow",
"(",
"10",
",",
"9",
")",
":",
"1",
")",
"*",
"(",
"(",
"stringOriginal",
".",
"match",
"(",
"trillionRegExp",
")",
")",
"?",
"Math",
".",
"pow",
"(",
"10",
",",
"12",
")",
":",
"1",
")",
"*",
"(",
"(",
"string",
".",
"indexOf",
"(",
"'%'",
")",
">",
"-",
"1",
")",
"?",
"0.01",
":",
"1",
")",
"*",
"(",
"(",
"(",
"string",
".",
"split",
"(",
"'-'",
")",
".",
"length",
"+",
"Math",
".",
"min",
"(",
"string",
".",
"split",
"(",
"'('",
")",
".",
"length",
"-",
"1",
",",
"string",
".",
"split",
"(",
"')'",
")",
".",
"length",
"-",
"1",
")",
")",
"%",
"2",
")",
"?",
"1",
":",
"-",
"1",
")",
"*",
"Number",
"(",
"string",
".",
"replace",
"(",
"/",
"[^0-9\\.]+",
"/",
"g",
",",
"''",
")",
")",
";",
"// round if we are talking about bytes",
"n",
".",
"_value",
"=",
"(",
"bytesMultiplier",
")",
"?",
"Math",
".",
"ceil",
"(",
"n",
".",
"_value",
")",
":",
"n",
".",
"_value",
";",
"}",
"}",
"return",
"n",
".",
"_value",
";",
"}"
] |
revert to number
|
[
"revert",
"to",
"number"
] |
240f37227f923076dbe9a8a24bce39655200f04b
|
https://github.com/rajgoel/reveal.js-plugins/blob/240f37227f923076dbe9a8a24bce39655200f04b/spreadsheet/ruleJS.all.full.js#L9911-L9954
|
9,269
|
rajgoel/reveal.js-plugins
|
spreadsheet/ruleJS.all.full.js
|
multiplier
|
function multiplier(x) {
var parts = x.toString().split('.');
if (parts.length < 2) {
return 1;
}
return Math.pow(10, parts[1].length);
}
|
javascript
|
function multiplier(x) {
var parts = x.toString().split('.');
if (parts.length < 2) {
return 1;
}
return Math.pow(10, parts[1].length);
}
|
[
"function",
"multiplier",
"(",
"x",
")",
"{",
"var",
"parts",
"=",
"x",
".",
"toString",
"(",
")",
".",
"split",
"(",
"'.'",
")",
";",
"if",
"(",
"parts",
".",
"length",
"<",
"2",
")",
"{",
"return",
"1",
";",
"}",
"return",
"Math",
".",
"pow",
"(",
"10",
",",
"parts",
"[",
"1",
"]",
".",
"length",
")",
";",
"}"
] |
Computes the multiplier necessary to make x >= 1,
effectively eliminating miscalculations caused by
finite precision.
|
[
"Computes",
"the",
"multiplier",
"necessary",
"to",
"make",
"x",
">",
"=",
"1",
"effectively",
"eliminating",
"miscalculations",
"caused",
"by",
"finite",
"precision",
"."
] |
240f37227f923076dbe9a8a24bce39655200f04b
|
https://github.com/rajgoel/reveal.js-plugins/blob/240f37227f923076dbe9a8a24bce39655200f04b/spreadsheet/ruleJS.all.full.js#L10475-L10481
|
9,270
|
rajgoel/reveal.js-plugins
|
spreadsheet/ruleJS.all.full.js
|
correctionFactor
|
function correctionFactor() {
var args = Array.prototype.slice.call(arguments);
return args.reduce(function (prev, next) {
var mp = multiplier(prev),
mn = multiplier(next);
return mp > mn ? mp : mn;
}, -Infinity);
}
|
javascript
|
function correctionFactor() {
var args = Array.prototype.slice.call(arguments);
return args.reduce(function (prev, next) {
var mp = multiplier(prev),
mn = multiplier(next);
return mp > mn ? mp : mn;
}, -Infinity);
}
|
[
"function",
"correctionFactor",
"(",
")",
"{",
"var",
"args",
"=",
"Array",
".",
"prototype",
".",
"slice",
".",
"call",
"(",
"arguments",
")",
";",
"return",
"args",
".",
"reduce",
"(",
"function",
"(",
"prev",
",",
"next",
")",
"{",
"var",
"mp",
"=",
"multiplier",
"(",
"prev",
")",
",",
"mn",
"=",
"multiplier",
"(",
"next",
")",
";",
"return",
"mp",
">",
"mn",
"?",
"mp",
":",
"mn",
";",
"}",
",",
"-",
"Infinity",
")",
";",
"}"
] |
Given a variable number of arguments, returns the maximum
multiplier that must be used to normalize an operation involving
all of them.
|
[
"Given",
"a",
"variable",
"number",
"of",
"arguments",
"returns",
"the",
"maximum",
"multiplier",
"that",
"must",
"be",
"used",
"to",
"normalize",
"an",
"operation",
"involving",
"all",
"of",
"them",
"."
] |
240f37227f923076dbe9a8a24bce39655200f04b
|
https://github.com/rajgoel/reveal.js-plugins/blob/240f37227f923076dbe9a8a24bce39655200f04b/spreadsheet/ruleJS.all.full.js#L10488-L10495
|
9,271
|
rajgoel/reveal.js-plugins
|
spreadsheet/ruleJS.all.full.js
|
dot
|
function dot(arr, arg) {
if (!isArray(arr[0])) arr = [ arr ];
if (!isArray(arg[0])) arg = [ arg ];
// convert column to row vector
var left = (arr[0].length === 1 && arr.length !== 1) ? jStat.transpose(arr) : arr,
right = (arg[0].length === 1 && arg.length !== 1) ? jStat.transpose(arg) : arg,
res = [],
row = 0,
nrow = left.length,
ncol = left[0].length,
sum, col;
for (; row < nrow; row++) {
res[row] = [];
sum = 0;
for (col = 0; col < ncol; col++)
sum += left[row][col] * right[row][col];
res[row] = sum;
}
return (res.length === 1) ? res[0] : res;
}
|
javascript
|
function dot(arr, arg) {
if (!isArray(arr[0])) arr = [ arr ];
if (!isArray(arg[0])) arg = [ arg ];
// convert column to row vector
var left = (arr[0].length === 1 && arr.length !== 1) ? jStat.transpose(arr) : arr,
right = (arg[0].length === 1 && arg.length !== 1) ? jStat.transpose(arg) : arg,
res = [],
row = 0,
nrow = left.length,
ncol = left[0].length,
sum, col;
for (; row < nrow; row++) {
res[row] = [];
sum = 0;
for (col = 0; col < ncol; col++)
sum += left[row][col] * right[row][col];
res[row] = sum;
}
return (res.length === 1) ? res[0] : res;
}
|
[
"function",
"dot",
"(",
"arr",
",",
"arg",
")",
"{",
"if",
"(",
"!",
"isArray",
"(",
"arr",
"[",
"0",
"]",
")",
")",
"arr",
"=",
"[",
"arr",
"]",
";",
"if",
"(",
"!",
"isArray",
"(",
"arg",
"[",
"0",
"]",
")",
")",
"arg",
"=",
"[",
"arg",
"]",
";",
"// convert column to row vector",
"var",
"left",
"=",
"(",
"arr",
"[",
"0",
"]",
".",
"length",
"===",
"1",
"&&",
"arr",
".",
"length",
"!==",
"1",
")",
"?",
"jStat",
".",
"transpose",
"(",
"arr",
")",
":",
"arr",
",",
"right",
"=",
"(",
"arg",
"[",
"0",
"]",
".",
"length",
"===",
"1",
"&&",
"arg",
".",
"length",
"!==",
"1",
")",
"?",
"jStat",
".",
"transpose",
"(",
"arg",
")",
":",
"arg",
",",
"res",
"=",
"[",
"]",
",",
"row",
"=",
"0",
",",
"nrow",
"=",
"left",
".",
"length",
",",
"ncol",
"=",
"left",
"[",
"0",
"]",
".",
"length",
",",
"sum",
",",
"col",
";",
"for",
"(",
";",
"row",
"<",
"nrow",
";",
"row",
"++",
")",
"{",
"res",
"[",
"row",
"]",
"=",
"[",
"]",
";",
"sum",
"=",
"0",
";",
"for",
"(",
"col",
"=",
"0",
";",
"col",
"<",
"ncol",
";",
"col",
"++",
")",
"sum",
"+=",
"left",
"[",
"row",
"]",
"[",
"col",
"]",
"*",
"right",
"[",
"row",
"]",
"[",
"col",
"]",
";",
"res",
"[",
"row",
"]",
"=",
"sum",
";",
"}",
"return",
"(",
"res",
".",
"length",
"===",
"1",
")",
"?",
"res",
"[",
"0",
"]",
":",
"res",
";",
"}"
] |
Returns the dot product of two matricies
|
[
"Returns",
"the",
"dot",
"product",
"of",
"two",
"matricies"
] |
240f37227f923076dbe9a8a24bce39655200f04b
|
https://github.com/rajgoel/reveal.js-plugins/blob/240f37227f923076dbe9a8a24bce39655200f04b/spreadsheet/ruleJS.all.full.js#L13185-L13204
|
9,272
|
rajgoel/reveal.js-plugins
|
spreadsheet/ruleJS.all.full.js
|
pow
|
function pow(arr, arg) {
return jStat.map(arr, function(value) { return Math.pow(value, arg); });
}
|
javascript
|
function pow(arr, arg) {
return jStat.map(arr, function(value) { return Math.pow(value, arg); });
}
|
[
"function",
"pow",
"(",
"arr",
",",
"arg",
")",
"{",
"return",
"jStat",
".",
"map",
"(",
"arr",
",",
"function",
"(",
"value",
")",
"{",
"return",
"Math",
".",
"pow",
"(",
"value",
",",
"arg",
")",
";",
"}",
")",
";",
"}"
] |
raise every element by a scalar
|
[
"raise",
"every",
"element",
"by",
"a",
"scalar"
] |
240f37227f923076dbe9a8a24bce39655200f04b
|
https://github.com/rajgoel/reveal.js-plugins/blob/240f37227f923076dbe9a8a24bce39655200f04b/spreadsheet/ruleJS.all.full.js#L13207-L13209
|
9,273
|
rajgoel/reveal.js-plugins
|
spreadsheet/ruleJS.all.full.js
|
aug
|
function aug(a, b) {
var newarr = a.slice(),
i = 0;
for (; i < newarr.length; i++) {
push.apply(newarr[i], b[i]);
}
return newarr;
}
|
javascript
|
function aug(a, b) {
var newarr = a.slice(),
i = 0;
for (; i < newarr.length; i++) {
push.apply(newarr[i], b[i]);
}
return newarr;
}
|
[
"function",
"aug",
"(",
"a",
",",
"b",
")",
"{",
"var",
"newarr",
"=",
"a",
".",
"slice",
"(",
")",
",",
"i",
"=",
"0",
";",
"for",
"(",
";",
"i",
"<",
"newarr",
".",
"length",
";",
"i",
"++",
")",
"{",
"push",
".",
"apply",
"(",
"newarr",
"[",
"i",
"]",
",",
"b",
"[",
"i",
"]",
")",
";",
"}",
"return",
"newarr",
";",
"}"
] |
augment one matrix by another
|
[
"augment",
"one",
"matrix",
"by",
"another"
] |
240f37227f923076dbe9a8a24bce39655200f04b
|
https://github.com/rajgoel/reveal.js-plugins/blob/240f37227f923076dbe9a8a24bce39655200f04b/spreadsheet/ruleJS.all.full.js#L13239-L13246
|
9,274
|
rajgoel/reveal.js-plugins
|
spreadsheet/ruleJS.all.full.js
|
det
|
function det(a) {
var alen = a.length,
alend = alen * 2,
vals = new Array(alend),
rowshift = alen - 1,
colshift = alend - 1,
mrow = rowshift - alen + 1,
mcol = colshift,
i = 0,
result = 0,
j;
// check for special 2x2 case
if (alen === 2) {
return a[0][0] * a[1][1] - a[0][1] * a[1][0];
}
for (; i < alend; i++) {
vals[i] = 1;
}
for (i = 0; i < alen; i++) {
for (j = 0; j < alen; j++) {
vals[(mrow < 0) ? mrow + alen : mrow ] *= a[i][j];
vals[(mcol < alen) ? mcol + alen : mcol ] *= a[i][j];
mrow++;
mcol--;
}
mrow = --rowshift - alen + 1;
mcol = --colshift;
}
for (i = 0; i < alen; i++) {
result += vals[i];
}
for (; i < alend; i++) {
result -= vals[i];
}
return result;
}
|
javascript
|
function det(a) {
var alen = a.length,
alend = alen * 2,
vals = new Array(alend),
rowshift = alen - 1,
colshift = alend - 1,
mrow = rowshift - alen + 1,
mcol = colshift,
i = 0,
result = 0,
j;
// check for special 2x2 case
if (alen === 2) {
return a[0][0] * a[1][1] - a[0][1] * a[1][0];
}
for (; i < alend; i++) {
vals[i] = 1;
}
for (i = 0; i < alen; i++) {
for (j = 0; j < alen; j++) {
vals[(mrow < 0) ? mrow + alen : mrow ] *= a[i][j];
vals[(mcol < alen) ? mcol + alen : mcol ] *= a[i][j];
mrow++;
mcol--;
}
mrow = --rowshift - alen + 1;
mcol = --colshift;
}
for (i = 0; i < alen; i++) {
result += vals[i];
}
for (; i < alend; i++) {
result -= vals[i];
}
return result;
}
|
[
"function",
"det",
"(",
"a",
")",
"{",
"var",
"alen",
"=",
"a",
".",
"length",
",",
"alend",
"=",
"alen",
"*",
"2",
",",
"vals",
"=",
"new",
"Array",
"(",
"alend",
")",
",",
"rowshift",
"=",
"alen",
"-",
"1",
",",
"colshift",
"=",
"alend",
"-",
"1",
",",
"mrow",
"=",
"rowshift",
"-",
"alen",
"+",
"1",
",",
"mcol",
"=",
"colshift",
",",
"i",
"=",
"0",
",",
"result",
"=",
"0",
",",
"j",
";",
"// check for special 2x2 case",
"if",
"(",
"alen",
"===",
"2",
")",
"{",
"return",
"a",
"[",
"0",
"]",
"[",
"0",
"]",
"*",
"a",
"[",
"1",
"]",
"[",
"1",
"]",
"-",
"a",
"[",
"0",
"]",
"[",
"1",
"]",
"*",
"a",
"[",
"1",
"]",
"[",
"0",
"]",
";",
"}",
"for",
"(",
";",
"i",
"<",
"alend",
";",
"i",
"++",
")",
"{",
"vals",
"[",
"i",
"]",
"=",
"1",
";",
"}",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"alen",
";",
"i",
"++",
")",
"{",
"for",
"(",
"j",
"=",
"0",
";",
"j",
"<",
"alen",
";",
"j",
"++",
")",
"{",
"vals",
"[",
"(",
"mrow",
"<",
"0",
")",
"?",
"mrow",
"+",
"alen",
":",
"mrow",
"]",
"*=",
"a",
"[",
"i",
"]",
"[",
"j",
"]",
";",
"vals",
"[",
"(",
"mcol",
"<",
"alen",
")",
"?",
"mcol",
"+",
"alen",
":",
"mcol",
"]",
"*=",
"a",
"[",
"i",
"]",
"[",
"j",
"]",
";",
"mrow",
"++",
";",
"mcol",
"--",
";",
"}",
"mrow",
"=",
"--",
"rowshift",
"-",
"alen",
"+",
"1",
";",
"mcol",
"=",
"--",
"colshift",
";",
"}",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"alen",
";",
"i",
"++",
")",
"{",
"result",
"+=",
"vals",
"[",
"i",
"]",
";",
"}",
"for",
"(",
";",
"i",
"<",
"alend",
";",
"i",
"++",
")",
"{",
"result",
"-=",
"vals",
"[",
"i",
"]",
";",
"}",
"return",
"result",
";",
"}"
] |
calculate the determinant of a matrix
|
[
"calculate",
"the",
"determinant",
"of",
"a",
"matrix"
] |
240f37227f923076dbe9a8a24bce39655200f04b
|
https://github.com/rajgoel/reveal.js-plugins/blob/240f37227f923076dbe9a8a24bce39655200f04b/spreadsheet/ruleJS.all.full.js#L13265-L13300
|
9,275
|
rajgoel/reveal.js-plugins
|
spreadsheet/ruleJS.all.full.js
|
function () {
if (this.done) {
return this.EOF;
}
if (!this._input) {
this.done = true;
}
var token,
match,
tempMatch,
index;
if (!this._more) {
this.yytext = '';
this.match = '';
}
var rules = this._currentRules();
for (var i = 0; i < rules.length; i++) {
tempMatch = this._input.match(this.rules[rules[i]]);
if (tempMatch && (!match || tempMatch[0].length > match[0].length)) {
match = tempMatch;
index = i;
if (this.options.backtrack_lexer) {
token = this.test_match(tempMatch, rules[i]);
if (token !== false) {
return token;
} else if (this._backtrack) {
match = false;
continue; // rule action called reject() implying a rule MISmatch.
} else {
// else: this is a lexer rule which consumes input without producing a token (e.g. whitespace)
return false;
}
} else if (!this.options.flex) {
break;
}
}
}
if (match) {
token = this.test_match(match, rules[index]);
if (token !== false) {
return token;
}
// else: this is a lexer rule which consumes input without producing a token (e.g. whitespace)
return false;
}
if (this._input === "") {
return this.EOF;
} else {
return this.parseError('Lexical error on line ' + (this.yylineno + 1) + '. Unrecognized text.\n' + this.showPosition(), {
text: "",
token: null,
line: this.yylineno
});
}
}
|
javascript
|
function () {
if (this.done) {
return this.EOF;
}
if (!this._input) {
this.done = true;
}
var token,
match,
tempMatch,
index;
if (!this._more) {
this.yytext = '';
this.match = '';
}
var rules = this._currentRules();
for (var i = 0; i < rules.length; i++) {
tempMatch = this._input.match(this.rules[rules[i]]);
if (tempMatch && (!match || tempMatch[0].length > match[0].length)) {
match = tempMatch;
index = i;
if (this.options.backtrack_lexer) {
token = this.test_match(tempMatch, rules[i]);
if (token !== false) {
return token;
} else if (this._backtrack) {
match = false;
continue; // rule action called reject() implying a rule MISmatch.
} else {
// else: this is a lexer rule which consumes input without producing a token (e.g. whitespace)
return false;
}
} else if (!this.options.flex) {
break;
}
}
}
if (match) {
token = this.test_match(match, rules[index]);
if (token !== false) {
return token;
}
// else: this is a lexer rule which consumes input without producing a token (e.g. whitespace)
return false;
}
if (this._input === "") {
return this.EOF;
} else {
return this.parseError('Lexical error on line ' + (this.yylineno + 1) + '. Unrecognized text.\n' + this.showPosition(), {
text: "",
token: null,
line: this.yylineno
});
}
}
|
[
"function",
"(",
")",
"{",
"if",
"(",
"this",
".",
"done",
")",
"{",
"return",
"this",
".",
"EOF",
";",
"}",
"if",
"(",
"!",
"this",
".",
"_input",
")",
"{",
"this",
".",
"done",
"=",
"true",
";",
"}",
"var",
"token",
",",
"match",
",",
"tempMatch",
",",
"index",
";",
"if",
"(",
"!",
"this",
".",
"_more",
")",
"{",
"this",
".",
"yytext",
"=",
"''",
";",
"this",
".",
"match",
"=",
"''",
";",
"}",
"var",
"rules",
"=",
"this",
".",
"_currentRules",
"(",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"rules",
".",
"length",
";",
"i",
"++",
")",
"{",
"tempMatch",
"=",
"this",
".",
"_input",
".",
"match",
"(",
"this",
".",
"rules",
"[",
"rules",
"[",
"i",
"]",
"]",
")",
";",
"if",
"(",
"tempMatch",
"&&",
"(",
"!",
"match",
"||",
"tempMatch",
"[",
"0",
"]",
".",
"length",
">",
"match",
"[",
"0",
"]",
".",
"length",
")",
")",
"{",
"match",
"=",
"tempMatch",
";",
"index",
"=",
"i",
";",
"if",
"(",
"this",
".",
"options",
".",
"backtrack_lexer",
")",
"{",
"token",
"=",
"this",
".",
"test_match",
"(",
"tempMatch",
",",
"rules",
"[",
"i",
"]",
")",
";",
"if",
"(",
"token",
"!==",
"false",
")",
"{",
"return",
"token",
";",
"}",
"else",
"if",
"(",
"this",
".",
"_backtrack",
")",
"{",
"match",
"=",
"false",
";",
"continue",
";",
"// rule action called reject() implying a rule MISmatch.",
"}",
"else",
"{",
"// else: this is a lexer rule which consumes input without producing a token (e.g. whitespace)",
"return",
"false",
";",
"}",
"}",
"else",
"if",
"(",
"!",
"this",
".",
"options",
".",
"flex",
")",
"{",
"break",
";",
"}",
"}",
"}",
"if",
"(",
"match",
")",
"{",
"token",
"=",
"this",
".",
"test_match",
"(",
"match",
",",
"rules",
"[",
"index",
"]",
")",
";",
"if",
"(",
"token",
"!==",
"false",
")",
"{",
"return",
"token",
";",
"}",
"// else: this is a lexer rule which consumes input without producing a token (e.g. whitespace)",
"return",
"false",
";",
"}",
"if",
"(",
"this",
".",
"_input",
"===",
"\"\"",
")",
"{",
"return",
"this",
".",
"EOF",
";",
"}",
"else",
"{",
"return",
"this",
".",
"parseError",
"(",
"'Lexical error on line '",
"+",
"(",
"this",
".",
"yylineno",
"+",
"1",
")",
"+",
"'. Unrecognized text.\\n'",
"+",
"this",
".",
"showPosition",
"(",
")",
",",
"{",
"text",
":",
"\"\"",
",",
"token",
":",
"null",
",",
"line",
":",
"this",
".",
"yylineno",
"}",
")",
";",
"}",
"}"
] |
return next match in input
|
[
"return",
"next",
"match",
"in",
"input"
] |
240f37227f923076dbe9a8a24bce39655200f04b
|
https://github.com/rajgoel/reveal.js-plugins/blob/240f37227f923076dbe9a8a24bce39655200f04b/spreadsheet/ruleJS.all.full.js#L20708-L20763
|
|
9,276
|
rajgoel/reveal.js-plugins
|
spreadsheet/ruleJS.all.full.js
|
function (type) {
var error = Exception.errors.filter(function (item) {
return item.type === type || item.output === type;
})[0];
return error ? error.output : null;
}
|
javascript
|
function (type) {
var error = Exception.errors.filter(function (item) {
return item.type === type || item.output === type;
})[0];
return error ? error.output : null;
}
|
[
"function",
"(",
"type",
")",
"{",
"var",
"error",
"=",
"Exception",
".",
"errors",
".",
"filter",
"(",
"function",
"(",
"item",
")",
"{",
"return",
"item",
".",
"type",
"===",
"type",
"||",
"item",
".",
"output",
"===",
"type",
";",
"}",
")",
"[",
"0",
"]",
";",
"return",
"error",
"?",
"error",
".",
"output",
":",
"null",
";",
"}"
] |
get error by type
@param {String} type
@returns {*}
|
[
"get",
"error",
"by",
"type"
] |
240f37227f923076dbe9a8a24bce39655200f04b
|
https://github.com/rajgoel/reveal.js-plugins/blob/240f37227f923076dbe9a8a24bce39655200f04b/spreadsheet/ruleJS.all.full.js#L20997-L21003
|
|
9,277
|
rajgoel/reveal.js-plugins
|
spreadsheet/ruleJS.all.full.js
|
function (id) {
var filtered = instance.matrix.data.filter(function (cell) {
if (cell.deps) {
return cell.deps.indexOf(id) > -1;
}
});
var deps = [];
filtered.forEach(function (cell) {
if (deps.indexOf(cell.id) === -1) {
deps.push(cell.id);
}
});
return deps;
}
|
javascript
|
function (id) {
var filtered = instance.matrix.data.filter(function (cell) {
if (cell.deps) {
return cell.deps.indexOf(id) > -1;
}
});
var deps = [];
filtered.forEach(function (cell) {
if (deps.indexOf(cell.id) === -1) {
deps.push(cell.id);
}
});
return deps;
}
|
[
"function",
"(",
"id",
")",
"{",
"var",
"filtered",
"=",
"instance",
".",
"matrix",
".",
"data",
".",
"filter",
"(",
"function",
"(",
"cell",
")",
"{",
"if",
"(",
"cell",
".",
"deps",
")",
"{",
"return",
"cell",
".",
"deps",
".",
"indexOf",
"(",
"id",
")",
">",
"-",
"1",
";",
"}",
"}",
")",
";",
"var",
"deps",
"=",
"[",
"]",
";",
"filtered",
".",
"forEach",
"(",
"function",
"(",
"cell",
")",
"{",
"if",
"(",
"deps",
".",
"indexOf",
"(",
"cell",
".",
"id",
")",
"===",
"-",
"1",
")",
"{",
"deps",
".",
"push",
"(",
"cell",
".",
"id",
")",
";",
"}",
"}",
")",
";",
"return",
"deps",
";",
"}"
] |
get dependencies by element
@param {String} id
@returns {Array}
|
[
"get",
"dependencies",
"by",
"element"
] |
240f37227f923076dbe9a8a24bce39655200f04b
|
https://github.com/rajgoel/reveal.js-plugins/blob/240f37227f923076dbe9a8a24bce39655200f04b/spreadsheet/ruleJS.all.full.js#L21239-L21254
|
|
9,278
|
rajgoel/reveal.js-plugins
|
spreadsheet/ruleJS.all.full.js
|
function (id) {
var deps = getDependencies(id);
if (deps.length) {
deps.forEach(function (refId) {
if (allDependencies.indexOf(refId) === -1) {
allDependencies.push(refId);
var item = instance.matrix.getItem(refId);
if (item.deps.length) {
getTotalDependencies(refId);
}
}
});
}
}
|
javascript
|
function (id) {
var deps = getDependencies(id);
if (deps.length) {
deps.forEach(function (refId) {
if (allDependencies.indexOf(refId) === -1) {
allDependencies.push(refId);
var item = instance.matrix.getItem(refId);
if (item.deps.length) {
getTotalDependencies(refId);
}
}
});
}
}
|
[
"function",
"(",
"id",
")",
"{",
"var",
"deps",
"=",
"getDependencies",
"(",
"id",
")",
";",
"if",
"(",
"deps",
".",
"length",
")",
"{",
"deps",
".",
"forEach",
"(",
"function",
"(",
"refId",
")",
"{",
"if",
"(",
"allDependencies",
".",
"indexOf",
"(",
"refId",
")",
"===",
"-",
"1",
")",
"{",
"allDependencies",
".",
"push",
"(",
"refId",
")",
";",
"var",
"item",
"=",
"instance",
".",
"matrix",
".",
"getItem",
"(",
"refId",
")",
";",
"if",
"(",
"item",
".",
"deps",
".",
"length",
")",
"{",
"getTotalDependencies",
"(",
"refId",
")",
";",
"}",
"}",
"}",
")",
";",
"}",
"}"
] |
get total dependencies
@param {String} id
|
[
"get",
"total",
"dependencies"
] |
240f37227f923076dbe9a8a24bce39655200f04b
|
https://github.com/rajgoel/reveal.js-plugins/blob/240f37227f923076dbe9a8a24bce39655200f04b/spreadsheet/ruleJS.all.full.js#L21262-L21277
|
|
9,279
|
rajgoel/reveal.js-plugins
|
spreadsheet/ruleJS.all.full.js
|
function (element) {
var allDependencies = instance.matrix.getElementDependencies(element),
id = element.getAttribute('id');
allDependencies.forEach(function (refId) {
var item = instance.matrix.getItem(refId);
if (item && item.formula) {
var refElement = document.getElementById(refId);
calculateElementFormula(item.formula, refElement);
}
});
}
|
javascript
|
function (element) {
var allDependencies = instance.matrix.getElementDependencies(element),
id = element.getAttribute('id');
allDependencies.forEach(function (refId) {
var item = instance.matrix.getItem(refId);
if (item && item.formula) {
var refElement = document.getElementById(refId);
calculateElementFormula(item.formula, refElement);
}
});
}
|
[
"function",
"(",
"element",
")",
"{",
"var",
"allDependencies",
"=",
"instance",
".",
"matrix",
".",
"getElementDependencies",
"(",
"element",
")",
",",
"id",
"=",
"element",
".",
"getAttribute",
"(",
"'id'",
")",
";",
"allDependencies",
".",
"forEach",
"(",
"function",
"(",
"refId",
")",
"{",
"var",
"item",
"=",
"instance",
".",
"matrix",
".",
"getItem",
"(",
"refId",
")",
";",
"if",
"(",
"item",
"&&",
"item",
".",
"formula",
")",
"{",
"var",
"refElement",
"=",
"document",
".",
"getElementById",
"(",
"refId",
")",
";",
"calculateElementFormula",
"(",
"item",
".",
"formula",
",",
"refElement",
")",
";",
"}",
"}",
")",
";",
"}"
] |
recalculate refs cell
@param {Element} element
|
[
"recalculate",
"refs",
"cell"
] |
240f37227f923076dbe9a8a24bce39655200f04b
|
https://github.com/rajgoel/reveal.js-plugins/blob/240f37227f923076dbe9a8a24bce39655200f04b/spreadsheet/ruleJS.all.full.js#L21297-L21308
|
|
9,280
|
rajgoel/reveal.js-plugins
|
spreadsheet/ruleJS.all.full.js
|
function (formula, element) {
// to avoid double translate formulas, update item data in parser
var parsed = parse(formula, element),
value = parsed.result,
error = parsed.error,
nodeName = element.nodeName.toUpperCase();
instance.matrix.updateElementItem(element, {value: value, error: error});
if (['INPUT'].indexOf(nodeName) === -1) {
element.innerText = value || error;
}
element.value = value || error;
return parsed;
}
|
javascript
|
function (formula, element) {
// to avoid double translate formulas, update item data in parser
var parsed = parse(formula, element),
value = parsed.result,
error = parsed.error,
nodeName = element.nodeName.toUpperCase();
instance.matrix.updateElementItem(element, {value: value, error: error});
if (['INPUT'].indexOf(nodeName) === -1) {
element.innerText = value || error;
}
element.value = value || error;
return parsed;
}
|
[
"function",
"(",
"formula",
",",
"element",
")",
"{",
"// to avoid double translate formulas, update item data in parser",
"var",
"parsed",
"=",
"parse",
"(",
"formula",
",",
"element",
")",
",",
"value",
"=",
"parsed",
".",
"result",
",",
"error",
"=",
"parsed",
".",
"error",
",",
"nodeName",
"=",
"element",
".",
"nodeName",
".",
"toUpperCase",
"(",
")",
";",
"instance",
".",
"matrix",
".",
"updateElementItem",
"(",
"element",
",",
"{",
"value",
":",
"value",
",",
"error",
":",
"error",
"}",
")",
";",
"if",
"(",
"[",
"'INPUT'",
"]",
".",
"indexOf",
"(",
"nodeName",
")",
"===",
"-",
"1",
")",
"{",
"element",
".",
"innerText",
"=",
"value",
"||",
"error",
";",
"}",
"element",
".",
"value",
"=",
"value",
"||",
"error",
";",
"return",
"parsed",
";",
"}"
] |
calculate element formula
@param {String} formula
@param {Element} element
@returns {Object}
|
[
"calculate",
"element",
"formula"
] |
240f37227f923076dbe9a8a24bce39655200f04b
|
https://github.com/rajgoel/reveal.js-plugins/blob/240f37227f923076dbe9a8a24bce39655200f04b/spreadsheet/ruleJS.all.full.js#L21316-L21332
|
|
9,281
|
rajgoel/reveal.js-plugins
|
spreadsheet/ruleJS.all.full.js
|
function (element) {
var id = element.getAttribute('id'),
formula = element.getAttribute('data-formula');
if (formula) {
// add item with basic properties to data array
instance.matrix.addItem({
id: id,
formula: formula
});
calculateElementFormula(formula, element);
}
}
|
javascript
|
function (element) {
var id = element.getAttribute('id'),
formula = element.getAttribute('data-formula');
if (formula) {
// add item with basic properties to data array
instance.matrix.addItem({
id: id,
formula: formula
});
calculateElementFormula(formula, element);
}
}
|
[
"function",
"(",
"element",
")",
"{",
"var",
"id",
"=",
"element",
".",
"getAttribute",
"(",
"'id'",
")",
",",
"formula",
"=",
"element",
".",
"getAttribute",
"(",
"'data-formula'",
")",
";",
"if",
"(",
"formula",
")",
"{",
"// add item with basic properties to data array",
"instance",
".",
"matrix",
".",
"addItem",
"(",
"{",
"id",
":",
"id",
",",
"formula",
":",
"formula",
"}",
")",
";",
"calculateElementFormula",
"(",
"formula",
",",
"element",
")",
";",
"}",
"}"
] |
register new found element to matrix
@param {Element} element
@returns {Object}
|
[
"register",
"new",
"found",
"element",
"to",
"matrix"
] |
240f37227f923076dbe9a8a24bce39655200f04b
|
https://github.com/rajgoel/reveal.js-plugins/blob/240f37227f923076dbe9a8a24bce39655200f04b/spreadsheet/ruleJS.all.full.js#L21339-L21354
|
|
9,282
|
rajgoel/reveal.js-plugins
|
spreadsheet/ruleJS.all.full.js
|
function (element) {
var id = element.getAttribute('id');
// on db click show formula
element.addEventListener('dblclick', function () {
var item = instance.matrix.getItem(id);
if (item && item.formula) {
item.formulaEdit = true;
element.value = '=' + item.formula;
}
});
element.addEventListener('blur', function () {
var item = instance.matrix.getItem(id);
if (item) {
if (item.formulaEdit) {
element.value = item.value || item.error;
}
item.formulaEdit = false;
}
});
// if pressed ESC restore original value
element.addEventListener('keyup', function (event) {
switch (event.keyCode) {
case 13: // ENTER
case 27: // ESC
// leave cell
listen();
break;
}
});
// re-calculate formula if ref cells value changed
element.addEventListener('change', function () {
// reset and remove item
instance.matrix.removeItem(id);
// check if inserted text could be the formula
var value = element.value;
if (value[0] === '=') {
element.setAttribute('data-formula', value.substr(1));
registerElementInMatrix(element);
}
// get ref cells and re-calculate formulas
recalculateElementDependencies(element);
});
}
|
javascript
|
function (element) {
var id = element.getAttribute('id');
// on db click show formula
element.addEventListener('dblclick', function () {
var item = instance.matrix.getItem(id);
if (item && item.formula) {
item.formulaEdit = true;
element.value = '=' + item.formula;
}
});
element.addEventListener('blur', function () {
var item = instance.matrix.getItem(id);
if (item) {
if (item.formulaEdit) {
element.value = item.value || item.error;
}
item.formulaEdit = false;
}
});
// if pressed ESC restore original value
element.addEventListener('keyup', function (event) {
switch (event.keyCode) {
case 13: // ENTER
case 27: // ESC
// leave cell
listen();
break;
}
});
// re-calculate formula if ref cells value changed
element.addEventListener('change', function () {
// reset and remove item
instance.matrix.removeItem(id);
// check if inserted text could be the formula
var value = element.value;
if (value[0] === '=') {
element.setAttribute('data-formula', value.substr(1));
registerElementInMatrix(element);
}
// get ref cells and re-calculate formulas
recalculateElementDependencies(element);
});
}
|
[
"function",
"(",
"element",
")",
"{",
"var",
"id",
"=",
"element",
".",
"getAttribute",
"(",
"'id'",
")",
";",
"// on db click show formula",
"element",
".",
"addEventListener",
"(",
"'dblclick'",
",",
"function",
"(",
")",
"{",
"var",
"item",
"=",
"instance",
".",
"matrix",
".",
"getItem",
"(",
"id",
")",
";",
"if",
"(",
"item",
"&&",
"item",
".",
"formula",
")",
"{",
"item",
".",
"formulaEdit",
"=",
"true",
";",
"element",
".",
"value",
"=",
"'='",
"+",
"item",
".",
"formula",
";",
"}",
"}",
")",
";",
"element",
".",
"addEventListener",
"(",
"'blur'",
",",
"function",
"(",
")",
"{",
"var",
"item",
"=",
"instance",
".",
"matrix",
".",
"getItem",
"(",
"id",
")",
";",
"if",
"(",
"item",
")",
"{",
"if",
"(",
"item",
".",
"formulaEdit",
")",
"{",
"element",
".",
"value",
"=",
"item",
".",
"value",
"||",
"item",
".",
"error",
";",
"}",
"item",
".",
"formulaEdit",
"=",
"false",
";",
"}",
"}",
")",
";",
"// if pressed ESC restore original value",
"element",
".",
"addEventListener",
"(",
"'keyup'",
",",
"function",
"(",
"event",
")",
"{",
"switch",
"(",
"event",
".",
"keyCode",
")",
"{",
"case",
"13",
":",
"// ENTER",
"case",
"27",
":",
"// ESC",
"// leave cell",
"listen",
"(",
")",
";",
"break",
";",
"}",
"}",
")",
";",
"// re-calculate formula if ref cells value changed",
"element",
".",
"addEventListener",
"(",
"'change'",
",",
"function",
"(",
")",
"{",
"// reset and remove item",
"instance",
".",
"matrix",
".",
"removeItem",
"(",
"id",
")",
";",
"// check if inserted text could be the formula",
"var",
"value",
"=",
"element",
".",
"value",
";",
"if",
"(",
"value",
"[",
"0",
"]",
"===",
"'='",
")",
"{",
"element",
".",
"setAttribute",
"(",
"'data-formula'",
",",
"value",
".",
"substr",
"(",
"1",
")",
")",
";",
"registerElementInMatrix",
"(",
"element",
")",
";",
"}",
"// get ref cells and re-calculate formulas",
"recalculateElementDependencies",
"(",
"element",
")",
";",
"}",
")",
";",
"}"
] |
register events for elements
@param element
|
[
"register",
"events",
"for",
"elements"
] |
240f37227f923076dbe9a8a24bce39655200f04b
|
https://github.com/rajgoel/reveal.js-plugins/blob/240f37227f923076dbe9a8a24bce39655200f04b/spreadsheet/ruleJS.all.full.js#L21360-L21412
|
|
9,283
|
rajgoel/reveal.js-plugins
|
spreadsheet/ruleJS.all.full.js
|
function (cell) {
var num = cell.match(/\d+$/),
alpha = cell.replace(num, '');
return {
alpha: alpha,
num: parseInt(num[0], 10)
}
}
|
javascript
|
function (cell) {
var num = cell.match(/\d+$/),
alpha = cell.replace(num, '');
return {
alpha: alpha,
num: parseInt(num[0], 10)
}
}
|
[
"function",
"(",
"cell",
")",
"{",
"var",
"num",
"=",
"cell",
".",
"match",
"(",
"/",
"\\d+$",
"/",
")",
",",
"alpha",
"=",
"cell",
".",
"replace",
"(",
"num",
",",
"''",
")",
";",
"return",
"{",
"alpha",
":",
"alpha",
",",
"num",
":",
"parseInt",
"(",
"num",
"[",
"0",
"]",
",",
"10",
")",
"}",
"}"
] |
get row name and column number
@param cell
@returns {{alpha: string, num: number}}
|
[
"get",
"row",
"name",
"and",
"column",
"number"
] |
240f37227f923076dbe9a8a24bce39655200f04b
|
https://github.com/rajgoel/reveal.js-plugins/blob/240f37227f923076dbe9a8a24bce39655200f04b/spreadsheet/ruleJS.all.full.js#L21526-L21534
|
|
9,284
|
rajgoel/reveal.js-plugins
|
spreadsheet/ruleJS.all.full.js
|
function (cell, counter) {
var alphaNum = instance.utils.getCellAlphaNum(cell),
alpha = alphaNum.alpha,
col = alpha,
row = parseInt(alphaNum.num + counter, 10);
if (row < 1) {
row = 1;
}
return col + '' + row;
}
|
javascript
|
function (cell, counter) {
var alphaNum = instance.utils.getCellAlphaNum(cell),
alpha = alphaNum.alpha,
col = alpha,
row = parseInt(alphaNum.num + counter, 10);
if (row < 1) {
row = 1;
}
return col + '' + row;
}
|
[
"function",
"(",
"cell",
",",
"counter",
")",
"{",
"var",
"alphaNum",
"=",
"instance",
".",
"utils",
".",
"getCellAlphaNum",
"(",
"cell",
")",
",",
"alpha",
"=",
"alphaNum",
".",
"alpha",
",",
"col",
"=",
"alpha",
",",
"row",
"=",
"parseInt",
"(",
"alphaNum",
".",
"num",
"+",
"counter",
",",
"10",
")",
";",
"if",
"(",
"row",
"<",
"1",
")",
"{",
"row",
"=",
"1",
";",
"}",
"return",
"col",
"+",
"''",
"+",
"row",
";",
"}"
] |
change row cell index A1 -> A2
@param {String} cell
@param {Number} counter
@returns {String}
|
[
"change",
"row",
"cell",
"index",
"A1",
"-",
">",
"A2"
] |
240f37227f923076dbe9a8a24bce39655200f04b
|
https://github.com/rajgoel/reveal.js-plugins/blob/240f37227f923076dbe9a8a24bce39655200f04b/spreadsheet/ruleJS.all.full.js#L21542-L21553
|
|
9,285
|
rajgoel/reveal.js-plugins
|
spreadsheet/ruleJS.all.full.js
|
function (cell, counter) {
var alphaNum = instance.utils.getCellAlphaNum(cell),
alpha = alphaNum.alpha,
col = instance.utils.toChar(parseInt(instance.utils.toNum(alpha) + counter, 10)),
row = alphaNum.num;
if (!col || col.length === 0) {
col = 'A';
}
var fixedCol = alpha[0] === '$' || false,
fixedRow = alpha[alpha.length - 1] === '$' || false;
col = (fixedCol ? '$' : '') + col;
row = (fixedRow ? '$' : '') + row;
return col + '' + row;
}
|
javascript
|
function (cell, counter) {
var alphaNum = instance.utils.getCellAlphaNum(cell),
alpha = alphaNum.alpha,
col = instance.utils.toChar(parseInt(instance.utils.toNum(alpha) + counter, 10)),
row = alphaNum.num;
if (!col || col.length === 0) {
col = 'A';
}
var fixedCol = alpha[0] === '$' || false,
fixedRow = alpha[alpha.length - 1] === '$' || false;
col = (fixedCol ? '$' : '') + col;
row = (fixedRow ? '$' : '') + row;
return col + '' + row;
}
|
[
"function",
"(",
"cell",
",",
"counter",
")",
"{",
"var",
"alphaNum",
"=",
"instance",
".",
"utils",
".",
"getCellAlphaNum",
"(",
"cell",
")",
",",
"alpha",
"=",
"alphaNum",
".",
"alpha",
",",
"col",
"=",
"instance",
".",
"utils",
".",
"toChar",
"(",
"parseInt",
"(",
"instance",
".",
"utils",
".",
"toNum",
"(",
"alpha",
")",
"+",
"counter",
",",
"10",
")",
")",
",",
"row",
"=",
"alphaNum",
".",
"num",
";",
"if",
"(",
"!",
"col",
"||",
"col",
".",
"length",
"===",
"0",
")",
"{",
"col",
"=",
"'A'",
";",
"}",
"var",
"fixedCol",
"=",
"alpha",
"[",
"0",
"]",
"===",
"'$'",
"||",
"false",
",",
"fixedRow",
"=",
"alpha",
"[",
"alpha",
".",
"length",
"-",
"1",
"]",
"===",
"'$'",
"||",
"false",
";",
"col",
"=",
"(",
"fixedCol",
"?",
"'$'",
":",
"''",
")",
"+",
"col",
";",
"row",
"=",
"(",
"fixedRow",
"?",
"'$'",
":",
"''",
")",
"+",
"row",
";",
"return",
"col",
"+",
"''",
"+",
"row",
";",
"}"
] |
change col cell index A1 -> B1 Z1 -> AA1
@param {String} cell
@param {Number} counter
@returns {String}
|
[
"change",
"col",
"cell",
"index",
"A1",
"-",
">",
"B1",
"Z1",
"-",
">",
"AA1"
] |
240f37227f923076dbe9a8a24bce39655200f04b
|
https://github.com/rajgoel/reveal.js-plugins/blob/240f37227f923076dbe9a8a24bce39655200f04b/spreadsheet/ruleJS.all.full.js#L21561-L21578
|
|
9,286
|
rajgoel/reveal.js-plugins
|
spreadsheet/ruleJS.all.full.js
|
function (formula, direction, delta) {
var type,
counter;
// left, right -> col
if (['left', 'right'].indexOf(direction) !== -1) {
type = 'col';
} else if (['up', 'down'].indexOf(direction) !== -1) {
type = 'row'
}
// down, up -> row
if (['down', 'right'].indexOf(direction) !== -1) {
counter = delta * 1;
} else if(['up', 'left'].indexOf(direction) !== -1) {
counter = delta * (-1);
}
if (type && counter) {
return formula.replace(/(\$?[A-Za-z]+\$?[0-9]+)/g, function (match) {
var alpha = instance.utils.getCellAlphaNum(match).alpha;
var fixedCol = alpha[0] === '$' || false,
fixedRow = alpha[alpha.length - 1] === '$' || false;
if (type === 'row' && fixedRow) {
return match;
}
if (type === 'col' && fixedCol) {
return match;
}
return (type === 'row' ? instance.utils.changeRowIndex(match, counter) : instance.utils.changeColIndex(match, counter));
});
}
return formula;
}
|
javascript
|
function (formula, direction, delta) {
var type,
counter;
// left, right -> col
if (['left', 'right'].indexOf(direction) !== -1) {
type = 'col';
} else if (['up', 'down'].indexOf(direction) !== -1) {
type = 'row'
}
// down, up -> row
if (['down', 'right'].indexOf(direction) !== -1) {
counter = delta * 1;
} else if(['up', 'left'].indexOf(direction) !== -1) {
counter = delta * (-1);
}
if (type && counter) {
return formula.replace(/(\$?[A-Za-z]+\$?[0-9]+)/g, function (match) {
var alpha = instance.utils.getCellAlphaNum(match).alpha;
var fixedCol = alpha[0] === '$' || false,
fixedRow = alpha[alpha.length - 1] === '$' || false;
if (type === 'row' && fixedRow) {
return match;
}
if (type === 'col' && fixedCol) {
return match;
}
return (type === 'row' ? instance.utils.changeRowIndex(match, counter) : instance.utils.changeColIndex(match, counter));
});
}
return formula;
}
|
[
"function",
"(",
"formula",
",",
"direction",
",",
"delta",
")",
"{",
"var",
"type",
",",
"counter",
";",
"// left, right -> col",
"if",
"(",
"[",
"'left'",
",",
"'right'",
"]",
".",
"indexOf",
"(",
"direction",
")",
"!==",
"-",
"1",
")",
"{",
"type",
"=",
"'col'",
";",
"}",
"else",
"if",
"(",
"[",
"'up'",
",",
"'down'",
"]",
".",
"indexOf",
"(",
"direction",
")",
"!==",
"-",
"1",
")",
"{",
"type",
"=",
"'row'",
"}",
"// down, up -> row",
"if",
"(",
"[",
"'down'",
",",
"'right'",
"]",
".",
"indexOf",
"(",
"direction",
")",
"!==",
"-",
"1",
")",
"{",
"counter",
"=",
"delta",
"*",
"1",
";",
"}",
"else",
"if",
"(",
"[",
"'up'",
",",
"'left'",
"]",
".",
"indexOf",
"(",
"direction",
")",
"!==",
"-",
"1",
")",
"{",
"counter",
"=",
"delta",
"*",
"(",
"-",
"1",
")",
";",
"}",
"if",
"(",
"type",
"&&",
"counter",
")",
"{",
"return",
"formula",
".",
"replace",
"(",
"/",
"(\\$?[A-Za-z]+\\$?[0-9]+)",
"/",
"g",
",",
"function",
"(",
"match",
")",
"{",
"var",
"alpha",
"=",
"instance",
".",
"utils",
".",
"getCellAlphaNum",
"(",
"match",
")",
".",
"alpha",
";",
"var",
"fixedCol",
"=",
"alpha",
"[",
"0",
"]",
"===",
"'$'",
"||",
"false",
",",
"fixedRow",
"=",
"alpha",
"[",
"alpha",
".",
"length",
"-",
"1",
"]",
"===",
"'$'",
"||",
"false",
";",
"if",
"(",
"type",
"===",
"'row'",
"&&",
"fixedRow",
")",
"{",
"return",
"match",
";",
"}",
"if",
"(",
"type",
"===",
"'col'",
"&&",
"fixedCol",
")",
"{",
"return",
"match",
";",
"}",
"return",
"(",
"type",
"===",
"'row'",
"?",
"instance",
".",
"utils",
".",
"changeRowIndex",
"(",
"match",
",",
"counter",
")",
":",
"instance",
".",
"utils",
".",
"changeColIndex",
"(",
"match",
",",
"counter",
")",
")",
";",
"}",
")",
";",
"}",
"return",
"formula",
";",
"}"
] |
update formula cells
@param {String} formula
@param {String} direction
@param {Number} delta
@returns {String}
|
[
"update",
"formula",
"cells"
] |
240f37227f923076dbe9a8a24bce39655200f04b
|
https://github.com/rajgoel/reveal.js-plugins/blob/240f37227f923076dbe9a8a24bce39655200f04b/spreadsheet/ruleJS.all.full.js#L21616-L21655
|
|
9,287
|
rajgoel/reveal.js-plugins
|
spreadsheet/ruleJS.all.full.js
|
function (cell) {
var num = cell.match(/\d+$/),
alpha = cell.replace(num, '');
return {
row: parseInt(num[0], 10) - 1,
col: instance.utils.toNum(alpha)
};
}
|
javascript
|
function (cell) {
var num = cell.match(/\d+$/),
alpha = cell.replace(num, '');
return {
row: parseInt(num[0], 10) - 1,
col: instance.utils.toNum(alpha)
};
}
|
[
"function",
"(",
"cell",
")",
"{",
"var",
"num",
"=",
"cell",
".",
"match",
"(",
"/",
"\\d+$",
"/",
")",
",",
"alpha",
"=",
"cell",
".",
"replace",
"(",
"num",
",",
"''",
")",
";",
"return",
"{",
"row",
":",
"parseInt",
"(",
"num",
"[",
"0",
"]",
",",
"10",
")",
"-",
"1",
",",
"col",
":",
"instance",
".",
"utils",
".",
"toNum",
"(",
"alpha",
")",
"}",
";",
"}"
] |
get cell coordinates
@param {String} cell A1
@returns {{row: Number, col: number}}
|
[
"get",
"cell",
"coordinates"
] |
240f37227f923076dbe9a8a24bce39655200f04b
|
https://github.com/rajgoel/reveal.js-plugins/blob/240f37227f923076dbe9a8a24bce39655200f04b/spreadsheet/ruleJS.all.full.js#L21709-L21717
|
|
9,288
|
rajgoel/reveal.js-plugins
|
spreadsheet/ruleJS.all.full.js
|
function (startCell, endCell, callback) {
var result = {
index: [], // list of cell index: A1, A2, A3
value: [] // list of cell value
};
var cols = {
start: 0,
end: 0
};
if (endCell.col >= startCell.col) {
cols = {
start: startCell.col,
end: endCell.col
};
} else {
cols = {
start: endCell.col,
end: startCell.col
};
}
var rows = {
start: 0,
end: 0
};
if (endCell.row >= startCell.row) {
rows = {
start: startCell.row,
end: endCell.row
};
} else {
rows = {
start: endCell.row,
end: startCell.row
};
}
for (var column = cols.start; column <= cols.end; column++) {
for (var row = rows.start; row <= rows.end; row++) {
var cellIndex = instance.utils.toChar(column) + (row + 1),
cellValue = instance.helper.cellValue.call(this, cellIndex);
result.index.push(cellIndex);
result.value.push(cellValue);
}
}
if (instance.utils.isFunction(callback)) {
return callback.apply(callback, [result]);
} else {
return result;
}
}
|
javascript
|
function (startCell, endCell, callback) {
var result = {
index: [], // list of cell index: A1, A2, A3
value: [] // list of cell value
};
var cols = {
start: 0,
end: 0
};
if (endCell.col >= startCell.col) {
cols = {
start: startCell.col,
end: endCell.col
};
} else {
cols = {
start: endCell.col,
end: startCell.col
};
}
var rows = {
start: 0,
end: 0
};
if (endCell.row >= startCell.row) {
rows = {
start: startCell.row,
end: endCell.row
};
} else {
rows = {
start: endCell.row,
end: startCell.row
};
}
for (var column = cols.start; column <= cols.end; column++) {
for (var row = rows.start; row <= rows.end; row++) {
var cellIndex = instance.utils.toChar(column) + (row + 1),
cellValue = instance.helper.cellValue.call(this, cellIndex);
result.index.push(cellIndex);
result.value.push(cellValue);
}
}
if (instance.utils.isFunction(callback)) {
return callback.apply(callback, [result]);
} else {
return result;
}
}
|
[
"function",
"(",
"startCell",
",",
"endCell",
",",
"callback",
")",
"{",
"var",
"result",
"=",
"{",
"index",
":",
"[",
"]",
",",
"// list of cell index: A1, A2, A3",
"value",
":",
"[",
"]",
"// list of cell value",
"}",
";",
"var",
"cols",
"=",
"{",
"start",
":",
"0",
",",
"end",
":",
"0",
"}",
";",
"if",
"(",
"endCell",
".",
"col",
">=",
"startCell",
".",
"col",
")",
"{",
"cols",
"=",
"{",
"start",
":",
"startCell",
".",
"col",
",",
"end",
":",
"endCell",
".",
"col",
"}",
";",
"}",
"else",
"{",
"cols",
"=",
"{",
"start",
":",
"endCell",
".",
"col",
",",
"end",
":",
"startCell",
".",
"col",
"}",
";",
"}",
"var",
"rows",
"=",
"{",
"start",
":",
"0",
",",
"end",
":",
"0",
"}",
";",
"if",
"(",
"endCell",
".",
"row",
">=",
"startCell",
".",
"row",
")",
"{",
"rows",
"=",
"{",
"start",
":",
"startCell",
".",
"row",
",",
"end",
":",
"endCell",
".",
"row",
"}",
";",
"}",
"else",
"{",
"rows",
"=",
"{",
"start",
":",
"endCell",
".",
"row",
",",
"end",
":",
"startCell",
".",
"row",
"}",
";",
"}",
"for",
"(",
"var",
"column",
"=",
"cols",
".",
"start",
";",
"column",
"<=",
"cols",
".",
"end",
";",
"column",
"++",
")",
"{",
"for",
"(",
"var",
"row",
"=",
"rows",
".",
"start",
";",
"row",
"<=",
"rows",
".",
"end",
";",
"row",
"++",
")",
"{",
"var",
"cellIndex",
"=",
"instance",
".",
"utils",
".",
"toChar",
"(",
"column",
")",
"+",
"(",
"row",
"+",
"1",
")",
",",
"cellValue",
"=",
"instance",
".",
"helper",
".",
"cellValue",
".",
"call",
"(",
"this",
",",
"cellIndex",
")",
";",
"result",
".",
"index",
".",
"push",
"(",
"cellIndex",
")",
";",
"result",
".",
"value",
".",
"push",
"(",
"cellValue",
")",
";",
"}",
"}",
"if",
"(",
"instance",
".",
"utils",
".",
"isFunction",
"(",
"callback",
")",
")",
"{",
"return",
"callback",
".",
"apply",
"(",
"callback",
",",
"[",
"result",
"]",
")",
";",
"}",
"else",
"{",
"return",
"result",
";",
"}",
"}"
] |
iterate cell range and get theirs indexes and values
@param {Object} startCell ex.: {row:1, col: 1}
@param {Object} endCell ex.: {row:10, col: 1}
@param {Function=} callback
@returns {{index: Array, value: Array}}
|
[
"iterate",
"cell",
"range",
"and",
"get",
"theirs",
"indexes",
"and",
"values"
] |
240f37227f923076dbe9a8a24bce39655200f04b
|
https://github.com/rajgoel/reveal.js-plugins/blob/240f37227f923076dbe9a8a24bce39655200f04b/spreadsheet/ruleJS.all.full.js#L21744-L21799
|
|
9,289
|
rajgoel/reveal.js-plugins
|
spreadsheet/ruleJS.all.full.js
|
function (type, exp1, exp2) {
var result;
switch (type) {
case '&':
result = exp1.toString() + exp2.toString();
break;
}
return result;
}
|
javascript
|
function (type, exp1, exp2) {
var result;
switch (type) {
case '&':
result = exp1.toString() + exp2.toString();
break;
}
return result;
}
|
[
"function",
"(",
"type",
",",
"exp1",
",",
"exp2",
")",
"{",
"var",
"result",
";",
"switch",
"(",
"type",
")",
"{",
"case",
"'&'",
":",
"result",
"=",
"exp1",
".",
"toString",
"(",
")",
"+",
"exp2",
".",
"toString",
"(",
")",
";",
"break",
";",
"}",
"return",
"result",
";",
"}"
] |
match special operation
@param {String} type
@param {String} exp1
@param {String} exp2
@returns {*}
|
[
"match",
"special",
"operation"
] |
240f37227f923076dbe9a8a24bce39655200f04b
|
https://github.com/rajgoel/reveal.js-plugins/blob/240f37227f923076dbe9a8a24bce39655200f04b/spreadsheet/ruleJS.all.full.js#L21878-L21887
|
|
9,290
|
rajgoel/reveal.js-plugins
|
spreadsheet/ruleJS.all.full.js
|
function (type, exp1, exp2) {
var result;
switch (type) {
case '=':
result = (exp1 === exp2);
break;
case '>':
result = (exp1 > exp2);
break;
case '<':
result = (exp1 < exp2);
break;
case '>=':
result = (exp1 >= exp2);
break;
case '<=':
result = (exp1 === exp2);
break;
case '<>':
result = (exp1 != exp2);
break;
case 'NOT':
result = (exp1 != exp2);
break;
}
return result;
}
|
javascript
|
function (type, exp1, exp2) {
var result;
switch (type) {
case '=':
result = (exp1 === exp2);
break;
case '>':
result = (exp1 > exp2);
break;
case '<':
result = (exp1 < exp2);
break;
case '>=':
result = (exp1 >= exp2);
break;
case '<=':
result = (exp1 === exp2);
break;
case '<>':
result = (exp1 != exp2);
break;
case 'NOT':
result = (exp1 != exp2);
break;
}
return result;
}
|
[
"function",
"(",
"type",
",",
"exp1",
",",
"exp2",
")",
"{",
"var",
"result",
";",
"switch",
"(",
"type",
")",
"{",
"case",
"'='",
":",
"result",
"=",
"(",
"exp1",
"===",
"exp2",
")",
";",
"break",
";",
"case",
"'>'",
":",
"result",
"=",
"(",
"exp1",
">",
"exp2",
")",
";",
"break",
";",
"case",
"'<'",
":",
"result",
"=",
"(",
"exp1",
"<",
"exp2",
")",
";",
"break",
";",
"case",
"'>='",
":",
"result",
"=",
"(",
"exp1",
">=",
"exp2",
")",
";",
"break",
";",
"case",
"'<='",
":",
"result",
"=",
"(",
"exp1",
"===",
"exp2",
")",
";",
"break",
";",
"case",
"'<>'",
":",
"result",
"=",
"(",
"exp1",
"!=",
"exp2",
")",
";",
"break",
";",
"case",
"'NOT'",
":",
"result",
"=",
"(",
"exp1",
"!=",
"exp2",
")",
";",
"break",
";",
"}",
"return",
"result",
";",
"}"
] |
match logic operation
@param {String} type
@param {String|Number} exp1
@param {String|Number} exp2
@returns {Boolean} result
|
[
"match",
"logic",
"operation"
] |
240f37227f923076dbe9a8a24bce39655200f04b
|
https://github.com/rajgoel/reveal.js-plugins/blob/240f37227f923076dbe9a8a24bce39655200f04b/spreadsheet/ruleJS.all.full.js#L21896-L21930
|
|
9,291
|
rajgoel/reveal.js-plugins
|
spreadsheet/ruleJS.all.full.js
|
function (type, number1, number2) {
var result;
number1 = helper.number(number1);
number2 = helper.number(number2);
if (isNaN(number1) || isNaN(number2)) {
if (number1[0] === '=' || number2[0] === '=') {
throw Error('NEED_UPDATE');
}
throw Error('VALUE');
}
switch (type) {
case '+':
result = number1 + number2;
break;
case '-':
result = number1 - number2;
break;
case '/':
result = number1 / number2;
if (result == Infinity) {
throw Error('DIV_ZERO');
} else if (isNaN(result)) {
throw Error('VALUE');
}
break;
case '*':
result = number1 * number2;
break;
case '^':
result = Math.pow(number1, number2);
break;
}
return result;
}
|
javascript
|
function (type, number1, number2) {
var result;
number1 = helper.number(number1);
number2 = helper.number(number2);
if (isNaN(number1) || isNaN(number2)) {
if (number1[0] === '=' || number2[0] === '=') {
throw Error('NEED_UPDATE');
}
throw Error('VALUE');
}
switch (type) {
case '+':
result = number1 + number2;
break;
case '-':
result = number1 - number2;
break;
case '/':
result = number1 / number2;
if (result == Infinity) {
throw Error('DIV_ZERO');
} else if (isNaN(result)) {
throw Error('VALUE');
}
break;
case '*':
result = number1 * number2;
break;
case '^':
result = Math.pow(number1, number2);
break;
}
return result;
}
|
[
"function",
"(",
"type",
",",
"number1",
",",
"number2",
")",
"{",
"var",
"result",
";",
"number1",
"=",
"helper",
".",
"number",
"(",
"number1",
")",
";",
"number2",
"=",
"helper",
".",
"number",
"(",
"number2",
")",
";",
"if",
"(",
"isNaN",
"(",
"number1",
")",
"||",
"isNaN",
"(",
"number2",
")",
")",
"{",
"if",
"(",
"number1",
"[",
"0",
"]",
"===",
"'='",
"||",
"number2",
"[",
"0",
"]",
"===",
"'='",
")",
"{",
"throw",
"Error",
"(",
"'NEED_UPDATE'",
")",
";",
"}",
"throw",
"Error",
"(",
"'VALUE'",
")",
";",
"}",
"switch",
"(",
"type",
")",
"{",
"case",
"'+'",
":",
"result",
"=",
"number1",
"+",
"number2",
";",
"break",
";",
"case",
"'-'",
":",
"result",
"=",
"number1",
"-",
"number2",
";",
"break",
";",
"case",
"'/'",
":",
"result",
"=",
"number1",
"/",
"number2",
";",
"if",
"(",
"result",
"==",
"Infinity",
")",
"{",
"throw",
"Error",
"(",
"'DIV_ZERO'",
")",
";",
"}",
"else",
"if",
"(",
"isNaN",
"(",
"result",
")",
")",
"{",
"throw",
"Error",
"(",
"'VALUE'",
")",
";",
"}",
"break",
";",
"case",
"'*'",
":",
"result",
"=",
"number1",
"*",
"number2",
";",
"break",
";",
"case",
"'^'",
":",
"result",
"=",
"Math",
".",
"pow",
"(",
"number1",
",",
"number2",
")",
";",
"break",
";",
"}",
"return",
"result",
";",
"}"
] |
match math operation
@param {String} type
@param {Number} number1
@param {Number} number2
@returns {*}
|
[
"match",
"math",
"operation"
] |
240f37227f923076dbe9a8a24bce39655200f04b
|
https://github.com/rajgoel/reveal.js-plugins/blob/240f37227f923076dbe9a8a24bce39655200f04b/spreadsheet/ruleJS.all.full.js#L21939-L21978
|
|
9,292
|
rajgoel/reveal.js-plugins
|
spreadsheet/ruleJS.all.full.js
|
function (fn, args) {
fn = fn.toUpperCase();
args = args || [];
if (instance.helper.SUPPORTED_FORMULAS.indexOf(fn) > -1) {
if (instance.formulas[fn]) {
return instance.formulas[fn].apply(this, args);
}
}
throw Error('NAME');
}
|
javascript
|
function (fn, args) {
fn = fn.toUpperCase();
args = args || [];
if (instance.helper.SUPPORTED_FORMULAS.indexOf(fn) > -1) {
if (instance.formulas[fn]) {
return instance.formulas[fn].apply(this, args);
}
}
throw Error('NAME');
}
|
[
"function",
"(",
"fn",
",",
"args",
")",
"{",
"fn",
"=",
"fn",
".",
"toUpperCase",
"(",
")",
";",
"args",
"=",
"args",
"||",
"[",
"]",
";",
"if",
"(",
"instance",
".",
"helper",
".",
"SUPPORTED_FORMULAS",
".",
"indexOf",
"(",
"fn",
")",
">",
"-",
"1",
")",
"{",
"if",
"(",
"instance",
".",
"formulas",
"[",
"fn",
"]",
")",
"{",
"return",
"instance",
".",
"formulas",
"[",
"fn",
"]",
".",
"apply",
"(",
"this",
",",
"args",
")",
";",
"}",
"}",
"throw",
"Error",
"(",
"'NAME'",
")",
";",
"}"
] |
call function from formula
@param {String} fn
@param {Array} args
@returns {*}
|
[
"call",
"function",
"from",
"formula"
] |
240f37227f923076dbe9a8a24bce39655200f04b
|
https://github.com/rajgoel/reveal.js-plugins/blob/240f37227f923076dbe9a8a24bce39655200f04b/spreadsheet/ruleJS.all.full.js#L21986-L21997
|
|
9,293
|
rajgoel/reveal.js-plugins
|
spreadsheet/ruleJS.all.full.js
|
function (args) {
args = args || [];
var str = args[0];
if (str) {
str = str.toUpperCase();
if (instance.formulas[str]) {
return ((typeof instance.formulas[str] === 'function') ? instance.formulas[str].apply(this, args) : instance.formulas[str]);
}
}
throw Error('NAME');
}
|
javascript
|
function (args) {
args = args || [];
var str = args[0];
if (str) {
str = str.toUpperCase();
if (instance.formulas[str]) {
return ((typeof instance.formulas[str] === 'function') ? instance.formulas[str].apply(this, args) : instance.formulas[str]);
}
}
throw Error('NAME');
}
|
[
"function",
"(",
"args",
")",
"{",
"args",
"=",
"args",
"||",
"[",
"]",
";",
"var",
"str",
"=",
"args",
"[",
"0",
"]",
";",
"if",
"(",
"str",
")",
"{",
"str",
"=",
"str",
".",
"toUpperCase",
"(",
")",
";",
"if",
"(",
"instance",
".",
"formulas",
"[",
"str",
"]",
")",
"{",
"return",
"(",
"(",
"typeof",
"instance",
".",
"formulas",
"[",
"str",
"]",
"===",
"'function'",
")",
"?",
"instance",
".",
"formulas",
"[",
"str",
"]",
".",
"apply",
"(",
"this",
",",
"args",
")",
":",
"instance",
".",
"formulas",
"[",
"str",
"]",
")",
";",
"}",
"}",
"throw",
"Error",
"(",
"'NAME'",
")",
";",
"}"
] |
get variable from formula
@param {Array} args
@returns {*}
|
[
"get",
"variable",
"from",
"formula"
] |
240f37227f923076dbe9a8a24bce39655200f04b
|
https://github.com/rajgoel/reveal.js-plugins/blob/240f37227f923076dbe9a8a24bce39655200f04b/spreadsheet/ruleJS.all.full.js#L22004-L22016
|
|
9,294
|
rajgoel/reveal.js-plugins
|
spreadsheet/ruleJS.all.full.js
|
function (cell) {
var value,
fnCellValue = instance.custom.cellValue,
element = this,
item = instance.matrix.getItem(cell);
// check if custom cellValue fn exists
if (instance.utils.isFunction(fnCellValue)) {
var cellCoords = instance.utils.cellCoords(cell),
cellId = instance.utils.translateCellCoords({row: element.row, col: element.col});
// get value
value = item ? item.value : fnCellValue(cellCoords.row, cellCoords.col);
if (instance.utils.isNull(value)) {
value = 0;
}
if (cellId) {
//update dependencies
instance.matrix.updateItem(cellId, {deps: [cell]});
}
} else {
// get value
value = item ? item.value : document.getElementById(cell).value;
//update dependencies
instance.matrix.updateElementItem(element, {deps: [cell]});
}
// check references error
if (item && item.deps) {
if (item.deps.indexOf(cellId) !== -1) {
throw Error('REF');
}
}
// check if any error occurs
if (item && item.error) {
throw Error(item.error);
}
// return value if is set
if (instance.utils.isSet(value)) {
var result = instance.helper.number(value);
return !isNaN(result) ? result : value;
}
// cell is not available
throw Error('NOT_AVAILABLE');
}
|
javascript
|
function (cell) {
var value,
fnCellValue = instance.custom.cellValue,
element = this,
item = instance.matrix.getItem(cell);
// check if custom cellValue fn exists
if (instance.utils.isFunction(fnCellValue)) {
var cellCoords = instance.utils.cellCoords(cell),
cellId = instance.utils.translateCellCoords({row: element.row, col: element.col});
// get value
value = item ? item.value : fnCellValue(cellCoords.row, cellCoords.col);
if (instance.utils.isNull(value)) {
value = 0;
}
if (cellId) {
//update dependencies
instance.matrix.updateItem(cellId, {deps: [cell]});
}
} else {
// get value
value = item ? item.value : document.getElementById(cell).value;
//update dependencies
instance.matrix.updateElementItem(element, {deps: [cell]});
}
// check references error
if (item && item.deps) {
if (item.deps.indexOf(cellId) !== -1) {
throw Error('REF');
}
}
// check if any error occurs
if (item && item.error) {
throw Error(item.error);
}
// return value if is set
if (instance.utils.isSet(value)) {
var result = instance.helper.number(value);
return !isNaN(result) ? result : value;
}
// cell is not available
throw Error('NOT_AVAILABLE');
}
|
[
"function",
"(",
"cell",
")",
"{",
"var",
"value",
",",
"fnCellValue",
"=",
"instance",
".",
"custom",
".",
"cellValue",
",",
"element",
"=",
"this",
",",
"item",
"=",
"instance",
".",
"matrix",
".",
"getItem",
"(",
"cell",
")",
";",
"// check if custom cellValue fn exists",
"if",
"(",
"instance",
".",
"utils",
".",
"isFunction",
"(",
"fnCellValue",
")",
")",
"{",
"var",
"cellCoords",
"=",
"instance",
".",
"utils",
".",
"cellCoords",
"(",
"cell",
")",
",",
"cellId",
"=",
"instance",
".",
"utils",
".",
"translateCellCoords",
"(",
"{",
"row",
":",
"element",
".",
"row",
",",
"col",
":",
"element",
".",
"col",
"}",
")",
";",
"// get value",
"value",
"=",
"item",
"?",
"item",
".",
"value",
":",
"fnCellValue",
"(",
"cellCoords",
".",
"row",
",",
"cellCoords",
".",
"col",
")",
";",
"if",
"(",
"instance",
".",
"utils",
".",
"isNull",
"(",
"value",
")",
")",
"{",
"value",
"=",
"0",
";",
"}",
"if",
"(",
"cellId",
")",
"{",
"//update dependencies",
"instance",
".",
"matrix",
".",
"updateItem",
"(",
"cellId",
",",
"{",
"deps",
":",
"[",
"cell",
"]",
"}",
")",
";",
"}",
"}",
"else",
"{",
"// get value",
"value",
"=",
"item",
"?",
"item",
".",
"value",
":",
"document",
".",
"getElementById",
"(",
"cell",
")",
".",
"value",
";",
"//update dependencies",
"instance",
".",
"matrix",
".",
"updateElementItem",
"(",
"element",
",",
"{",
"deps",
":",
"[",
"cell",
"]",
"}",
")",
";",
"}",
"// check references error",
"if",
"(",
"item",
"&&",
"item",
".",
"deps",
")",
"{",
"if",
"(",
"item",
".",
"deps",
".",
"indexOf",
"(",
"cellId",
")",
"!==",
"-",
"1",
")",
"{",
"throw",
"Error",
"(",
"'REF'",
")",
";",
"}",
"}",
"// check if any error occurs",
"if",
"(",
"item",
"&&",
"item",
".",
"error",
")",
"{",
"throw",
"Error",
"(",
"item",
".",
"error",
")",
";",
"}",
"// return value if is set",
"if",
"(",
"instance",
".",
"utils",
".",
"isSet",
"(",
"value",
")",
")",
"{",
"var",
"result",
"=",
"instance",
".",
"helper",
".",
"number",
"(",
"value",
")",
";",
"return",
"!",
"isNaN",
"(",
"result",
")",
"?",
"result",
":",
"value",
";",
"}",
"// cell is not available",
"throw",
"Error",
"(",
"'NOT_AVAILABLE'",
")",
";",
"}"
] |
Get cell value
@param {String} cell => A1 AA1
@returns {*}
|
[
"Get",
"cell",
"value"
] |
240f37227f923076dbe9a8a24bce39655200f04b
|
https://github.com/rajgoel/reveal.js-plugins/blob/240f37227f923076dbe9a8a24bce39655200f04b/spreadsheet/ruleJS.all.full.js#L22023-L22077
|
|
9,295
|
rajgoel/reveal.js-plugins
|
spreadsheet/ruleJS.all.full.js
|
function (start, end) {
var fnCellValue = instance.custom.cellValue,
coordsStart = instance.utils.cellCoords(start),
coordsEnd = instance.utils.cellCoords(end),
element = this;
// iterate cells to get values and indexes
var cells = instance.utils.iterateCells.call(this, coordsStart, coordsEnd),
result = [];
// check if custom cellValue fn exists
if (instance.utils.isFunction(fnCellValue)) {
var cellId = instance.utils.translateCellCoords({row: element.row, col: element.col});
//update dependencies
instance.matrix.updateItem(cellId, {deps: cells.index});
} else {
//update dependencies
instance.matrix.updateElementItem(element, {deps: cells.index});
}
result.push(cells.value);
return result;
}
|
javascript
|
function (start, end) {
var fnCellValue = instance.custom.cellValue,
coordsStart = instance.utils.cellCoords(start),
coordsEnd = instance.utils.cellCoords(end),
element = this;
// iterate cells to get values and indexes
var cells = instance.utils.iterateCells.call(this, coordsStart, coordsEnd),
result = [];
// check if custom cellValue fn exists
if (instance.utils.isFunction(fnCellValue)) {
var cellId = instance.utils.translateCellCoords({row: element.row, col: element.col});
//update dependencies
instance.matrix.updateItem(cellId, {deps: cells.index});
} else {
//update dependencies
instance.matrix.updateElementItem(element, {deps: cells.index});
}
result.push(cells.value);
return result;
}
|
[
"function",
"(",
"start",
",",
"end",
")",
"{",
"var",
"fnCellValue",
"=",
"instance",
".",
"custom",
".",
"cellValue",
",",
"coordsStart",
"=",
"instance",
".",
"utils",
".",
"cellCoords",
"(",
"start",
")",
",",
"coordsEnd",
"=",
"instance",
".",
"utils",
".",
"cellCoords",
"(",
"end",
")",
",",
"element",
"=",
"this",
";",
"// iterate cells to get values and indexes",
"var",
"cells",
"=",
"instance",
".",
"utils",
".",
"iterateCells",
".",
"call",
"(",
"this",
",",
"coordsStart",
",",
"coordsEnd",
")",
",",
"result",
"=",
"[",
"]",
";",
"// check if custom cellValue fn exists",
"if",
"(",
"instance",
".",
"utils",
".",
"isFunction",
"(",
"fnCellValue",
")",
")",
"{",
"var",
"cellId",
"=",
"instance",
".",
"utils",
".",
"translateCellCoords",
"(",
"{",
"row",
":",
"element",
".",
"row",
",",
"col",
":",
"element",
".",
"col",
"}",
")",
";",
"//update dependencies",
"instance",
".",
"matrix",
".",
"updateItem",
"(",
"cellId",
",",
"{",
"deps",
":",
"cells",
".",
"index",
"}",
")",
";",
"}",
"else",
"{",
"//update dependencies",
"instance",
".",
"matrix",
".",
"updateElementItem",
"(",
"element",
",",
"{",
"deps",
":",
"cells",
".",
"index",
"}",
")",
";",
"}",
"result",
".",
"push",
"(",
"cells",
".",
"value",
")",
";",
"return",
"result",
";",
"}"
] |
Get cell range values
@param {String} start cell A1
@param {String} end cell B3
@returns {Array}
|
[
"Get",
"cell",
"range",
"values"
] |
240f37227f923076dbe9a8a24bce39655200f04b
|
https://github.com/rajgoel/reveal.js-plugins/blob/240f37227f923076dbe9a8a24bce39655200f04b/spreadsheet/ruleJS.all.full.js#L22085-L22111
|
|
9,296
|
rajgoel/reveal.js-plugins
|
spreadsheet/ruleJS.all.full.js
|
function (id) {
id = id.replace(/\$/g, '');
return instance.helper.cellValue.call(this, id);
}
|
javascript
|
function (id) {
id = id.replace(/\$/g, '');
return instance.helper.cellValue.call(this, id);
}
|
[
"function",
"(",
"id",
")",
"{",
"id",
"=",
"id",
".",
"replace",
"(",
"/",
"\\$",
"/",
"g",
",",
"''",
")",
";",
"return",
"instance",
".",
"helper",
".",
"cellValue",
".",
"call",
"(",
"this",
",",
"id",
")",
";",
"}"
] |
Get fixed cell value
@param {String} id
@returns {*}
|
[
"Get",
"fixed",
"cell",
"value"
] |
240f37227f923076dbe9a8a24bce39655200f04b
|
https://github.com/rajgoel/reveal.js-plugins/blob/240f37227f923076dbe9a8a24bce39655200f04b/spreadsheet/ruleJS.all.full.js#L22118-L22121
|
|
9,297
|
rajgoel/reveal.js-plugins
|
spreadsheet/ruleJS.all.full.js
|
function (start, end) {
start = start.replace(/\$/g, '');
end = end.replace(/\$/g, '');
return instance.helper.cellRangeValue.call(this, start, end);
}
|
javascript
|
function (start, end) {
start = start.replace(/\$/g, '');
end = end.replace(/\$/g, '');
return instance.helper.cellRangeValue.call(this, start, end);
}
|
[
"function",
"(",
"start",
",",
"end",
")",
"{",
"start",
"=",
"start",
".",
"replace",
"(",
"/",
"\\$",
"/",
"g",
",",
"''",
")",
";",
"end",
"=",
"end",
".",
"replace",
"(",
"/",
"\\$",
"/",
"g",
",",
"''",
")",
";",
"return",
"instance",
".",
"helper",
".",
"cellRangeValue",
".",
"call",
"(",
"this",
",",
"start",
",",
"end",
")",
";",
"}"
] |
Get fixed cell range values
@param {String} start
@param {String} end
@returns {Array}
|
[
"Get",
"fixed",
"cell",
"range",
"values"
] |
240f37227f923076dbe9a8a24bce39655200f04b
|
https://github.com/rajgoel/reveal.js-plugins/blob/240f37227f923076dbe9a8a24bce39655200f04b/spreadsheet/ruleJS.all.full.js#L22129-L22134
|
|
9,298
|
rajgoel/reveal.js-plugins
|
spreadsheet/ruleJS.all.full.js
|
function (formula, element) {
var result = null,
error = null;
try {
parser.setObj(element);
result = parser.parse(formula);
var id;
if (element instanceof HTMLElement) {
id = element.getAttribute('id');
} else if (element && element.id) {
id = element.id;
}
var deps = instance.matrix.getDependencies(id);
if (deps.indexOf(id) !== -1) {
result = null;
deps.forEach(function (id) {
instance.matrix.updateItem(id, {value: null, error: Exception.get('REF')});
});
throw Error('REF');
}
} catch (ex) {
var message = Exception.get(ex.message);
if (message) {
error = message;
} else {
error = Exception.get('ERROR');
}
//console.debug(ex.prop);
//debugger;
//error = ex.message;
//error = Exception.get('ERROR');
}
return {
error: error,
result: result
}
}
|
javascript
|
function (formula, element) {
var result = null,
error = null;
try {
parser.setObj(element);
result = parser.parse(formula);
var id;
if (element instanceof HTMLElement) {
id = element.getAttribute('id');
} else if (element && element.id) {
id = element.id;
}
var deps = instance.matrix.getDependencies(id);
if (deps.indexOf(id) !== -1) {
result = null;
deps.forEach(function (id) {
instance.matrix.updateItem(id, {value: null, error: Exception.get('REF')});
});
throw Error('REF');
}
} catch (ex) {
var message = Exception.get(ex.message);
if (message) {
error = message;
} else {
error = Exception.get('ERROR');
}
//console.debug(ex.prop);
//debugger;
//error = ex.message;
//error = Exception.get('ERROR');
}
return {
error: error,
result: result
}
}
|
[
"function",
"(",
"formula",
",",
"element",
")",
"{",
"var",
"result",
"=",
"null",
",",
"error",
"=",
"null",
";",
"try",
"{",
"parser",
".",
"setObj",
"(",
"element",
")",
";",
"result",
"=",
"parser",
".",
"parse",
"(",
"formula",
")",
";",
"var",
"id",
";",
"if",
"(",
"element",
"instanceof",
"HTMLElement",
")",
"{",
"id",
"=",
"element",
".",
"getAttribute",
"(",
"'id'",
")",
";",
"}",
"else",
"if",
"(",
"element",
"&&",
"element",
".",
"id",
")",
"{",
"id",
"=",
"element",
".",
"id",
";",
"}",
"var",
"deps",
"=",
"instance",
".",
"matrix",
".",
"getDependencies",
"(",
"id",
")",
";",
"if",
"(",
"deps",
".",
"indexOf",
"(",
"id",
")",
"!==",
"-",
"1",
")",
"{",
"result",
"=",
"null",
";",
"deps",
".",
"forEach",
"(",
"function",
"(",
"id",
")",
"{",
"instance",
".",
"matrix",
".",
"updateItem",
"(",
"id",
",",
"{",
"value",
":",
"null",
",",
"error",
":",
"Exception",
".",
"get",
"(",
"'REF'",
")",
"}",
")",
";",
"}",
")",
";",
"throw",
"Error",
"(",
"'REF'",
")",
";",
"}",
"}",
"catch",
"(",
"ex",
")",
"{",
"var",
"message",
"=",
"Exception",
".",
"get",
"(",
"ex",
".",
"message",
")",
";",
"if",
"(",
"message",
")",
"{",
"error",
"=",
"message",
";",
"}",
"else",
"{",
"error",
"=",
"Exception",
".",
"get",
"(",
"'ERROR'",
")",
";",
"}",
"//console.debug(ex.prop);",
"//debugger;",
"//error = ex.message;",
"//error = Exception.get('ERROR');",
"}",
"return",
"{",
"error",
":",
"error",
",",
"result",
":",
"result",
"}",
"}"
] |
parse input string using parser
@returns {Object} {{error: *, result: *}}
@param formula
@param element
|
[
"parse",
"input",
"string",
"using",
"parser"
] |
240f37227f923076dbe9a8a24bce39655200f04b
|
https://github.com/rajgoel/reveal.js-plugins/blob/240f37227f923076dbe9a8a24bce39655200f04b/spreadsheet/ruleJS.all.full.js#L22143-L22192
|
|
9,299
|
rajgoel/reveal.js-plugins
|
spreadsheet/ruleJS.all.full.js
|
function () {
instance = this;
parser = new FormulaParser(instance);
instance.formulas = Formula;
instance.matrix = new Matrix();
instance.custom = {};
if (rootElement) {
instance.matrix.scan();
}
}
|
javascript
|
function () {
instance = this;
parser = new FormulaParser(instance);
instance.formulas = Formula;
instance.matrix = new Matrix();
instance.custom = {};
if (rootElement) {
instance.matrix.scan();
}
}
|
[
"function",
"(",
")",
"{",
"instance",
"=",
"this",
";",
"parser",
"=",
"new",
"FormulaParser",
"(",
"instance",
")",
";",
"instance",
".",
"formulas",
"=",
"Formula",
";",
"instance",
".",
"matrix",
"=",
"new",
"Matrix",
"(",
")",
";",
"instance",
".",
"custom",
"=",
"{",
"}",
";",
"if",
"(",
"rootElement",
")",
"{",
"instance",
".",
"matrix",
".",
"scan",
"(",
")",
";",
"}",
"}"
] |
initial method, create formulas, parser and matrix objects
|
[
"initial",
"method",
"create",
"formulas",
"parser",
"and",
"matrix",
"objects"
] |
240f37227f923076dbe9a8a24bce39655200f04b
|
https://github.com/rajgoel/reveal.js-plugins/blob/240f37227f923076dbe9a8a24bce39655200f04b/spreadsheet/ruleJS.all.full.js#L22197-L22210
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.