repo
stringlengths 5
67
| path
stringlengths 4
116
| func_name
stringlengths 0
58
| original_string
stringlengths 52
373k
| language
stringclasses 1
value | code
stringlengths 52
373k
| code_tokens
sequence | docstring
stringlengths 4
11.8k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 86
226
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
feedhenry/fh-forms | lib/middleware/formProjects.js | getTheme | function getTheme(req, res, next) {
var params = {
appId: req.params.projectid || req.params.id
};
forms.getAppTheme(_.extend(req.connectionOptions, params), function(err, theme) {
if (err) {
return next(err);
}
req.appformsResultPayload = req.appformsResultPayload || {};
if (_.isObject(req.appformsResultPayload.data) && theme && !req.getFullTheme) {
req.appformsResultPayload.data.theme = theme._id;
} else {
//Want the full theme definition
req.appformsResultPayload = {
data: theme
};
}
next();
});
} | javascript | function getTheme(req, res, next) {
var params = {
appId: req.params.projectid || req.params.id
};
forms.getAppTheme(_.extend(req.connectionOptions, params), function(err, theme) {
if (err) {
return next(err);
}
req.appformsResultPayload = req.appformsResultPayload || {};
if (_.isObject(req.appformsResultPayload.data) && theme && !req.getFullTheme) {
req.appformsResultPayload.data.theme = theme._id;
} else {
//Want the full theme definition
req.appformsResultPayload = {
data: theme
};
}
next();
});
} | [
"function",
"getTheme",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"var",
"params",
"=",
"{",
"appId",
":",
"req",
".",
"params",
".",
"projectid",
"||",
"req",
".",
"params",
".",
"id",
"}",
";",
"forms",
".",
"getAppTheme",
"(",
"_",
".",
"extend",
"(",
"req",
".",
"connectionOptions",
",",
"params",
")",
",",
"function",
"(",
"err",
",",
"theme",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"next",
"(",
"err",
")",
";",
"}",
"req",
".",
"appformsResultPayload",
"=",
"req",
".",
"appformsResultPayload",
"||",
"{",
"}",
";",
"if",
"(",
"_",
".",
"isObject",
"(",
"req",
".",
"appformsResultPayload",
".",
"data",
")",
"&&",
"theme",
"&&",
"!",
"req",
".",
"getFullTheme",
")",
"{",
"req",
".",
"appformsResultPayload",
".",
"data",
".",
"theme",
"=",
"theme",
".",
"_id",
";",
"}",
"else",
"{",
"req",
".",
"appformsResultPayload",
"=",
"{",
"data",
":",
"theme",
"}",
";",
"}",
"next",
"(",
")",
";",
"}",
")",
";",
"}"
] | Middleware To Get A Theme Assocaited With A Project
@param req
@param res
@param next | [
"Middleware",
"To",
"Get",
"A",
"Theme",
"Assocaited",
"With",
"A",
"Project"
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/middleware/formProjects.js#L68-L90 | train |
feedhenry/fh-forms | lib/middleware/formProjects.js | remove | function remove(req, res, next) {
var params = {
appId: req.params.id
};
forms.deleteAppReferences(req.connectionOptions, params, formsResultHandlers(constants.resultTypes.formProjects, req, next));
} | javascript | function remove(req, res, next) {
var params = {
appId: req.params.id
};
forms.deleteAppReferences(req.connectionOptions, params, formsResultHandlers(constants.resultTypes.formProjects, req, next));
} | [
"function",
"remove",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"var",
"params",
"=",
"{",
"appId",
":",
"req",
".",
"params",
".",
"id",
"}",
";",
"forms",
".",
"deleteAppReferences",
"(",
"req",
".",
"connectionOptions",
",",
"params",
",",
"formsResultHandlers",
"(",
"constants",
".",
"resultTypes",
".",
"formProjects",
",",
"req",
",",
"next",
")",
")",
";",
"}"
] | Removing A Forms Project. This is mainly done when projects are deleted.
Cleans up references to the project in the database. AppThemes/AppForms/AppConfig etc.
@param req
@param res
@param next | [
"Removing",
"A",
"Forms",
"Project",
".",
"This",
"is",
"mainly",
"done",
"when",
"projects",
"are",
"deleted",
"."
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/middleware/formProjects.js#L100-L106 | train |
feedhenry/fh-forms | lib/middleware/formProjects.js | get | function get(req, res, next) {
var params = {
appId: req.params.projectid || req.params.id
};
forms.getAppFormsForApp(_.extend(req.connectionOptions, params), formsResultHandlers(constants.resultTypes.formProjects, req, next));
} | javascript | function get(req, res, next) {
var params = {
appId: req.params.projectid || req.params.id
};
forms.getAppFormsForApp(_.extend(req.connectionOptions, params), formsResultHandlers(constants.resultTypes.formProjects, req, next));
} | [
"function",
"get",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"var",
"params",
"=",
"{",
"appId",
":",
"req",
".",
"params",
".",
"projectid",
"||",
"req",
".",
"params",
".",
"id",
"}",
";",
"forms",
".",
"getAppFormsForApp",
"(",
"_",
".",
"extend",
"(",
"req",
".",
"connectionOptions",
",",
"params",
")",
",",
"formsResultHandlers",
"(",
"constants",
".",
"resultTypes",
".",
"formProjects",
",",
"req",
",",
"next",
")",
")",
";",
"}"
] | Get Forms Related To A Project Guid
@param req
@param res
@param next | [
"Get",
"Forms",
"Related",
"To",
"A",
"Project",
"Guid"
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/middleware/formProjects.js#L114-L120 | train |
feedhenry/fh-forms | lib/middleware/formProjects.js | getFormIds | function getFormIds(req, res, next) {
var params = {
appId: req.params.projectid || req.params.id
};
forms.getAppFormsForApp(_.extend(req.connectionOptions, params), function(err, appFormResult) {
if (err) {
return next(err);
}
//Only Want The Form Ids
req.appformsResultPayload = {
data: _.map(_.compact(appFormResult.forms), function(form) {
return form._id.toString();
}),
type: constants.resultTypes.formProjects
};
next();
});
} | javascript | function getFormIds(req, res, next) {
var params = {
appId: req.params.projectid || req.params.id
};
forms.getAppFormsForApp(_.extend(req.connectionOptions, params), function(err, appFormResult) {
if (err) {
return next(err);
}
//Only Want The Form Ids
req.appformsResultPayload = {
data: _.map(_.compact(appFormResult.forms), function(form) {
return form._id.toString();
}),
type: constants.resultTypes.formProjects
};
next();
});
} | [
"function",
"getFormIds",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"var",
"params",
"=",
"{",
"appId",
":",
"req",
".",
"params",
".",
"projectid",
"||",
"req",
".",
"params",
".",
"id",
"}",
";",
"forms",
".",
"getAppFormsForApp",
"(",
"_",
".",
"extend",
"(",
"req",
".",
"connectionOptions",
",",
"params",
")",
",",
"function",
"(",
"err",
",",
"appFormResult",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"next",
"(",
"err",
")",
";",
"}",
"req",
".",
"appformsResultPayload",
"=",
"{",
"data",
":",
"_",
".",
"map",
"(",
"_",
".",
"compact",
"(",
"appFormResult",
".",
"forms",
")",
",",
"function",
"(",
"form",
")",
"{",
"return",
"form",
".",
"_id",
".",
"toString",
"(",
")",
";",
"}",
")",
",",
"type",
":",
"constants",
".",
"resultTypes",
".",
"formProjects",
"}",
";",
"next",
"(",
")",
";",
"}",
")",
";",
"}"
] | Getting Form Ids Only Associated With A Project
@param req
@param res
@param next | [
"Getting",
"Form",
"Ids",
"Only",
"Associated",
"With",
"A",
"Project"
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/middleware/formProjects.js#L128-L148 | train |
feedhenry/fh-forms | lib/middleware/formProjects.js | getConfig | function getConfig(req, res, next) {
var params = {
appId: req.params.projectid || req.params.id
};
forms.getAppConfig(req.connectionOptions, params, formsResultHandlers(constants.resultTypes.formProjects, req, next));
} | javascript | function getConfig(req, res, next) {
var params = {
appId: req.params.projectid || req.params.id
};
forms.getAppConfig(req.connectionOptions, params, formsResultHandlers(constants.resultTypes.formProjects, req, next));
} | [
"function",
"getConfig",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"var",
"params",
"=",
"{",
"appId",
":",
"req",
".",
"params",
".",
"projectid",
"||",
"req",
".",
"params",
".",
"id",
"}",
";",
"forms",
".",
"getAppConfig",
"(",
"req",
".",
"connectionOptions",
",",
"params",
",",
"formsResultHandlers",
"(",
"constants",
".",
"resultTypes",
".",
"formProjects",
",",
"req",
",",
"next",
")",
")",
";",
"}"
] | Get Config For A Single Project
@param req
@param res
@param next | [
"Get",
"Config",
"For",
"A",
"Single",
"Project"
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/middleware/formProjects.js#L157-L163 | train |
feedhenry/fh-forms | lib/middleware/formProjects.js | updateConfig | function updateConfig(req, res, next) {
var params = {
appId: req.params.id
};
forms.updateAppConfig(req.connectionOptions, _.extend(req.body, params), formsResultHandlers(constants.resultTypes.formProjects, req, next));
} | javascript | function updateConfig(req, res, next) {
var params = {
appId: req.params.id
};
forms.updateAppConfig(req.connectionOptions, _.extend(req.body, params), formsResultHandlers(constants.resultTypes.formProjects, req, next));
} | [
"function",
"updateConfig",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"var",
"params",
"=",
"{",
"appId",
":",
"req",
".",
"params",
".",
"id",
"}",
";",
"forms",
".",
"updateAppConfig",
"(",
"req",
".",
"connectionOptions",
",",
"_",
".",
"extend",
"(",
"req",
".",
"body",
",",
"params",
")",
",",
"formsResultHandlers",
"(",
"constants",
".",
"resultTypes",
".",
"formProjects",
",",
"req",
",",
"next",
")",
")",
";",
"}"
] | Update Config For A Single Project
@param req
@param res
@param next | [
"Update",
"Config",
"For",
"A",
"Single",
"Project"
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/middleware/formProjects.js#L172-L178 | train |
feedhenry/fh-forms | lib/middleware/formProjects.js | exportProjects | function exportProjects(req, res, next) {
var options = req.connectionOptions;
forms.exportAppForms(options, formsResultHandlers(constants.resultTypes.formProjects, req, next));
} | javascript | function exportProjects(req, res, next) {
var options = req.connectionOptions;
forms.exportAppForms(options, formsResultHandlers(constants.resultTypes.formProjects, req, next));
} | [
"function",
"exportProjects",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"var",
"options",
"=",
"req",
".",
"connectionOptions",
";",
"forms",
".",
"exportAppForms",
"(",
"options",
",",
"formsResultHandlers",
"(",
"constants",
".",
"resultTypes",
".",
"formProjects",
",",
"req",
",",
"next",
")",
")",
";",
"}"
] | Exporting All App Forms
@param req
@param res
@param next | [
"Exporting",
"All",
"App",
"Forms"
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/middleware/formProjects.js#L186-L190 | train |
feedhenry/fh-forms | lib/middleware/formProjects.js | importProjects | function importProjects(req, res, next) {
var options = req.connectionOptions;
var appFormsToImport = req.body || [];
if (!_.isArray(appFormsToImport)) {
return next("Expected An Array Of App Form Entries");
}
forms.importAppForms(options, appFormsToImport, formsResultHandlers(constants.resultTypes.formProjects, req, next));
} | javascript | function importProjects(req, res, next) {
var options = req.connectionOptions;
var appFormsToImport = req.body || [];
if (!_.isArray(appFormsToImport)) {
return next("Expected An Array Of App Form Entries");
}
forms.importAppForms(options, appFormsToImport, formsResultHandlers(constants.resultTypes.formProjects, req, next));
} | [
"function",
"importProjects",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"var",
"options",
"=",
"req",
".",
"connectionOptions",
";",
"var",
"appFormsToImport",
"=",
"req",
".",
"body",
"||",
"[",
"]",
";",
"if",
"(",
"!",
"_",
".",
"isArray",
"(",
"appFormsToImport",
")",
")",
"{",
"return",
"next",
"(",
"\"Expected An Array Of App Form Entries\"",
")",
";",
"}",
"forms",
".",
"importAppForms",
"(",
"options",
",",
"appFormsToImport",
",",
"formsResultHandlers",
"(",
"constants",
".",
"resultTypes",
".",
"formProjects",
",",
"req",
",",
"next",
")",
")",
";",
"}"
] | Importing All App Forms
@param req
@param res
@param next | [
"Importing",
"All",
"App",
"Forms"
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/middleware/formProjects.js#L198-L208 | train |
feedhenry/fh-forms | lib/middleware/formProjects.js | exportProjectConfig | function exportProjectConfig(req, res, next) {
var options = req.connectionOptions;
forms.exportAppConfig(options, formsResultHandlers(constants.resultTypes.formProjects, req, next));
} | javascript | function exportProjectConfig(req, res, next) {
var options = req.connectionOptions;
forms.exportAppConfig(options, formsResultHandlers(constants.resultTypes.formProjects, req, next));
} | [
"function",
"exportProjectConfig",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"var",
"options",
"=",
"req",
".",
"connectionOptions",
";",
"forms",
".",
"exportAppConfig",
"(",
"options",
",",
"formsResultHandlers",
"(",
"constants",
".",
"resultTypes",
".",
"formProjects",
",",
"req",
",",
"next",
")",
")",
";",
"}"
] | Exporting Project Config
@param req
@param res
@param next | [
"Exporting",
"Project",
"Config"
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/middleware/formProjects.js#L216-L220 | train |
feedhenry/fh-forms | lib/middleware/formProjects.js | importProjectConfig | function importProjectConfig(req, res, next) {
var options = req.connectionOptions;
var projectConfigToImport = req.body || [];
if (!_.isArray(projectConfigToImport)) {
return next("Expected An Array Of Project Config Values");
}
forms.importAppConfig(options, projectConfigToImport, formsResultHandlers(constants.resultTypes.formProjects, req, next));
} | javascript | function importProjectConfig(req, res, next) {
var options = req.connectionOptions;
var projectConfigToImport = req.body || [];
if (!_.isArray(projectConfigToImport)) {
return next("Expected An Array Of Project Config Values");
}
forms.importAppConfig(options, projectConfigToImport, formsResultHandlers(constants.resultTypes.formProjects, req, next));
} | [
"function",
"importProjectConfig",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"var",
"options",
"=",
"req",
".",
"connectionOptions",
";",
"var",
"projectConfigToImport",
"=",
"req",
".",
"body",
"||",
"[",
"]",
";",
"if",
"(",
"!",
"_",
".",
"isArray",
"(",
"projectConfigToImport",
")",
")",
"{",
"return",
"next",
"(",
"\"Expected An Array Of Project Config Values\"",
")",
";",
"}",
"forms",
".",
"importAppConfig",
"(",
"options",
",",
"projectConfigToImport",
",",
"formsResultHandlers",
"(",
"constants",
".",
"resultTypes",
".",
"formProjects",
",",
"req",
",",
"next",
")",
")",
";",
"}"
] | Importing Project Config.
@param req
@param res
@param next | [
"Importing",
"Project",
"Config",
"."
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/middleware/formProjects.js#L228-L238 | train |
feedhenry/fh-forms | lib/impl/pdfGeneration/doPdfGeneration.js | loadPdfTemplate | function loadPdfTemplate(params, cb) {
logger.debug("renderPDF loadPdfTemplate", params);
//Already have a compiled template, no need to compile it again.
if (pdfTemplate) {
return cb(null, pdfTemplate);
} else {
readAndCompileTemplate(function(err, compiledTemplate) {
pdfTemplate = compiledTemplate;
return cb(err, pdfTemplate);
});
}
} | javascript | function loadPdfTemplate(params, cb) {
logger.debug("renderPDF loadPdfTemplate", params);
//Already have a compiled template, no need to compile it again.
if (pdfTemplate) {
return cb(null, pdfTemplate);
} else {
readAndCompileTemplate(function(err, compiledTemplate) {
pdfTemplate = compiledTemplate;
return cb(err, pdfTemplate);
});
}
} | [
"function",
"loadPdfTemplate",
"(",
"params",
",",
"cb",
")",
"{",
"logger",
".",
"debug",
"(",
"\"renderPDF loadPdfTemplate\"",
",",
"params",
")",
";",
"if",
"(",
"pdfTemplate",
")",
"{",
"return",
"cb",
"(",
"null",
",",
"pdfTemplate",
")",
";",
"}",
"else",
"{",
"readAndCompileTemplate",
"(",
"function",
"(",
"err",
",",
"compiledTemplate",
")",
"{",
"pdfTemplate",
"=",
"compiledTemplate",
";",
"return",
"cb",
"(",
"err",
",",
"pdfTemplate",
")",
";",
"}",
")",
";",
"}",
"}"
] | Loading The Submission Template From Studio
@param params
- location
- pdfTemplateLoc
@param cb
@returns {*}
@private | [
"Loading",
"The",
"Submission",
"Template",
"From",
"Studio"
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/pdfGeneration/doPdfGeneration.js#L19-L31 | train |
cloudfour/drizzle-builder | src/write/index.js | write | function write(drizzleData) {
return Promise.all([
writePages(drizzleData),
writeCollections(drizzleData)
]).then(
() => drizzleData,
error => DrizzleError.error(error, drizzleData.options)
);
} | javascript | function write(drizzleData) {
return Promise.all([
writePages(drizzleData),
writeCollections(drizzleData)
]).then(
() => drizzleData,
error => DrizzleError.error(error, drizzleData.options)
);
} | [
"function",
"write",
"(",
"drizzleData",
")",
"{",
"return",
"Promise",
".",
"all",
"(",
"[",
"writePages",
"(",
"drizzleData",
")",
",",
"writeCollections",
"(",
"drizzleData",
")",
"]",
")",
".",
"then",
"(",
"(",
")",
"=>",
"drizzleData",
",",
"error",
"=>",
"DrizzleError",
".",
"error",
"(",
"error",
",",
"drizzleData",
".",
"options",
")",
")",
";",
"}"
] | Write pages and collection-pages to filesystem.
@param {Object} drizzleData All drizzle data so far
@return {Promise} resolving to drizzleData | [
"Write",
"pages",
"and",
"collection",
"-",
"pages",
"to",
"filesystem",
"."
] | 1c320cb059c749c28339a661d1768d3a643e5f1c | https://github.com/cloudfour/drizzle-builder/blob/1c320cb059c749c28339a661d1768d3a643e5f1c/src/write/index.js#L12-L20 | train |
stackgl/gl-shader-core | shader-core.js | relinkUniforms | function relinkUniforms(gl, program, locations, uniforms) {
for(var i=0; i<uniforms.length; ++i) {
locations[i] = gl.getUniformLocation(program, uniforms[i].name)
}
} | javascript | function relinkUniforms(gl, program, locations, uniforms) {
for(var i=0; i<uniforms.length; ++i) {
locations[i] = gl.getUniformLocation(program, uniforms[i].name)
}
} | [
"function",
"relinkUniforms",
"(",
"gl",
",",
"program",
",",
"locations",
",",
"uniforms",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"uniforms",
".",
"length",
";",
"++",
"i",
")",
"{",
"locations",
"[",
"i",
"]",
"=",
"gl",
".",
"getUniformLocation",
"(",
"program",
",",
"uniforms",
"[",
"i",
"]",
".",
"name",
")",
"}",
"}"
] | Relinks all uniforms | [
"Relinks",
"all",
"uniforms"
] | 25e021e9239ad7b73ce08ff0fdc97e2e68e1d075 | https://github.com/stackgl/gl-shader-core/blob/25e021e9239ad7b73ce08ff0fdc97e2e68e1d075/shader-core.js#L65-L69 | train |
stackgl/gl-shader-core | shader-core.js | createShader | function createShader(
gl
, vertSource
, fragSource
, uniforms
, attributes) {
//Compile vertex shader
var vertShader = gl.createShader(gl.VERTEX_SHADER)
gl.shaderSource(vertShader, vertSource)
gl.compileShader(vertShader)
if(!gl.getShaderParameter(vertShader, gl.COMPILE_STATUS)) {
var errLog = gl.getShaderInfoLog(vertShader)
console.error('gl-shader: Error compling vertex shader:', errLog)
throw new Error('gl-shader: Error compiling vertex shader:' + errLog)
}
//Compile fragment shader
var fragShader = gl.createShader(gl.FRAGMENT_SHADER)
gl.shaderSource(fragShader, fragSource)
gl.compileShader(fragShader)
if(!gl.getShaderParameter(fragShader, gl.COMPILE_STATUS)) {
var errLog = gl.getShaderInfoLog(fragShader)
console.error('gl-shader: Error compiling fragment shader:', errLog)
throw new Error('gl-shader: Error compiling fragment shader:' + errLog)
}
//Link program
var program = gl.createProgram()
gl.attachShader(program, fragShader)
gl.attachShader(program, vertShader)
//Optional default attriubte locations
attributes.forEach(function(a) {
if (typeof a.location === 'number')
gl.bindAttribLocation(program, a.location, a.name)
})
gl.linkProgram(program)
if(!gl.getProgramParameter(program, gl.LINK_STATUS)) {
var errLog = gl.getProgramInfoLog(program)
console.error('gl-shader: Error linking shader program:', errLog)
throw new Error('gl-shader: Error linking shader program:' + errLog)
}
//Return final linked shader object
var shader = new Shader(
gl,
program,
vertShader,
fragShader
)
shader.updateExports(uniforms, attributes)
return shader
} | javascript | function createShader(
gl
, vertSource
, fragSource
, uniforms
, attributes) {
//Compile vertex shader
var vertShader = gl.createShader(gl.VERTEX_SHADER)
gl.shaderSource(vertShader, vertSource)
gl.compileShader(vertShader)
if(!gl.getShaderParameter(vertShader, gl.COMPILE_STATUS)) {
var errLog = gl.getShaderInfoLog(vertShader)
console.error('gl-shader: Error compling vertex shader:', errLog)
throw new Error('gl-shader: Error compiling vertex shader:' + errLog)
}
//Compile fragment shader
var fragShader = gl.createShader(gl.FRAGMENT_SHADER)
gl.shaderSource(fragShader, fragSource)
gl.compileShader(fragShader)
if(!gl.getShaderParameter(fragShader, gl.COMPILE_STATUS)) {
var errLog = gl.getShaderInfoLog(fragShader)
console.error('gl-shader: Error compiling fragment shader:', errLog)
throw new Error('gl-shader: Error compiling fragment shader:' + errLog)
}
//Link program
var program = gl.createProgram()
gl.attachShader(program, fragShader)
gl.attachShader(program, vertShader)
//Optional default attriubte locations
attributes.forEach(function(a) {
if (typeof a.location === 'number')
gl.bindAttribLocation(program, a.location, a.name)
})
gl.linkProgram(program)
if(!gl.getProgramParameter(program, gl.LINK_STATUS)) {
var errLog = gl.getProgramInfoLog(program)
console.error('gl-shader: Error linking shader program:', errLog)
throw new Error('gl-shader: Error linking shader program:' + errLog)
}
//Return final linked shader object
var shader = new Shader(
gl,
program,
vertShader,
fragShader
)
shader.updateExports(uniforms, attributes)
return shader
} | [
"function",
"createShader",
"(",
"gl",
",",
"vertSource",
",",
"fragSource",
",",
"uniforms",
",",
"attributes",
")",
"{",
"var",
"vertShader",
"=",
"gl",
".",
"createShader",
"(",
"gl",
".",
"VERTEX_SHADER",
")",
"gl",
".",
"shaderSource",
"(",
"vertShader",
",",
"vertSource",
")",
"gl",
".",
"compileShader",
"(",
"vertShader",
")",
"if",
"(",
"!",
"gl",
".",
"getShaderParameter",
"(",
"vertShader",
",",
"gl",
".",
"COMPILE_STATUS",
")",
")",
"{",
"var",
"errLog",
"=",
"gl",
".",
"getShaderInfoLog",
"(",
"vertShader",
")",
"console",
".",
"error",
"(",
"'gl-shader: Error compling vertex shader:'",
",",
"errLog",
")",
"throw",
"new",
"Error",
"(",
"'gl-shader: Error compiling vertex shader:'",
"+",
"errLog",
")",
"}",
"var",
"fragShader",
"=",
"gl",
".",
"createShader",
"(",
"gl",
".",
"FRAGMENT_SHADER",
")",
"gl",
".",
"shaderSource",
"(",
"fragShader",
",",
"fragSource",
")",
"gl",
".",
"compileShader",
"(",
"fragShader",
")",
"if",
"(",
"!",
"gl",
".",
"getShaderParameter",
"(",
"fragShader",
",",
"gl",
".",
"COMPILE_STATUS",
")",
")",
"{",
"var",
"errLog",
"=",
"gl",
".",
"getShaderInfoLog",
"(",
"fragShader",
")",
"console",
".",
"error",
"(",
"'gl-shader: Error compiling fragment shader:'",
",",
"errLog",
")",
"throw",
"new",
"Error",
"(",
"'gl-shader: Error compiling fragment shader:'",
"+",
"errLog",
")",
"}",
"var",
"program",
"=",
"gl",
".",
"createProgram",
"(",
")",
"gl",
".",
"attachShader",
"(",
"program",
",",
"fragShader",
")",
"gl",
".",
"attachShader",
"(",
"program",
",",
"vertShader",
")",
"attributes",
".",
"forEach",
"(",
"function",
"(",
"a",
")",
"{",
"if",
"(",
"typeof",
"a",
".",
"location",
"===",
"'number'",
")",
"gl",
".",
"bindAttribLocation",
"(",
"program",
",",
"a",
".",
"location",
",",
"a",
".",
"name",
")",
"}",
")",
"gl",
".",
"linkProgram",
"(",
"program",
")",
"if",
"(",
"!",
"gl",
".",
"getProgramParameter",
"(",
"program",
",",
"gl",
".",
"LINK_STATUS",
")",
")",
"{",
"var",
"errLog",
"=",
"gl",
".",
"getProgramInfoLog",
"(",
"program",
")",
"console",
".",
"error",
"(",
"'gl-shader: Error linking shader program:'",
",",
"errLog",
")",
"throw",
"new",
"Error",
"(",
"'gl-shader: Error linking shader program:'",
"+",
"errLog",
")",
"}",
"var",
"shader",
"=",
"new",
"Shader",
"(",
"gl",
",",
"program",
",",
"vertShader",
",",
"fragShader",
")",
"shader",
".",
"updateExports",
"(",
"uniforms",
",",
"attributes",
")",
"return",
"shader",
"}"
] | Compiles and links a shader program with the given attribute and vertex list | [
"Compiles",
"and",
"links",
"a",
"shader",
"program",
"with",
"the",
"given",
"attribute",
"and",
"vertex",
"list"
] | 25e021e9239ad7b73ce08ff0fdc97e2e68e1d075 | https://github.com/stackgl/gl-shader-core/blob/25e021e9239ad7b73ce08ff0fdc97e2e68e1d075/shader-core.js#L72-L127 | train |
cloudfour/drizzle-builder | src/parse/pages.js | parsePages | function parsePages(options) {
return readFileTree(options.src.pages, options.keys.pages, options);
} | javascript | function parsePages(options) {
return readFileTree(options.src.pages, options.keys.pages, options);
} | [
"function",
"parsePages",
"(",
"options",
")",
"{",
"return",
"readFileTree",
"(",
"options",
".",
"src",
".",
"pages",
",",
"options",
".",
"keys",
".",
"pages",
",",
"options",
")",
";",
"}"
] | Parse page files.
@param {Object} Options
@return {Promise} resolving to page data | [
"Parse",
"page",
"files",
"."
] | 1c320cb059c749c28339a661d1768d3a643e5f1c | https://github.com/cloudfour/drizzle-builder/blob/1c320cb059c749c28339a661d1768d3a643e5f1c/src/parse/pages.js#L11-L13 | train |
crispy1989/node-zstreams | lib/transform.js | ZTransform | function ZTransform(options) {
if(options) {
if(options.objectMode) {
options.readableObjectMode = true;
options.writableObjectMode = true;
}
if(options.readableObjectMode && options.writableObjectMode) {
options.objectMode = true;
}
if(typeof options.transform === 'function') {
this._transform = options.transform;
}
if(typeof options.flush === 'function') {
this._flush = options.flush;
}
}
Transform.call(this, options);
// note: exclamation marks are used to convert to booleans
if(options && !options.objectMode && (!options.readableObjectMode) !== (!options.writableObjectMode)) {
this._writableState.objectMode = !!options.writableObjectMode;
this._readableState.objectMode = !!options.readableObjectMode;
}
if(options && options.readableObjectMode) {
this._readableState.highWaterMark = 16;
}
if(options && options.writableObjectMode) {
this._writableState.highWaterMark = 16;
}
streamMixins.call(this, Transform.prototype, options);
readableMixins.call(this, options);
writableMixins.call(this, options);
} | javascript | function ZTransform(options) {
if(options) {
if(options.objectMode) {
options.readableObjectMode = true;
options.writableObjectMode = true;
}
if(options.readableObjectMode && options.writableObjectMode) {
options.objectMode = true;
}
if(typeof options.transform === 'function') {
this._transform = options.transform;
}
if(typeof options.flush === 'function') {
this._flush = options.flush;
}
}
Transform.call(this, options);
// note: exclamation marks are used to convert to booleans
if(options && !options.objectMode && (!options.readableObjectMode) !== (!options.writableObjectMode)) {
this._writableState.objectMode = !!options.writableObjectMode;
this._readableState.objectMode = !!options.readableObjectMode;
}
if(options && options.readableObjectMode) {
this._readableState.highWaterMark = 16;
}
if(options && options.writableObjectMode) {
this._writableState.highWaterMark = 16;
}
streamMixins.call(this, Transform.prototype, options);
readableMixins.call(this, options);
writableMixins.call(this, options);
} | [
"function",
"ZTransform",
"(",
"options",
")",
"{",
"if",
"(",
"options",
")",
"{",
"if",
"(",
"options",
".",
"objectMode",
")",
"{",
"options",
".",
"readableObjectMode",
"=",
"true",
";",
"options",
".",
"writableObjectMode",
"=",
"true",
";",
"}",
"if",
"(",
"options",
".",
"readableObjectMode",
"&&",
"options",
".",
"writableObjectMode",
")",
"{",
"options",
".",
"objectMode",
"=",
"true",
";",
"}",
"if",
"(",
"typeof",
"options",
".",
"transform",
"===",
"'function'",
")",
"{",
"this",
".",
"_transform",
"=",
"options",
".",
"transform",
";",
"}",
"if",
"(",
"typeof",
"options",
".",
"flush",
"===",
"'function'",
")",
"{",
"this",
".",
"_flush",
"=",
"options",
".",
"flush",
";",
"}",
"}",
"Transform",
".",
"call",
"(",
"this",
",",
"options",
")",
";",
"if",
"(",
"options",
"&&",
"!",
"options",
".",
"objectMode",
"&&",
"(",
"!",
"options",
".",
"readableObjectMode",
")",
"!==",
"(",
"!",
"options",
".",
"writableObjectMode",
")",
")",
"{",
"this",
".",
"_writableState",
".",
"objectMode",
"=",
"!",
"!",
"options",
".",
"writableObjectMode",
";",
"this",
".",
"_readableState",
".",
"objectMode",
"=",
"!",
"!",
"options",
".",
"readableObjectMode",
";",
"}",
"if",
"(",
"options",
"&&",
"options",
".",
"readableObjectMode",
")",
"{",
"this",
".",
"_readableState",
".",
"highWaterMark",
"=",
"16",
";",
"}",
"if",
"(",
"options",
"&&",
"options",
".",
"writableObjectMode",
")",
"{",
"this",
".",
"_writableState",
".",
"highWaterMark",
"=",
"16",
";",
"}",
"streamMixins",
".",
"call",
"(",
"this",
",",
"Transform",
".",
"prototype",
",",
"options",
")",
";",
"readableMixins",
".",
"call",
"(",
"this",
",",
"options",
")",
";",
"writableMixins",
".",
"call",
"(",
"this",
",",
"options",
")",
";",
"}"
] | ZTransform transforms input to the stream through the _transform function.
@class ZTransform
@constructor
@extends Transform
@uses _Stream
@uses _Readable
@uses _Writable
@param {Object} [options] - Stream options | [
"ZTransform",
"transforms",
"input",
"to",
"the",
"stream",
"through",
"the",
"_transform",
"function",
"."
] | 4ec01a49d1d00c542ee1dfa4b3bedcf1324e9ffd | https://github.com/crispy1989/node-zstreams/blob/4ec01a49d1d00c542ee1dfa4b3bedcf1324e9ffd/lib/transform.js#L19-L50 | train |
crispy1989/node-zstreams | lib/streams/compound-duplex.js | CompoundDuplex | function CompoundDuplex(writable, readable, options) {
var self = this;
var convertToZStream = require('../index'); // for circular dependencies
if(!readable || typeof readable.read !== 'function') {
options = readable;
readable = writable;
writable = null;
}
if(writable && !writable._isZStream) {
writable = convertToZStream(writable);
}
if(!readable._isZStream) {
readable = convertToZStream(readable);
}
if(!writable) {
if(typeof readable.getStreamChain !== 'function') {
throw new Error('Can only use shorthand CompoundDuplex constructor if pipeline is all zstreams');
}
writable = readable.getStreamChain().getStreams()[0];
}
if(!options) options = {};
options.readableObjectMode = readable.isReadableObjectMode();
options.writableObjectMode = writable.isWritableObjectMode();
Duplex.call(this, options);
this._compoundReadable = readable;
this._compoundWritable = writable;
this._waitingForReadableData = false;
writable.on('chainerror', function(error) {
// Forward the error on; if the chain is to be destructed, the compound stream's _abortStream() method will be called
this.ignoreError();
self.emit('error', error);
});
readable.on('readable', function() {
if(self._waitingForReadableData) {
self._waitingForReadableData = false;
self._readSomeData();
}
});
readable.on('end', function() {
self.push(null);
});
} | javascript | function CompoundDuplex(writable, readable, options) {
var self = this;
var convertToZStream = require('../index'); // for circular dependencies
if(!readable || typeof readable.read !== 'function') {
options = readable;
readable = writable;
writable = null;
}
if(writable && !writable._isZStream) {
writable = convertToZStream(writable);
}
if(!readable._isZStream) {
readable = convertToZStream(readable);
}
if(!writable) {
if(typeof readable.getStreamChain !== 'function') {
throw new Error('Can only use shorthand CompoundDuplex constructor if pipeline is all zstreams');
}
writable = readable.getStreamChain().getStreams()[0];
}
if(!options) options = {};
options.readableObjectMode = readable.isReadableObjectMode();
options.writableObjectMode = writable.isWritableObjectMode();
Duplex.call(this, options);
this._compoundReadable = readable;
this._compoundWritable = writable;
this._waitingForReadableData = false;
writable.on('chainerror', function(error) {
// Forward the error on; if the chain is to be destructed, the compound stream's _abortStream() method will be called
this.ignoreError();
self.emit('error', error);
});
readable.on('readable', function() {
if(self._waitingForReadableData) {
self._waitingForReadableData = false;
self._readSomeData();
}
});
readable.on('end', function() {
self.push(null);
});
} | [
"function",
"CompoundDuplex",
"(",
"writable",
",",
"readable",
",",
"options",
")",
"{",
"var",
"self",
"=",
"this",
";",
"var",
"convertToZStream",
"=",
"require",
"(",
"'../index'",
")",
";",
"if",
"(",
"!",
"readable",
"||",
"typeof",
"readable",
".",
"read",
"!==",
"'function'",
")",
"{",
"options",
"=",
"readable",
";",
"readable",
"=",
"writable",
";",
"writable",
"=",
"null",
";",
"}",
"if",
"(",
"writable",
"&&",
"!",
"writable",
".",
"_isZStream",
")",
"{",
"writable",
"=",
"convertToZStream",
"(",
"writable",
")",
";",
"}",
"if",
"(",
"!",
"readable",
".",
"_isZStream",
")",
"{",
"readable",
"=",
"convertToZStream",
"(",
"readable",
")",
";",
"}",
"if",
"(",
"!",
"writable",
")",
"{",
"if",
"(",
"typeof",
"readable",
".",
"getStreamChain",
"!==",
"'function'",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Can only use shorthand CompoundDuplex constructor if pipeline is all zstreams'",
")",
";",
"}",
"writable",
"=",
"readable",
".",
"getStreamChain",
"(",
")",
".",
"getStreams",
"(",
")",
"[",
"0",
"]",
";",
"}",
"if",
"(",
"!",
"options",
")",
"options",
"=",
"{",
"}",
";",
"options",
".",
"readableObjectMode",
"=",
"readable",
".",
"isReadableObjectMode",
"(",
")",
";",
"options",
".",
"writableObjectMode",
"=",
"writable",
".",
"isWritableObjectMode",
"(",
")",
";",
"Duplex",
".",
"call",
"(",
"this",
",",
"options",
")",
";",
"this",
".",
"_compoundReadable",
"=",
"readable",
";",
"this",
".",
"_compoundWritable",
"=",
"writable",
";",
"this",
".",
"_waitingForReadableData",
"=",
"false",
";",
"writable",
".",
"on",
"(",
"'chainerror'",
",",
"function",
"(",
"error",
")",
"{",
"this",
".",
"ignoreError",
"(",
")",
";",
"self",
".",
"emit",
"(",
"'error'",
",",
"error",
")",
";",
"}",
")",
";",
"readable",
".",
"on",
"(",
"'readable'",
",",
"function",
"(",
")",
"{",
"if",
"(",
"self",
".",
"_waitingForReadableData",
")",
"{",
"self",
".",
"_waitingForReadableData",
"=",
"false",
";",
"self",
".",
"_readSomeData",
"(",
")",
";",
"}",
"}",
")",
";",
"readable",
".",
"on",
"(",
"'end'",
",",
"function",
"(",
")",
"{",
"self",
".",
"push",
"(",
"null",
")",
";",
"}",
")",
";",
"}"
] | Stream that allows encapsulating a set of streams piped together as a single stream.
@class CompoundDuplex
@constructor
@param {Writable} writable - The first stream in the pipeline to encapsulate. This is optional. If all
streams in the pipeline are ZStreams, the readable alone can be used to determine the first stream in the pipeline.
@param {Readable} readable - The last stream in the pipeline.
@param {Object} options - Stream options. | [
"Stream",
"that",
"allows",
"encapsulating",
"a",
"set",
"of",
"streams",
"piped",
"together",
"as",
"a",
"single",
"stream",
"."
] | 4ec01a49d1d00c542ee1dfa4b3bedcf1324e9ffd | https://github.com/crispy1989/node-zstreams/blob/4ec01a49d1d00c542ee1dfa4b3bedcf1324e9ffd/lib/streams/compound-duplex.js#L14-L65 | train |
feedhenry/fh-forms | lib/impl/dataSources/index.js | get | function get(connections, params, cb) {
//validateParams
//LookUpDataSource
//CheckFormsThatAre Using The Data Source
//Return Result.
async.waterfall([
function validateParams(cb) {
validate(params).has(CONSTANTS.DATA_SOURCE_ID, function(err) {
if (err) {
return cb(buildErrorResponse({error: new Error("An ID Parameter Is Required To Get A Data Source"), code: ERROR_CODES.FH_FORMS_INVALID_PARAMETERS}));
}
return cb(undefined, params[CONSTANTS.DATA_SOURCE_ID]);
});
},
function findDataSources(id, cb) {
var query = {
};
//Searching By ID.
query[CONSTANTS.DATA_SOURCE_ID] = id;
lookUpDataSources(connections, {
query: query,
lean: true,
includeAuditLog: params.includeAuditLog,
includeAuditLogData: params.includeAuditLogData
}, function(err, dataSources) {
if (err) {
return cb(buildErrorResponse({
error: err,
userDetail: "Unexpected Error When Searching For A Data Source",
code: ERROR_CODES.FH_FORMS_UNEXPECTED_ERROR
}));
}
//Checking if the data source exists. Should be only one
if (dataSources.length !== 1) {
return cb(buildErrorResponse({
error: new Error("Data Source Not Found"),
systemDetail: "Requested ID: " + params[CONSTANTS.DATA_SOURCE_ID],
code: ERROR_CODES.FH_FORMS_NOT_FOUND
}));
}
var dataSourceJSON = dataSources[0];
dataSourceJSON = processDataSourceResponse(dataSourceJSON, {
includeAuditLog: params.includeAuditLog
});
return cb(undefined, dataSourceJSON);
});
},
function checkForms(dataSourceJSON, cb) {
//Checking For Any Forms Associated With The Data Source
checkFormsUsingDataSource(connections, dataSourceJSON, cb);
}
], cb);
} | javascript | function get(connections, params, cb) {
//validateParams
//LookUpDataSource
//CheckFormsThatAre Using The Data Source
//Return Result.
async.waterfall([
function validateParams(cb) {
validate(params).has(CONSTANTS.DATA_SOURCE_ID, function(err) {
if (err) {
return cb(buildErrorResponse({error: new Error("An ID Parameter Is Required To Get A Data Source"), code: ERROR_CODES.FH_FORMS_INVALID_PARAMETERS}));
}
return cb(undefined, params[CONSTANTS.DATA_SOURCE_ID]);
});
},
function findDataSources(id, cb) {
var query = {
};
//Searching By ID.
query[CONSTANTS.DATA_SOURCE_ID] = id;
lookUpDataSources(connections, {
query: query,
lean: true,
includeAuditLog: params.includeAuditLog,
includeAuditLogData: params.includeAuditLogData
}, function(err, dataSources) {
if (err) {
return cb(buildErrorResponse({
error: err,
userDetail: "Unexpected Error When Searching For A Data Source",
code: ERROR_CODES.FH_FORMS_UNEXPECTED_ERROR
}));
}
//Checking if the data source exists. Should be only one
if (dataSources.length !== 1) {
return cb(buildErrorResponse({
error: new Error("Data Source Not Found"),
systemDetail: "Requested ID: " + params[CONSTANTS.DATA_SOURCE_ID],
code: ERROR_CODES.FH_FORMS_NOT_FOUND
}));
}
var dataSourceJSON = dataSources[0];
dataSourceJSON = processDataSourceResponse(dataSourceJSON, {
includeAuditLog: params.includeAuditLog
});
return cb(undefined, dataSourceJSON);
});
},
function checkForms(dataSourceJSON, cb) {
//Checking For Any Forms Associated With The Data Source
checkFormsUsingDataSource(connections, dataSourceJSON, cb);
}
], cb);
} | [
"function",
"get",
"(",
"connections",
",",
"params",
",",
"cb",
")",
"{",
"async",
".",
"waterfall",
"(",
"[",
"function",
"validateParams",
"(",
"cb",
")",
"{",
"validate",
"(",
"params",
")",
".",
"has",
"(",
"CONSTANTS",
".",
"DATA_SOURCE_ID",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"cb",
"(",
"buildErrorResponse",
"(",
"{",
"error",
":",
"new",
"Error",
"(",
"\"An ID Parameter Is Required To Get A Data Source\"",
")",
",",
"code",
":",
"ERROR_CODES",
".",
"FH_FORMS_INVALID_PARAMETERS",
"}",
")",
")",
";",
"}",
"return",
"cb",
"(",
"undefined",
",",
"params",
"[",
"CONSTANTS",
".",
"DATA_SOURCE_ID",
"]",
")",
";",
"}",
")",
";",
"}",
",",
"function",
"findDataSources",
"(",
"id",
",",
"cb",
")",
"{",
"var",
"query",
"=",
"{",
"}",
";",
"query",
"[",
"CONSTANTS",
".",
"DATA_SOURCE_ID",
"]",
"=",
"id",
";",
"lookUpDataSources",
"(",
"connections",
",",
"{",
"query",
":",
"query",
",",
"lean",
":",
"true",
",",
"includeAuditLog",
":",
"params",
".",
"includeAuditLog",
",",
"includeAuditLogData",
":",
"params",
".",
"includeAuditLogData",
"}",
",",
"function",
"(",
"err",
",",
"dataSources",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"cb",
"(",
"buildErrorResponse",
"(",
"{",
"error",
":",
"err",
",",
"userDetail",
":",
"\"Unexpected Error When Searching For A Data Source\"",
",",
"code",
":",
"ERROR_CODES",
".",
"FH_FORMS_UNEXPECTED_ERROR",
"}",
")",
")",
";",
"}",
"if",
"(",
"dataSources",
".",
"length",
"!==",
"1",
")",
"{",
"return",
"cb",
"(",
"buildErrorResponse",
"(",
"{",
"error",
":",
"new",
"Error",
"(",
"\"Data Source Not Found\"",
")",
",",
"systemDetail",
":",
"\"Requested ID: \"",
"+",
"params",
"[",
"CONSTANTS",
".",
"DATA_SOURCE_ID",
"]",
",",
"code",
":",
"ERROR_CODES",
".",
"FH_FORMS_NOT_FOUND",
"}",
")",
")",
";",
"}",
"var",
"dataSourceJSON",
"=",
"dataSources",
"[",
"0",
"]",
";",
"dataSourceJSON",
"=",
"processDataSourceResponse",
"(",
"dataSourceJSON",
",",
"{",
"includeAuditLog",
":",
"params",
".",
"includeAuditLog",
"}",
")",
";",
"return",
"cb",
"(",
"undefined",
",",
"dataSourceJSON",
")",
";",
"}",
")",
";",
"}",
",",
"function",
"checkForms",
"(",
"dataSourceJSON",
",",
"cb",
")",
"{",
"checkFormsUsingDataSource",
"(",
"connections",
",",
"dataSourceJSON",
",",
"cb",
")",
";",
"}",
"]",
",",
"cb",
")",
";",
"}"
] | Get A Specific Data Source Definition
@param connections
@param params
@param params._id: Data Source Id
@param params.includeAuditLog: flag to include a data source audit log or not.
@param params.includeAuditLogData: flag for including the data set with the audit log list.
@param cb | [
"Get",
"A",
"Specific",
"Data",
"Source",
"Definition"
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/dataSources/index.js#L26-L86 | train |
feedhenry/fh-forms | lib/impl/dataSources/index.js | list | function list(connections, params, callback) {
logger.debug("Listing Data Sources", params);
var currentTime = new Date(params.currentTime);
//If listing data sources needing a cache update, need to supply a valid date.
if (params.listDataSourcesNeedingUpdate && !params.currentTime && currentTime.toString() !== "Invalid Date") {
return callback(buildErrorResponse({error: new Error("An currentTime Date Object Is Required To List Data Sources Requiring Update"), code: ERROR_CODES.FH_FORMS_INVALID_PARAMETERS}));
}
async.waterfall([
function findDataSources(cb) {
var query = {};
lookUpDataSources(connections, {
query: query,
lean: true
}, function(err, dataSources) {
if (err) {
return cb(buildErrorResponse({
error: err,
userDetail: "Unexpected Error When Searching For A Data Source",
code: ERROR_CODES.FH_FORMS_UNEXPECTED_ERROR
}));
}
logger.debug("Listing Data Sources", {dataSources: dataSources});
//Only return Data Sources with a valid data source update time
if (params.listDataSourcesNeedingUpdate) {
dataSources = checkUpdateInterval(dataSources, currentTime);
}
logger.debug("Listing Data Sources", {dataSourceAfterFilter: dataSources});
dataSources = _.map(dataSources, processDataSourceResponse);
return cb(undefined, dataSources);
});
},
function getFormsUsingDataSources(dataSources, cb) {
async.map(dataSources, function(dataSource, cb) {
checkFormsUsingDataSource(connections, dataSource, cb);
}, cb);
}
], callback);
} | javascript | function list(connections, params, callback) {
logger.debug("Listing Data Sources", params);
var currentTime = new Date(params.currentTime);
//If listing data sources needing a cache update, need to supply a valid date.
if (params.listDataSourcesNeedingUpdate && !params.currentTime && currentTime.toString() !== "Invalid Date") {
return callback(buildErrorResponse({error: new Error("An currentTime Date Object Is Required To List Data Sources Requiring Update"), code: ERROR_CODES.FH_FORMS_INVALID_PARAMETERS}));
}
async.waterfall([
function findDataSources(cb) {
var query = {};
lookUpDataSources(connections, {
query: query,
lean: true
}, function(err, dataSources) {
if (err) {
return cb(buildErrorResponse({
error: err,
userDetail: "Unexpected Error When Searching For A Data Source",
code: ERROR_CODES.FH_FORMS_UNEXPECTED_ERROR
}));
}
logger.debug("Listing Data Sources", {dataSources: dataSources});
//Only return Data Sources with a valid data source update time
if (params.listDataSourcesNeedingUpdate) {
dataSources = checkUpdateInterval(dataSources, currentTime);
}
logger.debug("Listing Data Sources", {dataSourceAfterFilter: dataSources});
dataSources = _.map(dataSources, processDataSourceResponse);
return cb(undefined, dataSources);
});
},
function getFormsUsingDataSources(dataSources, cb) {
async.map(dataSources, function(dataSource, cb) {
checkFormsUsingDataSource(connections, dataSource, cb);
}, cb);
}
], callback);
} | [
"function",
"list",
"(",
"connections",
",",
"params",
",",
"callback",
")",
"{",
"logger",
".",
"debug",
"(",
"\"Listing Data Sources\"",
",",
"params",
")",
";",
"var",
"currentTime",
"=",
"new",
"Date",
"(",
"params",
".",
"currentTime",
")",
";",
"if",
"(",
"params",
".",
"listDataSourcesNeedingUpdate",
"&&",
"!",
"params",
".",
"currentTime",
"&&",
"currentTime",
".",
"toString",
"(",
")",
"!==",
"\"Invalid Date\"",
")",
"{",
"return",
"callback",
"(",
"buildErrorResponse",
"(",
"{",
"error",
":",
"new",
"Error",
"(",
"\"An currentTime Date Object Is Required To List Data Sources Requiring Update\"",
")",
",",
"code",
":",
"ERROR_CODES",
".",
"FH_FORMS_INVALID_PARAMETERS",
"}",
")",
")",
";",
"}",
"async",
".",
"waterfall",
"(",
"[",
"function",
"findDataSources",
"(",
"cb",
")",
"{",
"var",
"query",
"=",
"{",
"}",
";",
"lookUpDataSources",
"(",
"connections",
",",
"{",
"query",
":",
"query",
",",
"lean",
":",
"true",
"}",
",",
"function",
"(",
"err",
",",
"dataSources",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"cb",
"(",
"buildErrorResponse",
"(",
"{",
"error",
":",
"err",
",",
"userDetail",
":",
"\"Unexpected Error When Searching For A Data Source\"",
",",
"code",
":",
"ERROR_CODES",
".",
"FH_FORMS_UNEXPECTED_ERROR",
"}",
")",
")",
";",
"}",
"logger",
".",
"debug",
"(",
"\"Listing Data Sources\"",
",",
"{",
"dataSources",
":",
"dataSources",
"}",
")",
";",
"if",
"(",
"params",
".",
"listDataSourcesNeedingUpdate",
")",
"{",
"dataSources",
"=",
"checkUpdateInterval",
"(",
"dataSources",
",",
"currentTime",
")",
";",
"}",
"logger",
".",
"debug",
"(",
"\"Listing Data Sources\"",
",",
"{",
"dataSourceAfterFilter",
":",
"dataSources",
"}",
")",
";",
"dataSources",
"=",
"_",
".",
"map",
"(",
"dataSources",
",",
"processDataSourceResponse",
")",
";",
"return",
"cb",
"(",
"undefined",
",",
"dataSources",
")",
";",
"}",
")",
";",
"}",
",",
"function",
"getFormsUsingDataSources",
"(",
"dataSources",
",",
"cb",
")",
"{",
"async",
".",
"map",
"(",
"dataSources",
",",
"function",
"(",
"dataSource",
",",
"cb",
")",
"{",
"checkFormsUsingDataSource",
"(",
"connections",
",",
"dataSource",
",",
"cb",
")",
";",
"}",
",",
"cb",
")",
";",
"}",
"]",
",",
"callback",
")",
";",
"}"
] | Listing All Data Sources. In The Environment, this will include the current cache data.
@param connections
@param params
- listDataSourcesNeedingUpdate: Flag For Only Returning Data Sources That Require An Update
- currentTime: Time Stamp To Compare Data Source Last Updated Timestamps To
@param callback | [
"Listing",
"All",
"Data",
"Sources",
".",
"In",
"The",
"Environment",
"this",
"will",
"include",
"the",
"current",
"cache",
"data",
"."
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/dataSources/index.js#L96-L142 | train |
feedhenry/fh-forms | lib/impl/dataSources/index.js | create | function create(connections, dataSource, callback) {
async.waterfall([
function validateParams(cb) {
//If it is a deploy, the JSON can contain an _id param
if (connections.deploy) {
return cb(undefined, dataSource);
}
//Otherwise, check that it is not there.
validate(dataSource).hasno(CONSTANTS.DATA_SOURCE_ID, function(err) {
if (err) {
return cb(buildErrorResponse({error: new Error("Data Source ID Should Not Be Included When Creating A Data Source"), code: ERROR_CODES.FH_FORMS_INVALID_PARAMETERS}));
}
cb(undefined, dataSource);
});
},
function validateNameNotUsed(dataSource, cb) {
//Duplicate Names Are Not Allowed.
var DataSource = models.get(connections.mongooseConnection, models.MODELNAMES.DATA_SOURCE);
DataSource.count({name: dataSource.name}, function(err, numDuplicateDSs) {
if (numDuplicateDSs && numDuplicateDSs > 0) {
return cb({
userDetail: "Invalid Data To Create A Data Source" ,
systemDetail: "A Data Source With The Name " + dataSource.name + " Already Exists",
code: ERROR_CODES.FH_FORMS_INVALID_PARAMETERS
});
} else {
return cb(err, dataSource);
}
});
},
function createDataSource(dataSourceJSON, cb) {
dataSourceJSON = misc.sanitiseJSON(dataSourceJSON);
var DataSource = models.get(connections.mongooseConnection, models.MODELNAMES.DATA_SOURCE);
var newDataSource = new DataSource(dataSourceJSON);
newDataSource.save(function(err) {
if (err) {
return cb(buildErrorResponse({
error: err,
userDetail: "Invalid Data Source Creation Data.",
systemDetail: err.errors,
code: ERROR_CODES.FH_FORMS_INVALID_PARAMETERS
}));
}
newDataSource = processDataSourceResponse(newDataSource.toJSON());
return cb(undefined, newDataSource);
});
}
], callback);
} | javascript | function create(connections, dataSource, callback) {
async.waterfall([
function validateParams(cb) {
//If it is a deploy, the JSON can contain an _id param
if (connections.deploy) {
return cb(undefined, dataSource);
}
//Otherwise, check that it is not there.
validate(dataSource).hasno(CONSTANTS.DATA_SOURCE_ID, function(err) {
if (err) {
return cb(buildErrorResponse({error: new Error("Data Source ID Should Not Be Included When Creating A Data Source"), code: ERROR_CODES.FH_FORMS_INVALID_PARAMETERS}));
}
cb(undefined, dataSource);
});
},
function validateNameNotUsed(dataSource, cb) {
//Duplicate Names Are Not Allowed.
var DataSource = models.get(connections.mongooseConnection, models.MODELNAMES.DATA_SOURCE);
DataSource.count({name: dataSource.name}, function(err, numDuplicateDSs) {
if (numDuplicateDSs && numDuplicateDSs > 0) {
return cb({
userDetail: "Invalid Data To Create A Data Source" ,
systemDetail: "A Data Source With The Name " + dataSource.name + " Already Exists",
code: ERROR_CODES.FH_FORMS_INVALID_PARAMETERS
});
} else {
return cb(err, dataSource);
}
});
},
function createDataSource(dataSourceJSON, cb) {
dataSourceJSON = misc.sanitiseJSON(dataSourceJSON);
var DataSource = models.get(connections.mongooseConnection, models.MODELNAMES.DATA_SOURCE);
var newDataSource = new DataSource(dataSourceJSON);
newDataSource.save(function(err) {
if (err) {
return cb(buildErrorResponse({
error: err,
userDetail: "Invalid Data Source Creation Data.",
systemDetail: err.errors,
code: ERROR_CODES.FH_FORMS_INVALID_PARAMETERS
}));
}
newDataSource = processDataSourceResponse(newDataSource.toJSON());
return cb(undefined, newDataSource);
});
}
], callback);
} | [
"function",
"create",
"(",
"connections",
",",
"dataSource",
",",
"callback",
")",
"{",
"async",
".",
"waterfall",
"(",
"[",
"function",
"validateParams",
"(",
"cb",
")",
"{",
"if",
"(",
"connections",
".",
"deploy",
")",
"{",
"return",
"cb",
"(",
"undefined",
",",
"dataSource",
")",
";",
"}",
"validate",
"(",
"dataSource",
")",
".",
"hasno",
"(",
"CONSTANTS",
".",
"DATA_SOURCE_ID",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"cb",
"(",
"buildErrorResponse",
"(",
"{",
"error",
":",
"new",
"Error",
"(",
"\"Data Source ID Should Not Be Included When Creating A Data Source\"",
")",
",",
"code",
":",
"ERROR_CODES",
".",
"FH_FORMS_INVALID_PARAMETERS",
"}",
")",
")",
";",
"}",
"cb",
"(",
"undefined",
",",
"dataSource",
")",
";",
"}",
")",
";",
"}",
",",
"function",
"validateNameNotUsed",
"(",
"dataSource",
",",
"cb",
")",
"{",
"var",
"DataSource",
"=",
"models",
".",
"get",
"(",
"connections",
".",
"mongooseConnection",
",",
"models",
".",
"MODELNAMES",
".",
"DATA_SOURCE",
")",
";",
"DataSource",
".",
"count",
"(",
"{",
"name",
":",
"dataSource",
".",
"name",
"}",
",",
"function",
"(",
"err",
",",
"numDuplicateDSs",
")",
"{",
"if",
"(",
"numDuplicateDSs",
"&&",
"numDuplicateDSs",
">",
"0",
")",
"{",
"return",
"cb",
"(",
"{",
"userDetail",
":",
"\"Invalid Data To Create A Data Source\"",
",",
"systemDetail",
":",
"\"A Data Source With The Name \"",
"+",
"dataSource",
".",
"name",
"+",
"\" Already Exists\"",
",",
"code",
":",
"ERROR_CODES",
".",
"FH_FORMS_INVALID_PARAMETERS",
"}",
")",
";",
"}",
"else",
"{",
"return",
"cb",
"(",
"err",
",",
"dataSource",
")",
";",
"}",
"}",
")",
";",
"}",
",",
"function",
"createDataSource",
"(",
"dataSourceJSON",
",",
"cb",
")",
"{",
"dataSourceJSON",
"=",
"misc",
".",
"sanitiseJSON",
"(",
"dataSourceJSON",
")",
";",
"var",
"DataSource",
"=",
"models",
".",
"get",
"(",
"connections",
".",
"mongooseConnection",
",",
"models",
".",
"MODELNAMES",
".",
"DATA_SOURCE",
")",
";",
"var",
"newDataSource",
"=",
"new",
"DataSource",
"(",
"dataSourceJSON",
")",
";",
"newDataSource",
".",
"save",
"(",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"cb",
"(",
"buildErrorResponse",
"(",
"{",
"error",
":",
"err",
",",
"userDetail",
":",
"\"Invalid Data Source Creation Data.\"",
",",
"systemDetail",
":",
"err",
".",
"errors",
",",
"code",
":",
"ERROR_CODES",
".",
"FH_FORMS_INVALID_PARAMETERS",
"}",
")",
")",
";",
"}",
"newDataSource",
"=",
"processDataSourceResponse",
"(",
"newDataSource",
".",
"toJSON",
"(",
")",
")",
";",
"return",
"cb",
"(",
"undefined",
",",
"newDataSource",
")",
";",
"}",
")",
";",
"}",
"]",
",",
"callback",
")",
";",
"}"
] | Creating A New Data Source
@param connections
@param dataSource
@param callback | [
"Creating",
"A",
"New",
"Data",
"Source"
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/dataSources/index.js#L150-L207 | train |
feedhenry/fh-forms | lib/impl/dataSources/index.js | remove | function remove(connections, params, cb) {
var failed = validate(params).has(CONSTANTS.DATA_SOURCE_ID);
if (failed) {
return cb(buildErrorResponse({error: new Error("An ID Parameter Is Required To Remove A Data Source"), code: ERROR_CODES.FH_FORMS_INVALID_PARAMETERS}));
}
if (!misc.checkId(params[CONSTANTS.DATA_SOURCE_ID])) {
return cb(buildErrorResponse({error: new Error("Invalid ID Parameter"), code: ERROR_CODES.FH_FORMS_INVALID_PARAMETERS}));
}
var DataSource = models.get(connections.mongooseConnection, models.MODELNAMES.DATA_SOURCE);
async.waterfall([
function findAssociatedForms(cb) {
checkFormsUsingDataSource(connections, params, cb);
},
function verifyNoFormsAssociated(updatedDataSource, cb) {
//If there are any forms using this data source, then do not delete it.
logger.debug("Remove Data Source ", {updatedDataSource: updatedDataSource});
if (updatedDataSource.forms.length > 0) {
return cb(buildErrorResponse({
error: new Error("Forms Are Associated With This Data Source. Please Disassociate Forms From This Data Source Before Deleting."),
code: ERROR_CODES.FH_FORMS_UNEXPECTED_ERROR
}));
}
return cb(undefined, updatedDataSource);
},
function processResponse(updatedDataSource, cb) {
//Removing The Data Source
DataSource.remove({_id: updatedDataSource._id}, function(err) {
if (err) {
return cb(buildErrorResponse({
error: err,
userDetail: "Unexpected Error When Removing A Data Source",
code: ERROR_CODES.FH_FORMS_UNEXPECTED_ERROR
}));
}
//Data Source Removed Successfully
return cb(undefined, updatedDataSource);
});
},
function removeAduditLogs(updatedDataSource, cb) {
DataSource.clearAuditLogs(updatedDataSource._id, cb);
}
], cb);
} | javascript | function remove(connections, params, cb) {
var failed = validate(params).has(CONSTANTS.DATA_SOURCE_ID);
if (failed) {
return cb(buildErrorResponse({error: new Error("An ID Parameter Is Required To Remove A Data Source"), code: ERROR_CODES.FH_FORMS_INVALID_PARAMETERS}));
}
if (!misc.checkId(params[CONSTANTS.DATA_SOURCE_ID])) {
return cb(buildErrorResponse({error: new Error("Invalid ID Parameter"), code: ERROR_CODES.FH_FORMS_INVALID_PARAMETERS}));
}
var DataSource = models.get(connections.mongooseConnection, models.MODELNAMES.DATA_SOURCE);
async.waterfall([
function findAssociatedForms(cb) {
checkFormsUsingDataSource(connections, params, cb);
},
function verifyNoFormsAssociated(updatedDataSource, cb) {
//If there are any forms using this data source, then do not delete it.
logger.debug("Remove Data Source ", {updatedDataSource: updatedDataSource});
if (updatedDataSource.forms.length > 0) {
return cb(buildErrorResponse({
error: new Error("Forms Are Associated With This Data Source. Please Disassociate Forms From This Data Source Before Deleting."),
code: ERROR_CODES.FH_FORMS_UNEXPECTED_ERROR
}));
}
return cb(undefined, updatedDataSource);
},
function processResponse(updatedDataSource, cb) {
//Removing The Data Source
DataSource.remove({_id: updatedDataSource._id}, function(err) {
if (err) {
return cb(buildErrorResponse({
error: err,
userDetail: "Unexpected Error When Removing A Data Source",
code: ERROR_CODES.FH_FORMS_UNEXPECTED_ERROR
}));
}
//Data Source Removed Successfully
return cb(undefined, updatedDataSource);
});
},
function removeAduditLogs(updatedDataSource, cb) {
DataSource.clearAuditLogs(updatedDataSource._id, cb);
}
], cb);
} | [
"function",
"remove",
"(",
"connections",
",",
"params",
",",
"cb",
")",
"{",
"var",
"failed",
"=",
"validate",
"(",
"params",
")",
".",
"has",
"(",
"CONSTANTS",
".",
"DATA_SOURCE_ID",
")",
";",
"if",
"(",
"failed",
")",
"{",
"return",
"cb",
"(",
"buildErrorResponse",
"(",
"{",
"error",
":",
"new",
"Error",
"(",
"\"An ID Parameter Is Required To Remove A Data Source\"",
")",
",",
"code",
":",
"ERROR_CODES",
".",
"FH_FORMS_INVALID_PARAMETERS",
"}",
")",
")",
";",
"}",
"if",
"(",
"!",
"misc",
".",
"checkId",
"(",
"params",
"[",
"CONSTANTS",
".",
"DATA_SOURCE_ID",
"]",
")",
")",
"{",
"return",
"cb",
"(",
"buildErrorResponse",
"(",
"{",
"error",
":",
"new",
"Error",
"(",
"\"Invalid ID Parameter\"",
")",
",",
"code",
":",
"ERROR_CODES",
".",
"FH_FORMS_INVALID_PARAMETERS",
"}",
")",
")",
";",
"}",
"var",
"DataSource",
"=",
"models",
".",
"get",
"(",
"connections",
".",
"mongooseConnection",
",",
"models",
".",
"MODELNAMES",
".",
"DATA_SOURCE",
")",
";",
"async",
".",
"waterfall",
"(",
"[",
"function",
"findAssociatedForms",
"(",
"cb",
")",
"{",
"checkFormsUsingDataSource",
"(",
"connections",
",",
"params",
",",
"cb",
")",
";",
"}",
",",
"function",
"verifyNoFormsAssociated",
"(",
"updatedDataSource",
",",
"cb",
")",
"{",
"logger",
".",
"debug",
"(",
"\"Remove Data Source \"",
",",
"{",
"updatedDataSource",
":",
"updatedDataSource",
"}",
")",
";",
"if",
"(",
"updatedDataSource",
".",
"forms",
".",
"length",
">",
"0",
")",
"{",
"return",
"cb",
"(",
"buildErrorResponse",
"(",
"{",
"error",
":",
"new",
"Error",
"(",
"\"Forms Are Associated With This Data Source. Please Disassociate Forms From This Data Source Before Deleting.\"",
")",
",",
"code",
":",
"ERROR_CODES",
".",
"FH_FORMS_UNEXPECTED_ERROR",
"}",
")",
")",
";",
"}",
"return",
"cb",
"(",
"undefined",
",",
"updatedDataSource",
")",
";",
"}",
",",
"function",
"processResponse",
"(",
"updatedDataSource",
",",
"cb",
")",
"{",
"DataSource",
".",
"remove",
"(",
"{",
"_id",
":",
"updatedDataSource",
".",
"_id",
"}",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"cb",
"(",
"buildErrorResponse",
"(",
"{",
"error",
":",
"err",
",",
"userDetail",
":",
"\"Unexpected Error When Removing A Data Source\"",
",",
"code",
":",
"ERROR_CODES",
".",
"FH_FORMS_UNEXPECTED_ERROR",
"}",
")",
")",
";",
"}",
"return",
"cb",
"(",
"undefined",
",",
"updatedDataSource",
")",
";",
"}",
")",
";",
"}",
",",
"function",
"removeAduditLogs",
"(",
"updatedDataSource",
",",
"cb",
")",
"{",
"DataSource",
".",
"clearAuditLogs",
"(",
"updatedDataSource",
".",
"_id",
",",
"cb",
")",
";",
"}",
"]",
",",
"cb",
")",
";",
"}"
] | Removing A Data Source
@param connections
@param params
@param cb | [
"Removing",
"A",
"Data",
"Source"
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/dataSources/index.js#L215-L264 | train |
feedhenry/fh-forms | lib/impl/dataSources/index.js | validateDataSource | function validateDataSource(connections, dataSource, cb) {
var dataSourceToValidate = _.clone(dataSource);
var DataSource = models.get(connections.mongooseConnection, models.MODELNAMES.DATA_SOURCE);
//Expect The Data Source To Have Data
var failure = validate(dataSourceToValidate).has(CONSTANTS.DATA_SOURCE_DATA);
if (failure) {
return cb(buildErrorResponse({
error: new Error("No Data Passed To Validate"),
code: ERROR_CODES.FH_FORMS_INVALID_PARAMETERS
}));
}
//Generate A Hash
var hash = misc.generateHash(dataSourceToValidate.data);
//Populate A Cache Object
//LastRefreshed is populated just for the cache mongoose schema
var cache = {
dataHash: hash,
currentStatus: {
status: "ok"
},
data: dataSourceToValidate.data,
lastRefreshed: new Date().getTime(),
updateTimestamp: new Date().getTime()
};
dataSourceToValidate.cache = [cache];
//Create A New Mongoose. Note that this document is never saved. It is useful for consistent validation
var testDataSource = new DataSource(dataSourceToValidate);
//Validating Without Saving
testDataSource.validate(function(err) {
var valid = err ? false : true;
var dataSourceJSON = testDataSource.toJSON();
dataSourceJSON = processDataSourceResponse(dataSourceJSON);
dataSourceJSON = _.omit(dataSourceJSON, "lastRefreshed", "currentStatus", "updateTimestamp", CONSTANTS.DATA_SOURCE_ID);
dataSourceJSON.validationResult = {
valid: valid,
message: valid ? "Data Source Is Valid" : "Invalid Data Source Update Data."
};
return cb(undefined, dataSourceJSON);
});
} | javascript | function validateDataSource(connections, dataSource, cb) {
var dataSourceToValidate = _.clone(dataSource);
var DataSource = models.get(connections.mongooseConnection, models.MODELNAMES.DATA_SOURCE);
//Expect The Data Source To Have Data
var failure = validate(dataSourceToValidate).has(CONSTANTS.DATA_SOURCE_DATA);
if (failure) {
return cb(buildErrorResponse({
error: new Error("No Data Passed To Validate"),
code: ERROR_CODES.FH_FORMS_INVALID_PARAMETERS
}));
}
//Generate A Hash
var hash = misc.generateHash(dataSourceToValidate.data);
//Populate A Cache Object
//LastRefreshed is populated just for the cache mongoose schema
var cache = {
dataHash: hash,
currentStatus: {
status: "ok"
},
data: dataSourceToValidate.data,
lastRefreshed: new Date().getTime(),
updateTimestamp: new Date().getTime()
};
dataSourceToValidate.cache = [cache];
//Create A New Mongoose. Note that this document is never saved. It is useful for consistent validation
var testDataSource = new DataSource(dataSourceToValidate);
//Validating Without Saving
testDataSource.validate(function(err) {
var valid = err ? false : true;
var dataSourceJSON = testDataSource.toJSON();
dataSourceJSON = processDataSourceResponse(dataSourceJSON);
dataSourceJSON = _.omit(dataSourceJSON, "lastRefreshed", "currentStatus", "updateTimestamp", CONSTANTS.DATA_SOURCE_ID);
dataSourceJSON.validationResult = {
valid: valid,
message: valid ? "Data Source Is Valid" : "Invalid Data Source Update Data."
};
return cb(undefined, dataSourceJSON);
});
} | [
"function",
"validateDataSource",
"(",
"connections",
",",
"dataSource",
",",
"cb",
")",
"{",
"var",
"dataSourceToValidate",
"=",
"_",
".",
"clone",
"(",
"dataSource",
")",
";",
"var",
"DataSource",
"=",
"models",
".",
"get",
"(",
"connections",
".",
"mongooseConnection",
",",
"models",
".",
"MODELNAMES",
".",
"DATA_SOURCE",
")",
";",
"var",
"failure",
"=",
"validate",
"(",
"dataSourceToValidate",
")",
".",
"has",
"(",
"CONSTANTS",
".",
"DATA_SOURCE_DATA",
")",
";",
"if",
"(",
"failure",
")",
"{",
"return",
"cb",
"(",
"buildErrorResponse",
"(",
"{",
"error",
":",
"new",
"Error",
"(",
"\"No Data Passed To Validate\"",
")",
",",
"code",
":",
"ERROR_CODES",
".",
"FH_FORMS_INVALID_PARAMETERS",
"}",
")",
")",
";",
"}",
"var",
"hash",
"=",
"misc",
".",
"generateHash",
"(",
"dataSourceToValidate",
".",
"data",
")",
";",
"var",
"cache",
"=",
"{",
"dataHash",
":",
"hash",
",",
"currentStatus",
":",
"{",
"status",
":",
"\"ok\"",
"}",
",",
"data",
":",
"dataSourceToValidate",
".",
"data",
",",
"lastRefreshed",
":",
"new",
"Date",
"(",
")",
".",
"getTime",
"(",
")",
",",
"updateTimestamp",
":",
"new",
"Date",
"(",
")",
".",
"getTime",
"(",
")",
"}",
";",
"dataSourceToValidate",
".",
"cache",
"=",
"[",
"cache",
"]",
";",
"var",
"testDataSource",
"=",
"new",
"DataSource",
"(",
"dataSourceToValidate",
")",
";",
"testDataSource",
".",
"validate",
"(",
"function",
"(",
"err",
")",
"{",
"var",
"valid",
"=",
"err",
"?",
"false",
":",
"true",
";",
"var",
"dataSourceJSON",
"=",
"testDataSource",
".",
"toJSON",
"(",
")",
";",
"dataSourceJSON",
"=",
"processDataSourceResponse",
"(",
"dataSourceJSON",
")",
";",
"dataSourceJSON",
"=",
"_",
".",
"omit",
"(",
"dataSourceJSON",
",",
"\"lastRefreshed\"",
",",
"\"currentStatus\"",
",",
"\"updateTimestamp\"",
",",
"CONSTANTS",
".",
"DATA_SOURCE_ID",
")",
";",
"dataSourceJSON",
".",
"validationResult",
"=",
"{",
"valid",
":",
"valid",
",",
"message",
":",
"valid",
"?",
"\"Data Source Is Valid\"",
":",
"\"Invalid Data Source Update Data.\"",
"}",
";",
"return",
"cb",
"(",
"undefined",
",",
"dataSourceJSON",
")",
";",
"}",
")",
";",
"}"
] | Validating A Data Source Object.
@param connections
@param dataSource
@param cb | [
"Validating",
"A",
"Data",
"Source",
"Object",
"."
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/dataSources/index.js#L274-L323 | train |
feedhenry/fh-forms | lib/impl/dataSources/index.js | deploy | function deploy(connections, dataSource, cb) {
async.waterfall([
function validateParams(cb) {
var dataSourceValidator = validate(dataSource);
//The data source parameter should have an ID property.
dataSourceValidator.has(CONSTANTS.DATA_SOURCE_ID, function(err) {
if (err) {
return cb(buildErrorResponse({error: new Error("An ID Parameter Is Required To Deploy A Data Source"), code: ERROR_CODES.FH_FORMS_INVALID_PARAMETERS}));
}
cb(undefined, dataSource);
});
},
function findDataSource(dataSource, cb) {
var query = {
};
//Searching By ID.
query[CONSTANTS.DATA_SOURCE_ID] = dataSource[CONSTANTS.DATA_SOURCE_ID];
//Looking up a full data source document as we are updating
lookUpDataSources(connections, {
query: query,
lean: false
}, function(err, dataSources) {
if (err) {
return cb(buildErrorResponse({
error: err,
userDetail: "Unexpected Error When Searching For A Data Source",
code: ERROR_CODES.FH_FORMS_UNEXPECTED_ERROR
}));
}
//If no data sources found create, otherwise update.
if (dataSources.length === 0) {
connections.deploy = true;
create(connections, dataSource, cb);
} else {
update(connections, dataSource, cb);
}
});
}
], cb);
} | javascript | function deploy(connections, dataSource, cb) {
async.waterfall([
function validateParams(cb) {
var dataSourceValidator = validate(dataSource);
//The data source parameter should have an ID property.
dataSourceValidator.has(CONSTANTS.DATA_SOURCE_ID, function(err) {
if (err) {
return cb(buildErrorResponse({error: new Error("An ID Parameter Is Required To Deploy A Data Source"), code: ERROR_CODES.FH_FORMS_INVALID_PARAMETERS}));
}
cb(undefined, dataSource);
});
},
function findDataSource(dataSource, cb) {
var query = {
};
//Searching By ID.
query[CONSTANTS.DATA_SOURCE_ID] = dataSource[CONSTANTS.DATA_SOURCE_ID];
//Looking up a full data source document as we are updating
lookUpDataSources(connections, {
query: query,
lean: false
}, function(err, dataSources) {
if (err) {
return cb(buildErrorResponse({
error: err,
userDetail: "Unexpected Error When Searching For A Data Source",
code: ERROR_CODES.FH_FORMS_UNEXPECTED_ERROR
}));
}
//If no data sources found create, otherwise update.
if (dataSources.length === 0) {
connections.deploy = true;
create(connections, dataSource, cb);
} else {
update(connections, dataSource, cb);
}
});
}
], cb);
} | [
"function",
"deploy",
"(",
"connections",
",",
"dataSource",
",",
"cb",
")",
"{",
"async",
".",
"waterfall",
"(",
"[",
"function",
"validateParams",
"(",
"cb",
")",
"{",
"var",
"dataSourceValidator",
"=",
"validate",
"(",
"dataSource",
")",
";",
"dataSourceValidator",
".",
"has",
"(",
"CONSTANTS",
".",
"DATA_SOURCE_ID",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"cb",
"(",
"buildErrorResponse",
"(",
"{",
"error",
":",
"new",
"Error",
"(",
"\"An ID Parameter Is Required To Deploy A Data Source\"",
")",
",",
"code",
":",
"ERROR_CODES",
".",
"FH_FORMS_INVALID_PARAMETERS",
"}",
")",
")",
";",
"}",
"cb",
"(",
"undefined",
",",
"dataSource",
")",
";",
"}",
")",
";",
"}",
",",
"function",
"findDataSource",
"(",
"dataSource",
",",
"cb",
")",
"{",
"var",
"query",
"=",
"{",
"}",
";",
"query",
"[",
"CONSTANTS",
".",
"DATA_SOURCE_ID",
"]",
"=",
"dataSource",
"[",
"CONSTANTS",
".",
"DATA_SOURCE_ID",
"]",
";",
"lookUpDataSources",
"(",
"connections",
",",
"{",
"query",
":",
"query",
",",
"lean",
":",
"false",
"}",
",",
"function",
"(",
"err",
",",
"dataSources",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"cb",
"(",
"buildErrorResponse",
"(",
"{",
"error",
":",
"err",
",",
"userDetail",
":",
"\"Unexpected Error When Searching For A Data Source\"",
",",
"code",
":",
"ERROR_CODES",
".",
"FH_FORMS_UNEXPECTED_ERROR",
"}",
")",
")",
";",
"}",
"if",
"(",
"dataSources",
".",
"length",
"===",
"0",
")",
"{",
"connections",
".",
"deploy",
"=",
"true",
";",
"create",
"(",
"connections",
",",
"dataSource",
",",
"cb",
")",
";",
"}",
"else",
"{",
"update",
"(",
"connections",
",",
"dataSource",
",",
"cb",
")",
";",
"}",
"}",
")",
";",
"}",
"]",
",",
"cb",
")",
";",
"}"
] | Deploying A Data Source. Check If It Exists First, then update, if not create it. | [
"Deploying",
"A",
"Data",
"Source",
".",
"Check",
"If",
"It",
"Exists",
"First",
"then",
"update",
"if",
"not",
"create",
"it",
"."
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/dataSources/index.js#L328-L373 | train |
feedhenry/fh-forms | lib/middleware/parseMongoConnectionOptions.js | parseMongoConnectionOptions | function parseMongoConnectionOptions(req, res, next) {
var options = {};
options.uri = req.mongoUrl;
req.connectionOptions = options;
return next();
} | javascript | function parseMongoConnectionOptions(req, res, next) {
var options = {};
options.uri = req.mongoUrl;
req.connectionOptions = options;
return next();
} | [
"function",
"parseMongoConnectionOptions",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"var",
"options",
"=",
"{",
"}",
";",
"options",
".",
"uri",
"=",
"req",
".",
"mongoUrl",
";",
"req",
".",
"connectionOptions",
"=",
"options",
";",
"return",
"next",
"(",
")",
";",
"}"
] | Populating mongo connection options for forms operations.
@param req
@param res
@param next
@returns {*} | [
"Populating",
"mongo",
"connection",
"options",
"for",
"forms",
"operations",
"."
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/middleware/parseMongoConnectionOptions.js#L8-L15 | train |
crispy1989/node-zstreams | lib/streams/string-readable-stream.js | StringReadableStream | function StringReadableStream(str, options) {
if(!options) options = {};
delete options.objectMode;
delete options.readableObjectMode;
Readable.call(this, options);
this._currentString = str;
this._currentStringPos = 0;
this._stringChunkSize = options.chunkSize || 1024;
} | javascript | function StringReadableStream(str, options) {
if(!options) options = {};
delete options.objectMode;
delete options.readableObjectMode;
Readable.call(this, options);
this._currentString = str;
this._currentStringPos = 0;
this._stringChunkSize = options.chunkSize || 1024;
} | [
"function",
"StringReadableStream",
"(",
"str",
",",
"options",
")",
"{",
"if",
"(",
"!",
"options",
")",
"options",
"=",
"{",
"}",
";",
"delete",
"options",
".",
"objectMode",
";",
"delete",
"options",
".",
"readableObjectMode",
";",
"Readable",
".",
"call",
"(",
"this",
",",
"options",
")",
";",
"this",
".",
"_currentString",
"=",
"str",
";",
"this",
".",
"_currentStringPos",
"=",
"0",
";",
"this",
".",
"_stringChunkSize",
"=",
"options",
".",
"chunkSize",
"||",
"1024",
";",
"}"
] | A readable string that outputs data from a string given to the constructor.
@class StringReadableStream
@constructor
@param {String|Buffer} str - The string to output to the stream
@param {Object} options - Options for the stream
@param {Number} options.chunkSize - The size of chunk to output to the stream, defaults to 1024 | [
"A",
"readable",
"string",
"that",
"outputs",
"data",
"from",
"a",
"string",
"given",
"to",
"the",
"constructor",
"."
] | 4ec01a49d1d00c542ee1dfa4b3bedcf1324e9ffd | https://github.com/crispy1989/node-zstreams/blob/4ec01a49d1d00c542ee1dfa4b3bedcf1324e9ffd/lib/streams/string-readable-stream.js#L13-L21 | train |
cloudfour/drizzle-builder | src/parse/templates.js | parseTemplates | function parseTemplates(options) {
return readFileTree(options.src.templates, options.keys.templates, options);
} | javascript | function parseTemplates(options) {
return readFileTree(options.src.templates, options.keys.templates, options);
} | [
"function",
"parseTemplates",
"(",
"options",
")",
"{",
"return",
"readFileTree",
"(",
"options",
".",
"src",
".",
"templates",
",",
"options",
".",
"keys",
".",
"templates",
",",
"options",
")",
";",
"}"
] | Parse layout files.
@param {Object} options
@return {Promise} resolving to object of parsed template contents | [
"Parse",
"layout",
"files",
"."
] | 1c320cb059c749c28339a661d1768d3a643e5f1c | https://github.com/cloudfour/drizzle-builder/blob/1c320cb059c749c28339a661d1768d3a643e5f1c/src/parse/templates.js#L8-L10 | train |
feedhenry/fh-forms | lib/middleware/forms.js | list | function list(req, res, next) {
var notStats = req.query && (req.query.notStats === 'true' || req.query.notStats === true);
var opts = _.extend(req.connectionOptions, { notStats: notStats });
logger.debug("List Forms Middleware ", opts);
forms.getAllForms(opts, formsResultHandlers(constants.resultTypes.forms, req, next));
} | javascript | function list(req, res, next) {
var notStats = req.query && (req.query.notStats === 'true' || req.query.notStats === true);
var opts = _.extend(req.connectionOptions, { notStats: notStats });
logger.debug("List Forms Middleware ", opts);
forms.getAllForms(opts, formsResultHandlers(constants.resultTypes.forms, req, next));
} | [
"function",
"list",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"var",
"notStats",
"=",
"req",
".",
"query",
"&&",
"(",
"req",
".",
"query",
".",
"notStats",
"===",
"'true'",
"||",
"req",
".",
"query",
".",
"notStats",
"===",
"true",
")",
";",
"var",
"opts",
"=",
"_",
".",
"extend",
"(",
"req",
".",
"connectionOptions",
",",
"{",
"notStats",
":",
"notStats",
"}",
")",
";",
"logger",
".",
"debug",
"(",
"\"List Forms Middleware \"",
",",
"opts",
")",
";",
"forms",
".",
"getAllForms",
"(",
"opts",
",",
"formsResultHandlers",
"(",
"constants",
".",
"resultTypes",
".",
"forms",
",",
"req",
",",
"next",
")",
")",
";",
"}"
] | List All Forms
@param req
@param res
@param next | [
"List",
"All",
"Forms"
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/middleware/forms.js#L14-L20 | train |
feedhenry/fh-forms | lib/middleware/forms.js | listDeployedForms | function listDeployedForms(req, res, next) {
var projectForms = req.appformsResultPayload.data || [];
logger.debug("Middleware: listDeployedForms: ", {connection: req.connectionOptions, projectForms: projectForms});
//Only Want The Project Ids
projectForms = _.map(projectForms, function(form) {
if (_.isObject(form)) {
return form._id;
} else {
return form;
}
});
forms.findForms(req.connectionOptions, projectForms, formsResultHandlers(constants.resultTypes.forms, req, next));
} | javascript | function listDeployedForms(req, res, next) {
var projectForms = req.appformsResultPayload.data || [];
logger.debug("Middleware: listDeployedForms: ", {connection: req.connectionOptions, projectForms: projectForms});
//Only Want The Project Ids
projectForms = _.map(projectForms, function(form) {
if (_.isObject(form)) {
return form._id;
} else {
return form;
}
});
forms.findForms(req.connectionOptions, projectForms, formsResultHandlers(constants.resultTypes.forms, req, next));
} | [
"function",
"listDeployedForms",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"var",
"projectForms",
"=",
"req",
".",
"appformsResultPayload",
".",
"data",
"||",
"[",
"]",
";",
"logger",
".",
"debug",
"(",
"\"Middleware: listDeployedForms: \"",
",",
"{",
"connection",
":",
"req",
".",
"connectionOptions",
",",
"projectForms",
":",
"projectForms",
"}",
")",
";",
"projectForms",
"=",
"_",
".",
"map",
"(",
"projectForms",
",",
"function",
"(",
"form",
")",
"{",
"if",
"(",
"_",
".",
"isObject",
"(",
"form",
")",
")",
"{",
"return",
"form",
".",
"_id",
";",
"}",
"else",
"{",
"return",
"form",
";",
"}",
"}",
")",
";",
"forms",
".",
"findForms",
"(",
"req",
".",
"connectionOptions",
",",
"projectForms",
",",
"formsResultHandlers",
"(",
"constants",
".",
"resultTypes",
".",
"forms",
",",
"req",
",",
"next",
")",
")",
";",
"}"
] | Listing Forms Deployed To An Environment
@param req
@param res
@param next | [
"Listing",
"Forms",
"Deployed",
"To",
"An",
"Environment"
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/middleware/forms.js#L28-L42 | train |
feedhenry/fh-forms | lib/middleware/forms.js | search | function search(req, res, next) {
var projectForms = req.appformsResultPayload.data || [];
//Only Want The Project Ids
projectForms = _.map(projectForms, function(form) {
if (_.isObject(form)) {
return form._id;
} else {
return form;
}
});
var formsToFind = req.body || [];
formsToFind = _.filter(projectForms, function(projFormId) {
return formsToFind.indexOf(projFormId) > -1;
});
logger.debug("Middleware: search forms: ", {connection: req.connectionOptions, projectForms: projectForms});
forms.findForms(req.connectionOptions, formsToFind, function(err, formsList) {
if (err) {
return next(err);
}
async.map(formsList, function(foundForm, cb) {
var getParams = {
"_id": foundForm._id,
"showAdminFields": false
};
forms.getForm(_.extend(_.clone(req.connectionOptions), getParams), cb);
}, formsResultHandlers(constants.resultTypes.forms, req, next));
});
} | javascript | function search(req, res, next) {
var projectForms = req.appformsResultPayload.data || [];
//Only Want The Project Ids
projectForms = _.map(projectForms, function(form) {
if (_.isObject(form)) {
return form._id;
} else {
return form;
}
});
var formsToFind = req.body || [];
formsToFind = _.filter(projectForms, function(projFormId) {
return formsToFind.indexOf(projFormId) > -1;
});
logger.debug("Middleware: search forms: ", {connection: req.connectionOptions, projectForms: projectForms});
forms.findForms(req.connectionOptions, formsToFind, function(err, formsList) {
if (err) {
return next(err);
}
async.map(formsList, function(foundForm, cb) {
var getParams = {
"_id": foundForm._id,
"showAdminFields": false
};
forms.getForm(_.extend(_.clone(req.connectionOptions), getParams), cb);
}, formsResultHandlers(constants.resultTypes.forms, req, next));
});
} | [
"function",
"search",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"var",
"projectForms",
"=",
"req",
".",
"appformsResultPayload",
".",
"data",
"||",
"[",
"]",
";",
"projectForms",
"=",
"_",
".",
"map",
"(",
"projectForms",
",",
"function",
"(",
"form",
")",
"{",
"if",
"(",
"_",
".",
"isObject",
"(",
"form",
")",
")",
"{",
"return",
"form",
".",
"_id",
";",
"}",
"else",
"{",
"return",
"form",
";",
"}",
"}",
")",
";",
"var",
"formsToFind",
"=",
"req",
".",
"body",
"||",
"[",
"]",
";",
"formsToFind",
"=",
"_",
".",
"filter",
"(",
"projectForms",
",",
"function",
"(",
"projFormId",
")",
"{",
"return",
"formsToFind",
".",
"indexOf",
"(",
"projFormId",
")",
">",
"-",
"1",
";",
"}",
")",
";",
"logger",
".",
"debug",
"(",
"\"Middleware: search forms: \"",
",",
"{",
"connection",
":",
"req",
".",
"connectionOptions",
",",
"projectForms",
":",
"projectForms",
"}",
")",
";",
"forms",
".",
"findForms",
"(",
"req",
".",
"connectionOptions",
",",
"formsToFind",
",",
"function",
"(",
"err",
",",
"formsList",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"next",
"(",
"err",
")",
";",
"}",
"async",
".",
"map",
"(",
"formsList",
",",
"function",
"(",
"foundForm",
",",
"cb",
")",
"{",
"var",
"getParams",
"=",
"{",
"\"_id\"",
":",
"foundForm",
".",
"_id",
",",
"\"showAdminFields\"",
":",
"false",
"}",
";",
"forms",
".",
"getForm",
"(",
"_",
".",
"extend",
"(",
"_",
".",
"clone",
"(",
"req",
".",
"connectionOptions",
")",
",",
"getParams",
")",
",",
"cb",
")",
";",
"}",
",",
"formsResultHandlers",
"(",
"constants",
".",
"resultTypes",
".",
"forms",
",",
"req",
",",
"next",
")",
")",
";",
"}",
")",
";",
"}"
] | Function to list forms that are deployed.
The request should contain an array of deployed forms.
@param req
@param res
@param next | [
"Function",
"to",
"list",
"forms",
"that",
"are",
"deployed",
"."
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/middleware/forms.js#L53-L85 | train |
feedhenry/fh-forms | lib/middleware/forms.js | create | function create(req, res, next) {
var options = req.connectionOptions;
req.user = req.user || {};
var params = {
userEmail: req.user.email || req.body.updatedBy
};
options = _.extend(options, params);
logger.debug("Middleware: create form: ", {options: options});
forms.updateForm(options, req.body, formsResultHandlers(constants.resultTypes.forms, req, next));
} | javascript | function create(req, res, next) {
var options = req.connectionOptions;
req.user = req.user || {};
var params = {
userEmail: req.user.email || req.body.updatedBy
};
options = _.extend(options, params);
logger.debug("Middleware: create form: ", {options: options});
forms.updateForm(options, req.body, formsResultHandlers(constants.resultTypes.forms, req, next));
} | [
"function",
"create",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"var",
"options",
"=",
"req",
".",
"connectionOptions",
";",
"req",
".",
"user",
"=",
"req",
".",
"user",
"||",
"{",
"}",
";",
"var",
"params",
"=",
"{",
"userEmail",
":",
"req",
".",
"user",
".",
"email",
"||",
"req",
".",
"body",
".",
"updatedBy",
"}",
";",
"options",
"=",
"_",
".",
"extend",
"(",
"options",
",",
"params",
")",
";",
"logger",
".",
"debug",
"(",
"\"Middleware: create form: \"",
",",
"{",
"options",
":",
"options",
"}",
")",
";",
"forms",
".",
"updateForm",
"(",
"options",
",",
"req",
".",
"body",
",",
"formsResultHandlers",
"(",
"constants",
".",
"resultTypes",
".",
"forms",
",",
"req",
",",
"next",
")",
")",
";",
"}"
] | Create A New Form
@param req
@param res
@param next | [
"Create",
"A",
"New",
"Form"
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/middleware/forms.js#L93-L105 | train |
feedhenry/fh-forms | lib/middleware/forms.js | deploy | function deploy(req, res, next) {
var options = req.connectionOptions;
var form = req.body;
req.user = req.user || {};
if (req.appformsResultPayload && _.isObject(req.appformsResultPayload.data)) {
form = req.appformsResultPayload.data;
}
//Expect A Data Source Data Set To Be Available If Deploying A Form.
var params = {
userEmail: req.user.email || req.body.updatedBy,
expectDataSourceCache: true
};
options = _.extend(options, params);
logger.debug("Middleware: Deploy form: ", {options: options});
forms.updateOrCreateForm(options, form, formsResultHandlers(constants.resultTypes.forms, req, next));
} | javascript | function deploy(req, res, next) {
var options = req.connectionOptions;
var form = req.body;
req.user = req.user || {};
if (req.appformsResultPayload && _.isObject(req.appformsResultPayload.data)) {
form = req.appformsResultPayload.data;
}
//Expect A Data Source Data Set To Be Available If Deploying A Form.
var params = {
userEmail: req.user.email || req.body.updatedBy,
expectDataSourceCache: true
};
options = _.extend(options, params);
logger.debug("Middleware: Deploy form: ", {options: options});
forms.updateOrCreateForm(options, form, formsResultHandlers(constants.resultTypes.forms, req, next));
} | [
"function",
"deploy",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"var",
"options",
"=",
"req",
".",
"connectionOptions",
";",
"var",
"form",
"=",
"req",
".",
"body",
";",
"req",
".",
"user",
"=",
"req",
".",
"user",
"||",
"{",
"}",
";",
"if",
"(",
"req",
".",
"appformsResultPayload",
"&&",
"_",
".",
"isObject",
"(",
"req",
".",
"appformsResultPayload",
".",
"data",
")",
")",
"{",
"form",
"=",
"req",
".",
"appformsResultPayload",
".",
"data",
";",
"}",
"var",
"params",
"=",
"{",
"userEmail",
":",
"req",
".",
"user",
".",
"email",
"||",
"req",
".",
"body",
".",
"updatedBy",
",",
"expectDataSourceCache",
":",
"true",
"}",
";",
"options",
"=",
"_",
".",
"extend",
"(",
"options",
",",
"params",
")",
";",
"logger",
".",
"debug",
"(",
"\"Middleware: Deploy form: \"",
",",
"{",
"options",
":",
"options",
"}",
")",
";",
"forms",
".",
"updateOrCreateForm",
"(",
"options",
",",
"form",
",",
"formsResultHandlers",
"(",
"constants",
".",
"resultTypes",
".",
"forms",
",",
"req",
",",
"next",
")",
")",
";",
"}"
] | Deploying A Form. Creates A Form If It Already Exists
@param req
@param res
@param next | [
"Deploying",
"A",
"Form",
".",
"Creates",
"A",
"Form",
"If",
"It",
"Already",
"Exists"
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/middleware/forms.js#L113-L133 | train |
feedhenry/fh-forms | lib/middleware/forms.js | get | function get(req, res, next) {
//Admin Fields And Data Sources Should Not Be Shown For App Requests
var showAdminAndDataSources = !req.params.projectid;
var getParams = {
"_id": req.params.id,
"showAdminFields": showAdminAndDataSources,
includeDataSources: showAdminAndDataSources,
//Data Source Caches are required for app requests
expectDataSourceCache: !showAdminAndDataSources
};
logger.debug("Middleware: Get form: ", {getParams: getParams});
forms.getForm(_.extend(req.connectionOptions, getParams), formsResultHandlers(constants.resultTypes.forms, req, next));
} | javascript | function get(req, res, next) {
//Admin Fields And Data Sources Should Not Be Shown For App Requests
var showAdminAndDataSources = !req.params.projectid;
var getParams = {
"_id": req.params.id,
"showAdminFields": showAdminAndDataSources,
includeDataSources: showAdminAndDataSources,
//Data Source Caches are required for app requests
expectDataSourceCache: !showAdminAndDataSources
};
logger.debug("Middleware: Get form: ", {getParams: getParams});
forms.getForm(_.extend(req.connectionOptions, getParams), formsResultHandlers(constants.resultTypes.forms, req, next));
} | [
"function",
"get",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"var",
"showAdminAndDataSources",
"=",
"!",
"req",
".",
"params",
".",
"projectid",
";",
"var",
"getParams",
"=",
"{",
"\"_id\"",
":",
"req",
".",
"params",
".",
"id",
",",
"\"showAdminFields\"",
":",
"showAdminAndDataSources",
",",
"includeDataSources",
":",
"showAdminAndDataSources",
",",
"expectDataSourceCache",
":",
"!",
"showAdminAndDataSources",
"}",
";",
"logger",
".",
"debug",
"(",
"\"Middleware: Get form: \"",
",",
"{",
"getParams",
":",
"getParams",
"}",
")",
";",
"forms",
".",
"getForm",
"(",
"_",
".",
"extend",
"(",
"req",
".",
"connectionOptions",
",",
"getParams",
")",
",",
"formsResultHandlers",
"(",
"constants",
".",
"resultTypes",
".",
"forms",
",",
"req",
",",
"next",
")",
")",
";",
"}"
] | Get A Single Form Definition
@param req
@param res
@param next | [
"Get",
"A",
"Single",
"Form",
"Definition"
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/middleware/forms.js#L141-L157 | train |
feedhenry/fh-forms | lib/middleware/forms.js | update | function update(req, res, next) {
var options = req.connectionOptions;
req.appformsResultPayload = req.appformsResultPayload || {};
var params = {
userEmail: req.user.email
};
options = _.extend(options, params);
var form = req.body;
if (_.isObject(req.appformsResultPayload.data) && !req.body._id) {
form = req.appformsResultPayload.data;
}
logger.debug("Middleware: Update form: ", {options: options, form: form});
forms.updateForm(options, form, formsResultHandlers(constants.resultTypes.forms, req, next));
} | javascript | function update(req, res, next) {
var options = req.connectionOptions;
req.appformsResultPayload = req.appformsResultPayload || {};
var params = {
userEmail: req.user.email
};
options = _.extend(options, params);
var form = req.body;
if (_.isObject(req.appformsResultPayload.data) && !req.body._id) {
form = req.appformsResultPayload.data;
}
logger.debug("Middleware: Update form: ", {options: options, form: form});
forms.updateForm(options, form, formsResultHandlers(constants.resultTypes.forms, req, next));
} | [
"function",
"update",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"var",
"options",
"=",
"req",
".",
"connectionOptions",
";",
"req",
".",
"appformsResultPayload",
"=",
"req",
".",
"appformsResultPayload",
"||",
"{",
"}",
";",
"var",
"params",
"=",
"{",
"userEmail",
":",
"req",
".",
"user",
".",
"email",
"}",
";",
"options",
"=",
"_",
".",
"extend",
"(",
"options",
",",
"params",
")",
";",
"var",
"form",
"=",
"req",
".",
"body",
";",
"if",
"(",
"_",
".",
"isObject",
"(",
"req",
".",
"appformsResultPayload",
".",
"data",
")",
"&&",
"!",
"req",
".",
"body",
".",
"_id",
")",
"{",
"form",
"=",
"req",
".",
"appformsResultPayload",
".",
"data",
";",
"}",
"logger",
".",
"debug",
"(",
"\"Middleware: Update form: \"",
",",
"{",
"options",
":",
"options",
",",
"form",
":",
"form",
"}",
")",
";",
"forms",
".",
"updateForm",
"(",
"options",
",",
"form",
",",
"formsResultHandlers",
"(",
"constants",
".",
"resultTypes",
".",
"forms",
",",
"req",
",",
"next",
")",
")",
";",
"}"
] | Update A Single Existing Form
@param req
@param res
@param next | [
"Update",
"A",
"Single",
"Existing",
"Form"
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/middleware/forms.js#L165-L184 | train |
feedhenry/fh-forms | lib/middleware/forms.js | undeploy | function undeploy(req, res, next) {
var removeParams = {
_id: req.params.id
};
logger.debug("Middleware: undeploy form: ", {params: removeParams});
forms.deleteForm(_.extend(req.connectionOptions, removeParams), formsResultHandlers(constants.resultTypes.forms, req, next));
} | javascript | function undeploy(req, res, next) {
var removeParams = {
_id: req.params.id
};
logger.debug("Middleware: undeploy form: ", {params: removeParams});
forms.deleteForm(_.extend(req.connectionOptions, removeParams), formsResultHandlers(constants.resultTypes.forms, req, next));
} | [
"function",
"undeploy",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"var",
"removeParams",
"=",
"{",
"_id",
":",
"req",
".",
"params",
".",
"id",
"}",
";",
"logger",
".",
"debug",
"(",
"\"Middleware: undeploy form: \"",
",",
"{",
"params",
":",
"removeParams",
"}",
")",
";",
"forms",
".",
"deleteForm",
"(",
"_",
".",
"extend",
"(",
"req",
".",
"connectionOptions",
",",
"removeParams",
")",
",",
"formsResultHandlers",
"(",
"constants",
".",
"resultTypes",
".",
"forms",
",",
"req",
",",
"next",
")",
")",
";",
"}"
] | Undeploy An Existing Form. Does not remove any submission data.
@param req
@param res
@param next | [
"Undeploy",
"An",
"Existing",
"Form",
".",
"Does",
"not",
"remove",
"any",
"submission",
"data",
"."
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/middleware/forms.js#L209-L217 | train |
feedhenry/fh-forms | lib/middleware/forms.js | listSubscribers | function listSubscribers(req, res, next) {
var listSubscribersParams = {
_id: req.params.id
};
logger.debug("Middleware: listSubscribers: ", {params: listSubscribersParams});
forms.getNotifications(_.extend(req.connectionOptions, listSubscribersParams), formsResultHandlers(constants.resultTypes.forms, req, next));
} | javascript | function listSubscribers(req, res, next) {
var listSubscribersParams = {
_id: req.params.id
};
logger.debug("Middleware: listSubscribers: ", {params: listSubscribersParams});
forms.getNotifications(_.extend(req.connectionOptions, listSubscribersParams), formsResultHandlers(constants.resultTypes.forms, req, next));
} | [
"function",
"listSubscribers",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"var",
"listSubscribersParams",
"=",
"{",
"_id",
":",
"req",
".",
"params",
".",
"id",
"}",
";",
"logger",
".",
"debug",
"(",
"\"Middleware: listSubscribers: \"",
",",
"{",
"params",
":",
"listSubscribersParams",
"}",
")",
";",
"forms",
".",
"getNotifications",
"(",
"_",
".",
"extend",
"(",
"req",
".",
"connectionOptions",
",",
"listSubscribersParams",
")",
",",
"formsResultHandlers",
"(",
"constants",
".",
"resultTypes",
".",
"forms",
",",
"req",
",",
"next",
")",
")",
";",
"}"
] | List All Subscribers For A Form
@param req
@param res
@param next | [
"List",
"All",
"Subscribers",
"For",
"A",
"Form"
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/middleware/forms.js#L225-L233 | train |
feedhenry/fh-forms | lib/middleware/forms.js | updateSubscribers | function updateSubscribers(req, res, next) {
var updateSubscribersParams = {
_id: req.params.id
};
var subscribers = req.body.subscribers;
logger.debug("Middleware: listSubscribers: ", {params: updateSubscribersParams, subscribers: subscribers});
forms.updateNotifications(_.extend(req.connectionOptions, updateSubscribersParams), subscribers, formsResultHandlers(constants.resultTypes.forms, req, next));
} | javascript | function updateSubscribers(req, res, next) {
var updateSubscribersParams = {
_id: req.params.id
};
var subscribers = req.body.subscribers;
logger.debug("Middleware: listSubscribers: ", {params: updateSubscribersParams, subscribers: subscribers});
forms.updateNotifications(_.extend(req.connectionOptions, updateSubscribersParams), subscribers, formsResultHandlers(constants.resultTypes.forms, req, next));
} | [
"function",
"updateSubscribers",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"var",
"updateSubscribersParams",
"=",
"{",
"_id",
":",
"req",
".",
"params",
".",
"id",
"}",
";",
"var",
"subscribers",
"=",
"req",
".",
"body",
".",
"subscribers",
";",
"logger",
".",
"debug",
"(",
"\"Middleware: listSubscribers: \"",
",",
"{",
"params",
":",
"updateSubscribersParams",
",",
"subscribers",
":",
"subscribers",
"}",
")",
";",
"forms",
".",
"updateNotifications",
"(",
"_",
".",
"extend",
"(",
"req",
".",
"connectionOptions",
",",
"updateSubscribersParams",
")",
",",
"subscribers",
",",
"formsResultHandlers",
"(",
"constants",
".",
"resultTypes",
".",
"forms",
",",
"req",
",",
"next",
")",
")",
";",
"}"
] | Update The Subscribers Associated With A Form
@param req
@param res
@param next | [
"Update",
"The",
"Subscribers",
"Associated",
"With",
"A",
"Form"
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/middleware/forms.js#L241-L251 | train |
feedhenry/fh-forms | lib/middleware/forms.js | clone | function clone(req, res, next) {
var cloneFormParams = {
_id: req.params.id,
name: req.body.name,
userEmail: req.body.updatedBy
};
logger.debug("Middleware: clone form: ", {params: cloneFormParams});
forms.cloneForm(_.extend(req.connectionOptions, cloneFormParams), formsResultHandlers(constants.resultTypes.forms, req, next));
} | javascript | function clone(req, res, next) {
var cloneFormParams = {
_id: req.params.id,
name: req.body.name,
userEmail: req.body.updatedBy
};
logger.debug("Middleware: clone form: ", {params: cloneFormParams});
forms.cloneForm(_.extend(req.connectionOptions, cloneFormParams), formsResultHandlers(constants.resultTypes.forms, req, next));
} | [
"function",
"clone",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"var",
"cloneFormParams",
"=",
"{",
"_id",
":",
"req",
".",
"params",
".",
"id",
",",
"name",
":",
"req",
".",
"body",
".",
"name",
",",
"userEmail",
":",
"req",
".",
"body",
".",
"updatedBy",
"}",
";",
"logger",
".",
"debug",
"(",
"\"Middleware: clone form: \"",
",",
"{",
"params",
":",
"cloneFormParams",
"}",
")",
";",
"forms",
".",
"cloneForm",
"(",
"_",
".",
"extend",
"(",
"req",
".",
"connectionOptions",
",",
"cloneFormParams",
")",
",",
"formsResultHandlers",
"(",
"constants",
".",
"resultTypes",
".",
"forms",
",",
"req",
",",
"next",
")",
")",
";",
"}"
] | Clone An Existing Form
@param req
@param res
@param next | [
"Clone",
"An",
"Existing",
"Form"
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/middleware/forms.js#L260-L270 | train |
feedhenry/fh-forms | lib/middleware/forms.js | importForm | function importForm(req, res, next) {
req.appformsResultPayload = req.appformsResultPayload || {};
var formData = (req.appformsResultPayload.data && req.appformsResultPayload.type === constants.resultTypes.formTemplate) ? req.appformsResultPayload.data : undefined ;
var importFormParams = {
form: formData,
name: req.body.name,
description: req.body.description,
userEmail: req.user.email
};
logger.debug("Middleware: importForm form: ", {params: importFormParams});
forms.cloneForm(_.extend(req.connectionOptions, importFormParams), formsResultHandlers(constants.resultTypes.forms, req, next));
} | javascript | function importForm(req, res, next) {
req.appformsResultPayload = req.appformsResultPayload || {};
var formData = (req.appformsResultPayload.data && req.appformsResultPayload.type === constants.resultTypes.formTemplate) ? req.appformsResultPayload.data : undefined ;
var importFormParams = {
form: formData,
name: req.body.name,
description: req.body.description,
userEmail: req.user.email
};
logger.debug("Middleware: importForm form: ", {params: importFormParams});
forms.cloneForm(_.extend(req.connectionOptions, importFormParams), formsResultHandlers(constants.resultTypes.forms, req, next));
} | [
"function",
"importForm",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"req",
".",
"appformsResultPayload",
"=",
"req",
".",
"appformsResultPayload",
"||",
"{",
"}",
";",
"var",
"formData",
"=",
"(",
"req",
".",
"appformsResultPayload",
".",
"data",
"&&",
"req",
".",
"appformsResultPayload",
".",
"type",
"===",
"constants",
".",
"resultTypes",
".",
"formTemplate",
")",
"?",
"req",
".",
"appformsResultPayload",
".",
"data",
":",
"undefined",
";",
"var",
"importFormParams",
"=",
"{",
"form",
":",
"formData",
",",
"name",
":",
"req",
".",
"body",
".",
"name",
",",
"description",
":",
"req",
".",
"body",
".",
"description",
",",
"userEmail",
":",
"req",
".",
"user",
".",
"email",
"}",
";",
"logger",
".",
"debug",
"(",
"\"Middleware: importForm form: \"",
",",
"{",
"params",
":",
"importFormParams",
"}",
")",
";",
"forms",
".",
"cloneForm",
"(",
"_",
".",
"extend",
"(",
"req",
".",
"connectionOptions",
",",
"importFormParams",
")",
",",
"formsResultHandlers",
"(",
"constants",
".",
"resultTypes",
".",
"forms",
",",
"req",
",",
"next",
")",
")",
";",
"}"
] | Importing A Form From A Template | [
"Importing",
"A",
"Form",
"From",
"A",
"Template"
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/middleware/forms.js#L275-L289 | train |
feedhenry/fh-forms | lib/middleware/forms.js | projects | function projects(req, res, next) {
var params = {
"formId": req.params.id
};
logger.debug("Middleware: form projects: ", {params: params});
forms.getFormApps(_.extend(req.connectionOptions, params), formsResultHandlers(constants.resultTypes.formProjects, req, next));
} | javascript | function projects(req, res, next) {
var params = {
"formId": req.params.id
};
logger.debug("Middleware: form projects: ", {params: params});
forms.getFormApps(_.extend(req.connectionOptions, params), formsResultHandlers(constants.resultTypes.formProjects, req, next));
} | [
"function",
"projects",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"var",
"params",
"=",
"{",
"\"formId\"",
":",
"req",
".",
"params",
".",
"id",
"}",
";",
"logger",
".",
"debug",
"(",
"\"Middleware: form projects: \"",
",",
"{",
"params",
":",
"params",
"}",
")",
";",
"forms",
".",
"getFormApps",
"(",
"_",
".",
"extend",
"(",
"req",
".",
"connectionOptions",
",",
"params",
")",
",",
"formsResultHandlers",
"(",
"constants",
".",
"resultTypes",
".",
"formProjects",
",",
"req",
",",
"next",
")",
")",
";",
"}"
] | Get All Projects Associated With A Form
@param req
@param res
@param next | [
"Get",
"All",
"Projects",
"Associated",
"With",
"A",
"Form"
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/middleware/forms.js#L297-L305 | train |
feedhenry/fh-forms | lib/middleware/forms.js | submissions | function submissions(req, res, next) {
var params = {
formId: req.params.id
};
logger.debug("Middleware: form submissions: ", {params: params});
forms.getSubmissions(req.connectionOptions, params, function(err, getSubmissionResponse) {
if (err) {
logger.error("Middleware: form submissions ", {error: err});
}
getSubmissionResponse = getSubmissionResponse || {};
req.appformsResultPayload = {
data: getSubmissionResponse.submissions,
type: constants.resultTypes.submissions
};
next(err);
});
} | javascript | function submissions(req, res, next) {
var params = {
formId: req.params.id
};
logger.debug("Middleware: form submissions: ", {params: params});
forms.getSubmissions(req.connectionOptions, params, function(err, getSubmissionResponse) {
if (err) {
logger.error("Middleware: form submissions ", {error: err});
}
getSubmissionResponse = getSubmissionResponse || {};
req.appformsResultPayload = {
data: getSubmissionResponse.submissions,
type: constants.resultTypes.submissions
};
next(err);
});
} | [
"function",
"submissions",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"var",
"params",
"=",
"{",
"formId",
":",
"req",
".",
"params",
".",
"id",
"}",
";",
"logger",
".",
"debug",
"(",
"\"Middleware: form submissions: \"",
",",
"{",
"params",
":",
"params",
"}",
")",
";",
"forms",
".",
"getSubmissions",
"(",
"req",
".",
"connectionOptions",
",",
"params",
",",
"function",
"(",
"err",
",",
"getSubmissionResponse",
")",
"{",
"if",
"(",
"err",
")",
"{",
"logger",
".",
"error",
"(",
"\"Middleware: form submissions \"",
",",
"{",
"error",
":",
"err",
"}",
")",
";",
"}",
"getSubmissionResponse",
"=",
"getSubmissionResponse",
"||",
"{",
"}",
";",
"req",
".",
"appformsResultPayload",
"=",
"{",
"data",
":",
"getSubmissionResponse",
".",
"submissions",
",",
"type",
":",
"constants",
".",
"resultTypes",
".",
"submissions",
"}",
";",
"next",
"(",
"err",
")",
";",
"}",
")",
";",
"}"
] | List All Submissions Associated With A Form
@param req
@param res
@param next | [
"List",
"All",
"Submissions",
"Associated",
"With",
"A",
"Form"
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/middleware/forms.js#L313-L332 | train |
feedhenry/fh-forms | lib/middleware/forms.js | submitFormData | function submitFormData(req, res, next) {
var submission = req.body || {};
submission.appId = req.params.projectid;
submission.appEnvironment = req.params.environment;
submission.deviceId = submission.deviceId || "Device Unknown";
var submissionParams = {
submission: submission
};
logger.debug("Middleware: form submitFormData: ", {params: submissionParams});
forms.submitFormData(_.extend(submissionParams, req.connectionOptions), formsResultHandlers(constants.resultTypes.submissions, req, next));
} | javascript | function submitFormData(req, res, next) {
var submission = req.body || {};
submission.appId = req.params.projectid;
submission.appEnvironment = req.params.environment;
submission.deviceId = submission.deviceId || "Device Unknown";
var submissionParams = {
submission: submission
};
logger.debug("Middleware: form submitFormData: ", {params: submissionParams});
forms.submitFormData(_.extend(submissionParams, req.connectionOptions), formsResultHandlers(constants.resultTypes.submissions, req, next));
} | [
"function",
"submitFormData",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"var",
"submission",
"=",
"req",
".",
"body",
"||",
"{",
"}",
";",
"submission",
".",
"appId",
"=",
"req",
".",
"params",
".",
"projectid",
";",
"submission",
".",
"appEnvironment",
"=",
"req",
".",
"params",
".",
"environment",
";",
"submission",
".",
"deviceId",
"=",
"submission",
".",
"deviceId",
"||",
"\"Device Unknown\"",
";",
"var",
"submissionParams",
"=",
"{",
"submission",
":",
"submission",
"}",
";",
"logger",
".",
"debug",
"(",
"\"Middleware: form submitFormData: \"",
",",
"{",
"params",
":",
"submissionParams",
"}",
")",
";",
"forms",
".",
"submitFormData",
"(",
"_",
".",
"extend",
"(",
"submissionParams",
",",
"req",
".",
"connectionOptions",
")",
",",
"formsResultHandlers",
"(",
"constants",
".",
"resultTypes",
".",
"submissions",
",",
"req",
",",
"next",
")",
")",
";",
"}"
] | Make A Submission Against A Form
@param req
@param res
@param next | [
"Make",
"A",
"Submission",
"Against",
"A",
"Form"
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/middleware/forms.js#L340-L354 | train |
feedhenry/fh-forms | lib/impl/updateRules.js | createRules | function createRules(rulesToCreate, cb) {
function addRule(ruleToCreate, addRuleCallback) {
var fr = new rulesModel(ruleToCreate);
fr.save(function(err, frdoc) {
if (err) {
return addRuleCallback(err);
}
return addRuleCallback(null, frdoc);
});
}
async.map(rulesToCreate, addRule, cb);
} | javascript | function createRules(rulesToCreate, cb) {
function addRule(ruleToCreate, addRuleCallback) {
var fr = new rulesModel(ruleToCreate);
fr.save(function(err, frdoc) {
if (err) {
return addRuleCallback(err);
}
return addRuleCallback(null, frdoc);
});
}
async.map(rulesToCreate, addRule, cb);
} | [
"function",
"createRules",
"(",
"rulesToCreate",
",",
"cb",
")",
"{",
"function",
"addRule",
"(",
"ruleToCreate",
",",
"addRuleCallback",
")",
"{",
"var",
"fr",
"=",
"new",
"rulesModel",
"(",
"ruleToCreate",
")",
";",
"fr",
".",
"save",
"(",
"function",
"(",
"err",
",",
"frdoc",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"addRuleCallback",
"(",
"err",
")",
";",
"}",
"return",
"addRuleCallback",
"(",
"null",
",",
"frdoc",
")",
";",
"}",
")",
";",
"}",
"async",
".",
"map",
"(",
"rulesToCreate",
",",
"addRule",
",",
"cb",
")",
";",
"}"
] | iterate through the form field rules vs the new rules | [
"iterate",
"through",
"the",
"form",
"field",
"rules",
"vs",
"the",
"new",
"rules"
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/updateRules.js#L101-L115 | train |
feedhenry/fh-forms | lib/impl/updateRules.js | updateRules | function updateRules(rulesToUpdate, cb) {
function updateRule(ruleDetails, cb1) {
var id = ruleDetails._id;
rulesModel.findOne({_id: id}, function(err, ruleToUpdate) {
if (err) {
return cb1(err);
}
if (ruleToUpdate === null && !options.createIfNotFound) {
return cb1(new Error("No " + ruleType + " rule matches id " + id));
} else if (ruleToUpdate === null && options.createIfNotFound) {
ruleToUpdate = new rulesModel(ruleDetails);
}
for (var saveKey in ruleDetails) { // eslint-disable-line guard-for-in
ruleToUpdate[saveKey] = ruleDetails[saveKey];
}
ruleToUpdate.save(cb1);
});
}
async.map(rulesToUpdate, updateRule, cb);
} | javascript | function updateRules(rulesToUpdate, cb) {
function updateRule(ruleDetails, cb1) {
var id = ruleDetails._id;
rulesModel.findOne({_id: id}, function(err, ruleToUpdate) {
if (err) {
return cb1(err);
}
if (ruleToUpdate === null && !options.createIfNotFound) {
return cb1(new Error("No " + ruleType + " rule matches id " + id));
} else if (ruleToUpdate === null && options.createIfNotFound) {
ruleToUpdate = new rulesModel(ruleDetails);
}
for (var saveKey in ruleDetails) { // eslint-disable-line guard-for-in
ruleToUpdate[saveKey] = ruleDetails[saveKey];
}
ruleToUpdate.save(cb1);
});
}
async.map(rulesToUpdate, updateRule, cb);
} | [
"function",
"updateRules",
"(",
"rulesToUpdate",
",",
"cb",
")",
"{",
"function",
"updateRule",
"(",
"ruleDetails",
",",
"cb1",
")",
"{",
"var",
"id",
"=",
"ruleDetails",
".",
"_id",
";",
"rulesModel",
".",
"findOne",
"(",
"{",
"_id",
":",
"id",
"}",
",",
"function",
"(",
"err",
",",
"ruleToUpdate",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"cb1",
"(",
"err",
")",
";",
"}",
"if",
"(",
"ruleToUpdate",
"===",
"null",
"&&",
"!",
"options",
".",
"createIfNotFound",
")",
"{",
"return",
"cb1",
"(",
"new",
"Error",
"(",
"\"No \"",
"+",
"ruleType",
"+",
"\" rule matches id \"",
"+",
"id",
")",
")",
";",
"}",
"else",
"if",
"(",
"ruleToUpdate",
"===",
"null",
"&&",
"options",
".",
"createIfNotFound",
")",
"{",
"ruleToUpdate",
"=",
"new",
"rulesModel",
"(",
"ruleDetails",
")",
";",
"}",
"for",
"(",
"var",
"saveKey",
"in",
"ruleDetails",
")",
"{",
"ruleToUpdate",
"[",
"saveKey",
"]",
"=",
"ruleDetails",
"[",
"saveKey",
"]",
";",
"}",
"ruleToUpdate",
".",
"save",
"(",
"cb1",
")",
";",
"}",
")",
";",
"}",
"async",
".",
"map",
"(",
"rulesToUpdate",
",",
"updateRule",
",",
"cb",
")",
";",
"}"
] | process any updates | [
"process",
"any",
"updates"
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/updateRules.js#L137-L161 | train |
feedhenry/fh-forms | lib/impl/updateRules.js | deleteRules | function deleteRules(rulesToDelete, cb) {
var idsToRemove = _.pluck(rulesToDelete, "_id");
function deleteRule(fieldRuleId, cb1) {
rulesModel.findByIdAndRemove(fieldRuleId, cb1);
}
async.each(idsToRemove, deleteRule, cb);
} | javascript | function deleteRules(rulesToDelete, cb) {
var idsToRemove = _.pluck(rulesToDelete, "_id");
function deleteRule(fieldRuleId, cb1) {
rulesModel.findByIdAndRemove(fieldRuleId, cb1);
}
async.each(idsToRemove, deleteRule, cb);
} | [
"function",
"deleteRules",
"(",
"rulesToDelete",
",",
"cb",
")",
"{",
"var",
"idsToRemove",
"=",
"_",
".",
"pluck",
"(",
"rulesToDelete",
",",
"\"_id\"",
")",
";",
"function",
"deleteRule",
"(",
"fieldRuleId",
",",
"cb1",
")",
"{",
"rulesModel",
".",
"findByIdAndRemove",
"(",
"fieldRuleId",
",",
"cb1",
")",
";",
"}",
"async",
".",
"each",
"(",
"idsToRemove",
",",
"deleteRule",
",",
"cb",
")",
";",
"}"
] | process any deletes | [
"process",
"any",
"deletes"
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/updateRules.js#L164-L171 | train |
ForstaLabs/librelay-node | src/util.js | sleep | async function sleep(seconds) {
let ms = seconds * 1000;
while (ms > _maxTimeout) {
// Support sleeping longer than the javascript max setTimeout...
await new Promise(resolve => setTimeout(resolve, _maxTimeout));
ms -= _maxTimeout;
}
return await new Promise(resolve => setTimeout(resolve, ms, seconds));
} | javascript | async function sleep(seconds) {
let ms = seconds * 1000;
while (ms > _maxTimeout) {
// Support sleeping longer than the javascript max setTimeout...
await new Promise(resolve => setTimeout(resolve, _maxTimeout));
ms -= _maxTimeout;
}
return await new Promise(resolve => setTimeout(resolve, ms, seconds));
} | [
"async",
"function",
"sleep",
"(",
"seconds",
")",
"{",
"let",
"ms",
"=",
"seconds",
"*",
"1000",
";",
"while",
"(",
"ms",
">",
"_maxTimeout",
")",
"{",
"await",
"new",
"Promise",
"(",
"resolve",
"=>",
"setTimeout",
"(",
"resolve",
",",
"_maxTimeout",
")",
")",
";",
"ms",
"-=",
"_maxTimeout",
";",
"}",
"return",
"await",
"new",
"Promise",
"(",
"resolve",
"=>",
"setTimeout",
"(",
"resolve",
",",
"ms",
",",
"seconds",
")",
")",
";",
"}"
] | `setTimeout` max valid value.
Sleep for N seconds.
@param {number} seconds | [
"setTimeout",
"max",
"valid",
"value",
".",
"Sleep",
"for",
"N",
"seconds",
"."
] | f411c6585772ac67b842767bc7ce23edcbfae4ae | https://github.com/ForstaLabs/librelay-node/blob/f411c6585772ac67b842767bc7ce23edcbfae4ae/src/util.js#L26-L34 | train |
feedhenry/fh-forms | lib/impl/refactorRules.js | isFieldStillValidTarget | function isFieldStillValidTarget(fieldOrPageIdToCheck, pages, cb) {
var fieldExistsInForm = false;
var invalidPages = _.filter(pages, function(page) {
var currentPageId = page._id.toString();
if (currentPageId === fieldOrPageIdToCheck) {
fieldExistsInForm = true;
}
var invalidFieldList = _.filter(page.fields, function(field) {
var currentFieldId = field._id.toString();
if (currentFieldId === fieldOrPageIdToCheck) {
//Current field exists
fieldExistsInForm = true;
//Field is admin only, therefore it is an invalid target for a rule.
if (field.adminOnly) {
return true;
} else {
return false;
}
} else {
return false;
}
});
//If the invalidFieldList is > 0, it means that one of the fields was invalid.
return invalidFieldList.length > 0;
});
var invalidField = invalidPages.length > 0;
//Invalid if either the field is invalid, or it does not exist in the form.
if (invalidField === true || !fieldExistsInForm) {
return cb(true);
} else {
return cb();
}
} | javascript | function isFieldStillValidTarget(fieldOrPageIdToCheck, pages, cb) {
var fieldExistsInForm = false;
var invalidPages = _.filter(pages, function(page) {
var currentPageId = page._id.toString();
if (currentPageId === fieldOrPageIdToCheck) {
fieldExistsInForm = true;
}
var invalidFieldList = _.filter(page.fields, function(field) {
var currentFieldId = field._id.toString();
if (currentFieldId === fieldOrPageIdToCheck) {
//Current field exists
fieldExistsInForm = true;
//Field is admin only, therefore it is an invalid target for a rule.
if (field.adminOnly) {
return true;
} else {
return false;
}
} else {
return false;
}
});
//If the invalidFieldList is > 0, it means that one of the fields was invalid.
return invalidFieldList.length > 0;
});
var invalidField = invalidPages.length > 0;
//Invalid if either the field is invalid, or it does not exist in the form.
if (invalidField === true || !fieldExistsInForm) {
return cb(true);
} else {
return cb();
}
} | [
"function",
"isFieldStillValidTarget",
"(",
"fieldOrPageIdToCheck",
",",
"pages",
",",
"cb",
")",
"{",
"var",
"fieldExistsInForm",
"=",
"false",
";",
"var",
"invalidPages",
"=",
"_",
".",
"filter",
"(",
"pages",
",",
"function",
"(",
"page",
")",
"{",
"var",
"currentPageId",
"=",
"page",
".",
"_id",
".",
"toString",
"(",
")",
";",
"if",
"(",
"currentPageId",
"===",
"fieldOrPageIdToCheck",
")",
"{",
"fieldExistsInForm",
"=",
"true",
";",
"}",
"var",
"invalidFieldList",
"=",
"_",
".",
"filter",
"(",
"page",
".",
"fields",
",",
"function",
"(",
"field",
")",
"{",
"var",
"currentFieldId",
"=",
"field",
".",
"_id",
".",
"toString",
"(",
")",
";",
"if",
"(",
"currentFieldId",
"===",
"fieldOrPageIdToCheck",
")",
"{",
"fieldExistsInForm",
"=",
"true",
";",
"if",
"(",
"field",
".",
"adminOnly",
")",
"{",
"return",
"true",
";",
"}",
"else",
"{",
"return",
"false",
";",
"}",
"}",
"else",
"{",
"return",
"false",
";",
"}",
"}",
")",
";",
"return",
"invalidFieldList",
".",
"length",
">",
"0",
";",
"}",
")",
";",
"var",
"invalidField",
"=",
"invalidPages",
".",
"length",
">",
"0",
";",
"if",
"(",
"invalidField",
"===",
"true",
"||",
"!",
"fieldExistsInForm",
")",
"{",
"return",
"cb",
"(",
"true",
")",
";",
"}",
"else",
"{",
"return",
"cb",
"(",
")",
";",
"}",
"}"
] | A field target is not valid if it does not exist in the form or it is an adminOnly field.
@param fieldOrPageIdToCheck
@param pages
@returns {boolean} | [
"A",
"field",
"target",
"is",
"not",
"valid",
"if",
"it",
"does",
"not",
"exist",
"in",
"the",
"form",
"or",
"it",
"is",
"an",
"adminOnly",
"field",
"."
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/refactorRules.js#L94-L131 | train |
feedhenry/fh-forms | lib/impl/refactorRules.js | getSourceRepeatingSections | function getSourceRepeatingSections(rule) {
return _.chain(rule.ruleConditionalStatements)
.map(function(ruleConditionalStatement) {
var sourceId = ruleConditionalStatement.sourceField.toString();
return fieldSectionMapping[sourceId];
})
.filter(function(section) {
return section && section.repeating;
})
.map(function(repeatingSection) {
return repeatingSection._id.toString();
})
.uniq()
.value();
} | javascript | function getSourceRepeatingSections(rule) {
return _.chain(rule.ruleConditionalStatements)
.map(function(ruleConditionalStatement) {
var sourceId = ruleConditionalStatement.sourceField.toString();
return fieldSectionMapping[sourceId];
})
.filter(function(section) {
return section && section.repeating;
})
.map(function(repeatingSection) {
return repeatingSection._id.toString();
})
.uniq()
.value();
} | [
"function",
"getSourceRepeatingSections",
"(",
"rule",
")",
"{",
"return",
"_",
".",
"chain",
"(",
"rule",
".",
"ruleConditionalStatements",
")",
".",
"map",
"(",
"function",
"(",
"ruleConditionalStatement",
")",
"{",
"var",
"sourceId",
"=",
"ruleConditionalStatement",
".",
"sourceField",
".",
"toString",
"(",
")",
";",
"return",
"fieldSectionMapping",
"[",
"sourceId",
"]",
";",
"}",
")",
".",
"filter",
"(",
"function",
"(",
"section",
")",
"{",
"return",
"section",
"&&",
"section",
".",
"repeating",
";",
"}",
")",
".",
"map",
"(",
"function",
"(",
"repeatingSection",
")",
"{",
"return",
"repeatingSection",
".",
"_id",
".",
"toString",
"(",
")",
";",
"}",
")",
".",
"uniq",
"(",
")",
".",
"value",
"(",
")",
";",
"}"
] | Get ids of repeating sections with fields which act as sources in a rule
@param rule
@returns {String[]} | [
"Get",
"ids",
"of",
"repeating",
"sections",
"with",
"fields",
"which",
"act",
"as",
"sources",
"in",
"a",
"rule"
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/refactorRules.js#L182-L196 | train |
feedhenry/fh-forms | lib/impl/refactorRules.js | updateFormRules | function updateFormRules(cb) {
//Filters out any conditional statements that are no longer valid.
function filterConditionalStatements(rule) {
return _.filter(rule.ruleConditionalStatements, function(ruleCondStatement) {
var sourceField = ruleCondStatement.sourceField.toString();
if (invalidFields[sourceField]) {
/**
* If the user flagged the field in this rule for deletion, flag the rule for deletion.
*/
if (ruleDeletionFlags[sourceField]) {
rulesFlaggedForDeletion[rule._id.toString()] = true;
}
return false;
} else {
return true;
}
});
}
var updatedFieldRules = _.map(form.fieldRules, function(fieldRule) {
var filteredConditionalStatements = filterConditionalStatements(fieldRule);
var filteredTargets = _.filter(fieldRule.targetField, function(targetField) {
if (invalidFields[targetField]) {
return false;
} else {
return true;
}
});
fieldRule.ruleConditionalStatements = filteredConditionalStatements;
fieldRule.targetField = filteredTargets;
return fieldRule;
});
var updatedPageRules = _.map(form.pageRules, function(pageRule) {
pageRule.ruleConditionalStatements = filterConditionalStatements(pageRule);
return pageRule;
});
fieldRulesToDelete = _.filter(updatedFieldRules, function(fieldRule) {
var targetFields = fieldRule.targetField;
var conditionalStatements = fieldRule.ruleConditionalStatements;
var fieldRuleId = fieldRule._id.toString();
return targetFields.length === 0 || conditionalStatements.length === 0 || rulesFlaggedForDeletion[fieldRuleId];
});
pageRulesToDelete = _.filter(updatedPageRules, function(pageRule) {
var conditionalStatements = pageRule.ruleConditionalStatements;
var pageRuleId = pageRule._id.toString();
return conditionalStatements.length === 0 || rulesFlaggedForDeletion[pageRuleId];
});
fieldRulesToDelete = _.map(fieldRulesToDelete, function(fieldRule) {
return fieldRule._id.toString();
});
pageRulesToDelete = _.map(pageRulesToDelete, function(pageRule) {
return pageRule._id.toString();
});
//Now have all the rules that need to be deleted, these rules need to be removed from the field and page rules
updatedFieldRules = _.filter(updatedFieldRules, function(updatedFieldRule) {
return fieldRulesToDelete.indexOf(updatedFieldRule._id.toString()) === -1;
});
updatedPageRules = _.filter(updatedPageRules, function(updatedPageRule) {
return pageRulesToDelete.indexOf(updatedPageRule._id.toString()) === -1;
});
form.fieldRules = updatedFieldRules;
form.pageRules = updatedPageRules;
form.save(function(err) {
return cb(err);
});
} | javascript | function updateFormRules(cb) {
//Filters out any conditional statements that are no longer valid.
function filterConditionalStatements(rule) {
return _.filter(rule.ruleConditionalStatements, function(ruleCondStatement) {
var sourceField = ruleCondStatement.sourceField.toString();
if (invalidFields[sourceField]) {
/**
* If the user flagged the field in this rule for deletion, flag the rule for deletion.
*/
if (ruleDeletionFlags[sourceField]) {
rulesFlaggedForDeletion[rule._id.toString()] = true;
}
return false;
} else {
return true;
}
});
}
var updatedFieldRules = _.map(form.fieldRules, function(fieldRule) {
var filteredConditionalStatements = filterConditionalStatements(fieldRule);
var filteredTargets = _.filter(fieldRule.targetField, function(targetField) {
if (invalidFields[targetField]) {
return false;
} else {
return true;
}
});
fieldRule.ruleConditionalStatements = filteredConditionalStatements;
fieldRule.targetField = filteredTargets;
return fieldRule;
});
var updatedPageRules = _.map(form.pageRules, function(pageRule) {
pageRule.ruleConditionalStatements = filterConditionalStatements(pageRule);
return pageRule;
});
fieldRulesToDelete = _.filter(updatedFieldRules, function(fieldRule) {
var targetFields = fieldRule.targetField;
var conditionalStatements = fieldRule.ruleConditionalStatements;
var fieldRuleId = fieldRule._id.toString();
return targetFields.length === 0 || conditionalStatements.length === 0 || rulesFlaggedForDeletion[fieldRuleId];
});
pageRulesToDelete = _.filter(updatedPageRules, function(pageRule) {
var conditionalStatements = pageRule.ruleConditionalStatements;
var pageRuleId = pageRule._id.toString();
return conditionalStatements.length === 0 || rulesFlaggedForDeletion[pageRuleId];
});
fieldRulesToDelete = _.map(fieldRulesToDelete, function(fieldRule) {
return fieldRule._id.toString();
});
pageRulesToDelete = _.map(pageRulesToDelete, function(pageRule) {
return pageRule._id.toString();
});
//Now have all the rules that need to be deleted, these rules need to be removed from the field and page rules
updatedFieldRules = _.filter(updatedFieldRules, function(updatedFieldRule) {
return fieldRulesToDelete.indexOf(updatedFieldRule._id.toString()) === -1;
});
updatedPageRules = _.filter(updatedPageRules, function(updatedPageRule) {
return pageRulesToDelete.indexOf(updatedPageRule._id.toString()) === -1;
});
form.fieldRules = updatedFieldRules;
form.pageRules = updatedPageRules;
form.save(function(err) {
return cb(err);
});
} | [
"function",
"updateFormRules",
"(",
"cb",
")",
"{",
"function",
"filterConditionalStatements",
"(",
"rule",
")",
"{",
"return",
"_",
".",
"filter",
"(",
"rule",
".",
"ruleConditionalStatements",
",",
"function",
"(",
"ruleCondStatement",
")",
"{",
"var",
"sourceField",
"=",
"ruleCondStatement",
".",
"sourceField",
".",
"toString",
"(",
")",
";",
"if",
"(",
"invalidFields",
"[",
"sourceField",
"]",
")",
"{",
"if",
"(",
"ruleDeletionFlags",
"[",
"sourceField",
"]",
")",
"{",
"rulesFlaggedForDeletion",
"[",
"rule",
".",
"_id",
".",
"toString",
"(",
")",
"]",
"=",
"true",
";",
"}",
"return",
"false",
";",
"}",
"else",
"{",
"return",
"true",
";",
"}",
"}",
")",
";",
"}",
"var",
"updatedFieldRules",
"=",
"_",
".",
"map",
"(",
"form",
".",
"fieldRules",
",",
"function",
"(",
"fieldRule",
")",
"{",
"var",
"filteredConditionalStatements",
"=",
"filterConditionalStatements",
"(",
"fieldRule",
")",
";",
"var",
"filteredTargets",
"=",
"_",
".",
"filter",
"(",
"fieldRule",
".",
"targetField",
",",
"function",
"(",
"targetField",
")",
"{",
"if",
"(",
"invalidFields",
"[",
"targetField",
"]",
")",
"{",
"return",
"false",
";",
"}",
"else",
"{",
"return",
"true",
";",
"}",
"}",
")",
";",
"fieldRule",
".",
"ruleConditionalStatements",
"=",
"filteredConditionalStatements",
";",
"fieldRule",
".",
"targetField",
"=",
"filteredTargets",
";",
"return",
"fieldRule",
";",
"}",
")",
";",
"var",
"updatedPageRules",
"=",
"_",
".",
"map",
"(",
"form",
".",
"pageRules",
",",
"function",
"(",
"pageRule",
")",
"{",
"pageRule",
".",
"ruleConditionalStatements",
"=",
"filterConditionalStatements",
"(",
"pageRule",
")",
";",
"return",
"pageRule",
";",
"}",
")",
";",
"fieldRulesToDelete",
"=",
"_",
".",
"filter",
"(",
"updatedFieldRules",
",",
"function",
"(",
"fieldRule",
")",
"{",
"var",
"targetFields",
"=",
"fieldRule",
".",
"targetField",
";",
"var",
"conditionalStatements",
"=",
"fieldRule",
".",
"ruleConditionalStatements",
";",
"var",
"fieldRuleId",
"=",
"fieldRule",
".",
"_id",
".",
"toString",
"(",
")",
";",
"return",
"targetFields",
".",
"length",
"===",
"0",
"||",
"conditionalStatements",
".",
"length",
"===",
"0",
"||",
"rulesFlaggedForDeletion",
"[",
"fieldRuleId",
"]",
";",
"}",
")",
";",
"pageRulesToDelete",
"=",
"_",
".",
"filter",
"(",
"updatedPageRules",
",",
"function",
"(",
"pageRule",
")",
"{",
"var",
"conditionalStatements",
"=",
"pageRule",
".",
"ruleConditionalStatements",
";",
"var",
"pageRuleId",
"=",
"pageRule",
".",
"_id",
".",
"toString",
"(",
")",
";",
"return",
"conditionalStatements",
".",
"length",
"===",
"0",
"||",
"rulesFlaggedForDeletion",
"[",
"pageRuleId",
"]",
";",
"}",
")",
";",
"fieldRulesToDelete",
"=",
"_",
".",
"map",
"(",
"fieldRulesToDelete",
",",
"function",
"(",
"fieldRule",
")",
"{",
"return",
"fieldRule",
".",
"_id",
".",
"toString",
"(",
")",
";",
"}",
")",
";",
"pageRulesToDelete",
"=",
"_",
".",
"map",
"(",
"pageRulesToDelete",
",",
"function",
"(",
"pageRule",
")",
"{",
"return",
"pageRule",
".",
"_id",
".",
"toString",
"(",
")",
";",
"}",
")",
";",
"updatedFieldRules",
"=",
"_",
".",
"filter",
"(",
"updatedFieldRules",
",",
"function",
"(",
"updatedFieldRule",
")",
"{",
"return",
"fieldRulesToDelete",
".",
"indexOf",
"(",
"updatedFieldRule",
".",
"_id",
".",
"toString",
"(",
")",
")",
"===",
"-",
"1",
";",
"}",
")",
";",
"updatedPageRules",
"=",
"_",
".",
"filter",
"(",
"updatedPageRules",
",",
"function",
"(",
"updatedPageRule",
")",
"{",
"return",
"pageRulesToDelete",
".",
"indexOf",
"(",
"updatedPageRule",
".",
"_id",
".",
"toString",
"(",
")",
")",
"===",
"-",
"1",
";",
"}",
")",
";",
"form",
".",
"fieldRules",
"=",
"updatedFieldRules",
";",
"form",
".",
"pageRules",
"=",
"updatedPageRules",
";",
"form",
".",
"save",
"(",
"function",
"(",
"err",
")",
"{",
"return",
"cb",
"(",
"err",
")",
";",
"}",
")",
";",
"}"
] | Need to delete any rules that are to be deleted | [
"Need",
"to",
"delete",
"any",
"rules",
"that",
"are",
"to",
"be",
"deleted"
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/refactorRules.js#L306-L386 | train |
feedhenry/fh-forms | lib/impl/refactorRules.js | filterConditionalStatements | function filterConditionalStatements(rule) {
return _.filter(rule.ruleConditionalStatements, function(ruleCondStatement) {
var sourceField = ruleCondStatement.sourceField.toString();
if (invalidFields[sourceField]) {
/**
* If the user flagged the field in this rule for deletion, flag the rule for deletion.
*/
if (ruleDeletionFlags[sourceField]) {
rulesFlaggedForDeletion[rule._id.toString()] = true;
}
return false;
} else {
return true;
}
});
} | javascript | function filterConditionalStatements(rule) {
return _.filter(rule.ruleConditionalStatements, function(ruleCondStatement) {
var sourceField = ruleCondStatement.sourceField.toString();
if (invalidFields[sourceField]) {
/**
* If the user flagged the field in this rule for deletion, flag the rule for deletion.
*/
if (ruleDeletionFlags[sourceField]) {
rulesFlaggedForDeletion[rule._id.toString()] = true;
}
return false;
} else {
return true;
}
});
} | [
"function",
"filterConditionalStatements",
"(",
"rule",
")",
"{",
"return",
"_",
".",
"filter",
"(",
"rule",
".",
"ruleConditionalStatements",
",",
"function",
"(",
"ruleCondStatement",
")",
"{",
"var",
"sourceField",
"=",
"ruleCondStatement",
".",
"sourceField",
".",
"toString",
"(",
")",
";",
"if",
"(",
"invalidFields",
"[",
"sourceField",
"]",
")",
"{",
"if",
"(",
"ruleDeletionFlags",
"[",
"sourceField",
"]",
")",
"{",
"rulesFlaggedForDeletion",
"[",
"rule",
".",
"_id",
".",
"toString",
"(",
")",
"]",
"=",
"true",
";",
"}",
"return",
"false",
";",
"}",
"else",
"{",
"return",
"true",
";",
"}",
"}",
")",
";",
"}"
] | Filters out any conditional statements that are no longer valid. | [
"Filters",
"out",
"any",
"conditional",
"statements",
"that",
"are",
"no",
"longer",
"valid",
"."
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/refactorRules.js#L309-L325 | train |
cloudfour/drizzle-builder | src/write/collections.js | walkCollections | function walkCollections(patterns, drizzleData, writePromises = []) {
if (hasCollection(patterns)) {
writePromises.push(
writePage(
patterns.collection.id,
patterns.collection,
drizzleData.options.dest.patterns,
drizzleData.options.keys.collections.plural
)
);
}
for (const patternKey in patterns) {
if (!isCollection(patterns[patternKey])) {
walkCollections(patterns[patternKey], drizzleData, writePromises);
}
}
return writePromises;
} | javascript | function walkCollections(patterns, drizzleData, writePromises = []) {
if (hasCollection(patterns)) {
writePromises.push(
writePage(
patterns.collection.id,
patterns.collection,
drizzleData.options.dest.patterns,
drizzleData.options.keys.collections.plural
)
);
}
for (const patternKey in patterns) {
if (!isCollection(patterns[patternKey])) {
walkCollections(patterns[patternKey], drizzleData, writePromises);
}
}
return writePromises;
} | [
"function",
"walkCollections",
"(",
"patterns",
",",
"drizzleData",
",",
"writePromises",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"hasCollection",
"(",
"patterns",
")",
")",
"{",
"writePromises",
".",
"push",
"(",
"writePage",
"(",
"patterns",
".",
"collection",
".",
"id",
",",
"patterns",
".",
"collection",
",",
"drizzleData",
".",
"options",
".",
"dest",
".",
"patterns",
",",
"drizzleData",
".",
"options",
".",
"keys",
".",
"collections",
".",
"plural",
")",
")",
";",
"}",
"for",
"(",
"const",
"patternKey",
"in",
"patterns",
")",
"{",
"if",
"(",
"!",
"isCollection",
"(",
"patterns",
"[",
"patternKey",
"]",
")",
")",
"{",
"walkCollections",
"(",
"patterns",
"[",
"patternKey",
"]",
",",
"drizzleData",
",",
"writePromises",
")",
";",
"}",
"}",
"return",
"writePromises",
";",
"}"
] | Traverse patterns object and write out any collection objects to files.
@param {Object} pages current level of pages tree
@param {Object} drizzleData
@param {Array} writePromises All write promises so far
@return {Array} of Promises | [
"Traverse",
"patterns",
"object",
"and",
"write",
"out",
"any",
"collection",
"objects",
"to",
"files",
"."
] | 1c320cb059c749c28339a661d1768d3a643e5f1c | https://github.com/cloudfour/drizzle-builder/blob/1c320cb059c749c28339a661d1768d3a643e5f1c/src/write/collections.js#L15-L32 | train |
cloudfour/drizzle-builder | src/write/collections.js | writeCollections | function writeCollections(drizzleData) {
return Promise.all(walkCollections(drizzleData.patterns, drizzleData)).then(
writePromises => drizzleData,
error => DrizzleError.error(error, drizzleData.options.debug)
);
} | javascript | function writeCollections(drizzleData) {
return Promise.all(walkCollections(drizzleData.patterns, drizzleData)).then(
writePromises => drizzleData,
error => DrizzleError.error(error, drizzleData.options.debug)
);
} | [
"function",
"writeCollections",
"(",
"drizzleData",
")",
"{",
"return",
"Promise",
".",
"all",
"(",
"walkCollections",
"(",
"drizzleData",
".",
"patterns",
",",
"drizzleData",
")",
")",
".",
"then",
"(",
"writePromises",
"=>",
"drizzleData",
",",
"error",
"=>",
"DrizzleError",
".",
"error",
"(",
"error",
",",
"drizzleData",
".",
"options",
".",
"debug",
")",
")",
";",
"}"
] | Traverse the patterns object and write out collections HTML pages.
@param {Object} drizzleData
@return {Promise} resolving to {Object} drizzleData | [
"Traverse",
"the",
"patterns",
"object",
"and",
"write",
"out",
"collections",
"HTML",
"pages",
"."
] | 1c320cb059c749c28339a661d1768d3a643e5f1c | https://github.com/cloudfour/drizzle-builder/blob/1c320cb059c749c28339a661d1768d3a643e5f1c/src/write/collections.js#L40-L45 | train |
back4app/back4app-entity | src/back/models/attributes/AttributeDictionary.js | AttributeDictionary | function AttributeDictionary(attributes) {
expect(arguments).to.have.length.below(
2,
'Invalid arguments length when creating an AttributeDictionary (it has ' +
'to be passed less than 2 arguments)'
);
if (attributes) {
expect(typeof attributes).to.equal(
'object',
'Invalid argument type when creating an AttributeDictionary (it has to ' +
'be an object)'
);
if (attributes instanceof Array) {
for (var i = 0; i < attributes.length; i++) {
_addAttribute(this, attributes[i]);
}
} else {
for (var attribute in attributes) {
_addAttribute(this, attributes[attribute], attribute);
}
}
}
Object.preventExtensions(this);
Object.seal(this);
} | javascript | function AttributeDictionary(attributes) {
expect(arguments).to.have.length.below(
2,
'Invalid arguments length when creating an AttributeDictionary (it has ' +
'to be passed less than 2 arguments)'
);
if (attributes) {
expect(typeof attributes).to.equal(
'object',
'Invalid argument type when creating an AttributeDictionary (it has to ' +
'be an object)'
);
if (attributes instanceof Array) {
for (var i = 0; i < attributes.length; i++) {
_addAttribute(this, attributes[i]);
}
} else {
for (var attribute in attributes) {
_addAttribute(this, attributes[attribute], attribute);
}
}
}
Object.preventExtensions(this);
Object.seal(this);
} | [
"function",
"AttributeDictionary",
"(",
"attributes",
")",
"{",
"expect",
"(",
"arguments",
")",
".",
"to",
".",
"have",
".",
"length",
".",
"below",
"(",
"2",
",",
"'Invalid arguments length when creating an AttributeDictionary (it has '",
"+",
"'to be passed less than 2 arguments)'",
")",
";",
"if",
"(",
"attributes",
")",
"{",
"expect",
"(",
"typeof",
"attributes",
")",
".",
"to",
".",
"equal",
"(",
"'object'",
",",
"'Invalid argument type when creating an AttributeDictionary (it has to '",
"+",
"'be an object)'",
")",
";",
"if",
"(",
"attributes",
"instanceof",
"Array",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"attributes",
".",
"length",
";",
"i",
"++",
")",
"{",
"_addAttribute",
"(",
"this",
",",
"attributes",
"[",
"i",
"]",
")",
";",
"}",
"}",
"else",
"{",
"for",
"(",
"var",
"attribute",
"in",
"attributes",
")",
"{",
"_addAttribute",
"(",
"this",
",",
"attributes",
"[",
"attribute",
"]",
",",
"attribute",
")",
";",
"}",
"}",
"}",
"Object",
".",
"preventExtensions",
"(",
"this",
")",
";",
"Object",
".",
"seal",
"(",
"this",
")",
";",
"}"
] | Dictionary of Entity Attributes.
@constructor
@memberof module:back4app-entity/models/attributes
@param {?(module:back4app-entity/models/attributes.Attribute[]|
Object.<!string, !(module:back4app-entity/models/attributes.Attribute|
Object)>)}
[attributes] The attributes to be added in the dictionary. They can be given
as an Array or a Dictionary of
{@link module:back4app-entity/models/attributes.Attribute}.
@example
var attributeDictionary = new AttributeDictionary();
@example
var attributeDictionary = new AttributeDictionary(null);
@example
var attributeDictionary = new AttributeDictionary({});
@example
var attributeDictionary = new AttributeDictionary({
attribute1: new StringAttribute('attribute1'),
attribute2: new StringAttribute('attribute2')
}); | [
"Dictionary",
"of",
"Entity",
"Attributes",
"."
] | 16a15284d2e119508fcb4e0c88f647ffb285d2e9 | https://github.com/back4app/back4app-entity/blob/16a15284d2e119508fcb4e0c88f647ffb285d2e9/src/back/models/attributes/AttributeDictionary.js#L34-L61 | train |
back4app/back4app-entity | src/back/models/attributes/AttributeDictionary.js | _addAttribute | function _addAttribute() {
var attributeDictionary = arguments[0];
var attribute = null;
var name = null;
if (arguments.length === 2) {
attribute = arguments[1];
} else {
attribute = arguments[1];
name = arguments[2];
}
expect(attribute).to.be.an(
'object',
'Invalid argument type when adding an attribute ' + (name ? 'called "' +
name + '" ' : '') + 'in an AttributeDictionary (it has to be an object)'
);
if (name) {
if (attribute.name) {
expect(attribute.name).to.equal(
name,
'Invalid argument "name" when adding an attribute called "' +
attribute.name + '" in an AttributeDictionary (the name given in ' +
'argument and the name given in the attribute object should be equal)'
);
} else {
attribute.name = name;
}
}
if (!(attribute instanceof Attribute)) {
attribute = Attribute.resolve(attribute);
}
expect(attribute.constructor).to.not.equal(
Attribute,
'Invalid attribute "' + attribute.name + '". Attribute is an abstract ' +
'class and cannot be directly instantiated and added in an ' +
'AttributeDictionary'
);
expect(attributeDictionary).to.not.have.ownProperty(
attribute.name,
'Duplicated attribute name "' + attribute.name + '"'
);
Object.defineProperty(attributeDictionary, attribute.name, {
value: attribute,
enumerable: true,
writable: false,
configurable: false
});
} | javascript | function _addAttribute() {
var attributeDictionary = arguments[0];
var attribute = null;
var name = null;
if (arguments.length === 2) {
attribute = arguments[1];
} else {
attribute = arguments[1];
name = arguments[2];
}
expect(attribute).to.be.an(
'object',
'Invalid argument type when adding an attribute ' + (name ? 'called "' +
name + '" ' : '') + 'in an AttributeDictionary (it has to be an object)'
);
if (name) {
if (attribute.name) {
expect(attribute.name).to.equal(
name,
'Invalid argument "name" when adding an attribute called "' +
attribute.name + '" in an AttributeDictionary (the name given in ' +
'argument and the name given in the attribute object should be equal)'
);
} else {
attribute.name = name;
}
}
if (!(attribute instanceof Attribute)) {
attribute = Attribute.resolve(attribute);
}
expect(attribute.constructor).to.not.equal(
Attribute,
'Invalid attribute "' + attribute.name + '". Attribute is an abstract ' +
'class and cannot be directly instantiated and added in an ' +
'AttributeDictionary'
);
expect(attributeDictionary).to.not.have.ownProperty(
attribute.name,
'Duplicated attribute name "' + attribute.name + '"'
);
Object.defineProperty(attributeDictionary, attribute.name, {
value: attribute,
enumerable: true,
writable: false,
configurable: false
});
} | [
"function",
"_addAttribute",
"(",
")",
"{",
"var",
"attributeDictionary",
"=",
"arguments",
"[",
"0",
"]",
";",
"var",
"attribute",
"=",
"null",
";",
"var",
"name",
"=",
"null",
";",
"if",
"(",
"arguments",
".",
"length",
"===",
"2",
")",
"{",
"attribute",
"=",
"arguments",
"[",
"1",
"]",
";",
"}",
"else",
"{",
"attribute",
"=",
"arguments",
"[",
"1",
"]",
";",
"name",
"=",
"arguments",
"[",
"2",
"]",
";",
"}",
"expect",
"(",
"attribute",
")",
".",
"to",
".",
"be",
".",
"an",
"(",
"'object'",
",",
"'Invalid argument type when adding an attribute '",
"+",
"(",
"name",
"?",
"'called \"'",
"+",
"name",
"+",
"'\" '",
":",
"''",
")",
"+",
"'in an AttributeDictionary (it has to be an object)'",
")",
";",
"if",
"(",
"name",
")",
"{",
"if",
"(",
"attribute",
".",
"name",
")",
"{",
"expect",
"(",
"attribute",
".",
"name",
")",
".",
"to",
".",
"equal",
"(",
"name",
",",
"'Invalid argument \"name\" when adding an attribute called \"'",
"+",
"attribute",
".",
"name",
"+",
"'\" in an AttributeDictionary (the name given in '",
"+",
"'argument and the name given in the attribute object should be equal)'",
")",
";",
"}",
"else",
"{",
"attribute",
".",
"name",
"=",
"name",
";",
"}",
"}",
"if",
"(",
"!",
"(",
"attribute",
"instanceof",
"Attribute",
")",
")",
"{",
"attribute",
"=",
"Attribute",
".",
"resolve",
"(",
"attribute",
")",
";",
"}",
"expect",
"(",
"attribute",
".",
"constructor",
")",
".",
"to",
".",
"not",
".",
"equal",
"(",
"Attribute",
",",
"'Invalid attribute \"'",
"+",
"attribute",
".",
"name",
"+",
"'\". Attribute is an abstract '",
"+",
"'class and cannot be directly instantiated and added in an '",
"+",
"'AttributeDictionary'",
")",
";",
"expect",
"(",
"attributeDictionary",
")",
".",
"to",
".",
"not",
".",
"have",
".",
"ownProperty",
"(",
"attribute",
".",
"name",
",",
"'Duplicated attribute name \"'",
"+",
"attribute",
".",
"name",
"+",
"'\"'",
")",
";",
"Object",
".",
"defineProperty",
"(",
"attributeDictionary",
",",
"attribute",
".",
"name",
",",
"{",
"value",
":",
"attribute",
",",
"enumerable",
":",
"true",
",",
"writable",
":",
"false",
",",
"configurable",
":",
"false",
"}",
")",
";",
"}"
] | Adds a new attribute to the dictionary.
@name
module:back4app-entity/models/attributes.AttributeDictionary~_addAttribute
@function
@param {!module:back4app-entity/models/attributes.AttributeDictionary}
attributeDictionary It is the attribute dictionary to which the attribute
will be added.
@param {!module:back4app-entity/models/attributes.Attribute} attribute This
is the attribute to be added. It can be passed as a
{@link module:back4app-entity/models/attributes.Attribute} instance.
@param {?string} [name] This is the name of the attribute.
@private
@example
var attributeDictionary = new AttributeDictionary();
_addAttribute(
attributeDictionary,
new StringAttribute('attribute'),
'attribute'
);
Adds a new attribute to the dictionary.
@name
module:back4app-entity/models/attributes.AttributeDictionary~_addAttribute
@function
@param {!module:back4app-entity/models/attributes.AttributeDictionary}
attributeDictionary It is the attribute dictionary to which the attribute
will be added.
@param {!Object} attribute This is the attribute to be added. It can be
passed as an Object, as specified in
{@link module:back4app-entity/models/attributes.Attribute}.
@param {!string} [attribute.name] It is the name of the attribute. It is
optional if it is passed as an argument in the function.
@param {!string} [attribute.type='Object'] It is the type of the attribute.
It is optional and if not passed it will assume 'Object' as the default
value.
@param {!string} [attribute.multiplicity='1'] It is the multiplicity of the
attribute. It is optional and if not passed it will assume '1' as the default
value.
@param {?(boolean|number|string|Object|function)} [attribute.default] It is
the default expression of the attribute.
@param {?string} [name] This is the name of the attribute.
@private
@example
var attributeDictionary = new AttributeDictionary();
_addAttribute(attributeDictionary, {}, 'attribute'); | [
"Adds",
"a",
"new",
"attribute",
"to",
"the",
"dictionary",
"."
] | 16a15284d2e119508fcb4e0c88f647ffb285d2e9 | https://github.com/back4app/back4app-entity/blob/16a15284d2e119508fcb4e0c88f647ffb285d2e9/src/back/models/attributes/AttributeDictionary.js#L113-L167 | train |
back4app/back4app-entity | src/back/models/attributes/AttributeDictionary.js | concat | function concat(attributeDictionary, attribute) {
expect(arguments).to.have.length(
2,
'Invalid arguments length when concatenating an AttributeDictionary (it ' +
'has to be passed 2 arguments)'
);
expect(attributeDictionary).to.be.instanceof(
AttributeDictionary,
'Invalid argument "attributeDictionary" when concatenating an ' +
'AttributeDictionary (it has to be an AttributeDictionary)'
);
expect(attribute).to.be.instanceof(
Attribute,
'Invalid argument "attribute" when concatenating an AttributeDictionary ' +
'(it has to be an Attribute)'
);
var currentAttributes = [];
for (var currentAttribute in attributeDictionary) {
currentAttributes.push(attributeDictionary[currentAttribute]);
}
currentAttributes.push(attribute);
return new AttributeDictionary(currentAttributes);
} | javascript | function concat(attributeDictionary, attribute) {
expect(arguments).to.have.length(
2,
'Invalid arguments length when concatenating an AttributeDictionary (it ' +
'has to be passed 2 arguments)'
);
expect(attributeDictionary).to.be.instanceof(
AttributeDictionary,
'Invalid argument "attributeDictionary" when concatenating an ' +
'AttributeDictionary (it has to be an AttributeDictionary)'
);
expect(attribute).to.be.instanceof(
Attribute,
'Invalid argument "attribute" when concatenating an AttributeDictionary ' +
'(it has to be an Attribute)'
);
var currentAttributes = [];
for (var currentAttribute in attributeDictionary) {
currentAttributes.push(attributeDictionary[currentAttribute]);
}
currentAttributes.push(attribute);
return new AttributeDictionary(currentAttributes);
} | [
"function",
"concat",
"(",
"attributeDictionary",
",",
"attribute",
")",
"{",
"expect",
"(",
"arguments",
")",
".",
"to",
".",
"have",
".",
"length",
"(",
"2",
",",
"'Invalid arguments length when concatenating an AttributeDictionary (it '",
"+",
"'has to be passed 2 arguments)'",
")",
";",
"expect",
"(",
"attributeDictionary",
")",
".",
"to",
".",
"be",
".",
"instanceof",
"(",
"AttributeDictionary",
",",
"'Invalid argument \"attributeDictionary\" when concatenating an '",
"+",
"'AttributeDictionary (it has to be an AttributeDictionary)'",
")",
";",
"expect",
"(",
"attribute",
")",
".",
"to",
".",
"be",
".",
"instanceof",
"(",
"Attribute",
",",
"'Invalid argument \"attribute\" when concatenating an AttributeDictionary '",
"+",
"'(it has to be an Attribute)'",
")",
";",
"var",
"currentAttributes",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"currentAttribute",
"in",
"attributeDictionary",
")",
"{",
"currentAttributes",
".",
"push",
"(",
"attributeDictionary",
"[",
"currentAttribute",
"]",
")",
";",
"}",
"currentAttributes",
".",
"push",
"(",
"attribute",
")",
";",
"return",
"new",
"AttributeDictionary",
"(",
"currentAttributes",
")",
";",
"}"
] | Concatenates an AttributeDictionary instance with an Attribute instance and
returns a new AttributeDictionary.
@name module:back4app-entity/models/attributes.AttributeDictionary.concat
@function
@param {!module:back4app-entity/models/attributes.AttributeDictionary}
attributeDictionary The AttributeDictionary to be concatenated.
@param {!module:back4app-entity/models/attributes.Attribute} attribute
The Attribute to be concatenated.
@returns {module:back4app-entity/models/attributes.AttributeDictionary} The
new concatenated AttributeDictionary.
@example
var concatenatedAttributeDictionary = AttributeDictionary.concat(
attributeDictionary,
attribute
); | [
"Concatenates",
"an",
"AttributeDictionary",
"instance",
"with",
"an",
"Attribute",
"instance",
"and",
"returns",
"a",
"new",
"AttributeDictionary",
"."
] | 16a15284d2e119508fcb4e0c88f647ffb285d2e9 | https://github.com/back4app/back4app-entity/blob/16a15284d2e119508fcb4e0c88f647ffb285d2e9/src/back/models/attributes/AttributeDictionary.js#L186-L214 | train |
feedhenry/fh-forms | lib/impl/dataTargets.js | get | function get(connections, params, cb) {
var failed = validate(params).has(CONSTANTS.DATA_TARGET_ID);
if (failed) {
return cb(buildErrorResponse({error: new Error("An ID Parameter Is Required To Get A Data Target"), code: ERROR_CODES.FH_FORMS_INVALID_PARAMETERS}));
}
if (!misc.checkId(params._id)) {
return cb(buildErrorResponse({error: new Error("Invalid ID Paramter"), code: ERROR_CODES.FH_FORMS_INVALID_PARAMETERS}));
}
async.waterfall([
function findDataTargets(cb) {
var query = {
};
//Searching By ID.
query[CONSTANTS.DATA_TARGET_ID] = params._id;
lookUpDataTargets(connections, {
query: query,
lean: true
}, function(err, dataTargets) {
if (err) {
return cb(buildErrorResponse({
error: err,
userDetail: "Unexpected Error When Searching For A Data Target",
code: ERROR_CODES.FH_FORMS_UNEXPECTED_ERROR
}));
}
//Checking if the Data Target exists. Should be only one
if (dataTargets.length !== 1) {
return cb(buildErrorResponse({
error: new Error("Data Target Not Found"),
systemDetail: "Requested ID: " + params[CONSTANTS.DATA_TARGET_ID],
code: ERROR_CODES.FH_FORMS_NOT_FOUND
}));
}
return cb(undefined, dataTargets[0]);
});
},
function checkForms(dataTargetJSON, cb) {
//Checking For Any Forms Associated With The Data Target
checkFormsUsingDataTarget(connections, dataTargetJSON, cb);
}
], cb);
} | javascript | function get(connections, params, cb) {
var failed = validate(params).has(CONSTANTS.DATA_TARGET_ID);
if (failed) {
return cb(buildErrorResponse({error: new Error("An ID Parameter Is Required To Get A Data Target"), code: ERROR_CODES.FH_FORMS_INVALID_PARAMETERS}));
}
if (!misc.checkId(params._id)) {
return cb(buildErrorResponse({error: new Error("Invalid ID Paramter"), code: ERROR_CODES.FH_FORMS_INVALID_PARAMETERS}));
}
async.waterfall([
function findDataTargets(cb) {
var query = {
};
//Searching By ID.
query[CONSTANTS.DATA_TARGET_ID] = params._id;
lookUpDataTargets(connections, {
query: query,
lean: true
}, function(err, dataTargets) {
if (err) {
return cb(buildErrorResponse({
error: err,
userDetail: "Unexpected Error When Searching For A Data Target",
code: ERROR_CODES.FH_FORMS_UNEXPECTED_ERROR
}));
}
//Checking if the Data Target exists. Should be only one
if (dataTargets.length !== 1) {
return cb(buildErrorResponse({
error: new Error("Data Target Not Found"),
systemDetail: "Requested ID: " + params[CONSTANTS.DATA_TARGET_ID],
code: ERROR_CODES.FH_FORMS_NOT_FOUND
}));
}
return cb(undefined, dataTargets[0]);
});
},
function checkForms(dataTargetJSON, cb) {
//Checking For Any Forms Associated With The Data Target
checkFormsUsingDataTarget(connections, dataTargetJSON, cb);
}
], cb);
} | [
"function",
"get",
"(",
"connections",
",",
"params",
",",
"cb",
")",
"{",
"var",
"failed",
"=",
"validate",
"(",
"params",
")",
".",
"has",
"(",
"CONSTANTS",
".",
"DATA_TARGET_ID",
")",
";",
"if",
"(",
"failed",
")",
"{",
"return",
"cb",
"(",
"buildErrorResponse",
"(",
"{",
"error",
":",
"new",
"Error",
"(",
"\"An ID Parameter Is Required To Get A Data Target\"",
")",
",",
"code",
":",
"ERROR_CODES",
".",
"FH_FORMS_INVALID_PARAMETERS",
"}",
")",
")",
";",
"}",
"if",
"(",
"!",
"misc",
".",
"checkId",
"(",
"params",
".",
"_id",
")",
")",
"{",
"return",
"cb",
"(",
"buildErrorResponse",
"(",
"{",
"error",
":",
"new",
"Error",
"(",
"\"Invalid ID Paramter\"",
")",
",",
"code",
":",
"ERROR_CODES",
".",
"FH_FORMS_INVALID_PARAMETERS",
"}",
")",
")",
";",
"}",
"async",
".",
"waterfall",
"(",
"[",
"function",
"findDataTargets",
"(",
"cb",
")",
"{",
"var",
"query",
"=",
"{",
"}",
";",
"query",
"[",
"CONSTANTS",
".",
"DATA_TARGET_ID",
"]",
"=",
"params",
".",
"_id",
";",
"lookUpDataTargets",
"(",
"connections",
",",
"{",
"query",
":",
"query",
",",
"lean",
":",
"true",
"}",
",",
"function",
"(",
"err",
",",
"dataTargets",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"cb",
"(",
"buildErrorResponse",
"(",
"{",
"error",
":",
"err",
",",
"userDetail",
":",
"\"Unexpected Error When Searching For A Data Target\"",
",",
"code",
":",
"ERROR_CODES",
".",
"FH_FORMS_UNEXPECTED_ERROR",
"}",
")",
")",
";",
"}",
"if",
"(",
"dataTargets",
".",
"length",
"!==",
"1",
")",
"{",
"return",
"cb",
"(",
"buildErrorResponse",
"(",
"{",
"error",
":",
"new",
"Error",
"(",
"\"Data Target Not Found\"",
")",
",",
"systemDetail",
":",
"\"Requested ID: \"",
"+",
"params",
"[",
"CONSTANTS",
".",
"DATA_TARGET_ID",
"]",
",",
"code",
":",
"ERROR_CODES",
".",
"FH_FORMS_NOT_FOUND",
"}",
")",
")",
";",
"}",
"return",
"cb",
"(",
"undefined",
",",
"dataTargets",
"[",
"0",
"]",
")",
";",
"}",
")",
";",
"}",
",",
"function",
"checkForms",
"(",
"dataTargetJSON",
",",
"cb",
")",
"{",
"checkFormsUsingDataTarget",
"(",
"connections",
",",
"dataTargetJSON",
",",
"cb",
")",
";",
"}",
"]",
",",
"cb",
")",
";",
"}"
] | Get A Specific Data Target Definition
@param connections
@param params
@param cb | [
"Get",
"A",
"Specific",
"Data",
"Target",
"Definition"
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/dataTargets.js#L77-L126 | train |
feedhenry/fh-forms | lib/impl/dataTargets.js | remove | function remove(connections, params, cb) {
var failed = validate(params).has(CONSTANTS.DATA_TARGET_ID);
if (failed) {
return cb(buildErrorResponse({error: new Error("An ID Parameter Is Required To Remove A Data Target"), code: ERROR_CODES.FH_FORMS_INVALID_PARAMETERS}));
}
if (!misc.checkId(params._id)) {
return cb(buildErrorResponse({error: new Error("Invalid ID Paramter"), code: ERROR_CODES.FH_FORMS_INVALID_PARAMETERS}));
}
async.waterfall([
function findAssociatedForms(cb) {
checkFormsUsingDataTarget(connections, params, cb);
},
function verifyNoFormsAssociated(updatedDataTarget, cb) {
//If there is more than one form using this data target, then do not delete it.
if (updatedDataTarget.forms.length > 0) {
return cb(buildErrorResponse({
error: new Error("Forms Are Associated With This Data Target. Please Disassociate Forms From This Data Target Before Deleting."),
code: ERROR_CODES.FH_FORMS_UNEXPECTED_ERROR
}));
}
return cb(undefined, updatedDataTarget);
},
function processResponse(updatedDataTarget, cb) {
//Removing The Data Target
var DataTarget = models.get(connections.mongooseConnection, models.MODELNAMES.DATA_TARGET);
DataTarget.remove({_id: updatedDataTarget._id}, function(err) {
if (err) {
return cb(buildErrorResponse({
error: err,
userDetail: "Unexpected Error When Removing A Data Target",
code: ERROR_CODES.FH_FORMS_UNEXPECTED_ERROR
}));
}
//Data Target Removed Successfully
return cb();
});
}
], cb);
} | javascript | function remove(connections, params, cb) {
var failed = validate(params).has(CONSTANTS.DATA_TARGET_ID);
if (failed) {
return cb(buildErrorResponse({error: new Error("An ID Parameter Is Required To Remove A Data Target"), code: ERROR_CODES.FH_FORMS_INVALID_PARAMETERS}));
}
if (!misc.checkId(params._id)) {
return cb(buildErrorResponse({error: new Error("Invalid ID Paramter"), code: ERROR_CODES.FH_FORMS_INVALID_PARAMETERS}));
}
async.waterfall([
function findAssociatedForms(cb) {
checkFormsUsingDataTarget(connections, params, cb);
},
function verifyNoFormsAssociated(updatedDataTarget, cb) {
//If there is more than one form using this data target, then do not delete it.
if (updatedDataTarget.forms.length > 0) {
return cb(buildErrorResponse({
error: new Error("Forms Are Associated With This Data Target. Please Disassociate Forms From This Data Target Before Deleting."),
code: ERROR_CODES.FH_FORMS_UNEXPECTED_ERROR
}));
}
return cb(undefined, updatedDataTarget);
},
function processResponse(updatedDataTarget, cb) {
//Removing The Data Target
var DataTarget = models.get(connections.mongooseConnection, models.MODELNAMES.DATA_TARGET);
DataTarget.remove({_id: updatedDataTarget._id}, function(err) {
if (err) {
return cb(buildErrorResponse({
error: err,
userDetail: "Unexpected Error When Removing A Data Target",
code: ERROR_CODES.FH_FORMS_UNEXPECTED_ERROR
}));
}
//Data Target Removed Successfully
return cb();
});
}
], cb);
} | [
"function",
"remove",
"(",
"connections",
",",
"params",
",",
"cb",
")",
"{",
"var",
"failed",
"=",
"validate",
"(",
"params",
")",
".",
"has",
"(",
"CONSTANTS",
".",
"DATA_TARGET_ID",
")",
";",
"if",
"(",
"failed",
")",
"{",
"return",
"cb",
"(",
"buildErrorResponse",
"(",
"{",
"error",
":",
"new",
"Error",
"(",
"\"An ID Parameter Is Required To Remove A Data Target\"",
")",
",",
"code",
":",
"ERROR_CODES",
".",
"FH_FORMS_INVALID_PARAMETERS",
"}",
")",
")",
";",
"}",
"if",
"(",
"!",
"misc",
".",
"checkId",
"(",
"params",
".",
"_id",
")",
")",
"{",
"return",
"cb",
"(",
"buildErrorResponse",
"(",
"{",
"error",
":",
"new",
"Error",
"(",
"\"Invalid ID Paramter\"",
")",
",",
"code",
":",
"ERROR_CODES",
".",
"FH_FORMS_INVALID_PARAMETERS",
"}",
")",
")",
";",
"}",
"async",
".",
"waterfall",
"(",
"[",
"function",
"findAssociatedForms",
"(",
"cb",
")",
"{",
"checkFormsUsingDataTarget",
"(",
"connections",
",",
"params",
",",
"cb",
")",
";",
"}",
",",
"function",
"verifyNoFormsAssociated",
"(",
"updatedDataTarget",
",",
"cb",
")",
"{",
"if",
"(",
"updatedDataTarget",
".",
"forms",
".",
"length",
">",
"0",
")",
"{",
"return",
"cb",
"(",
"buildErrorResponse",
"(",
"{",
"error",
":",
"new",
"Error",
"(",
"\"Forms Are Associated With This Data Target. Please Disassociate Forms From This Data Target Before Deleting.\"",
")",
",",
"code",
":",
"ERROR_CODES",
".",
"FH_FORMS_UNEXPECTED_ERROR",
"}",
")",
")",
";",
"}",
"return",
"cb",
"(",
"undefined",
",",
"updatedDataTarget",
")",
";",
"}",
",",
"function",
"processResponse",
"(",
"updatedDataTarget",
",",
"cb",
")",
"{",
"var",
"DataTarget",
"=",
"models",
".",
"get",
"(",
"connections",
".",
"mongooseConnection",
",",
"models",
".",
"MODELNAMES",
".",
"DATA_TARGET",
")",
";",
"DataTarget",
".",
"remove",
"(",
"{",
"_id",
":",
"updatedDataTarget",
".",
"_id",
"}",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"cb",
"(",
"buildErrorResponse",
"(",
"{",
"error",
":",
"err",
",",
"userDetail",
":",
"\"Unexpected Error When Removing A Data Target\"",
",",
"code",
":",
"ERROR_CODES",
".",
"FH_FORMS_UNEXPECTED_ERROR",
"}",
")",
")",
";",
"}",
"return",
"cb",
"(",
")",
";",
"}",
")",
";",
"}",
"]",
",",
"cb",
")",
";",
"}"
] | Removing A Data Target
@param connections
@param params
@param cb | [
"Removing",
"A",
"Data",
"Target"
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/dataTargets.js#L135-L181 | train |
feedhenry/fh-forms | lib/impl/dataTargets.js | list | function list(connections, params, cb) {
async.waterfall([
function findDataTargets(cb) {
lookUpDataTargets(connections, {
query: {},
lean: true
}, function(err, dataTargets) {
if (err) {
return cb(buildErrorResponse({
error: err,
userDetail: "Unexpected Error When Searching For A Data Target",
code: ERROR_CODES.FH_FORMS_UNEXPECTED_ERROR
}));
}
return cb(undefined, dataTargets);
});
}
], cb);
} | javascript | function list(connections, params, cb) {
async.waterfall([
function findDataTargets(cb) {
lookUpDataTargets(connections, {
query: {},
lean: true
}, function(err, dataTargets) {
if (err) {
return cb(buildErrorResponse({
error: err,
userDetail: "Unexpected Error When Searching For A Data Target",
code: ERROR_CODES.FH_FORMS_UNEXPECTED_ERROR
}));
}
return cb(undefined, dataTargets);
});
}
], cb);
} | [
"function",
"list",
"(",
"connections",
",",
"params",
",",
"cb",
")",
"{",
"async",
".",
"waterfall",
"(",
"[",
"function",
"findDataTargets",
"(",
"cb",
")",
"{",
"lookUpDataTargets",
"(",
"connections",
",",
"{",
"query",
":",
"{",
"}",
",",
"lean",
":",
"true",
"}",
",",
"function",
"(",
"err",
",",
"dataTargets",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"cb",
"(",
"buildErrorResponse",
"(",
"{",
"error",
":",
"err",
",",
"userDetail",
":",
"\"Unexpected Error When Searching For A Data Target\"",
",",
"code",
":",
"ERROR_CODES",
".",
"FH_FORMS_UNEXPECTED_ERROR",
"}",
")",
")",
";",
"}",
"return",
"cb",
"(",
"undefined",
",",
"dataTargets",
")",
";",
"}",
")",
";",
"}",
"]",
",",
"cb",
")",
";",
"}"
] | Listing All Data Targets. In The Environment, this will include the current cache data.
@param connections
@param params
@param cb | [
"Listing",
"All",
"Data",
"Targets",
".",
"In",
"The",
"Environment",
"this",
"will",
"include",
"the",
"current",
"cache",
"data",
"."
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/dataTargets.js#L189-L208 | train |
feedhenry/fh-forms | lib/impl/dataTargets.js | create | function create(connections, dataTarget, cb) {
async.waterfall([
function validateParams(cb) {
validate(dataTarget).hasno(CONSTANTS.DATA_TARGET_ID, function(err) {
if (err) {
return cb(buildErrorResponse({error: new Error("Data Target ID Should Not Be Included When Creating A Data Target"), code: ERROR_CODES.FH_FORMS_INVALID_PARAMETERS}));
}
});
cb(undefined, dataTarget);
},
function createDataTarget(dataTargetJSON, cb) {
dataTargetJSON = sanitiseJSON(dataTargetJSON);
var DataTarget = models.get(connections.mongooseConnection, models.MODELNAMES.DATA_TARGET);
var newDataTarget = new DataTarget(dataTargetJSON);
newDataTarget.save(function(err) {
if (err) {
return cb(buildErrorResponse({
error: err,
userDetail: "Invalid Data Target Creation Data.",
systemDetail: err.errors,
code: ERROR_CODES.FH_FORMS_INVALID_PARAMETERS
}));
}
return cb(undefined, newDataTarget.toJSON());
});
}
], cb);
} | javascript | function create(connections, dataTarget, cb) {
async.waterfall([
function validateParams(cb) {
validate(dataTarget).hasno(CONSTANTS.DATA_TARGET_ID, function(err) {
if (err) {
return cb(buildErrorResponse({error: new Error("Data Target ID Should Not Be Included When Creating A Data Target"), code: ERROR_CODES.FH_FORMS_INVALID_PARAMETERS}));
}
});
cb(undefined, dataTarget);
},
function createDataTarget(dataTargetJSON, cb) {
dataTargetJSON = sanitiseJSON(dataTargetJSON);
var DataTarget = models.get(connections.mongooseConnection, models.MODELNAMES.DATA_TARGET);
var newDataTarget = new DataTarget(dataTargetJSON);
newDataTarget.save(function(err) {
if (err) {
return cb(buildErrorResponse({
error: err,
userDetail: "Invalid Data Target Creation Data.",
systemDetail: err.errors,
code: ERROR_CODES.FH_FORMS_INVALID_PARAMETERS
}));
}
return cb(undefined, newDataTarget.toJSON());
});
}
], cb);
} | [
"function",
"create",
"(",
"connections",
",",
"dataTarget",
",",
"cb",
")",
"{",
"async",
".",
"waterfall",
"(",
"[",
"function",
"validateParams",
"(",
"cb",
")",
"{",
"validate",
"(",
"dataTarget",
")",
".",
"hasno",
"(",
"CONSTANTS",
".",
"DATA_TARGET_ID",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"cb",
"(",
"buildErrorResponse",
"(",
"{",
"error",
":",
"new",
"Error",
"(",
"\"Data Target ID Should Not Be Included When Creating A Data Target\"",
")",
",",
"code",
":",
"ERROR_CODES",
".",
"FH_FORMS_INVALID_PARAMETERS",
"}",
")",
")",
";",
"}",
"}",
")",
";",
"cb",
"(",
"undefined",
",",
"dataTarget",
")",
";",
"}",
",",
"function",
"createDataTarget",
"(",
"dataTargetJSON",
",",
"cb",
")",
"{",
"dataTargetJSON",
"=",
"sanitiseJSON",
"(",
"dataTargetJSON",
")",
";",
"var",
"DataTarget",
"=",
"models",
".",
"get",
"(",
"connections",
".",
"mongooseConnection",
",",
"models",
".",
"MODELNAMES",
".",
"DATA_TARGET",
")",
";",
"var",
"newDataTarget",
"=",
"new",
"DataTarget",
"(",
"dataTargetJSON",
")",
";",
"newDataTarget",
".",
"save",
"(",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"cb",
"(",
"buildErrorResponse",
"(",
"{",
"error",
":",
"err",
",",
"userDetail",
":",
"\"Invalid Data Target Creation Data.\"",
",",
"systemDetail",
":",
"err",
".",
"errors",
",",
"code",
":",
"ERROR_CODES",
".",
"FH_FORMS_INVALID_PARAMETERS",
"}",
")",
")",
";",
"}",
"return",
"cb",
"(",
"undefined",
",",
"newDataTarget",
".",
"toJSON",
"(",
")",
")",
";",
"}",
")",
";",
"}",
"]",
",",
"cb",
")",
";",
"}"
] | Creating A New Data Target
@param connections
@param dataTarget
@param cb | [
"Creating",
"A",
"New",
"Data",
"Target"
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/dataTargets.js#L296-L328 | train |
feedhenry/fh-forms | lib/impl/dataTargets.js | validateDataTarget | function validateDataTarget(connections, dataTarget, cb) {
var DataTarget = models.get(connections.mongooseConnection, models.MODELNAMES.DATA_TARGET);
var testDataTarget = new DataTarget(dataTarget);
//Validating Without Saving
testDataTarget.validate(function(err) {
if (err) {
return cb(buildErrorResponse({
error: err,
userDetail: "Invalid Data Target Creation Data.",
systemDetail: err.errors,
code: ERROR_CODES.FH_FORMS_INVALID_PARAMETERS
}));
}
return cb(undefined, dataTarget);
});
} | javascript | function validateDataTarget(connections, dataTarget, cb) {
var DataTarget = models.get(connections.mongooseConnection, models.MODELNAMES.DATA_TARGET);
var testDataTarget = new DataTarget(dataTarget);
//Validating Without Saving
testDataTarget.validate(function(err) {
if (err) {
return cb(buildErrorResponse({
error: err,
userDetail: "Invalid Data Target Creation Data.",
systemDetail: err.errors,
code: ERROR_CODES.FH_FORMS_INVALID_PARAMETERS
}));
}
return cb(undefined, dataTarget);
});
} | [
"function",
"validateDataTarget",
"(",
"connections",
",",
"dataTarget",
",",
"cb",
")",
"{",
"var",
"DataTarget",
"=",
"models",
".",
"get",
"(",
"connections",
".",
"mongooseConnection",
",",
"models",
".",
"MODELNAMES",
".",
"DATA_TARGET",
")",
";",
"var",
"testDataTarget",
"=",
"new",
"DataTarget",
"(",
"dataTarget",
")",
";",
"testDataTarget",
".",
"validate",
"(",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"cb",
"(",
"buildErrorResponse",
"(",
"{",
"error",
":",
"err",
",",
"userDetail",
":",
"\"Invalid Data Target Creation Data.\"",
",",
"systemDetail",
":",
"err",
".",
"errors",
",",
"code",
":",
"ERROR_CODES",
".",
"FH_FORMS_INVALID_PARAMETERS",
"}",
")",
")",
";",
"}",
"return",
"cb",
"(",
"undefined",
",",
"dataTarget",
")",
";",
"}",
")",
";",
"}"
] | Validating A Data Target Object.
@param connections
@param dataTarget
@param cb | [
"Validating",
"A",
"Data",
"Target",
"Object",
"."
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/dataTargets.js#L336-L352 | train |
makeup-js/makeup-screenreader-trap | src/util.js | getSiblings | function getSiblings(el) {
const allSiblings = getPreviousSiblings(el).concat(getNextSiblings(el));
return allSiblings.filter(filterSibling);
} | javascript | function getSiblings(el) {
const allSiblings = getPreviousSiblings(el).concat(getNextSiblings(el));
return allSiblings.filter(filterSibling);
} | [
"function",
"getSiblings",
"(",
"el",
")",
"{",
"const",
"allSiblings",
"=",
"getPreviousSiblings",
"(",
"el",
")",
".",
"concat",
"(",
"getNextSiblings",
"(",
"el",
")",
")",
";",
"return",
"allSiblings",
".",
"filter",
"(",
"filterSibling",
")",
";",
"}"
] | returns all sibling element nodes of given element | [
"returns",
"all",
"sibling",
"element",
"nodes",
"of",
"given",
"element"
] | 4ce73c000f66194028d9992ee000c7c50b242148 | https://github.com/makeup-js/makeup-screenreader-trap/blob/4ce73c000f66194028d9992ee000c7c50b242148/src/util.js#L41-L45 | train |
feedhenry/fh-forms | lib/impl/updateForm.js | validatefieldCodes | function validatefieldCodes() {
//Flag for finding a duplicate field code
var duplicateFieldCode = false;
var invalidFieldCode = false;
var fieldCodes = {};
formData.pages = _.map(formData.pages, function(page) {
page.fields = _.map(page.fields, function(field) {
var fieldCode = field.fieldCode;
//If not set, then just return the field.
if (fieldCode === null || typeof(fieldCode) === "undefined") {
return field;
}
//Checking for duplicate field code. It must be a string.
if (typeof(fieldCode) === "string") {
//If the length of the code is 0, then don't save it.
if (fieldCode.length === 0) {
delete field.fieldCode;
} else {
//Checking for duplicate field code
if (fieldCodes[fieldCode]) {
duplicateFieldCode = true; //Flagging the field as duplicate
} else {
fieldCodes[fieldCode] = true;
}
}
} else {
invalidFieldCode = true; //Field codes must be a string.
}
return field;
});
return page;
});
if (duplicateFieldCode) {
return new Error("Duplicate Field Codes Detected. Field Codes Must Be Unique In A Form.");
}
if (invalidFieldCode) {
return new Error("Invalid Field Code. Field Codes Must Be A String.");
}
//All valid. can proceed to saving the form.
return undefined;
} | javascript | function validatefieldCodes() {
//Flag for finding a duplicate field code
var duplicateFieldCode = false;
var invalidFieldCode = false;
var fieldCodes = {};
formData.pages = _.map(formData.pages, function(page) {
page.fields = _.map(page.fields, function(field) {
var fieldCode = field.fieldCode;
//If not set, then just return the field.
if (fieldCode === null || typeof(fieldCode) === "undefined") {
return field;
}
//Checking for duplicate field code. It must be a string.
if (typeof(fieldCode) === "string") {
//If the length of the code is 0, then don't save it.
if (fieldCode.length === 0) {
delete field.fieldCode;
} else {
//Checking for duplicate field code
if (fieldCodes[fieldCode]) {
duplicateFieldCode = true; //Flagging the field as duplicate
} else {
fieldCodes[fieldCode] = true;
}
}
} else {
invalidFieldCode = true; //Field codes must be a string.
}
return field;
});
return page;
});
if (duplicateFieldCode) {
return new Error("Duplicate Field Codes Detected. Field Codes Must Be Unique In A Form.");
}
if (invalidFieldCode) {
return new Error("Invalid Field Code. Field Codes Must Be A String.");
}
//All valid. can proceed to saving the form.
return undefined;
} | [
"function",
"validatefieldCodes",
"(",
")",
"{",
"var",
"duplicateFieldCode",
"=",
"false",
";",
"var",
"invalidFieldCode",
"=",
"false",
";",
"var",
"fieldCodes",
"=",
"{",
"}",
";",
"formData",
".",
"pages",
"=",
"_",
".",
"map",
"(",
"formData",
".",
"pages",
",",
"function",
"(",
"page",
")",
"{",
"page",
".",
"fields",
"=",
"_",
".",
"map",
"(",
"page",
".",
"fields",
",",
"function",
"(",
"field",
")",
"{",
"var",
"fieldCode",
"=",
"field",
".",
"fieldCode",
";",
"if",
"(",
"fieldCode",
"===",
"null",
"||",
"typeof",
"(",
"fieldCode",
")",
"===",
"\"undefined\"",
")",
"{",
"return",
"field",
";",
"}",
"if",
"(",
"typeof",
"(",
"fieldCode",
")",
"===",
"\"string\"",
")",
"{",
"if",
"(",
"fieldCode",
".",
"length",
"===",
"0",
")",
"{",
"delete",
"field",
".",
"fieldCode",
";",
"}",
"else",
"{",
"if",
"(",
"fieldCodes",
"[",
"fieldCode",
"]",
")",
"{",
"duplicateFieldCode",
"=",
"true",
";",
"}",
"else",
"{",
"fieldCodes",
"[",
"fieldCode",
"]",
"=",
"true",
";",
"}",
"}",
"}",
"else",
"{",
"invalidFieldCode",
"=",
"true",
";",
"}",
"return",
"field",
";",
"}",
")",
";",
"return",
"page",
";",
"}",
")",
";",
"if",
"(",
"duplicateFieldCode",
")",
"{",
"return",
"new",
"Error",
"(",
"\"Duplicate Field Codes Detected. Field Codes Must Be Unique In A Form.\"",
")",
";",
"}",
"if",
"(",
"invalidFieldCode",
")",
"{",
"return",
"new",
"Error",
"(",
"\"Invalid Field Code. Field Codes Must Be A String.\"",
")",
";",
"}",
"return",
"undefined",
";",
"}"
] | User Field codes must be unique within a form.
All field codes must have a length > 0, otherwise don't save the form.
No asynchronous functionality in this function.
@param cb | [
"User",
"Field",
"codes",
"must",
"be",
"unique",
"within",
"a",
"form",
"."
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/updateForm.js#L82-L130 | train |
feedhenry/fh-forms | lib/impl/updateForm.js | validateDuplicateName | function validateDuplicateName(cb) {
var formId = formData._id;
var formName = formData.name;
if (!formName) {
return cb(new Error("No form name passed"));
}
var query = {};
//If there is a form id, then the query to the form model must exclude the current form id that is being updated.
if (formId) {
query.name = formName;
//Excluding the formId that is being updated.
query["_id"] = {"$nin": [formId]};
} else { //Just checking that the form name exists as a form is being created
query.name = formName;
}
formModel.count(query, function(err, count) {
if (err) {
return cb(err);
}
//If the number of found forms is > 0, then there is another form with the same name. Do not save the form.
if (count > 0) {
return cb(new Error("Form with name " + formName + " already exists found."));
} else {//No duplicates, can proceed with saving the form.
return cb();
}
});
} | javascript | function validateDuplicateName(cb) {
var formId = formData._id;
var formName = formData.name;
if (!formName) {
return cb(new Error("No form name passed"));
}
var query = {};
//If there is a form id, then the query to the form model must exclude the current form id that is being updated.
if (formId) {
query.name = formName;
//Excluding the formId that is being updated.
query["_id"] = {"$nin": [formId]};
} else { //Just checking that the form name exists as a form is being created
query.name = formName;
}
formModel.count(query, function(err, count) {
if (err) {
return cb(err);
}
//If the number of found forms is > 0, then there is another form with the same name. Do not save the form.
if (count > 0) {
return cb(new Error("Form with name " + formName + " already exists found."));
} else {//No duplicates, can proceed with saving the form.
return cb();
}
});
} | [
"function",
"validateDuplicateName",
"(",
"cb",
")",
"{",
"var",
"formId",
"=",
"formData",
".",
"_id",
";",
"var",
"formName",
"=",
"formData",
".",
"name",
";",
"if",
"(",
"!",
"formName",
")",
"{",
"return",
"cb",
"(",
"new",
"Error",
"(",
"\"No form name passed\"",
")",
")",
";",
"}",
"var",
"query",
"=",
"{",
"}",
";",
"if",
"(",
"formId",
")",
"{",
"query",
".",
"name",
"=",
"formName",
";",
"query",
"[",
"\"_id\"",
"]",
"=",
"{",
"\"$nin\"",
":",
"[",
"formId",
"]",
"}",
";",
"}",
"else",
"{",
"query",
".",
"name",
"=",
"formName",
";",
"}",
"formModel",
".",
"count",
"(",
"query",
",",
"function",
"(",
"err",
",",
"count",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"cb",
"(",
"err",
")",
";",
"}",
"if",
"(",
"count",
">",
"0",
")",
"{",
"return",
"cb",
"(",
"new",
"Error",
"(",
"\"Form with name \"",
"+",
"formName",
"+",
"\" already exists found.\"",
")",
")",
";",
"}",
"else",
"{",
"return",
"cb",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
] | Validating form duplicate names. | [
"Validating",
"form",
"duplicate",
"names",
"."
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/updateForm.js#L135-L166 | train |
feedhenry/fh-forms | lib/impl/updateForm.js | getFormDataSources | function getFormDataSources(formJSON) {
var dataSources;
var pages = formJSON.pages || [];
dataSources = _.map(pages, function(page) {
var fields = page.fields || [];
fields = _.map(fields, function(field) {
//If the field is defined as a Data Source field, and it has a data source, then return that data source.
if (field.dataSourceType === models.FORM_CONSTANTS.DATA_SOURCE_TYPE_DATA_SOURCE && field.dataSource) {
return field.dataSource;
} else {
return undefined;
}
});
//Removing any undefined values
return _.compact(fields);
});
//Remove all nested arrays
dataSources = _.flatten(dataSources);
logger.debug("Got Form Data Sources", dataSources);
//Only Want One Of Each Data Source
return _.uniq(dataSources);
} | javascript | function getFormDataSources(formJSON) {
var dataSources;
var pages = formJSON.pages || [];
dataSources = _.map(pages, function(page) {
var fields = page.fields || [];
fields = _.map(fields, function(field) {
//If the field is defined as a Data Source field, and it has a data source, then return that data source.
if (field.dataSourceType === models.FORM_CONSTANTS.DATA_SOURCE_TYPE_DATA_SOURCE && field.dataSource) {
return field.dataSource;
} else {
return undefined;
}
});
//Removing any undefined values
return _.compact(fields);
});
//Remove all nested arrays
dataSources = _.flatten(dataSources);
logger.debug("Got Form Data Sources", dataSources);
//Only Want One Of Each Data Source
return _.uniq(dataSources);
} | [
"function",
"getFormDataSources",
"(",
"formJSON",
")",
"{",
"var",
"dataSources",
";",
"var",
"pages",
"=",
"formJSON",
".",
"pages",
"||",
"[",
"]",
";",
"dataSources",
"=",
"_",
".",
"map",
"(",
"pages",
",",
"function",
"(",
"page",
")",
"{",
"var",
"fields",
"=",
"page",
".",
"fields",
"||",
"[",
"]",
";",
"fields",
"=",
"_",
".",
"map",
"(",
"fields",
",",
"function",
"(",
"field",
")",
"{",
"if",
"(",
"field",
".",
"dataSourceType",
"===",
"models",
".",
"FORM_CONSTANTS",
".",
"DATA_SOURCE_TYPE_DATA_SOURCE",
"&&",
"field",
".",
"dataSource",
")",
"{",
"return",
"field",
".",
"dataSource",
";",
"}",
"else",
"{",
"return",
"undefined",
";",
"}",
"}",
")",
";",
"return",
"_",
".",
"compact",
"(",
"fields",
")",
";",
"}",
")",
";",
"dataSources",
"=",
"_",
".",
"flatten",
"(",
"dataSources",
")",
";",
"logger",
".",
"debug",
"(",
"\"Got Form Data Sources\"",
",",
"dataSources",
")",
";",
"return",
"_",
".",
"uniq",
"(",
"dataSources",
")",
";",
"}"
] | Extracting any data sources that are contained in any field in the forms.
Will only return unique entries
@param formJSON -- JSON Definition Of The Form | [
"Extracting",
"any",
"data",
"sources",
"that",
"are",
"contained",
"in",
"any",
"field",
"in",
"the",
"forms",
".",
"Will",
"only",
"return",
"unique",
"entries"
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/updateForm.js#L173-L199 | train |
feedhenry/fh-forms | lib/impl/updateForm.js | findMatchingDocuments | function findMatchingDocuments(type, documentIDs, modelToSearch, cb) {
var errorTextDataType = type === models.MODELNAMES.DATA_SOURCE ? "Data Sources" : "Data Targets";
//If the form contains no data sources, then no need to verify
if (documentIDs.length === 0) {
return cb(undefined, []);
}
var query = {_id: {
"$in": documentIDs
}};
modelToSearch.find(query).exec(function(err, foundModels) {
if (err) {
return cb(buildErrorResponse({
error: err,
userDetail: "Unexpected Error Finding " + errorTextDataType
}));
}
//There should be the same number of data source documents
if (documentIDs.length !== foundModels.length) {
var missingDocumentId = _.find(documentIDs, function(documentId) {
return !_.findWhere(foundModels, {_id: documentId});
});
//If there is no missing data source, then something is wrong..
if (!missingDocumentId) {
return cb(buildErrorResponse({
error: new Error("Unexpected Error When Finding " + errorTextDataType),
systemDetail: "Expected A Missing " + errorTextDataType + " But Could Not Find It"
}));
}
return cb(buildErrorResponse({
userDetail: "A " + errorTextDataType + " Contained In The Form Could Not Be Found",
systemDetail: "Expected " + errorTextDataType + " With ID " + missingDocumentId + " To Be Found",
code: ERROR_CODES.FH_FORMS_INVALID_PARAMETERS
}));
}
//All documents found -- checking for cache if needed
if (options.expectDataSourceCache && type === models.MODELNAMES.DATA_SOURCE) {
var missingCache = _.find(foundModels, function(dataSource) {
return dataSource.cache.length === 0;
});
if (missingCache) {
return cb(buildErrorResponse({
error: new Error("Expected " + errorTextDataType + " Cached Data To Be Set"),
systemDetail: "Expected Cache For " + errorTextDataType + " ID " + missingCache._id + " To Be Set",
code: ERROR_CODES.FH_FORMS_INVALID_PARAMETERS
}));
}
}
//Checking that only one real time data target is assigned.
if (type === models.MODELNAMES.DATA_TARGET) {
var realTimeDataTargets = _.filter(foundModels, function(foundModel) {
return foundModel.type === models.CONSTANTS.DATA_TARGET_TYPE_REAL_TIME;
});
if (realTimeDataTargets.length > 1) {
return cb(buildErrorResponse({
error: new Error("Only One Real Time Data Target Can Be Assigned To A Form"),
code: ERROR_CODES.FH_FORMS_INVALID_PARAMETERS
}
));
}
}
return cb(undefined, foundModels);
});
} | javascript | function findMatchingDocuments(type, documentIDs, modelToSearch, cb) {
var errorTextDataType = type === models.MODELNAMES.DATA_SOURCE ? "Data Sources" : "Data Targets";
//If the form contains no data sources, then no need to verify
if (documentIDs.length === 0) {
return cb(undefined, []);
}
var query = {_id: {
"$in": documentIDs
}};
modelToSearch.find(query).exec(function(err, foundModels) {
if (err) {
return cb(buildErrorResponse({
error: err,
userDetail: "Unexpected Error Finding " + errorTextDataType
}));
}
//There should be the same number of data source documents
if (documentIDs.length !== foundModels.length) {
var missingDocumentId = _.find(documentIDs, function(documentId) {
return !_.findWhere(foundModels, {_id: documentId});
});
//If there is no missing data source, then something is wrong..
if (!missingDocumentId) {
return cb(buildErrorResponse({
error: new Error("Unexpected Error When Finding " + errorTextDataType),
systemDetail: "Expected A Missing " + errorTextDataType + " But Could Not Find It"
}));
}
return cb(buildErrorResponse({
userDetail: "A " + errorTextDataType + " Contained In The Form Could Not Be Found",
systemDetail: "Expected " + errorTextDataType + " With ID " + missingDocumentId + " To Be Found",
code: ERROR_CODES.FH_FORMS_INVALID_PARAMETERS
}));
}
//All documents found -- checking for cache if needed
if (options.expectDataSourceCache && type === models.MODELNAMES.DATA_SOURCE) {
var missingCache = _.find(foundModels, function(dataSource) {
return dataSource.cache.length === 0;
});
if (missingCache) {
return cb(buildErrorResponse({
error: new Error("Expected " + errorTextDataType + " Cached Data To Be Set"),
systemDetail: "Expected Cache For " + errorTextDataType + " ID " + missingCache._id + " To Be Set",
code: ERROR_CODES.FH_FORMS_INVALID_PARAMETERS
}));
}
}
//Checking that only one real time data target is assigned.
if (type === models.MODELNAMES.DATA_TARGET) {
var realTimeDataTargets = _.filter(foundModels, function(foundModel) {
return foundModel.type === models.CONSTANTS.DATA_TARGET_TYPE_REAL_TIME;
});
if (realTimeDataTargets.length > 1) {
return cb(buildErrorResponse({
error: new Error("Only One Real Time Data Target Can Be Assigned To A Form"),
code: ERROR_CODES.FH_FORMS_INVALID_PARAMETERS
}
));
}
}
return cb(undefined, foundModels);
});
} | [
"function",
"findMatchingDocuments",
"(",
"type",
",",
"documentIDs",
",",
"modelToSearch",
",",
"cb",
")",
"{",
"var",
"errorTextDataType",
"=",
"type",
"===",
"models",
".",
"MODELNAMES",
".",
"DATA_SOURCE",
"?",
"\"Data Sources\"",
":",
"\"Data Targets\"",
";",
"if",
"(",
"documentIDs",
".",
"length",
"===",
"0",
")",
"{",
"return",
"cb",
"(",
"undefined",
",",
"[",
"]",
")",
";",
"}",
"var",
"query",
"=",
"{",
"_id",
":",
"{",
"\"$in\"",
":",
"documentIDs",
"}",
"}",
";",
"modelToSearch",
".",
"find",
"(",
"query",
")",
".",
"exec",
"(",
"function",
"(",
"err",
",",
"foundModels",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"cb",
"(",
"buildErrorResponse",
"(",
"{",
"error",
":",
"err",
",",
"userDetail",
":",
"\"Unexpected Error Finding \"",
"+",
"errorTextDataType",
"}",
")",
")",
";",
"}",
"if",
"(",
"documentIDs",
".",
"length",
"!==",
"foundModels",
".",
"length",
")",
"{",
"var",
"missingDocumentId",
"=",
"_",
".",
"find",
"(",
"documentIDs",
",",
"function",
"(",
"documentId",
")",
"{",
"return",
"!",
"_",
".",
"findWhere",
"(",
"foundModels",
",",
"{",
"_id",
":",
"documentId",
"}",
")",
";",
"}",
")",
";",
"if",
"(",
"!",
"missingDocumentId",
")",
"{",
"return",
"cb",
"(",
"buildErrorResponse",
"(",
"{",
"error",
":",
"new",
"Error",
"(",
"\"Unexpected Error When Finding \"",
"+",
"errorTextDataType",
")",
",",
"systemDetail",
":",
"\"Expected A Missing \"",
"+",
"errorTextDataType",
"+",
"\" But Could Not Find It\"",
"}",
")",
")",
";",
"}",
"return",
"cb",
"(",
"buildErrorResponse",
"(",
"{",
"userDetail",
":",
"\"A \"",
"+",
"errorTextDataType",
"+",
"\" Contained In The Form Could Not Be Found\"",
",",
"systemDetail",
":",
"\"Expected \"",
"+",
"errorTextDataType",
"+",
"\" With ID \"",
"+",
"missingDocumentId",
"+",
"\" To Be Found\"",
",",
"code",
":",
"ERROR_CODES",
".",
"FH_FORMS_INVALID_PARAMETERS",
"}",
")",
")",
";",
"}",
"if",
"(",
"options",
".",
"expectDataSourceCache",
"&&",
"type",
"===",
"models",
".",
"MODELNAMES",
".",
"DATA_SOURCE",
")",
"{",
"var",
"missingCache",
"=",
"_",
".",
"find",
"(",
"foundModels",
",",
"function",
"(",
"dataSource",
")",
"{",
"return",
"dataSource",
".",
"cache",
".",
"length",
"===",
"0",
";",
"}",
")",
";",
"if",
"(",
"missingCache",
")",
"{",
"return",
"cb",
"(",
"buildErrorResponse",
"(",
"{",
"error",
":",
"new",
"Error",
"(",
"\"Expected \"",
"+",
"errorTextDataType",
"+",
"\" Cached Data To Be Set\"",
")",
",",
"systemDetail",
":",
"\"Expected Cache For \"",
"+",
"errorTextDataType",
"+",
"\" ID \"",
"+",
"missingCache",
".",
"_id",
"+",
"\" To Be Set\"",
",",
"code",
":",
"ERROR_CODES",
".",
"FH_FORMS_INVALID_PARAMETERS",
"}",
")",
")",
";",
"}",
"}",
"if",
"(",
"type",
"===",
"models",
".",
"MODELNAMES",
".",
"DATA_TARGET",
")",
"{",
"var",
"realTimeDataTargets",
"=",
"_",
".",
"filter",
"(",
"foundModels",
",",
"function",
"(",
"foundModel",
")",
"{",
"return",
"foundModel",
".",
"type",
"===",
"models",
".",
"CONSTANTS",
".",
"DATA_TARGET_TYPE_REAL_TIME",
";",
"}",
")",
";",
"if",
"(",
"realTimeDataTargets",
".",
"length",
">",
"1",
")",
"{",
"return",
"cb",
"(",
"buildErrorResponse",
"(",
"{",
"error",
":",
"new",
"Error",
"(",
"\"Only One Real Time Data Target Can Be Assigned To A Form\"",
")",
",",
"code",
":",
"ERROR_CODES",
".",
"FH_FORMS_INVALID_PARAMETERS",
"}",
")",
")",
";",
"}",
"}",
"return",
"cb",
"(",
"undefined",
",",
"foundModels",
")",
";",
"}",
")",
";",
"}"
] | Finding Matching Documents
@param type - Data Source or Data Target
@param documentIDs - Array Of Document IDs
@param modelToSearch - Model to search on
@param cb | [
"Finding",
"Matching",
"Documents"
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/updateForm.js#L208-L283 | train |
feedhenry/fh-forms | lib/impl/updateForm.js | verifyDataSources | function verifyDataSources(formDataSourceIds, cb) {
findMatchingDocuments(models.MODELNAMES.DATA_SOURCE, formDataSourceIds, dataSourceModel, cb);
} | javascript | function verifyDataSources(formDataSourceIds, cb) {
findMatchingDocuments(models.MODELNAMES.DATA_SOURCE, formDataSourceIds, dataSourceModel, cb);
} | [
"function",
"verifyDataSources",
"(",
"formDataSourceIds",
",",
"cb",
")",
"{",
"findMatchingDocuments",
"(",
"models",
".",
"MODELNAMES",
".",
"DATA_SOURCE",
",",
"formDataSourceIds",
",",
"dataSourceModel",
",",
"cb",
")",
";",
"}"
] | Function To Verify All Data Sources Attached To A Form.
@param formDataSourceIds -- Array Of Data Source IDs Attached To Verify | [
"Function",
"To",
"Verify",
"All",
"Data",
"Sources",
"Attached",
"To",
"A",
"Form",
"."
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/updateForm.js#L289-L291 | train |
feedhenry/fh-forms | lib/impl/updateForm.js | verifyDataTargets | function verifyDataTargets(dataTargetIds, cb) {
findMatchingDocuments(models.MODELNAMES.DATA_TARGET, dataTargetIds, dataTargetModel, cb);
} | javascript | function verifyDataTargets(dataTargetIds, cb) {
findMatchingDocuments(models.MODELNAMES.DATA_TARGET, dataTargetIds, dataTargetModel, cb);
} | [
"function",
"verifyDataTargets",
"(",
"dataTargetIds",
",",
"cb",
")",
"{",
"findMatchingDocuments",
"(",
"models",
".",
"MODELNAMES",
".",
"DATA_TARGET",
",",
"dataTargetIds",
",",
"dataTargetModel",
",",
"cb",
")",
";",
"}"
] | Verifying All Data Targets Associated With A Form
@param dataTargetIds
@param cb | [
"Verifying",
"All",
"Data",
"Targets",
"Associated",
"With",
"A",
"Form"
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/updateForm.js#L298-L300 | train |
feedhenry/fh-forms | lib/impl/updateForm.js | verifyFormDataSourcesAndTargets | function verifyFormDataSourcesAndTargets(formData, cb) {
var formDataSourceIds = getFormDataSources(formData);
var dataTargets = formData.dataTargets || [];
async.series({
dataSources : function(cb) {
verifyDataSources(formDataSourceIds, cb);
},
dataTargets: function(cb) {
verifyDataTargets(dataTargets, cb);
}
}, cb);
} | javascript | function verifyFormDataSourcesAndTargets(formData, cb) {
var formDataSourceIds = getFormDataSources(formData);
var dataTargets = formData.dataTargets || [];
async.series({
dataSources : function(cb) {
verifyDataSources(formDataSourceIds, cb);
},
dataTargets: function(cb) {
verifyDataTargets(dataTargets, cb);
}
}, cb);
} | [
"function",
"verifyFormDataSourcesAndTargets",
"(",
"formData",
",",
"cb",
")",
"{",
"var",
"formDataSourceIds",
"=",
"getFormDataSources",
"(",
"formData",
")",
";",
"var",
"dataTargets",
"=",
"formData",
".",
"dataTargets",
"||",
"[",
"]",
";",
"async",
".",
"series",
"(",
"{",
"dataSources",
":",
"function",
"(",
"cb",
")",
"{",
"verifyDataSources",
"(",
"formDataSourceIds",
",",
"cb",
")",
";",
"}",
",",
"dataTargets",
":",
"function",
"(",
"cb",
")",
"{",
"verifyDataTargets",
"(",
"dataTargets",
",",
"cb",
")",
";",
"}",
"}",
",",
"cb",
")",
";",
"}"
] | Verifying the presence of all Data Sources and Data Targets associated with the form. | [
"Verifying",
"the",
"presence",
"of",
"all",
"Data",
"Sources",
"and",
"Data",
"Targets",
"associated",
"with",
"the",
"form",
"."
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/updateForm.js#L303-L315 | train |
cloudmine/CloudMineSDK-JavaScript | js/cloudmine.js | WebService | function WebService(options) {
this.options = opts(this, options);
if(!this.options.apiroot) this.options.apiroot = "https://api.cloudmine.io";
var src = this.options.appid;
if (options.savelogin) {
if (!this.options.email) this.options.email = retrieve('email', src);
if (!this.options.username) this.options.username = retrieve('username', src);
if (!this.options.session_token) this.options.session_token = retrieve('session_token', src);
}
this.options.user_token = retrieve('ut', src) || store('ut', this.keygen(), src);
} | javascript | function WebService(options) {
this.options = opts(this, options);
if(!this.options.apiroot) this.options.apiroot = "https://api.cloudmine.io";
var src = this.options.appid;
if (options.savelogin) {
if (!this.options.email) this.options.email = retrieve('email', src);
if (!this.options.username) this.options.username = retrieve('username', src);
if (!this.options.session_token) this.options.session_token = retrieve('session_token', src);
}
this.options.user_token = retrieve('ut', src) || store('ut', this.keygen(), src);
} | [
"function",
"WebService",
"(",
"options",
")",
"{",
"this",
".",
"options",
"=",
"opts",
"(",
"this",
",",
"options",
")",
";",
"if",
"(",
"!",
"this",
".",
"options",
".",
"apiroot",
")",
"this",
".",
"options",
".",
"apiroot",
"=",
"\"https://api.cloudmine.io\"",
";",
"var",
"src",
"=",
"this",
".",
"options",
".",
"appid",
";",
"if",
"(",
"options",
".",
"savelogin",
")",
"{",
"if",
"(",
"!",
"this",
".",
"options",
".",
"email",
")",
"this",
".",
"options",
".",
"email",
"=",
"retrieve",
"(",
"'email'",
",",
"src",
")",
";",
"if",
"(",
"!",
"this",
".",
"options",
".",
"username",
")",
"this",
".",
"options",
".",
"username",
"=",
"retrieve",
"(",
"'username'",
",",
"src",
")",
";",
"if",
"(",
"!",
"this",
".",
"options",
".",
"session_token",
")",
"this",
".",
"options",
".",
"session_token",
"=",
"retrieve",
"(",
"'session_token'",
",",
"src",
")",
";",
"}",
"this",
".",
"options",
".",
"user_token",
"=",
"retrieve",
"(",
"'ut'",
",",
"src",
")",
"||",
"store",
"(",
"'ut'",
",",
"this",
".",
"keygen",
"(",
")",
",",
"src",
")",
";",
"}"
] | Construct a new WebService instance
<p>Each method on the WebService instance will return an APICall object which may be used to
access the results of the method called. You can chain multiple events together with the
returned object (an APICall instance).
<p>All events are at least guaranteed to have the callback signature: function(data, apicall).
supported events:
<p> 200, 201, 400, 401, 404, 409, ok, created, badrequest, unauthorized, notfound, conflict,
success, error, complete, meta, result, abort
<p>Event order: success callbacks, meta callbacks, result callbacks, error callbacks, complete
callbacks
<p>Example:
<pre class='code'>
var ws = new cloudmine.WebService({appid: "abc", apikey: "abc", appname: 'SampleApp', appversion: '1.0'});
ws.get("MyKey").on("success", function(data, apicall) {
console.log("MyKey value: %o", data["MyKey"]);
}).on("error", function(data, apicall) {
console.log("Failed to get MyKey: %o", apicall.status);
}).on("unauthorized", function(data, apicall) {
console.log("I'm not authorized to access 'appid'");
}).on(404, function(data, apicall) {
console.log("Could not find 'MyKey'");
}).on("complete", function(data, apicall) {
console.log("Finished get on 'MyKey':", data);
});
</pre>
<p>Refer to APICall's documentation for further information on events.
@param {object} Default configuration for this WebService
@config {string} [appid] The application id for requests (Required)
@config {string} [apikey] The api key for requests (Required)
@config {string} [xuniqueid] The X-Unique-ID you want to apply to all requests using this WebService (optional)
@config {string} [appname] An alphanumeric identifier for your app, used for stats purposes
@config {string} [appversion] A version identifier for you app, used for stats purposes
@config {boolean} [applevel] If true, always send requests to application.
If false, always send requests to user-level, trigger error if not logged in.
Otherwise, send requests to user-level if logged in.
@config {boolean} [savelogin] If true, session token and email / username will be persisted between logins.
@config {integer} [limit] Set the default result limit for requests
@config {string} [sort] Set the field on which to sort results
@config {integer} [skip] Set the default number of results to skip for requests
@config {boolean} [count] Return the count of results for request.
@config {string} [snippet] Run the specified code snippet during the request.
@config {string|object} [params] Parameters to give the code snippet (applies only for code snippets)
@config {boolean} [dontwait] Don't wait for the result of the code snippet (applies only for code snippets)
@config {boolean} [resultsonly] Only return results from the code snippet (applies only for code snippets)
@name WebService
@constructor | [
"Construct",
"a",
"new",
"WebService",
"instance"
] | 647a84cd3631e7399d0802cdf069d7104a4b2192 | https://github.com/cloudmine/CloudMineSDK-JavaScript/blob/647a84cd3631e7399d0802cdf069d7104a4b2192/js/cloudmine.js#L57-L69 | train |
cloudmine/CloudMineSDK-JavaScript | js/cloudmine.js | function(snippet, parameters, options) {
options = opts(this, options);
parameters = merge({}, options.params, parameters);
options.params = null;
options.snippet = null;
var call_opts = {
action: 'run/' + snippet,
type: options.method || 'GET',
options: options
};
if(call_opts.type === 'GET')
call_opts.query = parameters;
else {
call_opts.data = JSON.stringify(parameters);
}
return new APICall(call_opts);
} | javascript | function(snippet, parameters, options) {
options = opts(this, options);
parameters = merge({}, options.params, parameters);
options.params = null;
options.snippet = null;
var call_opts = {
action: 'run/' + snippet,
type: options.method || 'GET',
options: options
};
if(call_opts.type === 'GET')
call_opts.query = parameters;
else {
call_opts.data = JSON.stringify(parameters);
}
return new APICall(call_opts);
} | [
"function",
"(",
"snippet",
",",
"parameters",
",",
"options",
")",
"{",
"options",
"=",
"opts",
"(",
"this",
",",
"options",
")",
";",
"parameters",
"=",
"merge",
"(",
"{",
"}",
",",
"options",
".",
"params",
",",
"parameters",
")",
";",
"options",
".",
"params",
"=",
"null",
";",
"options",
".",
"snippet",
"=",
"null",
";",
"var",
"call_opts",
"=",
"{",
"action",
":",
"'run/'",
"+",
"snippet",
",",
"type",
":",
"options",
".",
"method",
"||",
"'GET'",
",",
"options",
":",
"options",
"}",
";",
"if",
"(",
"call_opts",
".",
"type",
"===",
"'GET'",
")",
"call_opts",
".",
"query",
"=",
"parameters",
";",
"else",
"{",
"call_opts",
".",
"data",
"=",
"JSON",
".",
"stringify",
"(",
"parameters",
")",
";",
"}",
"return",
"new",
"APICall",
"(",
"call_opts",
")",
";",
"}"
] | Run a code snippet directly.
Default http method is 'GET', to change the method set the method option for options.
@param {string} snippet The name of the code snippet to run.
@param {object} params Data to send to the code snippet (optional).
@param {object} [options] Override defaults set on WebService. See WebService constructor for parameters.
@return {APICall} An APICall instance for the web service request used to attach events. | [
"Run",
"a",
"code",
"snippet",
"directly",
".",
"Default",
"http",
"method",
"is",
"GET",
"to",
"change",
"the",
"method",
"set",
"the",
"method",
"option",
"for",
"options",
"."
] | 647a84cd3631e7399d0802cdf069d7104a4b2192 | https://github.com/cloudmine/CloudMineSDK-JavaScript/blob/647a84cd3631e7399d0802cdf069d7104a4b2192/js/cloudmine.js#L254-L273 | train |
|
cloudmine/CloudMineSDK-JavaScript | js/cloudmine.js | function(notification, options) {
options = opts(this, options);
return new APICall({
action: 'push',
type: 'POST',
query: server_params(options),
options: options,
data: JSON.stringify(notification)
});
} | javascript | function(notification, options) {
options = opts(this, options);
return new APICall({
action: 'push',
type: 'POST',
query: server_params(options),
options: options,
data: JSON.stringify(notification)
});
} | [
"function",
"(",
"notification",
",",
"options",
")",
"{",
"options",
"=",
"opts",
"(",
"this",
",",
"options",
")",
";",
"return",
"new",
"APICall",
"(",
"{",
"action",
":",
"'push'",
",",
"type",
":",
"'POST'",
",",
"query",
":",
"server_params",
"(",
"options",
")",
",",
"options",
":",
"options",
",",
"data",
":",
"JSON",
".",
"stringify",
"(",
"notification",
")",
"}",
")",
";",
"}"
] | Sends a push notification to your users.
This requires an API key with push permission.
@param {object} [notification] A notification object. This object can have one or more fields for dispatching the notification.
@param {object} [options] Override defaults set on WebService. See WebService constructor for parameters.
@return {APICall} An APICall instance for the web service request used to attach events. | [
"Sends",
"a",
"push",
"notification",
"to",
"your",
"users",
".",
"This",
"requires",
"an",
"API",
"key",
"with",
"push",
"permission",
"."
] | 647a84cd3631e7399d0802cdf069d7104a4b2192 | https://github.com/cloudmine/CloudMineSDK-JavaScript/blob/647a84cd3631e7399d0802cdf069d7104a4b2192/js/cloudmine.js#L420-L429 | train |
|
cloudmine/CloudMineSDK-JavaScript | js/cloudmine.js | function(id, options) {
options = opts(this, options);
return new APICall({
action: 'account/' + id,
type: 'GET',
query: server_params(options),
options: options
});
} | javascript | function(id, options) {
options = opts(this, options);
return new APICall({
action: 'account/' + id,
type: 'GET',
query: server_params(options),
options: options
});
} | [
"function",
"(",
"id",
",",
"options",
")",
"{",
"options",
"=",
"opts",
"(",
"this",
",",
"options",
")",
";",
"return",
"new",
"APICall",
"(",
"{",
"action",
":",
"'account/'",
"+",
"id",
",",
"type",
":",
"'GET'",
",",
"query",
":",
"server_params",
"(",
"options",
")",
",",
"options",
":",
"options",
"}",
")",
";",
"}"
] | Get specific user by id.
@param {string} id User id being requested.
@param {object} [options] Override defaults set on WebService. See WebService constructor for parameters.
Results may be affected by defaults and/or by the options parameter.
@return {APICall} An APICall instance for the web service request used to attach events. | [
"Get",
"specific",
"user",
"by",
"id",
"."
] | 647a84cd3631e7399d0802cdf069d7104a4b2192 | https://github.com/cloudmine/CloudMineSDK-JavaScript/blob/647a84cd3631e7399d0802cdf069d7104a4b2192/js/cloudmine.js#L439-L447 | train |
|
cloudmine/CloudMineSDK-JavaScript | js/cloudmine.js | function(key, file, options) {
options = opts(this, options);
if (!key) key = this.keygen();
if (!options.filename) options.filename = key;
// Warning: may not necessarily use ajax to perform upload.
var apicall = new APICall({
action: 'binary/' + key,
type: 'post',
later: true,
encoding: 'binary',
options: options,
processResponse: APICall.basicResponse
});
function upload(data, type) {
if (!options.contentType) options.contentType = type || defaultType;
APICall.binaryUpload(apicall, data, options.filename, options.contentType).done();
}
if (isString(file) || (Buffer && file instanceof Buffer)) {
// Upload by filename
if (isNode) {
if (isString(file)) file = fs.readFileSync(file);
upload(file);
}
else NotSupported();
} else if (file.toDataURL) {
// Canvas will have a toDataURL function.
upload(file, 'image/png');
} else if (CanvasRenderingContext2D && file instanceof CanvasRenderingContext2D) {
upload(file.canvas, 'image/png');
} else if (isBinary(file)) {
// Binary files are base64 encoded from a buffer.
var reader = new FileReader();
/** @private */
reader.onabort = function() {
apicall.setData("FileReader aborted").abort();
}
/** @private */
reader.onerror = function(e) {
apicall.setData(e.target.error).abort();
}
/** @private */
reader.onload = function(e) {
upload(e.target.result);
}
// Don't need to transform Files to Blobs.
if (File && file instanceof File) {
if (!options.contentType && file.type != "") options.contentType = file.type;
} else {
file = new Blob([ new Uint8Array(file) ], {type: options.contentType || defaultType});
}
reader.readAsDataURL(file);
} else NotSupported();
return apicall;
} | javascript | function(key, file, options) {
options = opts(this, options);
if (!key) key = this.keygen();
if (!options.filename) options.filename = key;
// Warning: may not necessarily use ajax to perform upload.
var apicall = new APICall({
action: 'binary/' + key,
type: 'post',
later: true,
encoding: 'binary',
options: options,
processResponse: APICall.basicResponse
});
function upload(data, type) {
if (!options.contentType) options.contentType = type || defaultType;
APICall.binaryUpload(apicall, data, options.filename, options.contentType).done();
}
if (isString(file) || (Buffer && file instanceof Buffer)) {
// Upload by filename
if (isNode) {
if (isString(file)) file = fs.readFileSync(file);
upload(file);
}
else NotSupported();
} else if (file.toDataURL) {
// Canvas will have a toDataURL function.
upload(file, 'image/png');
} else if (CanvasRenderingContext2D && file instanceof CanvasRenderingContext2D) {
upload(file.canvas, 'image/png');
} else if (isBinary(file)) {
// Binary files are base64 encoded from a buffer.
var reader = new FileReader();
/** @private */
reader.onabort = function() {
apicall.setData("FileReader aborted").abort();
}
/** @private */
reader.onerror = function(e) {
apicall.setData(e.target.error).abort();
}
/** @private */
reader.onload = function(e) {
upload(e.target.result);
}
// Don't need to transform Files to Blobs.
if (File && file instanceof File) {
if (!options.contentType && file.type != "") options.contentType = file.type;
} else {
file = new Blob([ new Uint8Array(file) ], {type: options.contentType || defaultType});
}
reader.readAsDataURL(file);
} else NotSupported();
return apicall;
} | [
"function",
"(",
"key",
",",
"file",
",",
"options",
")",
"{",
"options",
"=",
"opts",
"(",
"this",
",",
"options",
")",
";",
"if",
"(",
"!",
"key",
")",
"key",
"=",
"this",
".",
"keygen",
"(",
")",
";",
"if",
"(",
"!",
"options",
".",
"filename",
")",
"options",
".",
"filename",
"=",
"key",
";",
"var",
"apicall",
"=",
"new",
"APICall",
"(",
"{",
"action",
":",
"'binary/'",
"+",
"key",
",",
"type",
":",
"'post'",
",",
"later",
":",
"true",
",",
"encoding",
":",
"'binary'",
",",
"options",
":",
"options",
",",
"processResponse",
":",
"APICall",
".",
"basicResponse",
"}",
")",
";",
"function",
"upload",
"(",
"data",
",",
"type",
")",
"{",
"if",
"(",
"!",
"options",
".",
"contentType",
")",
"options",
".",
"contentType",
"=",
"type",
"||",
"defaultType",
";",
"APICall",
".",
"binaryUpload",
"(",
"apicall",
",",
"data",
",",
"options",
".",
"filename",
",",
"options",
".",
"contentType",
")",
".",
"done",
"(",
")",
";",
"}",
"if",
"(",
"isString",
"(",
"file",
")",
"||",
"(",
"Buffer",
"&&",
"file",
"instanceof",
"Buffer",
")",
")",
"{",
"if",
"(",
"isNode",
")",
"{",
"if",
"(",
"isString",
"(",
"file",
")",
")",
"file",
"=",
"fs",
".",
"readFileSync",
"(",
"file",
")",
";",
"upload",
"(",
"file",
")",
";",
"}",
"else",
"NotSupported",
"(",
")",
";",
"}",
"else",
"if",
"(",
"file",
".",
"toDataURL",
")",
"{",
"upload",
"(",
"file",
",",
"'image/png'",
")",
";",
"}",
"else",
"if",
"(",
"CanvasRenderingContext2D",
"&&",
"file",
"instanceof",
"CanvasRenderingContext2D",
")",
"{",
"upload",
"(",
"file",
".",
"canvas",
",",
"'image/png'",
")",
";",
"}",
"else",
"if",
"(",
"isBinary",
"(",
"file",
")",
")",
"{",
"var",
"reader",
"=",
"new",
"FileReader",
"(",
")",
";",
"reader",
".",
"onabort",
"=",
"function",
"(",
")",
"{",
"apicall",
".",
"setData",
"(",
"\"FileReader aborted\"",
")",
".",
"abort",
"(",
")",
";",
"}",
"reader",
".",
"onerror",
"=",
"function",
"(",
"e",
")",
"{",
"apicall",
".",
"setData",
"(",
"e",
".",
"target",
".",
"error",
")",
".",
"abort",
"(",
")",
";",
"}",
"reader",
".",
"onload",
"=",
"function",
"(",
"e",
")",
"{",
"upload",
"(",
"e",
".",
"target",
".",
"result",
")",
";",
"}",
"if",
"(",
"File",
"&&",
"file",
"instanceof",
"File",
")",
"{",
"if",
"(",
"!",
"options",
".",
"contentType",
"&&",
"file",
".",
"type",
"!=",
"\"\"",
")",
"options",
".",
"contentType",
"=",
"file",
".",
"type",
";",
"}",
"else",
"{",
"file",
"=",
"new",
"Blob",
"(",
"[",
"new",
"Uint8Array",
"(",
"file",
")",
"]",
",",
"{",
"type",
":",
"options",
".",
"contentType",
"||",
"defaultType",
"}",
")",
";",
"}",
"reader",
".",
"readAsDataURL",
"(",
"file",
")",
";",
"}",
"else",
"NotSupported",
"(",
")",
";",
"return",
"apicall",
";",
"}"
] | Upload a file stored in CloudMine.
@param {string} key The binary file's object key.
@param {file|string} file FileAPI: A HTML5 FileAPI File object, Node.js: The filename to upload.
@param {object} [options] Override defaults set on WebService. See WebService constructor for parameters.
@return {APICall} An APICall instance for the web service request used to attach events. | [
"Upload",
"a",
"file",
"stored",
"in",
"CloudMine",
"."
] | 647a84cd3631e7399d0802cdf069d7104a4b2192 | https://github.com/cloudmine/CloudMineSDK-JavaScript/blob/647a84cd3631e7399d0802cdf069d7104a4b2192/js/cloudmine.js#L509-L572 | train |
|
cloudmine/CloudMineSDK-JavaScript | js/cloudmine.js | function(key, options) {
options = opts(this, options);
var response = {success: {}}, query;
if (options.filename) {
query = {
force_download: true,
apikey: options.apikey,
session_token: options.session_token,
filename: options.filename
}
}
var apicall = new APICall({
action: 'binary/' + key,
type: 'GET',
later: true,
encoding: 'binary',
options: options,
query: query
});
// Download file directly to computer if given a filename.
if (options.filename) {
if (isNode) {
apicall.setProcessor(function(data) {
response.success[key] = fs.writeFileSync(options.filename, data, 'binary');
return response;
}).done();
} else {
function detach() {
if (iframe.parentNode) document.body.removeChild(iframe);
}
var iframe = document.createElement('iframe');
iframe.style.display = 'none';
document.body.appendChild(iframe);
setTimeout(function() { iframe.src = apicall.url; }, 25);
iframe.onload = function() {
clearTimeout(detach.timer);
detach.timer = setTimeout(detach, 5000);
};
detach.timer = setTimeout(detach, 60000);
response.success[key] = iframe;
}
apicall.done(response);
} else if (options.mode === 'buffer' && (ArrayBuffer || Buffer)) {
apicall.setProcessor(function(data) {
var buffer;
if (Buffer) {
buffer = new Buffer(data, 'binary');
} else {
buffer = new ArrayBuffer(data.length);
var charView = new Uint8Array(buffer);
for (var i = 0; i < data.length; ++i) {
charView[i] = data[i] & 0xFF;
}
}
response.success[key] = buffer;
return response;
}).done();
} else {
// Raw data return. Do not attempt to process the result.
apicall.setProcessor(function(data) {
response.success[key] = data;
return response;
}).done();
}
return apicall;
} | javascript | function(key, options) {
options = opts(this, options);
var response = {success: {}}, query;
if (options.filename) {
query = {
force_download: true,
apikey: options.apikey,
session_token: options.session_token,
filename: options.filename
}
}
var apicall = new APICall({
action: 'binary/' + key,
type: 'GET',
later: true,
encoding: 'binary',
options: options,
query: query
});
// Download file directly to computer if given a filename.
if (options.filename) {
if (isNode) {
apicall.setProcessor(function(data) {
response.success[key] = fs.writeFileSync(options.filename, data, 'binary');
return response;
}).done();
} else {
function detach() {
if (iframe.parentNode) document.body.removeChild(iframe);
}
var iframe = document.createElement('iframe');
iframe.style.display = 'none';
document.body.appendChild(iframe);
setTimeout(function() { iframe.src = apicall.url; }, 25);
iframe.onload = function() {
clearTimeout(detach.timer);
detach.timer = setTimeout(detach, 5000);
};
detach.timer = setTimeout(detach, 60000);
response.success[key] = iframe;
}
apicall.done(response);
} else if (options.mode === 'buffer' && (ArrayBuffer || Buffer)) {
apicall.setProcessor(function(data) {
var buffer;
if (Buffer) {
buffer = new Buffer(data, 'binary');
} else {
buffer = new ArrayBuffer(data.length);
var charView = new Uint8Array(buffer);
for (var i = 0; i < data.length; ++i) {
charView[i] = data[i] & 0xFF;
}
}
response.success[key] = buffer;
return response;
}).done();
} else {
// Raw data return. Do not attempt to process the result.
apicall.setProcessor(function(data) {
response.success[key] = data;
return response;
}).done();
}
return apicall;
} | [
"function",
"(",
"key",
",",
"options",
")",
"{",
"options",
"=",
"opts",
"(",
"this",
",",
"options",
")",
";",
"var",
"response",
"=",
"{",
"success",
":",
"{",
"}",
"}",
",",
"query",
";",
"if",
"(",
"options",
".",
"filename",
")",
"{",
"query",
"=",
"{",
"force_download",
":",
"true",
",",
"apikey",
":",
"options",
".",
"apikey",
",",
"session_token",
":",
"options",
".",
"session_token",
",",
"filename",
":",
"options",
".",
"filename",
"}",
"}",
"var",
"apicall",
"=",
"new",
"APICall",
"(",
"{",
"action",
":",
"'binary/'",
"+",
"key",
",",
"type",
":",
"'GET'",
",",
"later",
":",
"true",
",",
"encoding",
":",
"'binary'",
",",
"options",
":",
"options",
",",
"query",
":",
"query",
"}",
")",
";",
"if",
"(",
"options",
".",
"filename",
")",
"{",
"if",
"(",
"isNode",
")",
"{",
"apicall",
".",
"setProcessor",
"(",
"function",
"(",
"data",
")",
"{",
"response",
".",
"success",
"[",
"key",
"]",
"=",
"fs",
".",
"writeFileSync",
"(",
"options",
".",
"filename",
",",
"data",
",",
"'binary'",
")",
";",
"return",
"response",
";",
"}",
")",
".",
"done",
"(",
")",
";",
"}",
"else",
"{",
"function",
"detach",
"(",
")",
"{",
"if",
"(",
"iframe",
".",
"parentNode",
")",
"document",
".",
"body",
".",
"removeChild",
"(",
"iframe",
")",
";",
"}",
"var",
"iframe",
"=",
"document",
".",
"createElement",
"(",
"'iframe'",
")",
";",
"iframe",
".",
"style",
".",
"display",
"=",
"'none'",
";",
"document",
".",
"body",
".",
"appendChild",
"(",
"iframe",
")",
";",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"iframe",
".",
"src",
"=",
"apicall",
".",
"url",
";",
"}",
",",
"25",
")",
";",
"iframe",
".",
"onload",
"=",
"function",
"(",
")",
"{",
"clearTimeout",
"(",
"detach",
".",
"timer",
")",
";",
"detach",
".",
"timer",
"=",
"setTimeout",
"(",
"detach",
",",
"5000",
")",
";",
"}",
";",
"detach",
".",
"timer",
"=",
"setTimeout",
"(",
"detach",
",",
"60000",
")",
";",
"response",
".",
"success",
"[",
"key",
"]",
"=",
"iframe",
";",
"}",
"apicall",
".",
"done",
"(",
"response",
")",
";",
"}",
"else",
"if",
"(",
"options",
".",
"mode",
"===",
"'buffer'",
"&&",
"(",
"ArrayBuffer",
"||",
"Buffer",
")",
")",
"{",
"apicall",
".",
"setProcessor",
"(",
"function",
"(",
"data",
")",
"{",
"var",
"buffer",
";",
"if",
"(",
"Buffer",
")",
"{",
"buffer",
"=",
"new",
"Buffer",
"(",
"data",
",",
"'binary'",
")",
";",
"}",
"else",
"{",
"buffer",
"=",
"new",
"ArrayBuffer",
"(",
"data",
".",
"length",
")",
";",
"var",
"charView",
"=",
"new",
"Uint8Array",
"(",
"buffer",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"data",
".",
"length",
";",
"++",
"i",
")",
"{",
"charView",
"[",
"i",
"]",
"=",
"data",
"[",
"i",
"]",
"&",
"0xFF",
";",
"}",
"}",
"response",
".",
"success",
"[",
"key",
"]",
"=",
"buffer",
";",
"return",
"response",
";",
"}",
")",
".",
"done",
"(",
")",
";",
"}",
"else",
"{",
"apicall",
".",
"setProcessor",
"(",
"function",
"(",
"data",
")",
"{",
"response",
".",
"success",
"[",
"key",
"]",
"=",
"data",
";",
"return",
"response",
";",
"}",
")",
".",
"done",
"(",
")",
";",
"}",
"return",
"apicall",
";",
"}"
] | Download a file stored in CloudMine.
@param {string} key The binary file's object key.
@param {object} [options] Override defaults set on WebService. See WebService constructor for parameters.
@config {string} [filename] If present, the file will be downloaded directly to the computer with the
filename given. This does not validate the filename given!
@config {string} [mode] If buffer, automatically move returning data to either an ArrayBuffer or Buffer
if supported. Otherwise the result will be a standard string.
@return {APICall} An APICall instance for the web service request used to attach events. | [
"Download",
"a",
"file",
"stored",
"in",
"CloudMine",
"."
] | 647a84cd3631e7399d0802cdf069d7104a4b2192 | https://github.com/cloudmine/CloudMineSDK-JavaScript/blob/647a84cd3631e7399d0802cdf069d7104a4b2192/js/cloudmine.js#L584-L655 | train |
|
cloudmine/CloudMineSDK-JavaScript | js/cloudmine.js | function(user_id, profile, options) {
options = opts(this, options);
return new APICall({
action: 'account/' + user_id,
type: 'POST',
options: options,
query: server_params(options),
data: JSON.stringify(profile)
});
} | javascript | function(user_id, profile, options) {
options = opts(this, options);
return new APICall({
action: 'account/' + user_id,
type: 'POST',
options: options,
query: server_params(options),
data: JSON.stringify(profile)
});
} | [
"function",
"(",
"user_id",
",",
"profile",
",",
"options",
")",
"{",
"options",
"=",
"opts",
"(",
"this",
",",
"options",
")",
";",
"return",
"new",
"APICall",
"(",
"{",
"action",
":",
"'account/'",
"+",
"user_id",
",",
"type",
":",
"'POST'",
",",
"options",
":",
"options",
",",
"query",
":",
"server_params",
"(",
"options",
")",
",",
"data",
":",
"JSON",
".",
"stringify",
"(",
"profile",
")",
"}",
")",
";",
"}"
] | Update a user object without having a session token. Requires the use of the master key
@param {string} user_id the user id of the user to update.
@param {object} profile a JSON object representing the profile
@param {object} [options] Override defaults set on WebService. See WebService constructor for parameters. | [
"Update",
"a",
"user",
"object",
"without",
"having",
"a",
"session",
"token",
".",
"Requires",
"the",
"use",
"of",
"the",
"master",
"key"
] | 647a84cd3631e7399d0802cdf069d7104a4b2192 | https://github.com/cloudmine/CloudMineSDK-JavaScript/blob/647a84cd3631e7399d0802cdf069d7104a4b2192/js/cloudmine.js#L751-L760 | train |
|
cloudmine/CloudMineSDK-JavaScript | js/cloudmine.js | function(user_id, password, options) {
options = opts(this, options);
var payload = JSON.stringify({
password: password
});
return new APICall({
action: 'account/' + user_id + '/password/change',
type: 'POST',
options: options,
processResponse: APICall.basicResponse,
data: payload
});
} | javascript | function(user_id, password, options) {
options = opts(this, options);
var payload = JSON.stringify({
password: password
});
return new APICall({
action: 'account/' + user_id + '/password/change',
type: 'POST',
options: options,
processResponse: APICall.basicResponse,
data: payload
});
} | [
"function",
"(",
"user_id",
",",
"password",
",",
"options",
")",
"{",
"options",
"=",
"opts",
"(",
"this",
",",
"options",
")",
";",
"var",
"payload",
"=",
"JSON",
".",
"stringify",
"(",
"{",
"password",
":",
"password",
"}",
")",
";",
"return",
"new",
"APICall",
"(",
"{",
"action",
":",
"'account/'",
"+",
"user_id",
"+",
"'/password/change'",
",",
"type",
":",
"'POST'",
",",
"options",
":",
"options",
",",
"processResponse",
":",
"APICall",
".",
"basicResponse",
",",
"data",
":",
"payload",
"}",
")",
";",
"}"
] | Update a user password without having a session token. Requires the use of the master key
@param {string} user_id The id of the user to change the password.
@param {string} password The new password for the user.
@param {object} [options] Override defaults set on WebService. See WebService constructor for parameters.
@return {APICall} An APICall instance for the web service request used to attach events. | [
"Update",
"a",
"user",
"password",
"without",
"having",
"a",
"session",
"token",
".",
"Requires",
"the",
"use",
"of",
"the",
"master",
"key"
] | 647a84cd3631e7399d0802cdf069d7104a4b2192 | https://github.com/cloudmine/CloudMineSDK-JavaScript/blob/647a84cd3631e7399d0802cdf069d7104a4b2192/js/cloudmine.js#L832-L846 | train |
|
cloudmine/CloudMineSDK-JavaScript | js/cloudmine.js | function(email, options) {
options = opts(this, options);
options.applevel = true;
var payload = JSON.stringify({
email: email
});
return new APICall({
action: 'account/password/reset',
type: 'POST',
options: options,
processResponse: APICall.basicResponse,
data: payload
});
} | javascript | function(email, options) {
options = opts(this, options);
options.applevel = true;
var payload = JSON.stringify({
email: email
});
return new APICall({
action: 'account/password/reset',
type: 'POST',
options: options,
processResponse: APICall.basicResponse,
data: payload
});
} | [
"function",
"(",
"email",
",",
"options",
")",
"{",
"options",
"=",
"opts",
"(",
"this",
",",
"options",
")",
";",
"options",
".",
"applevel",
"=",
"true",
";",
"var",
"payload",
"=",
"JSON",
".",
"stringify",
"(",
"{",
"email",
":",
"email",
"}",
")",
";",
"return",
"new",
"APICall",
"(",
"{",
"action",
":",
"'account/password/reset'",
",",
"type",
":",
"'POST'",
",",
"options",
":",
"options",
",",
"processResponse",
":",
"APICall",
".",
"basicResponse",
",",
"data",
":",
"payload",
"}",
")",
";",
"}"
] | Initiate a password reset request.
@param {string} email The email to send a reset password email to.
@param {object} [options] Override defaults set on WebService. See WebService constructor for parameters.
@return {APICall} An APICall instance for the web service request used to attach events. | [
"Initiate",
"a",
"password",
"reset",
"request",
"."
] | 647a84cd3631e7399d0802cdf069d7104a4b2192 | https://github.com/cloudmine/CloudMineSDK-JavaScript/blob/647a84cd3631e7399d0802cdf069d7104a4b2192/js/cloudmine.js#L889-L903 | train |
|
cloudmine/CloudMineSDK-JavaScript | js/cloudmine.js | function(token, newPassword, options) {
options = opts(this, options);
options.applevel = true;
var payload = JSON.stringify({
password: newPassword
});
return new APICall({
action: "account/password/reset/" + token,
type: 'POST',
data: payload,
processResponse: APICall.basicResponse,
options: options
});
} | javascript | function(token, newPassword, options) {
options = opts(this, options);
options.applevel = true;
var payload = JSON.stringify({
password: newPassword
});
return new APICall({
action: "account/password/reset/" + token,
type: 'POST',
data: payload,
processResponse: APICall.basicResponse,
options: options
});
} | [
"function",
"(",
"token",
",",
"newPassword",
",",
"options",
")",
"{",
"options",
"=",
"opts",
"(",
"this",
",",
"options",
")",
";",
"options",
".",
"applevel",
"=",
"true",
";",
"var",
"payload",
"=",
"JSON",
".",
"stringify",
"(",
"{",
"password",
":",
"newPassword",
"}",
")",
";",
"return",
"new",
"APICall",
"(",
"{",
"action",
":",
"\"account/password/reset/\"",
"+",
"token",
",",
"type",
":",
"'POST'",
",",
"data",
":",
"payload",
",",
"processResponse",
":",
"APICall",
".",
"basicResponse",
",",
"options",
":",
"options",
"}",
")",
";",
"}"
] | Change the password for an account from the token received from password reset.
@param {string} token The token for password reset. Usually received by email.
@param {string} newPassword The password to assign to the user.
@param {object} [options] Override defaults set on WebService. See WebService constructor for parameters.
@return {APICall} An APICall instance for the web service request used to attach events. | [
"Change",
"the",
"password",
"for",
"an",
"account",
"from",
"the",
"token",
"received",
"from",
"password",
"reset",
"."
] | 647a84cd3631e7399d0802cdf069d7104a4b2192 | https://github.com/cloudmine/CloudMineSDK-JavaScript/blob/647a84cd3631e7399d0802cdf069d7104a4b2192/js/cloudmine.js#L912-L926 | train |
|
cloudmine/CloudMineSDK-JavaScript | js/cloudmine.js | function(query, options) {
options = opts(this, options);
if(!options.session_token) throw new Error("Must be logged in to perform a social query");
if(query.headers && !isObject(query.headers)) throw new Error("Headers must be an object");
if(query.params && !isObject(query.params)) throw new Error("Extra parameters must be an object");
var url = "social/"+query.network+"/"+query.endpoint;
var urlParams = {};
if(query.headers) urlParams.headers = query.headers;
if(query.params) urlParams.params = query.params;
var apicall = new APICall({
action: url,
type: query.method,
query: urlParams,
options: options,
data: query.data,
contentType: 'application/octet-stream'
});
return apicall;
} | javascript | function(query, options) {
options = opts(this, options);
if(!options.session_token) throw new Error("Must be logged in to perform a social query");
if(query.headers && !isObject(query.headers)) throw new Error("Headers must be an object");
if(query.params && !isObject(query.params)) throw new Error("Extra parameters must be an object");
var url = "social/"+query.network+"/"+query.endpoint;
var urlParams = {};
if(query.headers) urlParams.headers = query.headers;
if(query.params) urlParams.params = query.params;
var apicall = new APICall({
action: url,
type: query.method,
query: urlParams,
options: options,
data: query.data,
contentType: 'application/octet-stream'
});
return apicall;
} | [
"function",
"(",
"query",
",",
"options",
")",
"{",
"options",
"=",
"opts",
"(",
"this",
",",
"options",
")",
";",
"if",
"(",
"!",
"options",
".",
"session_token",
")",
"throw",
"new",
"Error",
"(",
"\"Must be logged in to perform a social query\"",
")",
";",
"if",
"(",
"query",
".",
"headers",
"&&",
"!",
"isObject",
"(",
"query",
".",
"headers",
")",
")",
"throw",
"new",
"Error",
"(",
"\"Headers must be an object\"",
")",
";",
"if",
"(",
"query",
".",
"params",
"&&",
"!",
"isObject",
"(",
"query",
".",
"params",
")",
")",
"throw",
"new",
"Error",
"(",
"\"Extra parameters must be an object\"",
")",
";",
"var",
"url",
"=",
"\"social/\"",
"+",
"query",
".",
"network",
"+",
"\"/\"",
"+",
"query",
".",
"endpoint",
";",
"var",
"urlParams",
"=",
"{",
"}",
";",
"if",
"(",
"query",
".",
"headers",
")",
"urlParams",
".",
"headers",
"=",
"query",
".",
"headers",
";",
"if",
"(",
"query",
".",
"params",
")",
"urlParams",
".",
"params",
"=",
"query",
".",
"params",
";",
"var",
"apicall",
"=",
"new",
"APICall",
"(",
"{",
"action",
":",
"url",
",",
"type",
":",
"query",
".",
"method",
",",
"query",
":",
"urlParams",
",",
"options",
":",
"options",
",",
"data",
":",
"query",
".",
"data",
",",
"contentType",
":",
"'application/octet-stream'",
"}",
")",
";",
"return",
"apicall",
";",
"}"
] | Query a social network.
Must be logged in as a user who has logged in to a social network.
@param {object} query An object with the parameters of the query.
@config {string} query.network A network to authenticate against. @see WebService.SocialNetworks
@config {string} query.endpoint The endpoint to hit, on the social network side. See the social network's documentation for more details.
@config {string} query.method HTTP verb to use when querying.
@config {object} query.headers Extra headers to pass in the HTTP request to the social network.
@config {object} query.params Extra parameters to pass in the HTTP request to the social network.
@config {string} query.data Data to pass in the body of the HTTP request.
@param {object} [options] Override defaults set on WebService. See WebService constructor for parameters.
@throws {Error} If the user is not logged in.
@throws {Error} If query.headers is truthy and not an object.
@throws {Error} If query.params is truthy and not an object.
@return {APICall} An APICall instance for the web service request used to attach events. | [
"Query",
"a",
"social",
"network",
".",
"Must",
"be",
"logged",
"in",
"as",
"a",
"user",
"who",
"has",
"logged",
"in",
"to",
"a",
"social",
"network",
"."
] | 647a84cd3631e7399d0802cdf069d7104a4b2192 | https://github.com/cloudmine/CloudMineSDK-JavaScript/blob/647a84cd3631e7399d0802cdf069d7104a4b2192/js/cloudmine.js#L1077-L1101 | train |
|
cloudmine/CloudMineSDK-JavaScript | js/cloudmine.js | function(auth, password, options) {
if (isObject(auth)) options = password;
else auth = {email: auth, password: password}
options = opts(this, options);
options.applevel = true;
var config = {
action: 'account',
type: 'DELETE',
options: options,
processResponse: APICall.basicResponse
};
// Drop session if we are referring to ourselves.
if (auth.email == this.options.email) {
this.options.session_token = null;
this.options.email = null;
if (options.savelogin) {
store('email', null, this.options.appid);
store('username', null, this.options.appid);
store('session_token', null, this.options.appid);
}
}
if (auth.password) {
// Non-master key access
config.data = JSON.stringify({
email: auth.email,
username: auth.username,
password: auth.password
})
} else {
// Master key access
config.action += '/' + auth.email;
}
return new APICall(config);
} | javascript | function(auth, password, options) {
if (isObject(auth)) options = password;
else auth = {email: auth, password: password}
options = opts(this, options);
options.applevel = true;
var config = {
action: 'account',
type: 'DELETE',
options: options,
processResponse: APICall.basicResponse
};
// Drop session if we are referring to ourselves.
if (auth.email == this.options.email) {
this.options.session_token = null;
this.options.email = null;
if (options.savelogin) {
store('email', null, this.options.appid);
store('username', null, this.options.appid);
store('session_token', null, this.options.appid);
}
}
if (auth.password) {
// Non-master key access
config.data = JSON.stringify({
email: auth.email,
username: auth.username,
password: auth.password
})
} else {
// Master key access
config.action += '/' + auth.email;
}
return new APICall(config);
} | [
"function",
"(",
"auth",
",",
"password",
",",
"options",
")",
"{",
"if",
"(",
"isObject",
"(",
"auth",
")",
")",
"options",
"=",
"password",
";",
"else",
"auth",
"=",
"{",
"email",
":",
"auth",
",",
"password",
":",
"password",
"}",
"options",
"=",
"opts",
"(",
"this",
",",
"options",
")",
";",
"options",
".",
"applevel",
"=",
"true",
";",
"var",
"config",
"=",
"{",
"action",
":",
"'account'",
",",
"type",
":",
"'DELETE'",
",",
"options",
":",
"options",
",",
"processResponse",
":",
"APICall",
".",
"basicResponse",
"}",
";",
"if",
"(",
"auth",
".",
"email",
"==",
"this",
".",
"options",
".",
"email",
")",
"{",
"this",
".",
"options",
".",
"session_token",
"=",
"null",
";",
"this",
".",
"options",
".",
"email",
"=",
"null",
";",
"if",
"(",
"options",
".",
"savelogin",
")",
"{",
"store",
"(",
"'email'",
",",
"null",
",",
"this",
".",
"options",
".",
"appid",
")",
";",
"store",
"(",
"'username'",
",",
"null",
",",
"this",
".",
"options",
".",
"appid",
")",
";",
"store",
"(",
"'session_token'",
",",
"null",
",",
"this",
".",
"options",
".",
"appid",
")",
";",
"}",
"}",
"if",
"(",
"auth",
".",
"password",
")",
"{",
"config",
".",
"data",
"=",
"JSON",
".",
"stringify",
"(",
"{",
"email",
":",
"auth",
".",
"email",
",",
"username",
":",
"auth",
".",
"username",
",",
"password",
":",
"auth",
".",
"password",
"}",
")",
"}",
"else",
"{",
"config",
".",
"action",
"+=",
"'/'",
"+",
"auth",
".",
"email",
";",
"}",
"return",
"new",
"APICall",
"(",
"config",
")",
";",
"}"
] | Delete a user.
If you are using the master api key, omit the user password to delete the user.
If you are not using the master api key, provide the user name and password in the corresponding
email and password fields.
@param {object} data An object that may contain email / username fields and optionally a password field.
@param {object} [options] Override defaults set on WebService. See WebService constructor for parameters.
@return {APICall} An APICall instance for the web service request used to attach events.
@function
@name deleteUser
@memberOf WebService.prototype
Delete a user.
If you are using the master api key, omit the user password to delete the user.
If you are not using the master api key, provide the user name and password in the corresponding
email and password fields.
@param {string} email The email of the user to delete. If using a master key use a user id.
@param {string} password The password for the account. Omit if using a master key.
@param {object} [options] Override defaults set on WebService. See WebService constructor for parameters.
@return {APICall} An APICall instance for the web service request used to attach events.
@function
@name deleteUser^2
@memberOf WebService.prototype | [
"Delete",
"a",
"user",
".",
"If",
"you",
"are",
"using",
"the",
"master",
"api",
"key",
"omit",
"the",
"user",
"password",
"to",
"delete",
"the",
"user",
".",
"If",
"you",
"are",
"not",
"using",
"the",
"master",
"api",
"key",
"provide",
"the",
"user",
"name",
"and",
"password",
"in",
"the",
"corresponding",
"email",
"and",
"password",
"fields",
"."
] | 647a84cd3631e7399d0802cdf069d7104a4b2192 | https://github.com/cloudmine/CloudMineSDK-JavaScript/blob/647a84cd3631e7399d0802cdf069d7104a4b2192/js/cloudmine.js#L1199-L1237 | train |
|
cloudmine/CloudMineSDK-JavaScript | js/cloudmine.js | function(aclid, options){
options = opts(this, options);
return new APICall({
action: 'access/' + aclid,
type: 'DELETE',
processResponse: APICall.basicResponse,
options: options
});
} | javascript | function(aclid, options){
options = opts(this, options);
return new APICall({
action: 'access/' + aclid,
type: 'DELETE',
processResponse: APICall.basicResponse,
options: options
});
} | [
"function",
"(",
"aclid",
",",
"options",
")",
"{",
"options",
"=",
"opts",
"(",
"this",
",",
"options",
")",
";",
"return",
"new",
"APICall",
"(",
"{",
"action",
":",
"'access/'",
"+",
"aclid",
",",
"type",
":",
"'DELETE'",
",",
"processResponse",
":",
"APICall",
".",
"basicResponse",
",",
"options",
":",
"options",
"}",
")",
";",
"}"
] | Deletes an ACL via id.
@param {string} aclid The ACL id value to be deleted.
@param {object} [options] Override defaults set on WebService. See WebService constructor for parameters.
@return {APICall} An APICall instance for the web service request used to attach events.
@function
@name deleteACL
@memberOf WebService.prototype | [
"Deletes",
"an",
"ACL",
"via",
"id",
"."
] | 647a84cd3631e7399d0802cdf069d7104a4b2192 | https://github.com/cloudmine/CloudMineSDK-JavaScript/blob/647a84cd3631e7399d0802cdf069d7104a4b2192/js/cloudmine.js#L1285-L1294 | train |
|
cloudmine/CloudMineSDK-JavaScript | js/cloudmine.js | function() {
if (this.options.applevel === true || this.options.applevel === false) return this.options.applevel;
return this.options.session_token == null;
} | javascript | function() {
if (this.options.applevel === true || this.options.applevel === false) return this.options.applevel;
return this.options.session_token == null;
} | [
"function",
"(",
")",
"{",
"if",
"(",
"this",
".",
"options",
".",
"applevel",
"===",
"true",
"||",
"this",
".",
"options",
".",
"applevel",
"===",
"false",
")",
"return",
"this",
".",
"options",
".",
"applevel",
";",
"return",
"this",
".",
"options",
".",
"session_token",
"==",
"null",
";",
"}"
] | Determine if this store is using application data.
@return {boolean} true if this store is using application data, false if is using user-level data. | [
"Determine",
"if",
"this",
"store",
"is",
"using",
"application",
"data",
"."
] | 647a84cd3631e7399d0802cdf069d7104a4b2192 | https://github.com/cloudmine/CloudMineSDK-JavaScript/blob/647a84cd3631e7399d0802cdf069d7104a4b2192/js/cloudmine.js#L1395-L1398 | train |
|
cloudmine/CloudMineSDK-JavaScript | js/cloudmine.js | function(eventType, callback, context) {
if (isFunction(callback)) {
context = context || this;
if (!this._events[eventType]) this._events[eventType] = [];
// normal callback not called.
var self = this;
this._events[eventType].push([callback, context, function() {
self.off(eventType, callback, context);
callback.apply(this, arguments);
}]);
}
return this;
} | javascript | function(eventType, callback, context) {
if (isFunction(callback)) {
context = context || this;
if (!this._events[eventType]) this._events[eventType] = [];
// normal callback not called.
var self = this;
this._events[eventType].push([callback, context, function() {
self.off(eventType, callback, context);
callback.apply(this, arguments);
}]);
}
return this;
} | [
"function",
"(",
"eventType",
",",
"callback",
",",
"context",
")",
"{",
"if",
"(",
"isFunction",
"(",
"callback",
")",
")",
"{",
"context",
"=",
"context",
"||",
"this",
";",
"if",
"(",
"!",
"this",
".",
"_events",
"[",
"eventType",
"]",
")",
"this",
".",
"_events",
"[",
"eventType",
"]",
"=",
"[",
"]",
";",
"var",
"self",
"=",
"this",
";",
"this",
".",
"_events",
"[",
"eventType",
"]",
".",
"push",
"(",
"[",
"callback",
",",
"context",
",",
"function",
"(",
")",
"{",
"self",
".",
"off",
"(",
"eventType",
",",
"callback",
",",
"context",
")",
";",
"callback",
".",
"apply",
"(",
"this",
",",
"arguments",
")",
";",
"}",
"]",
")",
";",
"}",
"return",
"this",
";",
"}"
] | Attach an event listener to this APICall object.
@param {string|number} eventType The event to listen to. Can be an http code as number or string,
success, meta, result, error.
@param {function} callback Callback to call upon event trigger.
@param {object} context Context to call the callback in.
@return {APICall} The current APICall object | [
"Attach",
"an",
"event",
"listener",
"to",
"this",
"APICall",
"object",
"."
] | 647a84cd3631e7399d0802cdf069d7104a4b2192 | https://github.com/cloudmine/CloudMineSDK-JavaScript/blob/647a84cd3631e7399d0802cdf069d7104a4b2192/js/cloudmine.js#L1602-L1615 | train |
|
cloudmine/CloudMineSDK-JavaScript | js/cloudmine.js | function(event/*, arg1...*/) {
var events = this._events[event];
if (events != null) {
var args = slice(arguments, 1);
each(events, function(event) {
event[2].apply(event[1], args);
});
}
return this;
} | javascript | function(event/*, arg1...*/) {
var events = this._events[event];
if (events != null) {
var args = slice(arguments, 1);
each(events, function(event) {
event[2].apply(event[1], args);
});
}
return this;
} | [
"function",
"(",
"event",
")",
"{",
"var",
"events",
"=",
"this",
".",
"_events",
"[",
"event",
"]",
";",
"if",
"(",
"events",
"!=",
"null",
")",
"{",
"var",
"args",
"=",
"slice",
"(",
"arguments",
",",
"1",
")",
";",
"each",
"(",
"events",
",",
"function",
"(",
"event",
")",
"{",
"event",
"[",
"2",
"]",
".",
"apply",
"(",
"event",
"[",
"1",
"]",
",",
"args",
")",
";",
"}",
")",
";",
"}",
"return",
"this",
";",
"}"
] | Trigger an event on this APICall object. This will call all event handlers in order.
All parameters following event will be sent to the event handlers.
@param {string|number} event The event to trigger.
@return {APICall} The current APICall object | [
"Trigger",
"an",
"event",
"on",
"this",
"APICall",
"object",
".",
"This",
"will",
"call",
"all",
"event",
"handlers",
"in",
"order",
".",
"All",
"parameters",
"following",
"event",
"will",
"be",
"sent",
"to",
"the",
"event",
"handlers",
"."
] | 647a84cd3631e7399d0802cdf069d7104a4b2192 | https://github.com/cloudmine/CloudMineSDK-JavaScript/blob/647a84cd3631e7399d0802cdf069d7104a4b2192/js/cloudmine.js#L1623-L1633 | train |
|
cloudmine/CloudMineSDK-JavaScript | js/cloudmine.js | function(eventType, callback, context) {
if (eventType == null && callback == null && context == null) {
this._events = {};
} else if (eventType == null) {
each(this._events, function(value, key, collection) {
collection._events[key] = removeCallbacks(value, callback, context);
});
} else {
this._events[eventType] = removeCallbacks(this._events[eventType], callback, context);
}
return this;
} | javascript | function(eventType, callback, context) {
if (eventType == null && callback == null && context == null) {
this._events = {};
} else if (eventType == null) {
each(this._events, function(value, key, collection) {
collection._events[key] = removeCallbacks(value, callback, context);
});
} else {
this._events[eventType] = removeCallbacks(this._events[eventType], callback, context);
}
return this;
} | [
"function",
"(",
"eventType",
",",
"callback",
",",
"context",
")",
"{",
"if",
"(",
"eventType",
"==",
"null",
"&&",
"callback",
"==",
"null",
"&&",
"context",
"==",
"null",
")",
"{",
"this",
".",
"_events",
"=",
"{",
"}",
";",
"}",
"else",
"if",
"(",
"eventType",
"==",
"null",
")",
"{",
"each",
"(",
"this",
".",
"_events",
",",
"function",
"(",
"value",
",",
"key",
",",
"collection",
")",
"{",
"collection",
".",
"_events",
"[",
"key",
"]",
"=",
"removeCallbacks",
"(",
"value",
",",
"callback",
",",
"context",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"this",
".",
"_events",
"[",
"eventType",
"]",
"=",
"removeCallbacks",
"(",
"this",
".",
"_events",
"[",
"eventType",
"]",
",",
"callback",
",",
"context",
")",
";",
"}",
"return",
"this",
";",
"}"
] | Remove event handlers.
Event handlers will be removed based on the parameters given. If no parameters are given, all
event handlers will be removed.
@param {string|number} eventType The event type which can be an http code as number or string,
or can be success, error, meta, result, abort.
@param {function} callback The function that was used to create the callback.
@param {object} context The context to call the callback in.
@return {APICall} The current APICall object | [
"Remove",
"event",
"handlers",
".",
"Event",
"handlers",
"will",
"be",
"removed",
"based",
"on",
"the",
"parameters",
"given",
".",
"If",
"no",
"parameters",
"are",
"given",
"all",
"event",
"handlers",
"will",
"be",
"removed",
"."
] | 647a84cd3631e7399d0802cdf069d7104a4b2192 | https://github.com/cloudmine/CloudMineSDK-JavaScript/blob/647a84cd3631e7399d0802cdf069d7104a4b2192/js/cloudmine.js#L1645-L1656 | train |
|
cloudmine/CloudMineSDK-JavaScript | js/cloudmine.js | function() {
if (this.xhr) {
this.xhr.abort();
} else if (this.config) {
this.config.complete.call(this, this.xhr, 'abort');
}
// Cleanup leftover state.
if (this.xhr) {
this.xhr = undefined;
delete this.xhr;
}
if (this.config) {
this.config = undefined;
delete this.config;
}
return this;
} | javascript | function() {
if (this.xhr) {
this.xhr.abort();
} else if (this.config) {
this.config.complete.call(this, this.xhr, 'abort');
}
// Cleanup leftover state.
if (this.xhr) {
this.xhr = undefined;
delete this.xhr;
}
if (this.config) {
this.config = undefined;
delete this.config;
}
return this;
} | [
"function",
"(",
")",
"{",
"if",
"(",
"this",
".",
"xhr",
")",
"{",
"this",
".",
"xhr",
".",
"abort",
"(",
")",
";",
"}",
"else",
"if",
"(",
"this",
".",
"config",
")",
"{",
"this",
".",
"config",
".",
"complete",
".",
"call",
"(",
"this",
",",
"this",
".",
"xhr",
",",
"'abort'",
")",
";",
"}",
"if",
"(",
"this",
".",
"xhr",
")",
"{",
"this",
".",
"xhr",
"=",
"undefined",
";",
"delete",
"this",
".",
"xhr",
";",
"}",
"if",
"(",
"this",
".",
"config",
")",
"{",
"this",
".",
"config",
"=",
"undefined",
";",
"delete",
"this",
".",
"config",
";",
"}",
"return",
"this",
";",
"}"
] | Aborts the current connection. This is ineffective for running synchronous calls or completed
calls. Synchronous calls can be achieved by setting async to false in WebService.
@return {APICall} The current APICall object | [
"Aborts",
"the",
"current",
"connection",
".",
"This",
"is",
"ineffective",
"for",
"running",
"synchronous",
"calls",
"or",
"completed",
"calls",
".",
"Synchronous",
"calls",
"can",
"be",
"achieved",
"by",
"setting",
"async",
"to",
"false",
"in",
"WebService",
"."
] | 647a84cd3631e7399d0802cdf069d7104a4b2192 | https://github.com/cloudmine/CloudMineSDK-JavaScript/blob/647a84cd3631e7399d0802cdf069d7104a4b2192/js/cloudmine.js#L1679-L1697 | train |
|
back4app/back4app-entity | src/back/utils/objects.js | copy | function copy(o) {
expect(arguments).to.have.length(
1,
'Invalid argument length when copying an object (it has to be passed ' +
'1 argument)'
);
expect(o).to.be.an(
'object',
'Invalid argument "o" when copying an object (it has to be an object)'
);
var oCopy = {};
for (var property in o) {
oCopy[property] = o[property];
}
return oCopy;
} | javascript | function copy(o) {
expect(arguments).to.have.length(
1,
'Invalid argument length when copying an object (it has to be passed ' +
'1 argument)'
);
expect(o).to.be.an(
'object',
'Invalid argument "o" when copying an object (it has to be an object)'
);
var oCopy = {};
for (var property in o) {
oCopy[property] = o[property];
}
return oCopy;
} | [
"function",
"copy",
"(",
"o",
")",
"{",
"expect",
"(",
"arguments",
")",
".",
"to",
".",
"have",
".",
"length",
"(",
"1",
",",
"'Invalid argument length when copying an object (it has to be passed '",
"+",
"'1 argument)'",
")",
";",
"expect",
"(",
"o",
")",
".",
"to",
".",
"be",
".",
"an",
"(",
"'object'",
",",
"'Invalid argument \"o\" when copying an object (it has to be an object)'",
")",
";",
"var",
"oCopy",
"=",
"{",
"}",
";",
"for",
"(",
"var",
"property",
"in",
"o",
")",
"{",
"oCopy",
"[",
"property",
"]",
"=",
"o",
"[",
"property",
"]",
";",
"}",
"return",
"oCopy",
";",
"}"
] | Makes a copy of a given object.
@param {!Object} o The object to be copied.
@returns {Object} The new copy of the given object.
@example
var copy = objects.copy(myObject); | [
"Makes",
"a",
"copy",
"of",
"a",
"given",
"object",
"."
] | 16a15284d2e119508fcb4e0c88f647ffb285d2e9 | https://github.com/back4app/back4app-entity/blob/16a15284d2e119508fcb4e0c88f647ffb285d2e9/src/back/utils/objects.js#L24-L43 | train |
taskworld/legendary-pancake | examples/homepage/src/documentationPages.js | rerouteLinks | function rerouteLinks (html) {
return html.replace(/href="(\.\/[a-z0-9\-]+\.md)"/g, (all, key) => {
const found = documentationPages.filter((page) => page.key === key)[0]
if (!found) return all
/* global __legendary_pancake_base_pathname__ */
const base = __legendary_pancake_base_pathname__ // eslint-disable-line camelcase
const pathname = found.pathname
return `href="${base}${pathname}" data-to="${pathname}"`
})
} | javascript | function rerouteLinks (html) {
return html.replace(/href="(\.\/[a-z0-9\-]+\.md)"/g, (all, key) => {
const found = documentationPages.filter((page) => page.key === key)[0]
if (!found) return all
/* global __legendary_pancake_base_pathname__ */
const base = __legendary_pancake_base_pathname__ // eslint-disable-line camelcase
const pathname = found.pathname
return `href="${base}${pathname}" data-to="${pathname}"`
})
} | [
"function",
"rerouteLinks",
"(",
"html",
")",
"{",
"return",
"html",
".",
"replace",
"(",
"/",
"href=\"(\\.\\/[a-z0-9\\-]+\\.md)\"",
"/",
"g",
",",
"(",
"all",
",",
"key",
")",
"=>",
"{",
"const",
"found",
"=",
"documentationPages",
".",
"filter",
"(",
"(",
"page",
")",
"=>",
"page",
".",
"key",
"===",
"key",
")",
"[",
"0",
"]",
"if",
"(",
"!",
"found",
")",
"return",
"all",
"const",
"base",
"=",
"__legendary_pancake_base_pathname__",
"const",
"pathname",
"=",
"found",
".",
"pathname",
"return",
"`",
"${",
"base",
"}",
"${",
"pathname",
"}",
"${",
"pathname",
"}",
"`",
"}",
")",
"}"
] | Rewrite links to direct to the correct page. | [
"Rewrite",
"links",
"to",
"direct",
"to",
"the",
"correct",
"page",
"."
] | 5e3a3ff81f7a65808a3bfe945767368db0d46e8c | https://github.com/taskworld/legendary-pancake/blob/5e3a3ff81f7a65808a3bfe945767368db0d46e8c/examples/homepage/src/documentationPages.js#L53-L62 | train |
feedhenry/fh-forms | lib/impl/dataSources/updateCache.js | updateValidAndInvalidDataSources | function updateValidAndInvalidDataSources(dataSourcesToSplit, currentInvalidDataSources) {
logger.debug("dataSourcesToSplit", dataSourcesToSplit);
currentInvalidDataSources = currentInvalidDataSources || [];
var validInvalid = _.partition(dataSourcesToSplit, function(dataSourceUpdateData) {
if (dataSourceUpdateData) {
return !dataSourceUpdateData.error;
}
return true;
});
var validDataSources = validInvalid[0];
//Updating any data sources that are no longer valid
var invalidDataSources = _.union(validInvalid[1], currentInvalidDataSources);
return {
valid: validDataSources,
invalid: invalidDataSources
};
} | javascript | function updateValidAndInvalidDataSources(dataSourcesToSplit, currentInvalidDataSources) {
logger.debug("dataSourcesToSplit", dataSourcesToSplit);
currentInvalidDataSources = currentInvalidDataSources || [];
var validInvalid = _.partition(dataSourcesToSplit, function(dataSourceUpdateData) {
if (dataSourceUpdateData) {
return !dataSourceUpdateData.error;
}
return true;
});
var validDataSources = validInvalid[0];
//Updating any data sources that are no longer valid
var invalidDataSources = _.union(validInvalid[1], currentInvalidDataSources);
return {
valid: validDataSources,
invalid: invalidDataSources
};
} | [
"function",
"updateValidAndInvalidDataSources",
"(",
"dataSourcesToSplit",
",",
"currentInvalidDataSources",
")",
"{",
"logger",
".",
"debug",
"(",
"\"dataSourcesToSplit\"",
",",
"dataSourcesToSplit",
")",
";",
"currentInvalidDataSources",
"=",
"currentInvalidDataSources",
"||",
"[",
"]",
";",
"var",
"validInvalid",
"=",
"_",
".",
"partition",
"(",
"dataSourcesToSplit",
",",
"function",
"(",
"dataSourceUpdateData",
")",
"{",
"if",
"(",
"dataSourceUpdateData",
")",
"{",
"return",
"!",
"dataSourceUpdateData",
".",
"error",
";",
"}",
"return",
"true",
";",
"}",
")",
";",
"var",
"validDataSources",
"=",
"validInvalid",
"[",
"0",
"]",
";",
"var",
"invalidDataSources",
"=",
"_",
".",
"union",
"(",
"validInvalid",
"[",
"1",
"]",
",",
"currentInvalidDataSources",
")",
";",
"return",
"{",
"valid",
":",
"validDataSources",
",",
"invalid",
":",
"invalidDataSources",
"}",
";",
"}"
] | Splitting Data Sources Into Invalid And Valid Data Sources.
@param dataSourcesToSplit
@param currentInvalidDataSources
@returns {{valid, invalid: Array}} | [
"Splitting",
"Data",
"Sources",
"Into",
"Invalid",
"And",
"Valid",
"Data",
"Sources",
"."
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/dataSources/updateCache.js#L20-L39 | train |
feedhenry/fh-forms | lib/impl/dataSources/updateCache.js | findDataSources | function findDataSources(connections, dataSources, cb) {
//Just Want The Data Source IDs.
logger.debug("findDataSources", {dataSources: dataSources});
var dataSourceIDsToUpdate = _.map(dataSources, function(dataSourceUpdateData) {
return dataSourceUpdateData.error ? null : dataSourceUpdateData._id;
});
dataSourceIDsToUpdate = _.compact(dataSourceIDsToUpdate);
//No Valid Data Sources To Update. No Need To Search For Data Sources
if (dataSourceIDsToUpdate.length === 0) {
return cb(undefined, dataSourceIDsToUpdate);
}
var query = {
};
//Searching By ID. Just one mongo call to get them all. More Efficient
query[CONSTANTS.DATA_SOURCE_ID] = {
"$in": dataSourceIDsToUpdate
};
lookUpDataSources(connections, {
query: query
}, function(err, foundDataSources) {
if (err) {
logger.error("Error Finding Data Sources ", {error: err});
return cb(buildErrorResponse({
error: err,
userDetail: "Unexpected Error When Searching For A Data Source",
code: ERROR_CODES.FH_FORMS_UNEXPECTED_ERROR
}));
}
//Map Found Data Source Documents
var dsWithDocuments = _.map(dataSources, function(validDataSource) {
var matchingDocument = _.find(foundDataSources, function(dataSourceDocument) {
return _.isEqual(dataSourceDocument._id.toString(), validDataSource._id.toString());
});
//If the document is found, assign it to the object, if not, set an error
if (matchingDocument) {
validDataSource.document = matchingDocument;
} else {
validDataSource.error = buildErrorResponse({
error: new Error("Data Source Not Found"),
userDetail: "Data Source Not Found",
code: ERROR_CODES.FH_FORMS_NOT_FOUND
});
}
return validDataSource;
});
var validInvalidDataSources = updateValidAndInvalidDataSources(dsWithDocuments, []);
logger.debug("findDataSources", {validInvalidDataSources: validInvalidDataSources});
cb(undefined, validInvalidDataSources.valid, validInvalidDataSources.invalid);
});
} | javascript | function findDataSources(connections, dataSources, cb) {
//Just Want The Data Source IDs.
logger.debug("findDataSources", {dataSources: dataSources});
var dataSourceIDsToUpdate = _.map(dataSources, function(dataSourceUpdateData) {
return dataSourceUpdateData.error ? null : dataSourceUpdateData._id;
});
dataSourceIDsToUpdate = _.compact(dataSourceIDsToUpdate);
//No Valid Data Sources To Update. No Need To Search For Data Sources
if (dataSourceIDsToUpdate.length === 0) {
return cb(undefined, dataSourceIDsToUpdate);
}
var query = {
};
//Searching By ID. Just one mongo call to get them all. More Efficient
query[CONSTANTS.DATA_SOURCE_ID] = {
"$in": dataSourceIDsToUpdate
};
lookUpDataSources(connections, {
query: query
}, function(err, foundDataSources) {
if (err) {
logger.error("Error Finding Data Sources ", {error: err});
return cb(buildErrorResponse({
error: err,
userDetail: "Unexpected Error When Searching For A Data Source",
code: ERROR_CODES.FH_FORMS_UNEXPECTED_ERROR
}));
}
//Map Found Data Source Documents
var dsWithDocuments = _.map(dataSources, function(validDataSource) {
var matchingDocument = _.find(foundDataSources, function(dataSourceDocument) {
return _.isEqual(dataSourceDocument._id.toString(), validDataSource._id.toString());
});
//If the document is found, assign it to the object, if not, set an error
if (matchingDocument) {
validDataSource.document = matchingDocument;
} else {
validDataSource.error = buildErrorResponse({
error: new Error("Data Source Not Found"),
userDetail: "Data Source Not Found",
code: ERROR_CODES.FH_FORMS_NOT_FOUND
});
}
return validDataSource;
});
var validInvalidDataSources = updateValidAndInvalidDataSources(dsWithDocuments, []);
logger.debug("findDataSources", {validInvalidDataSources: validInvalidDataSources});
cb(undefined, validInvalidDataSources.valid, validInvalidDataSources.invalid);
});
} | [
"function",
"findDataSources",
"(",
"connections",
",",
"dataSources",
",",
"cb",
")",
"{",
"logger",
".",
"debug",
"(",
"\"findDataSources\"",
",",
"{",
"dataSources",
":",
"dataSources",
"}",
")",
";",
"var",
"dataSourceIDsToUpdate",
"=",
"_",
".",
"map",
"(",
"dataSources",
",",
"function",
"(",
"dataSourceUpdateData",
")",
"{",
"return",
"dataSourceUpdateData",
".",
"error",
"?",
"null",
":",
"dataSourceUpdateData",
".",
"_id",
";",
"}",
")",
";",
"dataSourceIDsToUpdate",
"=",
"_",
".",
"compact",
"(",
"dataSourceIDsToUpdate",
")",
";",
"if",
"(",
"dataSourceIDsToUpdate",
".",
"length",
"===",
"0",
")",
"{",
"return",
"cb",
"(",
"undefined",
",",
"dataSourceIDsToUpdate",
")",
";",
"}",
"var",
"query",
"=",
"{",
"}",
";",
"query",
"[",
"CONSTANTS",
".",
"DATA_SOURCE_ID",
"]",
"=",
"{",
"\"$in\"",
":",
"dataSourceIDsToUpdate",
"}",
";",
"lookUpDataSources",
"(",
"connections",
",",
"{",
"query",
":",
"query",
"}",
",",
"function",
"(",
"err",
",",
"foundDataSources",
")",
"{",
"if",
"(",
"err",
")",
"{",
"logger",
".",
"error",
"(",
"\"Error Finding Data Sources \"",
",",
"{",
"error",
":",
"err",
"}",
")",
";",
"return",
"cb",
"(",
"buildErrorResponse",
"(",
"{",
"error",
":",
"err",
",",
"userDetail",
":",
"\"Unexpected Error When Searching For A Data Source\"",
",",
"code",
":",
"ERROR_CODES",
".",
"FH_FORMS_UNEXPECTED_ERROR",
"}",
")",
")",
";",
"}",
"var",
"dsWithDocuments",
"=",
"_",
".",
"map",
"(",
"dataSources",
",",
"function",
"(",
"validDataSource",
")",
"{",
"var",
"matchingDocument",
"=",
"_",
".",
"find",
"(",
"foundDataSources",
",",
"function",
"(",
"dataSourceDocument",
")",
"{",
"return",
"_",
".",
"isEqual",
"(",
"dataSourceDocument",
".",
"_id",
".",
"toString",
"(",
")",
",",
"validDataSource",
".",
"_id",
".",
"toString",
"(",
")",
")",
";",
"}",
")",
";",
"if",
"(",
"matchingDocument",
")",
"{",
"validDataSource",
".",
"document",
"=",
"matchingDocument",
";",
"}",
"else",
"{",
"validDataSource",
".",
"error",
"=",
"buildErrorResponse",
"(",
"{",
"error",
":",
"new",
"Error",
"(",
"\"Data Source Not Found\"",
")",
",",
"userDetail",
":",
"\"Data Source Not Found\"",
",",
"code",
":",
"ERROR_CODES",
".",
"FH_FORMS_NOT_FOUND",
"}",
")",
";",
"}",
"return",
"validDataSource",
";",
"}",
")",
";",
"var",
"validInvalidDataSources",
"=",
"updateValidAndInvalidDataSources",
"(",
"dsWithDocuments",
",",
"[",
"]",
")",
";",
"logger",
".",
"debug",
"(",
"\"findDataSources\"",
",",
"{",
"validInvalidDataSources",
":",
"validInvalidDataSources",
"}",
")",
";",
"cb",
"(",
"undefined",
",",
"validInvalidDataSources",
".",
"valid",
",",
"validInvalidDataSources",
".",
"invalid",
")",
";",
"}",
")",
";",
"}"
] | Finding All Data Sources That Need To Be Updated
@param dataSources
@param connections
@param cb
@returns {*} | [
"Finding",
"All",
"Data",
"Sources",
"That",
"Need",
"To",
"Be",
"Updated"
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/dataSources/updateCache.js#L48-L109 | train |
feedhenry/fh-forms | lib/impl/dataSources/updateCache.js | validateParams | function validateParams(dataSources, cb) {
dataSources = _.map(dataSources, function(dataSourceUpdateData) {
var failed = validate(dataSourceUpdateData).has(CONSTANTS.DATA_SOURCE_ID);
if (failed) {
dataSourceUpdateData.error = buildErrorResponse({error: new Error("Invalid Parameters For Updating Data Source Data Cache"), code: ERROR_CODES.FH_FORMS_INVALID_PARAMETERS});
}
if (!misc.checkId(dataSourceUpdateData._id)) {
dataSourceUpdateData.error = buildErrorResponse({error: new Error("Invalid ID Paramter " + dataSourceUpdateData._id), code: ERROR_CODES.FH_FORMS_INVALID_PARAMETERS});
}
return dataSourceUpdateData;
});
//Filter out any data sources with invalid parameters.
cb(undefined, dataSources);
} | javascript | function validateParams(dataSources, cb) {
dataSources = _.map(dataSources, function(dataSourceUpdateData) {
var failed = validate(dataSourceUpdateData).has(CONSTANTS.DATA_SOURCE_ID);
if (failed) {
dataSourceUpdateData.error = buildErrorResponse({error: new Error("Invalid Parameters For Updating Data Source Data Cache"), code: ERROR_CODES.FH_FORMS_INVALID_PARAMETERS});
}
if (!misc.checkId(dataSourceUpdateData._id)) {
dataSourceUpdateData.error = buildErrorResponse({error: new Error("Invalid ID Paramter " + dataSourceUpdateData._id), code: ERROR_CODES.FH_FORMS_INVALID_PARAMETERS});
}
return dataSourceUpdateData;
});
//Filter out any data sources with invalid parameters.
cb(undefined, dataSources);
} | [
"function",
"validateParams",
"(",
"dataSources",
",",
"cb",
")",
"{",
"dataSources",
"=",
"_",
".",
"map",
"(",
"dataSources",
",",
"function",
"(",
"dataSourceUpdateData",
")",
"{",
"var",
"failed",
"=",
"validate",
"(",
"dataSourceUpdateData",
")",
".",
"has",
"(",
"CONSTANTS",
".",
"DATA_SOURCE_ID",
")",
";",
"if",
"(",
"failed",
")",
"{",
"dataSourceUpdateData",
".",
"error",
"=",
"buildErrorResponse",
"(",
"{",
"error",
":",
"new",
"Error",
"(",
"\"Invalid Parameters For Updating Data Source Data Cache\"",
")",
",",
"code",
":",
"ERROR_CODES",
".",
"FH_FORMS_INVALID_PARAMETERS",
"}",
")",
";",
"}",
"if",
"(",
"!",
"misc",
".",
"checkId",
"(",
"dataSourceUpdateData",
".",
"_id",
")",
")",
"{",
"dataSourceUpdateData",
".",
"error",
"=",
"buildErrorResponse",
"(",
"{",
"error",
":",
"new",
"Error",
"(",
"\"Invalid ID Paramter \"",
"+",
"dataSourceUpdateData",
".",
"_id",
")",
",",
"code",
":",
"ERROR_CODES",
".",
"FH_FORMS_INVALID_PARAMETERS",
"}",
")",
";",
"}",
"return",
"dataSourceUpdateData",
";",
"}",
")",
";",
"cb",
"(",
"undefined",
",",
"dataSources",
")",
";",
"}"
] | Validating Data Source Parameters
@param dataSources
@param cb | [
"Validating",
"Data",
"Source",
"Parameters"
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/dataSources/updateCache.js#L116-L134 | train |
feedhenry/fh-forms | lib/impl/dataSources/updateCache.js | updateDataSourceCaches | function updateDataSourceCaches(params, dsWithDocuments, dsWithNoDocuments, cb) {
//Updating All Of The Data Sources
//Generating Hashes For The Incoming Data Set. Useful for determining if the stored data set has changed.
dsWithDocuments = _.map(dsWithDocuments, function(dataSourceData) {
dataSourceData.dataHash = dataSourceData.error ? null : misc.generateHash(dataSourceData.data);
return dataSourceData;
});
async.map(dsWithDocuments, function(dataSourceWithDocument, cb) {
return updateDataSourceEntry(params, dataSourceWithDocument, cb);
}, function(err, updatedDocuments) {
logger.debug("ARGUMENTS", arguments);
//Documents are now either updated or failed
var validInvalidDataSources = updateValidAndInvalidDataSources(updatedDocuments, dsWithNoDocuments);
return cb(undefined, validInvalidDataSources.valid, validInvalidDataSources.invalid);
});
} | javascript | function updateDataSourceCaches(params, dsWithDocuments, dsWithNoDocuments, cb) {
//Updating All Of The Data Sources
//Generating Hashes For The Incoming Data Set. Useful for determining if the stored data set has changed.
dsWithDocuments = _.map(dsWithDocuments, function(dataSourceData) {
dataSourceData.dataHash = dataSourceData.error ? null : misc.generateHash(dataSourceData.data);
return dataSourceData;
});
async.map(dsWithDocuments, function(dataSourceWithDocument, cb) {
return updateDataSourceEntry(params, dataSourceWithDocument, cb);
}, function(err, updatedDocuments) {
logger.debug("ARGUMENTS", arguments);
//Documents are now either updated or failed
var validInvalidDataSources = updateValidAndInvalidDataSources(updatedDocuments, dsWithNoDocuments);
return cb(undefined, validInvalidDataSources.valid, validInvalidDataSources.invalid);
});
} | [
"function",
"updateDataSourceCaches",
"(",
"params",
",",
"dsWithDocuments",
",",
"dsWithNoDocuments",
",",
"cb",
")",
"{",
"dsWithDocuments",
"=",
"_",
".",
"map",
"(",
"dsWithDocuments",
",",
"function",
"(",
"dataSourceData",
")",
"{",
"dataSourceData",
".",
"dataHash",
"=",
"dataSourceData",
".",
"error",
"?",
"null",
":",
"misc",
".",
"generateHash",
"(",
"dataSourceData",
".",
"data",
")",
";",
"return",
"dataSourceData",
";",
"}",
")",
";",
"async",
".",
"map",
"(",
"dsWithDocuments",
",",
"function",
"(",
"dataSourceWithDocument",
",",
"cb",
")",
"{",
"return",
"updateDataSourceEntry",
"(",
"params",
",",
"dataSourceWithDocument",
",",
"cb",
")",
";",
"}",
",",
"function",
"(",
"err",
",",
"updatedDocuments",
")",
"{",
"logger",
".",
"debug",
"(",
"\"ARGUMENTS\"",
",",
"arguments",
")",
";",
"var",
"validInvalidDataSources",
"=",
"updateValidAndInvalidDataSources",
"(",
"updatedDocuments",
",",
"dsWithNoDocuments",
")",
";",
"return",
"cb",
"(",
"undefined",
",",
"validInvalidDataSources",
".",
"valid",
",",
"validInvalidDataSources",
".",
"invalid",
")",
";",
"}",
")",
";",
"}"
] | Updating All Data Source Caches With New Data Sets Or Errors
@param params
- currentTime
@param dsWithDocuments
@param dsWithNoDocuments
@param cb | [
"Updating",
"All",
"Data",
"Source",
"Caches",
"With",
"New",
"Data",
"Sets",
"Or",
"Errors"
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/dataSources/updateCache.js#L144-L162 | train |
feedhenry/fh-forms | lib/impl/dataSources/updateCache.js | updateForms | function updateForms(params, validDataSources, invalidDataSources, cb) {
//Only interested In Data Sources Where Data Was Actually Updated. If the data set is still the same, then no need to mark the form as updated the form.
var dataSoucesUpdated = _.filter(validDataSources, function(dataSourceData) {
return dataSourceData.dataChanged === true;
});
//Updating Any Forms That Reference Updated Data Sources
var updatedDataSourceIds = _.map(dataSoucesUpdated, function(validDataSourceData) {
return validDataSourceData._id;
});
//Need to find and update any forms associated with the data sources.
var Form = models.get(params.connections.mongooseConnection, models.MODELNAMES.FORM);
//Flagging Any Forms That Are Using The Updated Data Sources As Being Updated. This is useful for client/cloud apps that need to determine if they need to load the entire form again.
Form.update({
"dataSources.formDataSources": {"$in": updatedDataSourceIds}
}, {
"$set": {
"dataSources.lastRefresh": params.currentTime
}
}, { multi: true }, function(err) {
if (err) {
return cb(buildErrorResponse({
error: new Error("Error Updating Forms Refresh Fields"),
code: ERROR_CODES.FH_FORMS_UNEXPECTED_ERROR
}));
}
//No error, forms updated, moving on
cb(undefined, validDataSources, invalidDataSources);
});
} | javascript | function updateForms(params, validDataSources, invalidDataSources, cb) {
//Only interested In Data Sources Where Data Was Actually Updated. If the data set is still the same, then no need to mark the form as updated the form.
var dataSoucesUpdated = _.filter(validDataSources, function(dataSourceData) {
return dataSourceData.dataChanged === true;
});
//Updating Any Forms That Reference Updated Data Sources
var updatedDataSourceIds = _.map(dataSoucesUpdated, function(validDataSourceData) {
return validDataSourceData._id;
});
//Need to find and update any forms associated with the data sources.
var Form = models.get(params.connections.mongooseConnection, models.MODELNAMES.FORM);
//Flagging Any Forms That Are Using The Updated Data Sources As Being Updated. This is useful for client/cloud apps that need to determine if they need to load the entire form again.
Form.update({
"dataSources.formDataSources": {"$in": updatedDataSourceIds}
}, {
"$set": {
"dataSources.lastRefresh": params.currentTime
}
}, { multi: true }, function(err) {
if (err) {
return cb(buildErrorResponse({
error: new Error("Error Updating Forms Refresh Fields"),
code: ERROR_CODES.FH_FORMS_UNEXPECTED_ERROR
}));
}
//No error, forms updated, moving on
cb(undefined, validDataSources, invalidDataSources);
});
} | [
"function",
"updateForms",
"(",
"params",
",",
"validDataSources",
",",
"invalidDataSources",
",",
"cb",
")",
"{",
"var",
"dataSoucesUpdated",
"=",
"_",
".",
"filter",
"(",
"validDataSources",
",",
"function",
"(",
"dataSourceData",
")",
"{",
"return",
"dataSourceData",
".",
"dataChanged",
"===",
"true",
";",
"}",
")",
";",
"var",
"updatedDataSourceIds",
"=",
"_",
".",
"map",
"(",
"dataSoucesUpdated",
",",
"function",
"(",
"validDataSourceData",
")",
"{",
"return",
"validDataSourceData",
".",
"_id",
";",
"}",
")",
";",
"var",
"Form",
"=",
"models",
".",
"get",
"(",
"params",
".",
"connections",
".",
"mongooseConnection",
",",
"models",
".",
"MODELNAMES",
".",
"FORM",
")",
";",
"Form",
".",
"update",
"(",
"{",
"\"dataSources.formDataSources\"",
":",
"{",
"\"$in\"",
":",
"updatedDataSourceIds",
"}",
"}",
",",
"{",
"\"$set\"",
":",
"{",
"\"dataSources.lastRefresh\"",
":",
"params",
".",
"currentTime",
"}",
"}",
",",
"{",
"multi",
":",
"true",
"}",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"cb",
"(",
"buildErrorResponse",
"(",
"{",
"error",
":",
"new",
"Error",
"(",
"\"Error Updating Forms Refresh Fields\"",
")",
",",
"code",
":",
"ERROR_CODES",
".",
"FH_FORMS_UNEXPECTED_ERROR",
"}",
")",
")",
";",
"}",
"cb",
"(",
"undefined",
",",
"validDataSources",
",",
"invalidDataSources",
")",
";",
"}",
")",
";",
"}"
] | Updating All Forms Associated With Valid Data Source Updates
@param params
- currentTime
- connections
@param validDataSources
@param invalidDataSources
@param cb | [
"Updating",
"All",
"Forms",
"Associated",
"With",
"Valid",
"Data",
"Source",
"Updates"
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/dataSources/updateCache.js#L173-L205 | train |
feedhenry/fh-forms | lib/impl/dataSources/updateCache.js | saveAuditLogEntryAndUpdateDataSource | function saveAuditLogEntryAndUpdateDataSource(params, callback) {
var cacheElement = params.cacheElement;
var dataSourceDocument = params.dataSourceDocument;
var dataSourceData = params.dataSourceData;
async.waterfall([
function saveAuditLog(cb) {
//An Audit Log Entry Is Based On The Cache Update Entry.
var auditLogEntry = cacheElement.toJSON();
//Adding Service Details To The Audit Log Entry
_.extend(auditLogEntry, _.pick(dataSourceDocument, "serviceGuid", "endpoint"));
//Adding the audit log
var AuditLog = models.get(params.connections.mongooseConnection, models.MODELNAMES.DATA_SOURCE_AUDIT_LOG);
auditLogEntry.dataSource = dataSourceDocument._id;
var auditLogToSave = new AuditLog(auditLogEntry);
auditLogToSave.save(function(err, savedAuditLog) {
if (err) {
return cb(err);
}
dataSourceDocument.auditLogs.push(savedAuditLog);
return cb();
});
},
function saveDataSource(cb) {
//Having Attempted To Save, the updated data source has to be validated again to clear old validation errors before trying to save again.
dataSourceDocument.validate(function() {
//Data Source Data Is Now valid, can save it - whether it is in an error state or not.
dataSourceDocument.save(function(err) {
if (err) {
dataSourceData.error = buildErrorResponse({
error: err,
userDetail: "Unexpected Error When Saving Data Source Data",
code: ERROR_CODES.FH_FORMS_UNEXPECTED_ERROR
});
logger.error("Error Updating Data Source ", {error: dataSourceData.error, dataSourceDocument: dataSourceDocument, cache: dataSourceDocument.cache[0]});
//Not interested in the document if the save is invalid
dataSourceData = _.omit(dataSourceData, 'document');
return cb(undefined, dataSourceData);
}
logger.debug("updateDataSourceEntry: Finished Updating Data Source", dataSourceDocument);
//Save Was Successful, return updated document
dataSourceData.document = dataSourceDocument;
return cb(undefined, dataSourceData);
});
});
}
], callback);
} | javascript | function saveAuditLogEntryAndUpdateDataSource(params, callback) {
var cacheElement = params.cacheElement;
var dataSourceDocument = params.dataSourceDocument;
var dataSourceData = params.dataSourceData;
async.waterfall([
function saveAuditLog(cb) {
//An Audit Log Entry Is Based On The Cache Update Entry.
var auditLogEntry = cacheElement.toJSON();
//Adding Service Details To The Audit Log Entry
_.extend(auditLogEntry, _.pick(dataSourceDocument, "serviceGuid", "endpoint"));
//Adding the audit log
var AuditLog = models.get(params.connections.mongooseConnection, models.MODELNAMES.DATA_SOURCE_AUDIT_LOG);
auditLogEntry.dataSource = dataSourceDocument._id;
var auditLogToSave = new AuditLog(auditLogEntry);
auditLogToSave.save(function(err, savedAuditLog) {
if (err) {
return cb(err);
}
dataSourceDocument.auditLogs.push(savedAuditLog);
return cb();
});
},
function saveDataSource(cb) {
//Having Attempted To Save, the updated data source has to be validated again to clear old validation errors before trying to save again.
dataSourceDocument.validate(function() {
//Data Source Data Is Now valid, can save it - whether it is in an error state or not.
dataSourceDocument.save(function(err) {
if (err) {
dataSourceData.error = buildErrorResponse({
error: err,
userDetail: "Unexpected Error When Saving Data Source Data",
code: ERROR_CODES.FH_FORMS_UNEXPECTED_ERROR
});
logger.error("Error Updating Data Source ", {error: dataSourceData.error, dataSourceDocument: dataSourceDocument, cache: dataSourceDocument.cache[0]});
//Not interested in the document if the save is invalid
dataSourceData = _.omit(dataSourceData, 'document');
return cb(undefined, dataSourceData);
}
logger.debug("updateDataSourceEntry: Finished Updating Data Source", dataSourceDocument);
//Save Was Successful, return updated document
dataSourceData.document = dataSourceDocument;
return cb(undefined, dataSourceData);
});
});
}
], callback);
} | [
"function",
"saveAuditLogEntryAndUpdateDataSource",
"(",
"params",
",",
"callback",
")",
"{",
"var",
"cacheElement",
"=",
"params",
".",
"cacheElement",
";",
"var",
"dataSourceDocument",
"=",
"params",
".",
"dataSourceDocument",
";",
"var",
"dataSourceData",
"=",
"params",
".",
"dataSourceData",
";",
"async",
".",
"waterfall",
"(",
"[",
"function",
"saveAuditLog",
"(",
"cb",
")",
"{",
"var",
"auditLogEntry",
"=",
"cacheElement",
".",
"toJSON",
"(",
")",
";",
"_",
".",
"extend",
"(",
"auditLogEntry",
",",
"_",
".",
"pick",
"(",
"dataSourceDocument",
",",
"\"serviceGuid\"",
",",
"\"endpoint\"",
")",
")",
";",
"var",
"AuditLog",
"=",
"models",
".",
"get",
"(",
"params",
".",
"connections",
".",
"mongooseConnection",
",",
"models",
".",
"MODELNAMES",
".",
"DATA_SOURCE_AUDIT_LOG",
")",
";",
"auditLogEntry",
".",
"dataSource",
"=",
"dataSourceDocument",
".",
"_id",
";",
"var",
"auditLogToSave",
"=",
"new",
"AuditLog",
"(",
"auditLogEntry",
")",
";",
"auditLogToSave",
".",
"save",
"(",
"function",
"(",
"err",
",",
"savedAuditLog",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"cb",
"(",
"err",
")",
";",
"}",
"dataSourceDocument",
".",
"auditLogs",
".",
"push",
"(",
"savedAuditLog",
")",
";",
"return",
"cb",
"(",
")",
";",
"}",
")",
";",
"}",
",",
"function",
"saveDataSource",
"(",
"cb",
")",
"{",
"dataSourceDocument",
".",
"validate",
"(",
"function",
"(",
")",
"{",
"dataSourceDocument",
".",
"save",
"(",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"dataSourceData",
".",
"error",
"=",
"buildErrorResponse",
"(",
"{",
"error",
":",
"err",
",",
"userDetail",
":",
"\"Unexpected Error When Saving Data Source Data\"",
",",
"code",
":",
"ERROR_CODES",
".",
"FH_FORMS_UNEXPECTED_ERROR",
"}",
")",
";",
"logger",
".",
"error",
"(",
"\"Error Updating Data Source \"",
",",
"{",
"error",
":",
"dataSourceData",
".",
"error",
",",
"dataSourceDocument",
":",
"dataSourceDocument",
",",
"cache",
":",
"dataSourceDocument",
".",
"cache",
"[",
"0",
"]",
"}",
")",
";",
"dataSourceData",
"=",
"_",
".",
"omit",
"(",
"dataSourceData",
",",
"'document'",
")",
";",
"return",
"cb",
"(",
"undefined",
",",
"dataSourceData",
")",
";",
"}",
"logger",
".",
"debug",
"(",
"\"updateDataSourceEntry: Finished Updating Data Source\"",
",",
"dataSourceDocument",
")",
";",
"dataSourceData",
".",
"document",
"=",
"dataSourceDocument",
";",
"return",
"cb",
"(",
"undefined",
",",
"dataSourceData",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}",
"]",
",",
"callback",
")",
";",
"}"
] | Saving The Updated Data Source and Updating The Audit Log.
@param params
@param params.cacheElement - Cache Element Being Updated
@param params.dataSourceDocument - The Mongoose Data Source Document
@param params.dataSourceData - The Data Source Data To Be Updated
@param params.connections.mongooseConnection - The Mongoose Connection
@param callback | [
"Saving",
"The",
"Updated",
"Data",
"Source",
"and",
"Updating",
"The",
"Audit",
"Log",
"."
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/dataSources/updateCache.js#L216-L274 | train |
feedhenry/fh-forms | lib/impl/dataSources/updateCache.js | updateDataSourceEntry | function updateDataSourceEntry(params, dataSourceData, callback) {
var dataToUpdate = dataSourceData.data;
var dataSourceDocument = dataSourceData.document;
logger.debug("updateDataSourceEntry ", params, dataSourceData);
//If there is no cache entry, create a new one to validate.
var cacheElement = dataSourceDocument.cache[0];
if (!cacheElement) {
dataSourceDocument.cache.push({});
}
cacheElement = dataSourceDocument.cache[0];
//Assigning the last attempt to update the data source
cacheElement.updateTimestamp = params.currentTime;
var existingData = cacheElement.data;
var existingHash = cacheElement.dataHash;
logger.debug("updateDataSourceEntry ", {dataToUpdate: dataToUpdate, cacheElement: cacheElement, existingData: existingData, existingHash: existingHash});
if (dataSourceData.dataError || dataSourceData.error) {
cacheElement.currentStatus = {
status: "error",
error: dataSourceData.dataError || dataSourceData.error
};
} else if (dataSourceData.dataHash !== cacheElement.dataHash) {
//If the hashes are different, need to update the data set and hash
cacheElement.data = dataToUpdate;
cacheElement.dataHash = dataSourceData.dataHash;
dataSourceData.dataChanged = true;
}
logger.debug("updateDataSourceEntry ", {cacheElementBeforeValidation: cacheElement});
async.waterfall([
function validateDataPassed(cb) {
//Validating That the Data That Was Passed is correct.
dataSourceDocument.save(function(err) {
if (err) {
logger.warn("Error Validating Data Source ", {error: err});
//Not Valid, don't try to save it, mark it as an error state
dataSourceData.error = buildErrorResponse({
error: err,
userDetail: "Invalid Data For Cache Update.",
systemDetail: err.message,
code: ERROR_CODES.FH_FORMS_INVALID_PARAMETERS
});
//If there is a validation error, save it with the exiting data set Data Source for viewing later.
cacheElement.data = existingData ? existingData : [];
cacheElement.dataHash = existingHash;
cacheElement.currentStatus = {
status: "error",
error: dataSourceData.error
};
}
if (!dataSourceData.error && !dataSourceData.dataError) {
//marking the status as ok.
cacheElement.currentStatus = {
status: "ok",
error: null
};
//Resetting the backOffIndex as it is a valid Data Source update.
cacheElement.backOffIndex = 0;
cacheElement.markModified('currentStatus');
} else {
//The data source encountered an error. Increment the backOffIndex.
cacheElement.backOffIndex = cacheElement.backOffIndex ? cacheElement.backOffIndex + 1 : 1;
}
//Mark The Submission As Refreshed
cacheElement.lastRefreshed = params.currentTime;
logger.debug("updateDataSourceEntry ", {cacheElementAfterValidate: cacheElement});
cb();
});
},
async.apply(saveAuditLogEntryAndUpdateDataSource, _.extend({
cacheElement: cacheElement,
dataSourceDocument: dataSourceDocument,
dataSourceData: dataSourceData
}, params))
], callback);
} | javascript | function updateDataSourceEntry(params, dataSourceData, callback) {
var dataToUpdate = dataSourceData.data;
var dataSourceDocument = dataSourceData.document;
logger.debug("updateDataSourceEntry ", params, dataSourceData);
//If there is no cache entry, create a new one to validate.
var cacheElement = dataSourceDocument.cache[0];
if (!cacheElement) {
dataSourceDocument.cache.push({});
}
cacheElement = dataSourceDocument.cache[0];
//Assigning the last attempt to update the data source
cacheElement.updateTimestamp = params.currentTime;
var existingData = cacheElement.data;
var existingHash = cacheElement.dataHash;
logger.debug("updateDataSourceEntry ", {dataToUpdate: dataToUpdate, cacheElement: cacheElement, existingData: existingData, existingHash: existingHash});
if (dataSourceData.dataError || dataSourceData.error) {
cacheElement.currentStatus = {
status: "error",
error: dataSourceData.dataError || dataSourceData.error
};
} else if (dataSourceData.dataHash !== cacheElement.dataHash) {
//If the hashes are different, need to update the data set and hash
cacheElement.data = dataToUpdate;
cacheElement.dataHash = dataSourceData.dataHash;
dataSourceData.dataChanged = true;
}
logger.debug("updateDataSourceEntry ", {cacheElementBeforeValidation: cacheElement});
async.waterfall([
function validateDataPassed(cb) {
//Validating That the Data That Was Passed is correct.
dataSourceDocument.save(function(err) {
if (err) {
logger.warn("Error Validating Data Source ", {error: err});
//Not Valid, don't try to save it, mark it as an error state
dataSourceData.error = buildErrorResponse({
error: err,
userDetail: "Invalid Data For Cache Update.",
systemDetail: err.message,
code: ERROR_CODES.FH_FORMS_INVALID_PARAMETERS
});
//If there is a validation error, save it with the exiting data set Data Source for viewing later.
cacheElement.data = existingData ? existingData : [];
cacheElement.dataHash = existingHash;
cacheElement.currentStatus = {
status: "error",
error: dataSourceData.error
};
}
if (!dataSourceData.error && !dataSourceData.dataError) {
//marking the status as ok.
cacheElement.currentStatus = {
status: "ok",
error: null
};
//Resetting the backOffIndex as it is a valid Data Source update.
cacheElement.backOffIndex = 0;
cacheElement.markModified('currentStatus');
} else {
//The data source encountered an error. Increment the backOffIndex.
cacheElement.backOffIndex = cacheElement.backOffIndex ? cacheElement.backOffIndex + 1 : 1;
}
//Mark The Submission As Refreshed
cacheElement.lastRefreshed = params.currentTime;
logger.debug("updateDataSourceEntry ", {cacheElementAfterValidate: cacheElement});
cb();
});
},
async.apply(saveAuditLogEntryAndUpdateDataSource, _.extend({
cacheElement: cacheElement,
dataSourceDocument: dataSourceDocument,
dataSourceData: dataSourceData
}, params))
], callback);
} | [
"function",
"updateDataSourceEntry",
"(",
"params",
",",
"dataSourceData",
",",
"callback",
")",
"{",
"var",
"dataToUpdate",
"=",
"dataSourceData",
".",
"data",
";",
"var",
"dataSourceDocument",
"=",
"dataSourceData",
".",
"document",
";",
"logger",
".",
"debug",
"(",
"\"updateDataSourceEntry \"",
",",
"params",
",",
"dataSourceData",
")",
";",
"var",
"cacheElement",
"=",
"dataSourceDocument",
".",
"cache",
"[",
"0",
"]",
";",
"if",
"(",
"!",
"cacheElement",
")",
"{",
"dataSourceDocument",
".",
"cache",
".",
"push",
"(",
"{",
"}",
")",
";",
"}",
"cacheElement",
"=",
"dataSourceDocument",
".",
"cache",
"[",
"0",
"]",
";",
"cacheElement",
".",
"updateTimestamp",
"=",
"params",
".",
"currentTime",
";",
"var",
"existingData",
"=",
"cacheElement",
".",
"data",
";",
"var",
"existingHash",
"=",
"cacheElement",
".",
"dataHash",
";",
"logger",
".",
"debug",
"(",
"\"updateDataSourceEntry \"",
",",
"{",
"dataToUpdate",
":",
"dataToUpdate",
",",
"cacheElement",
":",
"cacheElement",
",",
"existingData",
":",
"existingData",
",",
"existingHash",
":",
"existingHash",
"}",
")",
";",
"if",
"(",
"dataSourceData",
".",
"dataError",
"||",
"dataSourceData",
".",
"error",
")",
"{",
"cacheElement",
".",
"currentStatus",
"=",
"{",
"status",
":",
"\"error\"",
",",
"error",
":",
"dataSourceData",
".",
"dataError",
"||",
"dataSourceData",
".",
"error",
"}",
";",
"}",
"else",
"if",
"(",
"dataSourceData",
".",
"dataHash",
"!==",
"cacheElement",
".",
"dataHash",
")",
"{",
"cacheElement",
".",
"data",
"=",
"dataToUpdate",
";",
"cacheElement",
".",
"dataHash",
"=",
"dataSourceData",
".",
"dataHash",
";",
"dataSourceData",
".",
"dataChanged",
"=",
"true",
";",
"}",
"logger",
".",
"debug",
"(",
"\"updateDataSourceEntry \"",
",",
"{",
"cacheElementBeforeValidation",
":",
"cacheElement",
"}",
")",
";",
"async",
".",
"waterfall",
"(",
"[",
"function",
"validateDataPassed",
"(",
"cb",
")",
"{",
"dataSourceDocument",
".",
"save",
"(",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"logger",
".",
"warn",
"(",
"\"Error Validating Data Source \"",
",",
"{",
"error",
":",
"err",
"}",
")",
";",
"dataSourceData",
".",
"error",
"=",
"buildErrorResponse",
"(",
"{",
"error",
":",
"err",
",",
"userDetail",
":",
"\"Invalid Data For Cache Update.\"",
",",
"systemDetail",
":",
"err",
".",
"message",
",",
"code",
":",
"ERROR_CODES",
".",
"FH_FORMS_INVALID_PARAMETERS",
"}",
")",
";",
"cacheElement",
".",
"data",
"=",
"existingData",
"?",
"existingData",
":",
"[",
"]",
";",
"cacheElement",
".",
"dataHash",
"=",
"existingHash",
";",
"cacheElement",
".",
"currentStatus",
"=",
"{",
"status",
":",
"\"error\"",
",",
"error",
":",
"dataSourceData",
".",
"error",
"}",
";",
"}",
"if",
"(",
"!",
"dataSourceData",
".",
"error",
"&&",
"!",
"dataSourceData",
".",
"dataError",
")",
"{",
"cacheElement",
".",
"currentStatus",
"=",
"{",
"status",
":",
"\"ok\"",
",",
"error",
":",
"null",
"}",
";",
"cacheElement",
".",
"backOffIndex",
"=",
"0",
";",
"cacheElement",
".",
"markModified",
"(",
"'currentStatus'",
")",
";",
"}",
"else",
"{",
"cacheElement",
".",
"backOffIndex",
"=",
"cacheElement",
".",
"backOffIndex",
"?",
"cacheElement",
".",
"backOffIndex",
"+",
"1",
":",
"1",
";",
"}",
"cacheElement",
".",
"lastRefreshed",
"=",
"params",
".",
"currentTime",
";",
"logger",
".",
"debug",
"(",
"\"updateDataSourceEntry \"",
",",
"{",
"cacheElementAfterValidate",
":",
"cacheElement",
"}",
")",
";",
"cb",
"(",
")",
";",
"}",
")",
";",
"}",
",",
"async",
".",
"apply",
"(",
"saveAuditLogEntryAndUpdateDataSource",
",",
"_",
".",
"extend",
"(",
"{",
"cacheElement",
":",
"cacheElement",
",",
"dataSourceDocument",
":",
"dataSourceDocument",
",",
"dataSourceData",
":",
"dataSourceData",
"}",
",",
"params",
")",
")",
"]",
",",
"callback",
")",
";",
"}"
] | Update A Single Data Source Data Entry.
@param params
- currentTime
@param dataSourceData
@param callback | [
"Update",
"A",
"Single",
"Data",
"Source",
"Data",
"Entry",
"."
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/dataSources/updateCache.js#L284-L372 | train |
feedhenry/fh-forms | lib/impl/dataSources/updateCache.js | prepareResponse | function prepareResponse(validDataSources, invalidDataSources, cb) {
//There Were Errors Updating Data Sources, should return an error
logger.debug("prepareResponse Before", validDataSources);
//For The Valid Data Sources, Just want the updated Document JSON
validDataSources = _.map(validDataSources, function(validDataSourceData) {
return processDataSourceResponse(validDataSourceData.document.toJSON());
});
logger.debug("prepareResponse After", validDataSources);
var returnError;
if (invalidDataSources.length > 0) {
returnError = buildErrorResponse({
error: new Error("Error Updating Data Sources"),
code: ERROR_CODES.FH_FORMS_UNEXPECTED_ERROR
});
}
return cb(returnError, {
validDataSourceUpdates: validDataSources,
invalidDataSourceUpdates: invalidDataSources
});
} | javascript | function prepareResponse(validDataSources, invalidDataSources, cb) {
//There Were Errors Updating Data Sources, should return an error
logger.debug("prepareResponse Before", validDataSources);
//For The Valid Data Sources, Just want the updated Document JSON
validDataSources = _.map(validDataSources, function(validDataSourceData) {
return processDataSourceResponse(validDataSourceData.document.toJSON());
});
logger.debug("prepareResponse After", validDataSources);
var returnError;
if (invalidDataSources.length > 0) {
returnError = buildErrorResponse({
error: new Error("Error Updating Data Sources"),
code: ERROR_CODES.FH_FORMS_UNEXPECTED_ERROR
});
}
return cb(returnError, {
validDataSourceUpdates: validDataSources,
invalidDataSourceUpdates: invalidDataSources
});
} | [
"function",
"prepareResponse",
"(",
"validDataSources",
",",
"invalidDataSources",
",",
"cb",
")",
"{",
"logger",
".",
"debug",
"(",
"\"prepareResponse Before\"",
",",
"validDataSources",
")",
";",
"validDataSources",
"=",
"_",
".",
"map",
"(",
"validDataSources",
",",
"function",
"(",
"validDataSourceData",
")",
"{",
"return",
"processDataSourceResponse",
"(",
"validDataSourceData",
".",
"document",
".",
"toJSON",
"(",
")",
")",
";",
"}",
")",
";",
"logger",
".",
"debug",
"(",
"\"prepareResponse After\"",
",",
"validDataSources",
")",
";",
"var",
"returnError",
";",
"if",
"(",
"invalidDataSources",
".",
"length",
">",
"0",
")",
"{",
"returnError",
"=",
"buildErrorResponse",
"(",
"{",
"error",
":",
"new",
"Error",
"(",
"\"Error Updating Data Sources\"",
")",
",",
"code",
":",
"ERROR_CODES",
".",
"FH_FORMS_UNEXPECTED_ERROR",
"}",
")",
";",
"}",
"return",
"cb",
"(",
"returnError",
",",
"{",
"validDataSourceUpdates",
":",
"validDataSources",
",",
"invalidDataSourceUpdates",
":",
"invalidDataSources",
"}",
")",
";",
"}"
] | Preparing The JSON Response For The Data Source Cache Update.
@param validDataSources
@param invalidDataSources
@param cb
@returns {*} | [
"Preparing",
"The",
"JSON",
"Response",
"For",
"The",
"Data",
"Source",
"Cache",
"Update",
"."
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/dataSources/updateCache.js#L381-L404 | train |
feedhenry/fh-forms | lib/impl/getForms.js | getSubmissionStorage | function getSubmissionStorage(cb) {
//If no stats are required, don't try and do the map-reduce operation.
if (options.notStats) {
return cb();
}
// NOTE: this function executes in MongoDB rather than Node.js
//Need a map-reduce operation to count the files, otherwise would have to load all submissions into memory which is bad.
var mapFileSizesFunction = function() {
var key = this.formId;
var formFields = this.formFields || [];
//Iterating over all form fields
for (var formFieldIdx = 0; formFieldIdx < formFields.length; formFieldIdx++) {
var formField = formFields[formFieldIdx];
var fieldValues = formField.fieldValues || [];
//Iterating over all of the field values
for (var fieldValueIdx = 0 ; fieldValueIdx < fieldValues.length ; fieldValueIdx++) {
var fieldValue = fieldValues[fieldValueIdx] || {};
//If the value has a file size associated with it, then emit that file size
if (fieldValue.fileSize) {
emit(key, fieldValue.fileSize); // eslint-disable-line no-undef
}
}
}
};
// NOTE: this function executes in MongoDB rather than Node.js
//Function to sum up all of the file sizes for each submission
var reduceFileSizesFunction = function(formId, fileSizes) {
var totalFileSizes = 0;
for (var fileSizeIdx = 0; fileSizeIdx < fileSizes.length ; fileSizeIdx++) {
totalFileSizes += fileSizes[fileSizeIdx];
}
return totalFileSizes;
};
logger.debug("getSubmissionStorage", {options: options});
Promise.race([
// Don't wait longer than 30 seconds for mongodb mapReduce.
// Note that it should still complete, but if it's not back in
// 30 seconds, we continue without it.
new Promise(resolve => setTimeout(resolve, 30000)),
//Map-Reduce Operation to count the file sizes.
connections.databaseConnection.collection('formsubmissions').mapReduce(mapFileSizesFunction, reduceFileSizesFunction, {out : {inline: 1}, verbose:true})
])
.then(out => {
fileSizesByForm = out && out.results ? out.results : [];
return cb();
})
.catch(err => {
//If there are no submissions, then the collection does not
//exist. No need to error out of the request.
if (err.message.indexOf("ns doesn't exist") > -1) {
return cb();
} else {
return cb(err);
}
});
} | javascript | function getSubmissionStorage(cb) {
//If no stats are required, don't try and do the map-reduce operation.
if (options.notStats) {
return cb();
}
// NOTE: this function executes in MongoDB rather than Node.js
//Need a map-reduce operation to count the files, otherwise would have to load all submissions into memory which is bad.
var mapFileSizesFunction = function() {
var key = this.formId;
var formFields = this.formFields || [];
//Iterating over all form fields
for (var formFieldIdx = 0; formFieldIdx < formFields.length; formFieldIdx++) {
var formField = formFields[formFieldIdx];
var fieldValues = formField.fieldValues || [];
//Iterating over all of the field values
for (var fieldValueIdx = 0 ; fieldValueIdx < fieldValues.length ; fieldValueIdx++) {
var fieldValue = fieldValues[fieldValueIdx] || {};
//If the value has a file size associated with it, then emit that file size
if (fieldValue.fileSize) {
emit(key, fieldValue.fileSize); // eslint-disable-line no-undef
}
}
}
};
// NOTE: this function executes in MongoDB rather than Node.js
//Function to sum up all of the file sizes for each submission
var reduceFileSizesFunction = function(formId, fileSizes) {
var totalFileSizes = 0;
for (var fileSizeIdx = 0; fileSizeIdx < fileSizes.length ; fileSizeIdx++) {
totalFileSizes += fileSizes[fileSizeIdx];
}
return totalFileSizes;
};
logger.debug("getSubmissionStorage", {options: options});
Promise.race([
// Don't wait longer than 30 seconds for mongodb mapReduce.
// Note that it should still complete, but if it's not back in
// 30 seconds, we continue without it.
new Promise(resolve => setTimeout(resolve, 30000)),
//Map-Reduce Operation to count the file sizes.
connections.databaseConnection.collection('formsubmissions').mapReduce(mapFileSizesFunction, reduceFileSizesFunction, {out : {inline: 1}, verbose:true})
])
.then(out => {
fileSizesByForm = out && out.results ? out.results : [];
return cb();
})
.catch(err => {
//If there are no submissions, then the collection does not
//exist. No need to error out of the request.
if (err.message.indexOf("ns doesn't exist") > -1) {
return cb();
} else {
return cb(err);
}
});
} | [
"function",
"getSubmissionStorage",
"(",
"cb",
")",
"{",
"if",
"(",
"options",
".",
"notStats",
")",
"{",
"return",
"cb",
"(",
")",
";",
"}",
"var",
"mapFileSizesFunction",
"=",
"function",
"(",
")",
"{",
"var",
"key",
"=",
"this",
".",
"formId",
";",
"var",
"formFields",
"=",
"this",
".",
"formFields",
"||",
"[",
"]",
";",
"for",
"(",
"var",
"formFieldIdx",
"=",
"0",
";",
"formFieldIdx",
"<",
"formFields",
".",
"length",
";",
"formFieldIdx",
"++",
")",
"{",
"var",
"formField",
"=",
"formFields",
"[",
"formFieldIdx",
"]",
";",
"var",
"fieldValues",
"=",
"formField",
".",
"fieldValues",
"||",
"[",
"]",
";",
"for",
"(",
"var",
"fieldValueIdx",
"=",
"0",
";",
"fieldValueIdx",
"<",
"fieldValues",
".",
"length",
";",
"fieldValueIdx",
"++",
")",
"{",
"var",
"fieldValue",
"=",
"fieldValues",
"[",
"fieldValueIdx",
"]",
"||",
"{",
"}",
";",
"if",
"(",
"fieldValue",
".",
"fileSize",
")",
"{",
"emit",
"(",
"key",
",",
"fieldValue",
".",
"fileSize",
")",
";",
"}",
"}",
"}",
"}",
";",
"var",
"reduceFileSizesFunction",
"=",
"function",
"(",
"formId",
",",
"fileSizes",
")",
"{",
"var",
"totalFileSizes",
"=",
"0",
";",
"for",
"(",
"var",
"fileSizeIdx",
"=",
"0",
";",
"fileSizeIdx",
"<",
"fileSizes",
".",
"length",
";",
"fileSizeIdx",
"++",
")",
"{",
"totalFileSizes",
"+=",
"fileSizes",
"[",
"fileSizeIdx",
"]",
";",
"}",
"return",
"totalFileSizes",
";",
"}",
";",
"logger",
".",
"debug",
"(",
"\"getSubmissionStorage\"",
",",
"{",
"options",
":",
"options",
"}",
")",
";",
"Promise",
".",
"race",
"(",
"[",
"new",
"Promise",
"(",
"resolve",
"=>",
"setTimeout",
"(",
"resolve",
",",
"30000",
")",
")",
",",
"connections",
".",
"databaseConnection",
".",
"collection",
"(",
"'formsubmissions'",
")",
".",
"mapReduce",
"(",
"mapFileSizesFunction",
",",
"reduceFileSizesFunction",
",",
"{",
"out",
":",
"{",
"inline",
":",
"1",
"}",
",",
"verbose",
":",
"true",
"}",
")",
"]",
")",
".",
"then",
"(",
"out",
"=>",
"{",
"fileSizesByForm",
"=",
"out",
"&&",
"out",
".",
"results",
"?",
"out",
".",
"results",
":",
"[",
"]",
";",
"return",
"cb",
"(",
")",
";",
"}",
")",
".",
"catch",
"(",
"err",
"=>",
"{",
"if",
"(",
"err",
".",
"message",
".",
"indexOf",
"(",
"\"ns doesn't exist\"",
")",
">",
"-",
"1",
")",
"{",
"return",
"cb",
"(",
")",
";",
"}",
"else",
"{",
"return",
"cb",
"(",
"err",
")",
";",
"}",
"}",
")",
";",
"}"
] | Function for getting the current submission storage.
Submission Storage = formsubmissions + fileStorage.chunks + fileStorage.files | [
"Function",
"for",
"getting",
"the",
"current",
"submission",
"storage",
"."
] | 87df586b9589e3c636e1e607163862cfb64872dd | https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/getForms.js#L57-L126 | train |
cloudfour/drizzle-builder | src/utils/object.js | deepObj | function deepObj(pathKeys, obj, createEntries = true) {
return pathKeys.reduce((prev, curr) => {
if (typeof prev[curr] === 'undefined') {
if (createEntries) {
prev[curr] = {};
} else {
DrizzleError.error(
new DrizzleError(
`Property ${curr} not found on supplied object`,
DrizzleError.LEVELS.ERROR
)
);
}
}
return prev[curr];
}, obj);
} | javascript | function deepObj(pathKeys, obj, createEntries = true) {
return pathKeys.reduce((prev, curr) => {
if (typeof prev[curr] === 'undefined') {
if (createEntries) {
prev[curr] = {};
} else {
DrizzleError.error(
new DrizzleError(
`Property ${curr} not found on supplied object`,
DrizzleError.LEVELS.ERROR
)
);
}
}
return prev[curr];
}, obj);
} | [
"function",
"deepObj",
"(",
"pathKeys",
",",
"obj",
",",
"createEntries",
"=",
"true",
")",
"{",
"return",
"pathKeys",
".",
"reduce",
"(",
"(",
"prev",
",",
"curr",
")",
"=>",
"{",
"if",
"(",
"typeof",
"prev",
"[",
"curr",
"]",
"===",
"'undefined'",
")",
"{",
"if",
"(",
"createEntries",
")",
"{",
"prev",
"[",
"curr",
"]",
"=",
"{",
"}",
";",
"}",
"else",
"{",
"DrizzleError",
".",
"error",
"(",
"new",
"DrizzleError",
"(",
"`",
"${",
"curr",
"}",
"`",
",",
"DrizzleError",
".",
"LEVELS",
".",
"ERROR",
")",
")",
";",
"}",
"}",
"return",
"prev",
"[",
"curr",
"]",
";",
"}",
",",
"obj",
")",
";",
"}"
] | Return a reference to the deeply-nested object indicated by the items
in `pathKeys`. If `createEntries`, entry levels will be created as needed
if they don't yet exist on `obj`.
@param {Array} pathKeys Elements making up the "path" to the reference
@param {Object} Object to add needed references to
@example deepRef(['foo', 'bar', 'baz'], { foo: {} }, true); // => foo.bar.baz | [
"Return",
"a",
"reference",
"to",
"the",
"deeply",
"-",
"nested",
"object",
"indicated",
"by",
"the",
"items",
"in",
"pathKeys",
".",
"If",
"createEntries",
"entry",
"levels",
"will",
"be",
"created",
"as",
"needed",
"if",
"they",
"don",
"t",
"yet",
"exist",
"on",
"obj",
"."
] | 1c320cb059c749c28339a661d1768d3a643e5f1c | https://github.com/cloudfour/drizzle-builder/blob/1c320cb059c749c28339a661d1768d3a643e5f1c/src/utils/object.js#L16-L32 | train |
cloudfour/drizzle-builder | src/utils/object.js | deepCollection | function deepCollection(collectionId, obj) {
const pathBits = idKeys(collectionId);
pathBits.pop();
pathBits.push('collection');
pathBits.shift();
return deepObj(pathBits, obj, false);
} | javascript | function deepCollection(collectionId, obj) {
const pathBits = idKeys(collectionId);
pathBits.pop();
pathBits.push('collection');
pathBits.shift();
return deepObj(pathBits, obj, false);
} | [
"function",
"deepCollection",
"(",
"collectionId",
",",
"obj",
")",
"{",
"const",
"pathBits",
"=",
"idKeys",
"(",
"collectionId",
")",
";",
"pathBits",
".",
"pop",
"(",
")",
";",
"pathBits",
".",
"push",
"(",
"'collection'",
")",
";",
"pathBits",
".",
"shift",
"(",
")",
";",
"return",
"deepObj",
"(",
"pathBits",
",",
"obj",
",",
"false",
")",
";",
"}"
] | Given a nested pattern `obj` and a `patternId`, find its collection
in the object `obj`.
@see deepPattern | [
"Given",
"a",
"nested",
"pattern",
"obj",
"and",
"a",
"patternId",
"find",
"its",
"collection",
"in",
"the",
"object",
"obj",
"."
] | 1c320cb059c749c28339a661d1768d3a643e5f1c | https://github.com/cloudfour/drizzle-builder/blob/1c320cb059c749c28339a661d1768d3a643e5f1c/src/utils/object.js#L57-L63 | train |
cloudfour/drizzle-builder | src/utils/object.js | isObject | function isObject(obj) {
const objType = typeof obj;
return objType === 'object' && Boolean(obj) && !Array.isArray(obj);
} | javascript | function isObject(obj) {
const objType = typeof obj;
return objType === 'object' && Boolean(obj) && !Array.isArray(obj);
} | [
"function",
"isObject",
"(",
"obj",
")",
"{",
"const",
"objType",
"=",
"typeof",
"obj",
";",
"return",
"objType",
"===",
"'object'",
"&&",
"Boolean",
"(",
"obj",
")",
"&&",
"!",
"Array",
".",
"isArray",
"(",
"obj",
")",
";",
"}"
] | IsObject function opinionated against Arrays
@param {Obj}
@return {Boolean} | [
"IsObject",
"function",
"opinionated",
"against",
"Arrays"
] | 1c320cb059c749c28339a661d1768d3a643e5f1c | https://github.com/cloudfour/drizzle-builder/blob/1c320cb059c749c28339a661d1768d3a643e5f1c/src/utils/object.js#L70-L73 | train |
cloudfour/drizzle-builder | src/utils/object.js | flattenById | function flattenById(obj, keyedObj = {}) {
if (obj.hasOwnProperty('id')) {
keyedObj[obj.id] = obj;
}
for (var key in obj) {
if (isObject(obj[key])) {
flattenById(obj[key], keyedObj);
}
}
return keyedObj;
} | javascript | function flattenById(obj, keyedObj = {}) {
if (obj.hasOwnProperty('id')) {
keyedObj[obj.id] = obj;
}
for (var key in obj) {
if (isObject(obj[key])) {
flattenById(obj[key], keyedObj);
}
}
return keyedObj;
} | [
"function",
"flattenById",
"(",
"obj",
",",
"keyedObj",
"=",
"{",
"}",
")",
"{",
"if",
"(",
"obj",
".",
"hasOwnProperty",
"(",
"'id'",
")",
")",
"{",
"keyedObj",
"[",
"obj",
".",
"id",
"]",
"=",
"obj",
";",
"}",
"for",
"(",
"var",
"key",
"in",
"obj",
")",
"{",
"if",
"(",
"isObject",
"(",
"obj",
"[",
"key",
"]",
")",
")",
"{",
"flattenById",
"(",
"obj",
"[",
"key",
"]",
",",
"keyedObj",
")",
";",
"}",
"}",
"return",
"keyedObj",
";",
"}"
] | Take a deeply-nested object and return a single-level object keyed
by the `id` property of original object entries.
@param {Obj} obj
@param {Obj} keyedObj For recursion; not strictly necessary but...
@return {Obj} keyed by ids | [
"Take",
"a",
"deeply",
"-",
"nested",
"object",
"and",
"return",
"a",
"single",
"-",
"level",
"object",
"keyed",
"by",
"the",
"id",
"property",
"of",
"original",
"object",
"entries",
"."
] | 1c320cb059c749c28339a661d1768d3a643e5f1c | https://github.com/cloudfour/drizzle-builder/blob/1c320cb059c749c28339a661d1768d3a643e5f1c/src/utils/object.js#L83-L93 | train |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.