repo
stringlengths 5
67
| path
stringlengths 4
116
| func_name
stringlengths 0
58
| original_string
stringlengths 52
373k
| language
stringclasses 1
value | code
stringlengths 52
373k
| code_tokens
list | docstring
stringlengths 4
11.8k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 86
226
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
stormpath/express-stormpath
|
lib/oauth/error-responder.js
|
oauthErrorResponder
|
function oauthErrorResponder(req, res, err) {
var accepts = req.accepts(['html', 'json']);
var config = req.app.get('stormpathConfig');
if (accepts === 'json') {
return writeJsonError(res, err);
}
return renderLoginFormWithError(req, res, config, err);
}
|
javascript
|
function oauthErrorResponder(req, res, err) {
var accepts = req.accepts(['html', 'json']);
var config = req.app.get('stormpathConfig');
if (accepts === 'json') {
return writeJsonError(res, err);
}
return renderLoginFormWithError(req, res, config, err);
}
|
[
"function",
"oauthErrorResponder",
"(",
"req",
",",
"res",
",",
"err",
")",
"{",
"var",
"accepts",
"=",
"req",
".",
"accepts",
"(",
"[",
"'html'",
",",
"'json'",
"]",
")",
";",
"var",
"config",
"=",
"req",
".",
"app",
".",
"get",
"(",
"'stormpathConfig'",
")",
";",
"if",
"(",
"accepts",
"===",
"'json'",
")",
"{",
"return",
"writeJsonError",
"(",
"res",
",",
"err",
")",
";",
"}",
"return",
"renderLoginFormWithError",
"(",
"req",
",",
"res",
",",
"config",
",",
"err",
")",
";",
"}"
] |
Takes an error object and responds either by
rendering the login form with the error, or
by returning the error as JSON.
@method
@param {Object} req - The http request.
@param {Object} res - The http response.
@param {Object} err - The error to handle.
|
[
"Takes",
"an",
"error",
"object",
"and",
"responds",
"either",
"by",
"rendering",
"the",
"login",
"form",
"with",
"the",
"error",
"or",
"by",
"returning",
"the",
"error",
"as",
"JSON",
"."
] |
aed8d26ba51272755ea4eab706b4417e4bbeed99
|
https://github.com/stormpath/express-stormpath/blob/aed8d26ba51272755ea4eab706b4417e4bbeed99/lib/oauth/error-responder.js#L71-L80
|
train
|
stormpath/express-stormpath
|
lib/controllers/register.js
|
defaultUnverifiedHtmlResponse
|
function defaultUnverifiedHtmlResponse(req, res) {
var config = req.app.get('stormpathConfig');
res.redirect(302, config.web.login.uri + '?status=unverified');
}
|
javascript
|
function defaultUnverifiedHtmlResponse(req, res) {
var config = req.app.get('stormpathConfig');
res.redirect(302, config.web.login.uri + '?status=unverified');
}
|
[
"function",
"defaultUnverifiedHtmlResponse",
"(",
"req",
",",
"res",
")",
"{",
"var",
"config",
"=",
"req",
".",
"app",
".",
"get",
"(",
"'stormpathConfig'",
")",
";",
"res",
".",
"redirect",
"(",
"302",
",",
"config",
".",
"web",
".",
"login",
".",
"uri",
"+",
"'?status=unverified'",
")",
";",
"}"
] |
Delivers the default response for registration attempts that accept an HTML
content type, where the new account is in an unverified state. In this
situation we redirect to the login page with a query parameter that
indidcates that the account is unverified
@function
@param {Object} req - The http request.
@param {Object} res - The http response.
|
[
"Delivers",
"the",
"default",
"response",
"for",
"registration",
"attempts",
"that",
"accept",
"an",
"HTML",
"content",
"type",
"where",
"the",
"new",
"account",
"is",
"in",
"an",
"unverified",
"state",
".",
"In",
"this",
"situation",
"we",
"redirect",
"to",
"the",
"login",
"page",
"with",
"a",
"query",
"parameter",
"that",
"indidcates",
"that",
"the",
"account",
"is",
"unverified"
] |
aed8d26ba51272755ea4eab706b4417e4bbeed99
|
https://github.com/stormpath/express-stormpath/blob/aed8d26ba51272755ea4eab706b4417e4bbeed99/lib/controllers/register.js#L22-L25
|
train
|
stormpath/express-stormpath
|
lib/controllers/register.js
|
defaultAutoAuthorizeHtmlResponse
|
function defaultAutoAuthorizeHtmlResponse(req, res) {
var config = req.app.get('stormpathConfig');
res.redirect(302, url.parse(req.query.next || '').path || config.web.register.nextUri);
}
|
javascript
|
function defaultAutoAuthorizeHtmlResponse(req, res) {
var config = req.app.get('stormpathConfig');
res.redirect(302, url.parse(req.query.next || '').path || config.web.register.nextUri);
}
|
[
"function",
"defaultAutoAuthorizeHtmlResponse",
"(",
"req",
",",
"res",
")",
"{",
"var",
"config",
"=",
"req",
".",
"app",
".",
"get",
"(",
"'stormpathConfig'",
")",
";",
"res",
".",
"redirect",
"(",
"302",
",",
"url",
".",
"parse",
"(",
"req",
".",
"query",
".",
"next",
"||",
"''",
")",
".",
"path",
"||",
"config",
".",
"web",
".",
"register",
".",
"nextUri",
")",
";",
"}"
] |
Delivers the default response for registration attempts that accept an HTML
content type, where the new account is in a verified state and the config
has requested that we automatically log in the user. In this situation we
redirect to the next URI that is in the url, or the nextUri that is defined
on the registration configuration
@function
@param {Object} req - The http request.
@param {Object} res - The http response.
|
[
"Delivers",
"the",
"default",
"response",
"for",
"registration",
"attempts",
"that",
"accept",
"an",
"HTML",
"content",
"type",
"where",
"the",
"new",
"account",
"is",
"in",
"a",
"verified",
"state",
"and",
"the",
"config",
"has",
"requested",
"that",
"we",
"automatically",
"log",
"in",
"the",
"user",
".",
"In",
"this",
"situation",
"we",
"redirect",
"to",
"the",
"next",
"URI",
"that",
"is",
"in",
"the",
"url",
"or",
"the",
"nextUri",
"that",
"is",
"defined",
"on",
"the",
"registration",
"configuration"
] |
aed8d26ba51272755ea4eab706b4417e4bbeed99
|
https://github.com/stormpath/express-stormpath/blob/aed8d26ba51272755ea4eab706b4417e4bbeed99/lib/controllers/register.js#L56-L59
|
train
|
stormpath/express-stormpath
|
lib/controllers/register.js
|
defaultJsonResponse
|
function defaultJsonResponse(req, res) {
res.json({
account: helpers.strippedAccount(req.user)
});
}
|
javascript
|
function defaultJsonResponse(req, res) {
res.json({
account: helpers.strippedAccount(req.user)
});
}
|
[
"function",
"defaultJsonResponse",
"(",
"req",
",",
"res",
")",
"{",
"res",
".",
"json",
"(",
"{",
"account",
":",
"helpers",
".",
"strippedAccount",
"(",
"req",
".",
"user",
")",
"}",
")",
";",
"}"
] |
Delivers the default response for registration attempts that accept a JSON
content type. In this situation we simply return the new account object as
JSON
@function
@param {Object} req - The http request.
@param {Object} res - The http response.
|
[
"Delivers",
"the",
"default",
"response",
"for",
"registration",
"attempts",
"that",
"accept",
"a",
"JSON",
"content",
"type",
".",
"In",
"this",
"situation",
"we",
"simply",
"return",
"the",
"new",
"account",
"object",
"as",
"JSON"
] |
aed8d26ba51272755ea4eab706b4417e4bbeed99
|
https://github.com/stormpath/express-stormpath/blob/aed8d26ba51272755ea4eab706b4417e4bbeed99/lib/controllers/register.js#L71-L75
|
train
|
stormpath/express-stormpath
|
lib/controllers/register.js
|
applyDefaultAccountFields
|
function applyDefaultAccountFields(stormpathConfig, req) {
var registerFields = stormpathConfig.web.register.form.fields;
if ((!registerFields.givenName || !registerFields.givenName.required || !registerFields.givenName.enabled) && !req.body.givenName) {
req.body.givenName = 'UNKNOWN';
}
if ((!registerFields.surname || !registerFields.surname.required || !registerFields.surname.enabled) && !req.body.surname) {
req.body.surname = 'UNKNOWN';
}
}
|
javascript
|
function applyDefaultAccountFields(stormpathConfig, req) {
var registerFields = stormpathConfig.web.register.form.fields;
if ((!registerFields.givenName || !registerFields.givenName.required || !registerFields.givenName.enabled) && !req.body.givenName) {
req.body.givenName = 'UNKNOWN';
}
if ((!registerFields.surname || !registerFields.surname.required || !registerFields.surname.enabled) && !req.body.surname) {
req.body.surname = 'UNKNOWN';
}
}
|
[
"function",
"applyDefaultAccountFields",
"(",
"stormpathConfig",
",",
"req",
")",
"{",
"var",
"registerFields",
"=",
"stormpathConfig",
".",
"web",
".",
"register",
".",
"form",
".",
"fields",
";",
"if",
"(",
"(",
"!",
"registerFields",
".",
"givenName",
"||",
"!",
"registerFields",
".",
"givenName",
".",
"required",
"||",
"!",
"registerFields",
".",
"givenName",
".",
"enabled",
")",
"&&",
"!",
"req",
".",
"body",
".",
"givenName",
")",
"{",
"req",
".",
"body",
".",
"givenName",
"=",
"'UNKNOWN'",
";",
"}",
"if",
"(",
"(",
"!",
"registerFields",
".",
"surname",
"||",
"!",
"registerFields",
".",
"surname",
".",
"required",
"||",
"!",
"registerFields",
".",
"surname",
".",
"enabled",
")",
"&&",
"!",
"req",
".",
"body",
".",
"surname",
")",
"{",
"req",
".",
"body",
".",
"surname",
"=",
"'UNKNOWN'",
";",
"}",
"}"
] |
The Stormpath API requires the `givenName` and `surname` fields to be
provided, but as a convenience our framework integrations allow you to
omit this data and fill those fields with the string `UNKNOWN` - but only
if the field is not explicitly required.
@function
@param {Object} stormpathConfig - The express-stormpath configuration object
@param {Object} req - The http request.
|
[
"The",
"Stormpath",
"API",
"requires",
"the",
"givenName",
"and",
"surname",
"fields",
"to",
"be",
"provided",
"but",
"as",
"a",
"convenience",
"our",
"framework",
"integrations",
"allow",
"you",
"to",
"omit",
"this",
"data",
"and",
"fill",
"those",
"fields",
"with",
"the",
"string",
"UNKNOWN",
"-",
"but",
"only",
"if",
"the",
"field",
"is",
"not",
"explicitly",
"required",
"."
] |
aed8d26ba51272755ea4eab706b4417e4bbeed99
|
https://github.com/stormpath/express-stormpath/blob/aed8d26ba51272755ea4eab706b4417e4bbeed99/lib/controllers/register.js#L88-L98
|
train
|
stormpath/express-stormpath
|
lib/oauth/linkedin.js
|
function (req, config, callback) {
var baseUrl = config.web.baseUrl || req.protocol + '://' + getHost(req);
var linkedInAuthUrl = 'https://www.linkedin.com/uas/oauth2/accessToken';
var linkedInProvider = config.web.social.linkedin;
var options = {
form: {
grant_type: 'authorization_code',
code: req.query.code,
redirect_uri: baseUrl + linkedInProvider.uri,
client_id: linkedInProvider.clientId,
client_secret: linkedInProvider.clientSecret
}
};
request.post(linkedInAuthUrl, options, function (err, result, body) {
var parsedBody;
try {
parsedBody = JSON.parse(body);
} catch (err) {
return callback(err);
}
if (parsedBody.error) {
var errorMessage;
switch (parsedBody.error) {
case 'unauthorized_client':
errorMessage = 'Unable to authenticate with LinkedIn. Please verify that your configuration is correct.';
break;
default:
errorMessage = 'LinkedIn error when exchanging auth code for access token: ' + parsedBody.error_description + ' (' + parsedBody.error + ')';
}
return callback(new Error(errorMessage));
}
callback(err, parsedBody.access_token);
});
}
|
javascript
|
function (req, config, callback) {
var baseUrl = config.web.baseUrl || req.protocol + '://' + getHost(req);
var linkedInAuthUrl = 'https://www.linkedin.com/uas/oauth2/accessToken';
var linkedInProvider = config.web.social.linkedin;
var options = {
form: {
grant_type: 'authorization_code',
code: req.query.code,
redirect_uri: baseUrl + linkedInProvider.uri,
client_id: linkedInProvider.clientId,
client_secret: linkedInProvider.clientSecret
}
};
request.post(linkedInAuthUrl, options, function (err, result, body) {
var parsedBody;
try {
parsedBody = JSON.parse(body);
} catch (err) {
return callback(err);
}
if (parsedBody.error) {
var errorMessage;
switch (parsedBody.error) {
case 'unauthorized_client':
errorMessage = 'Unable to authenticate with LinkedIn. Please verify that your configuration is correct.';
break;
default:
errorMessage = 'LinkedIn error when exchanging auth code for access token: ' + parsedBody.error_description + ' (' + parsedBody.error + ')';
}
return callback(new Error(errorMessage));
}
callback(err, parsedBody.access_token);
});
}
|
[
"function",
"(",
"req",
",",
"config",
",",
"callback",
")",
"{",
"var",
"baseUrl",
"=",
"config",
".",
"web",
".",
"baseUrl",
"||",
"req",
".",
"protocol",
"+",
"'://'",
"+",
"getHost",
"(",
"req",
")",
";",
"var",
"linkedInAuthUrl",
"=",
"'https://www.linkedin.com/uas/oauth2/accessToken'",
";",
"var",
"linkedInProvider",
"=",
"config",
".",
"web",
".",
"social",
".",
"linkedin",
";",
"var",
"options",
"=",
"{",
"form",
":",
"{",
"grant_type",
":",
"'authorization_code'",
",",
"code",
":",
"req",
".",
"query",
".",
"code",
",",
"redirect_uri",
":",
"baseUrl",
"+",
"linkedInProvider",
".",
"uri",
",",
"client_id",
":",
"linkedInProvider",
".",
"clientId",
",",
"client_secret",
":",
"linkedInProvider",
".",
"clientSecret",
"}",
"}",
";",
"request",
".",
"post",
"(",
"linkedInAuthUrl",
",",
"options",
",",
"function",
"(",
"err",
",",
"result",
",",
"body",
")",
"{",
"var",
"parsedBody",
";",
"try",
"{",
"parsedBody",
"=",
"JSON",
".",
"parse",
"(",
"body",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"return",
"callback",
"(",
"err",
")",
";",
"}",
"if",
"(",
"parsedBody",
".",
"error",
")",
"{",
"var",
"errorMessage",
";",
"switch",
"(",
"parsedBody",
".",
"error",
")",
"{",
"case",
"'unauthorized_client'",
":",
"errorMessage",
"=",
"'Unable to authenticate with LinkedIn. Please verify that your configuration is correct.'",
";",
"break",
";",
"default",
":",
"errorMessage",
"=",
"'LinkedIn error when exchanging auth code for access token: '",
"+",
"parsedBody",
".",
"error_description",
"+",
"' ('",
"+",
"parsedBody",
".",
"error",
"+",
"')'",
";",
"}",
"return",
"callback",
"(",
"new",
"Error",
"(",
"errorMessage",
")",
")",
";",
"}",
"callback",
"(",
"err",
",",
"parsedBody",
".",
"access_token",
")",
";",
"}",
")",
";",
"}"
] |
Exchange a LinkedIn authentication code for a OAuth access token.
@method
@private
@param {Object} req - The http request.
@param {string} config - The Stormpath express config object.
@param {string} callback - The callback to call once a response has been resolved.
|
[
"Exchange",
"a",
"LinkedIn",
"authentication",
"code",
"for",
"a",
"OAuth",
"access",
"token",
"."
] |
aed8d26ba51272755ea4eab706b4417e4bbeed99
|
https://github.com/stormpath/express-stormpath/blob/aed8d26ba51272755ea4eab706b4417e4bbeed99/lib/oauth/linkedin.js#L18-L59
|
train
|
|
stormpath/express-stormpath
|
lib/okta/error-transformer.js
|
oktaErrorTransformer
|
function oktaErrorTransformer(err) {
if (err && err.errorCauses) {
err.errorCauses.forEach(function (cause) {
if (cause.errorSummary === 'login: An object with this field already exists in the current organization') {
err.userMessage = 'An account with that email address already exists.';
} else if (!err.userMessage) {
// This clause allows the first error cause to be returned to the user
err.userMessage = cause.errorSummary;
}
});
}
// For OAuth errors
if (err && err.error_description) {
err.message = err.error_description;
}
if (err && err.error === 'invalid_grant') {
err.status = 400;
err.code = 7104;
err.message = 'Invalid username or password.';
}
return err;
}
|
javascript
|
function oktaErrorTransformer(err) {
if (err && err.errorCauses) {
err.errorCauses.forEach(function (cause) {
if (cause.errorSummary === 'login: An object with this field already exists in the current organization') {
err.userMessage = 'An account with that email address already exists.';
} else if (!err.userMessage) {
// This clause allows the first error cause to be returned to the user
err.userMessage = cause.errorSummary;
}
});
}
// For OAuth errors
if (err && err.error_description) {
err.message = err.error_description;
}
if (err && err.error === 'invalid_grant') {
err.status = 400;
err.code = 7104;
err.message = 'Invalid username or password.';
}
return err;
}
|
[
"function",
"oktaErrorTransformer",
"(",
"err",
")",
"{",
"if",
"(",
"err",
"&&",
"err",
".",
"errorCauses",
")",
"{",
"err",
".",
"errorCauses",
".",
"forEach",
"(",
"function",
"(",
"cause",
")",
"{",
"if",
"(",
"cause",
".",
"errorSummary",
"===",
"'login: An object with this field already exists in the current organization'",
")",
"{",
"err",
".",
"userMessage",
"=",
"'An account with that email address already exists.'",
";",
"}",
"else",
"if",
"(",
"!",
"err",
".",
"userMessage",
")",
"{",
"err",
".",
"userMessage",
"=",
"cause",
".",
"errorSummary",
";",
"}",
"}",
")",
";",
"}",
"if",
"(",
"err",
"&&",
"err",
".",
"error_description",
")",
"{",
"err",
".",
"message",
"=",
"err",
".",
"error_description",
";",
"}",
"if",
"(",
"err",
"&&",
"err",
".",
"error",
"===",
"'invalid_grant'",
")",
"{",
"err",
".",
"status",
"=",
"400",
";",
"err",
".",
"code",
"=",
"7104",
";",
"err",
".",
"message",
"=",
"'Invalid username or password.'",
";",
"}",
"return",
"err",
";",
"}"
] |
Translates user creation errors into an end-user friendly userMessage
@param {*} err
|
[
"Translates",
"user",
"creation",
"errors",
"into",
"an",
"end",
"-",
"user",
"friendly",
"userMessage"
] |
aed8d26ba51272755ea4eab706b4417e4bbeed99
|
https://github.com/stormpath/express-stormpath/blob/aed8d26ba51272755ea4eab706b4417e4bbeed99/lib/okta/error-transformer.js#L7-L31
|
train
|
stormpath/express-stormpath
|
lib/controllers/forgot-password.js
|
function (form) {
var data = {
email: form.data.email
};
if (req.organization) {
data.accountStore = {
href: req.organization.href
};
}
application.sendPasswordResetEmail(data, function (err) {
if (err) {
logger.info('A user tried to reset their password, but supplied an invalid email address: ' + form.data.email + '.');
}
res.redirect(config.web.forgotPassword.nextUri);
});
}
|
javascript
|
function (form) {
var data = {
email: form.data.email
};
if (req.organization) {
data.accountStore = {
href: req.organization.href
};
}
application.sendPasswordResetEmail(data, function (err) {
if (err) {
logger.info('A user tried to reset their password, but supplied an invalid email address: ' + form.data.email + '.');
}
res.redirect(config.web.forgotPassword.nextUri);
});
}
|
[
"function",
"(",
"form",
")",
"{",
"var",
"data",
"=",
"{",
"email",
":",
"form",
".",
"data",
".",
"email",
"}",
";",
"if",
"(",
"req",
".",
"organization",
")",
"{",
"data",
".",
"accountStore",
"=",
"{",
"href",
":",
"req",
".",
"organization",
".",
"href",
"}",
";",
"}",
"application",
".",
"sendPasswordResetEmail",
"(",
"data",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"logger",
".",
"info",
"(",
"'A user tried to reset their password, but supplied an invalid email address: '",
"+",
"form",
".",
"data",
".",
"email",
"+",
"'.'",
")",
";",
"}",
"res",
".",
"redirect",
"(",
"config",
".",
"web",
".",
"forgotPassword",
".",
"nextUri",
")",
";",
"}",
")",
";",
"}"
] |
If we get here, it means the user is submitting a password reset request, so we should attempt to send the user a password reset email.
|
[
"If",
"we",
"get",
"here",
"it",
"means",
"the",
"user",
"is",
"submitting",
"a",
"password",
"reset",
"request",
"so",
"we",
"should",
"attempt",
"to",
"send",
"the",
"user",
"a",
"password",
"reset",
"email",
"."
] |
aed8d26ba51272755ea4eab706b4417e4bbeed99
|
https://github.com/stormpath/express-stormpath/blob/aed8d26ba51272755ea4eab706b4417e4bbeed99/lib/controllers/forgot-password.js#L55-L73
|
train
|
|
stormpath/express-stormpath
|
lib/controllers/login.js
|
function (form) {
if (config.web.multiTenancy.enabled && req.organization) {
setAccountStoreByHref(form.data, req.organization);
} else {
/**
* Delete this form field, it's automatically added by the
* forms library. If we don't delete it, we submit a null
* name key to the REST API and we get an error.
*/
delete form.data.organizationNameKey;
}
helpers.authenticate(form.data, req, res, function (err) {
if (err) {
if (err.code === 2014) {
err.message = err.userMessage = 'Invalid Username, Password, or Organization';
}
err = oktaErrorTransformer(err);
return renderForm(form, { error: err.userMessage || err.message });
}
helpers.loginResponder(req, res);
});
}
|
javascript
|
function (form) {
if (config.web.multiTenancy.enabled && req.organization) {
setAccountStoreByHref(form.data, req.organization);
} else {
/**
* Delete this form field, it's automatically added by the
* forms library. If we don't delete it, we submit a null
* name key to the REST API and we get an error.
*/
delete form.data.organizationNameKey;
}
helpers.authenticate(form.data, req, res, function (err) {
if (err) {
if (err.code === 2014) {
err.message = err.userMessage = 'Invalid Username, Password, or Organization';
}
err = oktaErrorTransformer(err);
return renderForm(form, { error: err.userMessage || err.message });
}
helpers.loginResponder(req, res);
});
}
|
[
"function",
"(",
"form",
")",
"{",
"if",
"(",
"config",
".",
"web",
".",
"multiTenancy",
".",
"enabled",
"&&",
"req",
".",
"organization",
")",
"{",
"setAccountStoreByHref",
"(",
"form",
".",
"data",
",",
"req",
".",
"organization",
")",
";",
"}",
"else",
"{",
"delete",
"form",
".",
"data",
".",
"organizationNameKey",
";",
"}",
"helpers",
".",
"authenticate",
"(",
"form",
".",
"data",
",",
"req",
",",
"res",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"if",
"(",
"err",
".",
"code",
"===",
"2014",
")",
"{",
"err",
".",
"message",
"=",
"err",
".",
"userMessage",
"=",
"'Invalid Username, Password, or Organization'",
";",
"}",
"err",
"=",
"oktaErrorTransformer",
"(",
"err",
")",
";",
"return",
"renderForm",
"(",
"form",
",",
"{",
"error",
":",
"err",
".",
"userMessage",
"||",
"err",
".",
"message",
"}",
")",
";",
"}",
"helpers",
".",
"loginResponder",
"(",
"req",
",",
"res",
")",
";",
"}",
")",
";",
"}"
] |
If we get here, it means the user is submitting a login request, so we should attempt to log the user into their account.
|
[
"If",
"we",
"get",
"here",
"it",
"means",
"the",
"user",
"is",
"submitting",
"a",
"login",
"request",
"so",
"we",
"should",
"attempt",
"to",
"log",
"the",
"user",
"into",
"their",
"account",
"."
] |
aed8d26ba51272755ea4eab706b4417e4bbeed99
|
https://github.com/stormpath/express-stormpath/blob/aed8d26ba51272755ea4eab706b4417e4bbeed99/lib/controllers/login.js#L122-L147
|
train
|
|
stormpath/express-stormpath
|
lib/helpers/get-form-view-model.js
|
getFormFields
|
function getFormFields(form) {
// Grab all fields that are enabled, and return them as an array.
// If enabled, remove that property and apply the field name.
var fields = Object.keys(form.fields).reduce(function (result, fieldKey) {
var field = _.clone(form.fields[fieldKey]);
if (!field.enabled) {
return result;
}
// Append the field to field order in case it's not present.
if (form.fieldOrder.indexOf(fieldKey) === -1) {
form.fieldOrder.push(fieldKey);
}
field.name = fieldKey;
delete field.enabled;
result.push(field);
return result;
}, []);
// Sort fields by the defined fieldOrder.
// Fields that are not in fieldOrder will be placed at the end of the array.
fields.sort(function (a, b) {
var indexA = form.fieldOrder.indexOf(a.name);
var indexB = form.fieldOrder.indexOf(b.name);
if (indexA === -1) {
return 0;
}
if (indexB === -1) {
return -1;
}
if (indexA > indexB) {
return 1;
}
if (indexA < indexB) {
return -1;
}
return 0;
});
return fields;
}
|
javascript
|
function getFormFields(form) {
// Grab all fields that are enabled, and return them as an array.
// If enabled, remove that property and apply the field name.
var fields = Object.keys(form.fields).reduce(function (result, fieldKey) {
var field = _.clone(form.fields[fieldKey]);
if (!field.enabled) {
return result;
}
// Append the field to field order in case it's not present.
if (form.fieldOrder.indexOf(fieldKey) === -1) {
form.fieldOrder.push(fieldKey);
}
field.name = fieldKey;
delete field.enabled;
result.push(field);
return result;
}, []);
// Sort fields by the defined fieldOrder.
// Fields that are not in fieldOrder will be placed at the end of the array.
fields.sort(function (a, b) {
var indexA = form.fieldOrder.indexOf(a.name);
var indexB = form.fieldOrder.indexOf(b.name);
if (indexA === -1) {
return 0;
}
if (indexB === -1) {
return -1;
}
if (indexA > indexB) {
return 1;
}
if (indexA < indexB) {
return -1;
}
return 0;
});
return fields;
}
|
[
"function",
"getFormFields",
"(",
"form",
")",
"{",
"var",
"fields",
"=",
"Object",
".",
"keys",
"(",
"form",
".",
"fields",
")",
".",
"reduce",
"(",
"function",
"(",
"result",
",",
"fieldKey",
")",
"{",
"var",
"field",
"=",
"_",
".",
"clone",
"(",
"form",
".",
"fields",
"[",
"fieldKey",
"]",
")",
";",
"if",
"(",
"!",
"field",
".",
"enabled",
")",
"{",
"return",
"result",
";",
"}",
"if",
"(",
"form",
".",
"fieldOrder",
".",
"indexOf",
"(",
"fieldKey",
")",
"===",
"-",
"1",
")",
"{",
"form",
".",
"fieldOrder",
".",
"push",
"(",
"fieldKey",
")",
";",
"}",
"field",
".",
"name",
"=",
"fieldKey",
";",
"delete",
"field",
".",
"enabled",
";",
"result",
".",
"push",
"(",
"field",
")",
";",
"return",
"result",
";",
"}",
",",
"[",
"]",
")",
";",
"fields",
".",
"sort",
"(",
"function",
"(",
"a",
",",
"b",
")",
"{",
"var",
"indexA",
"=",
"form",
".",
"fieldOrder",
".",
"indexOf",
"(",
"a",
".",
"name",
")",
";",
"var",
"indexB",
"=",
"form",
".",
"fieldOrder",
".",
"indexOf",
"(",
"b",
".",
"name",
")",
";",
"if",
"(",
"indexA",
"===",
"-",
"1",
")",
"{",
"return",
"0",
";",
"}",
"if",
"(",
"indexB",
"===",
"-",
"1",
")",
"{",
"return",
"-",
"1",
";",
"}",
"if",
"(",
"indexA",
">",
"indexB",
")",
"{",
"return",
"1",
";",
"}",
"if",
"(",
"indexA",
"<",
"indexB",
")",
"{",
"return",
"-",
"1",
";",
"}",
"return",
"0",
";",
"}",
")",
";",
"return",
"fields",
";",
"}"
] |
Returns list of all enabled fields, as defined by `form.fields`,
and ordered by `form.fieldOrder`.
@method
@param {Object} form - The form from the Stormpath configuration.
|
[
"Returns",
"list",
"of",
"all",
"enabled",
"fields",
"as",
"defined",
"by",
"form",
".",
"fields",
"and",
"ordered",
"by",
"form",
".",
"fieldOrder",
"."
] |
aed8d26ba51272755ea4eab706b4417e4bbeed99
|
https://github.com/stormpath/express-stormpath/blob/aed8d26ba51272755ea4eab706b4417e4bbeed99/lib/helpers/get-form-view-model.js#L17-L66
|
train
|
stormpath/express-stormpath
|
lib/helpers/get-form-view-model.js
|
getAccountStores
|
function getAccountStores(application, callback) {
var options = { expand: 'accountStore' };
// Get account store mappings.
application.getAccountStoreMappings(options, function (err, accountStoreMappings) {
if (err) {
return callback(err);
}
// Iterate over all account stores, and filter out the ones that
// don't have a provider (Organizations dont have providers)
accountStoreMappings.filter(function (accountStoreMapping, next) {
next(!!accountStoreMapping.accountStore.provider);
}, function (accountStoreMappings) {
if (err) {
return callback(err);
}
// Get the account store, and expand the provider so that we can
// inspect the provider ID
async.map(accountStoreMappings, function (accountStoreMapping, next) {
accountStoreMapping.getAccountStore({ expand: 'provider' }, next);
}, callback);
});
});
}
|
javascript
|
function getAccountStores(application, callback) {
var options = { expand: 'accountStore' };
// Get account store mappings.
application.getAccountStoreMappings(options, function (err, accountStoreMappings) {
if (err) {
return callback(err);
}
// Iterate over all account stores, and filter out the ones that
// don't have a provider (Organizations dont have providers)
accountStoreMappings.filter(function (accountStoreMapping, next) {
next(!!accountStoreMapping.accountStore.provider);
}, function (accountStoreMappings) {
if (err) {
return callback(err);
}
// Get the account store, and expand the provider so that we can
// inspect the provider ID
async.map(accountStoreMappings, function (accountStoreMapping, next) {
accountStoreMapping.getAccountStore({ expand: 'provider' }, next);
}, callback);
});
});
}
|
[
"function",
"getAccountStores",
"(",
"application",
",",
"callback",
")",
"{",
"var",
"options",
"=",
"{",
"expand",
":",
"'accountStore'",
"}",
";",
"application",
".",
"getAccountStoreMappings",
"(",
"options",
",",
"function",
"(",
"err",
",",
"accountStoreMappings",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"callback",
"(",
"err",
")",
";",
"}",
"accountStoreMappings",
".",
"filter",
"(",
"function",
"(",
"accountStoreMapping",
",",
"next",
")",
"{",
"next",
"(",
"!",
"!",
"accountStoreMapping",
".",
"accountStore",
".",
"provider",
")",
";",
"}",
",",
"function",
"(",
"accountStoreMappings",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"callback",
"(",
"err",
")",
";",
"}",
"async",
".",
"map",
"(",
"accountStoreMappings",
",",
"function",
"(",
"accountStoreMapping",
",",
"next",
")",
"{",
"accountStoreMapping",
".",
"getAccountStore",
"(",
"{",
"expand",
":",
"'provider'",
"}",
",",
"next",
")",
";",
"}",
",",
"callback",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] |
Returns a list of account stores for the specified application.
@method
@param {Object} application - The Stormpath Application to get account stores from.
@param {Function} callback - Callback function (error, providers).
|
[
"Returns",
"a",
"list",
"of",
"account",
"stores",
"for",
"the",
"specified",
"application",
"."
] |
aed8d26ba51272755ea4eab706b4417e4bbeed99
|
https://github.com/stormpath/express-stormpath/blob/aed8d26ba51272755ea4eab706b4417e4bbeed99/lib/helpers/get-form-view-model.js#L76-L101
|
train
|
stormpath/express-stormpath
|
lib/helpers/get-form-view-model.js
|
getAccountStoreModel
|
function getAccountStoreModel(accountStore) {
var provider = accountStore.provider;
return {
href: accountStore.href,
name: accountStore.name,
provider: {
href: provider.href,
providerId: provider.providerId,
callbackUri: provider.callbackUri,
clientId: provider.clientId
}
};
}
|
javascript
|
function getAccountStoreModel(accountStore) {
var provider = accountStore.provider;
return {
href: accountStore.href,
name: accountStore.name,
provider: {
href: provider.href,
providerId: provider.providerId,
callbackUri: provider.callbackUri,
clientId: provider.clientId
}
};
}
|
[
"function",
"getAccountStoreModel",
"(",
"accountStore",
")",
"{",
"var",
"provider",
"=",
"accountStore",
".",
"provider",
";",
"return",
"{",
"href",
":",
"accountStore",
".",
"href",
",",
"name",
":",
"accountStore",
".",
"name",
",",
"provider",
":",
"{",
"href",
":",
"provider",
".",
"href",
",",
"providerId",
":",
"provider",
".",
"providerId",
",",
"callbackUri",
":",
"provider",
".",
"callbackUri",
",",
"clientId",
":",
"provider",
".",
"clientId",
"}",
"}",
";",
"}"
] |
Takes an account store object and returns a
new object with only the fields that we want
to expose to the public.
@method
@param {Object} accountStore - The account store.
|
[
"Takes",
"an",
"account",
"store",
"object",
"and",
"returns",
"a",
"new",
"object",
"with",
"only",
"the",
"fields",
"that",
"we",
"want",
"to",
"expose",
"to",
"the",
"public",
"."
] |
aed8d26ba51272755ea4eab706b4417e4bbeed99
|
https://github.com/stormpath/express-stormpath/blob/aed8d26ba51272755ea4eab706b4417e4bbeed99/lib/helpers/get-form-view-model.js#L112-L125
|
train
|
stormpath/express-stormpath
|
lib/helpers/handle-accept-request.js
|
handleAcceptRequest
|
function handleAcceptRequest(req, res, handlers, fallbackHandler) {
var config = req.app.get('stormpathConfig');
// Accepted is an ordered list of preferred types, as specified by the request.
var accepted = req.accepts();
var produces = config.web.produces;
// Our default response is HTML, if the client does not specify something more
// specific. As such, map the wildcard type to html.
accepted = accepted.map(function (contentType) {
return contentType === '*/*' ? 'text/html' : contentType;
});
// Of the accepted types, find the ones that are allowed by the configuration.
var allowedResponseTypes = _.intersection(produces, accepted);
// Of the allowed response types, find the first handler that matches. But
// always override with the SPA handler if SPA is enabled.
var handler;
allowedResponseTypes.some(function (contentType) {
if (config.web.spa.enabled && contentType === 'text/html') {
handler = spaResponseHandler(config);
return true;
}
if (contentType in handlers) {
handler = handlers[contentType];
return true;
}
});
if (!handler) {
return fallbackHandler();
}
handler(req, res);
}
|
javascript
|
function handleAcceptRequest(req, res, handlers, fallbackHandler) {
var config = req.app.get('stormpathConfig');
// Accepted is an ordered list of preferred types, as specified by the request.
var accepted = req.accepts();
var produces = config.web.produces;
// Our default response is HTML, if the client does not specify something more
// specific. As such, map the wildcard type to html.
accepted = accepted.map(function (contentType) {
return contentType === '*/*' ? 'text/html' : contentType;
});
// Of the accepted types, find the ones that are allowed by the configuration.
var allowedResponseTypes = _.intersection(produces, accepted);
// Of the allowed response types, find the first handler that matches. But
// always override with the SPA handler if SPA is enabled.
var handler;
allowedResponseTypes.some(function (contentType) {
if (config.web.spa.enabled && contentType === 'text/html') {
handler = spaResponseHandler(config);
return true;
}
if (contentType in handlers) {
handler = handlers[contentType];
return true;
}
});
if (!handler) {
return fallbackHandler();
}
handler(req, res);
}
|
[
"function",
"handleAcceptRequest",
"(",
"req",
",",
"res",
",",
"handlers",
",",
"fallbackHandler",
")",
"{",
"var",
"config",
"=",
"req",
".",
"app",
".",
"get",
"(",
"'stormpathConfig'",
")",
";",
"var",
"accepted",
"=",
"req",
".",
"accepts",
"(",
")",
";",
"var",
"produces",
"=",
"config",
".",
"web",
".",
"produces",
";",
"accepted",
"=",
"accepted",
".",
"map",
"(",
"function",
"(",
"contentType",
")",
"{",
"return",
"contentType",
"===",
"'*/*'",
"?",
"'text/html'",
":",
"contentType",
";",
"}",
")",
";",
"var",
"allowedResponseTypes",
"=",
"_",
".",
"intersection",
"(",
"produces",
",",
"accepted",
")",
";",
"var",
"handler",
";",
"allowedResponseTypes",
".",
"some",
"(",
"function",
"(",
"contentType",
")",
"{",
"if",
"(",
"config",
".",
"web",
".",
"spa",
".",
"enabled",
"&&",
"contentType",
"===",
"'text/html'",
")",
"{",
"handler",
"=",
"spaResponseHandler",
"(",
"config",
")",
";",
"return",
"true",
";",
"}",
"if",
"(",
"contentType",
"in",
"handlers",
")",
"{",
"handler",
"=",
"handlers",
"[",
"contentType",
"]",
";",
"return",
"true",
";",
"}",
"}",
")",
";",
"if",
"(",
"!",
"handler",
")",
"{",
"return",
"fallbackHandler",
"(",
")",
";",
"}",
"handler",
"(",
"req",
",",
"res",
")",
";",
"}"
] |
Determines which handler should be used to fulfill a response, given the
Accept header of the request and the content types that are allowed by the
`stormpath.web.produces` configuration. Also handles the serving of the SPA
root page, if needed.
@method
@private
@param {Object} req - HTTP request.
@param {Object} res - HTTP response.
@param {Object} handlers - Object where the keys are content types and the
functions are handlers that will be called, if needed, to fulfill the
response as that type.
@param {Function} fallbackHandler - Handler to call when an acceptable
content type could not be resolved.
|
[
"Determines",
"which",
"handler",
"should",
"be",
"used",
"to",
"fulfill",
"a",
"response",
"given",
"the",
"Accept",
"header",
"of",
"the",
"request",
"and",
"the",
"content",
"types",
"that",
"are",
"allowed",
"by",
"the",
"stormpath",
".",
"web",
".",
"produces",
"configuration",
".",
"Also",
"handles",
"the",
"serving",
"of",
"the",
"SPA",
"root",
"page",
"if",
"needed",
"."
] |
aed8d26ba51272755ea4eab706b4417e4bbeed99
|
https://github.com/stormpath/express-stormpath/blob/aed8d26ba51272755ea4eab706b4417e4bbeed99/lib/helpers/handle-accept-request.js#L23-L60
|
train
|
stormpath/express-stormpath
|
lib/controllers/verify-email.js
|
function (form) {
var options = {
login: form.data.email
};
if (req.organization) {
options.accountStore = {
href: req.organization.href
};
}
application.resendVerificationEmail(options, function (err, account) {
// Code 2016 means that an account does not exist for the given email
// address. We don't want to leak information about the account
// list, so allow this continue without error.
if (err && err.code !== 2016) {
logger.info('A user tried to resend their account verification email, but failed: ' + err.message);
return helpers.render(req, res, view, { error: err.message, form: form });
}
if (account) {
emailVerificationHandler(new Account(account));
}
res.redirect(config.web.login.uri + '?status=unverified');
});
}
|
javascript
|
function (form) {
var options = {
login: form.data.email
};
if (req.organization) {
options.accountStore = {
href: req.organization.href
};
}
application.resendVerificationEmail(options, function (err, account) {
// Code 2016 means that an account does not exist for the given email
// address. We don't want to leak information about the account
// list, so allow this continue without error.
if (err && err.code !== 2016) {
logger.info('A user tried to resend their account verification email, but failed: ' + err.message);
return helpers.render(req, res, view, { error: err.message, form: form });
}
if (account) {
emailVerificationHandler(new Account(account));
}
res.redirect(config.web.login.uri + '?status=unverified');
});
}
|
[
"function",
"(",
"form",
")",
"{",
"var",
"options",
"=",
"{",
"login",
":",
"form",
".",
"data",
".",
"email",
"}",
";",
"if",
"(",
"req",
".",
"organization",
")",
"{",
"options",
".",
"accountStore",
"=",
"{",
"href",
":",
"req",
".",
"organization",
".",
"href",
"}",
";",
"}",
"application",
".",
"resendVerificationEmail",
"(",
"options",
",",
"function",
"(",
"err",
",",
"account",
")",
"{",
"if",
"(",
"err",
"&&",
"err",
".",
"code",
"!==",
"2016",
")",
"{",
"logger",
".",
"info",
"(",
"'A user tried to resend their account verification email, but failed: '",
"+",
"err",
".",
"message",
")",
";",
"return",
"helpers",
".",
"render",
"(",
"req",
",",
"res",
",",
"view",
",",
"{",
"error",
":",
"err",
".",
"message",
",",
"form",
":",
"form",
"}",
")",
";",
"}",
"if",
"(",
"account",
")",
"{",
"emailVerificationHandler",
"(",
"new",
"Account",
"(",
"account",
")",
")",
";",
"}",
"res",
".",
"redirect",
"(",
"config",
".",
"web",
".",
"login",
".",
"uri",
"+",
"'?status=unverified'",
")",
";",
"}",
")",
";",
"}"
] |
If we get here, it means the user is submitting a request to resend their account verification email, so we should attempt to send the user another verification email.
|
[
"If",
"we",
"get",
"here",
"it",
"means",
"the",
"user",
"is",
"submitting",
"a",
"request",
"to",
"resend",
"their",
"account",
"verification",
"email",
"so",
"we",
"should",
"attempt",
"to",
"send",
"the",
"user",
"another",
"verification",
"email",
"."
] |
aed8d26ba51272755ea4eab706b4417e4bbeed99
|
https://github.com/stormpath/express-stormpath/blob/aed8d26ba51272755ea4eab706b4417e4bbeed99/lib/controllers/verify-email.js#L98-L124
|
train
|
|
stormpath/express-stormpath
|
lib/helpers/write-json-error.js
|
writeJsonError
|
function writeJsonError(res, err, statusCode) {
var status = err.status || err.statusCode || statusCode || 400;
var message = 'Unknown error. Please contact support.';
if (err) {
message = err.userMessage || err.message;
}
res.status(status);
res.json({
status: status,
message: message
});
res.end();
}
|
javascript
|
function writeJsonError(res, err, statusCode) {
var status = err.status || err.statusCode || statusCode || 400;
var message = 'Unknown error. Please contact support.';
if (err) {
message = err.userMessage || err.message;
}
res.status(status);
res.json({
status: status,
message: message
});
res.end();
}
|
[
"function",
"writeJsonError",
"(",
"res",
",",
"err",
",",
"statusCode",
")",
"{",
"var",
"status",
"=",
"err",
".",
"status",
"||",
"err",
".",
"statusCode",
"||",
"statusCode",
"||",
"400",
";",
"var",
"message",
"=",
"'Unknown error. Please contact support.'",
";",
"if",
"(",
"err",
")",
"{",
"message",
"=",
"err",
".",
"userMessage",
"||",
"err",
".",
"message",
";",
"}",
"res",
".",
"status",
"(",
"status",
")",
";",
"res",
".",
"json",
"(",
"{",
"status",
":",
"status",
",",
"message",
":",
"message",
"}",
")",
";",
"res",
".",
"end",
"(",
")",
";",
"}"
] |
Use this method to render JSON error responses.
@function
@param {Object} res - Express http response.
@param {Object} err - An error object.
|
[
"Use",
"this",
"method",
"to",
"render",
"JSON",
"error",
"responses",
"."
] |
aed8d26ba51272755ea4eab706b4417e4bbeed99
|
https://github.com/stormpath/express-stormpath/blob/aed8d26ba51272755ea4eab706b4417e4bbeed99/lib/helpers/write-json-error.js#L11-L27
|
train
|
stormpath/express-stormpath
|
lib/helpers/stripped-account-response.js
|
strippedAccount
|
function strippedAccount(account, expansionMap) {
expansionMap = typeof expansionMap === 'object' ? expansionMap : {};
var strippedAccount = _.clone(account);
var hiddenProperties = ['stormpathMigrationRecoveryAnswer', 'emailVerificationToken'];
// Profile data is copied onto custom data, so we don't need to expose profile
if (strippedAccount.profile) {
delete strippedAccount.profile;
}
delete strippedAccount.credentials;
delete strippedAccount._links;
Object.keys(strippedAccount).forEach(function (property) {
var expandable = !!expansionMap[property];
if (strippedAccount[property] && (strippedAccount[property].href || strippedAccount[property].items) && expandable === false) {
delete strippedAccount[property];
}
if (property === 'customData') {
if (expandable) {
Object.keys(strippedAccount[property]).forEach(function (subProperty) {
if (hiddenProperties.indexOf(subProperty) > -1) {
delete strippedAccount[property][subProperty];
}
if (subProperty.match('stormpathApiKey')) {
delete strippedAccount[property][subProperty];
}
});
} else {
delete strippedAccount.customData;
}
}
});
return strippedAccount;
}
|
javascript
|
function strippedAccount(account, expansionMap) {
expansionMap = typeof expansionMap === 'object' ? expansionMap : {};
var strippedAccount = _.clone(account);
var hiddenProperties = ['stormpathMigrationRecoveryAnswer', 'emailVerificationToken'];
// Profile data is copied onto custom data, so we don't need to expose profile
if (strippedAccount.profile) {
delete strippedAccount.profile;
}
delete strippedAccount.credentials;
delete strippedAccount._links;
Object.keys(strippedAccount).forEach(function (property) {
var expandable = !!expansionMap[property];
if (strippedAccount[property] && (strippedAccount[property].href || strippedAccount[property].items) && expandable === false) {
delete strippedAccount[property];
}
if (property === 'customData') {
if (expandable) {
Object.keys(strippedAccount[property]).forEach(function (subProperty) {
if (hiddenProperties.indexOf(subProperty) > -1) {
delete strippedAccount[property][subProperty];
}
if (subProperty.match('stormpathApiKey')) {
delete strippedAccount[property][subProperty];
}
});
} else {
delete strippedAccount.customData;
}
}
});
return strippedAccount;
}
|
[
"function",
"strippedAccount",
"(",
"account",
",",
"expansionMap",
")",
"{",
"expansionMap",
"=",
"typeof",
"expansionMap",
"===",
"'object'",
"?",
"expansionMap",
":",
"{",
"}",
";",
"var",
"strippedAccount",
"=",
"_",
".",
"clone",
"(",
"account",
")",
";",
"var",
"hiddenProperties",
"=",
"[",
"'stormpathMigrationRecoveryAnswer'",
",",
"'emailVerificationToken'",
"]",
";",
"if",
"(",
"strippedAccount",
".",
"profile",
")",
"{",
"delete",
"strippedAccount",
".",
"profile",
";",
"}",
"delete",
"strippedAccount",
".",
"credentials",
";",
"delete",
"strippedAccount",
".",
"_links",
";",
"Object",
".",
"keys",
"(",
"strippedAccount",
")",
".",
"forEach",
"(",
"function",
"(",
"property",
")",
"{",
"var",
"expandable",
"=",
"!",
"!",
"expansionMap",
"[",
"property",
"]",
";",
"if",
"(",
"strippedAccount",
"[",
"property",
"]",
"&&",
"(",
"strippedAccount",
"[",
"property",
"]",
".",
"href",
"||",
"strippedAccount",
"[",
"property",
"]",
".",
"items",
")",
"&&",
"expandable",
"===",
"false",
")",
"{",
"delete",
"strippedAccount",
"[",
"property",
"]",
";",
"}",
"if",
"(",
"property",
"===",
"'customData'",
")",
"{",
"if",
"(",
"expandable",
")",
"{",
"Object",
".",
"keys",
"(",
"strippedAccount",
"[",
"property",
"]",
")",
".",
"forEach",
"(",
"function",
"(",
"subProperty",
")",
"{",
"if",
"(",
"hiddenProperties",
".",
"indexOf",
"(",
"subProperty",
")",
">",
"-",
"1",
")",
"{",
"delete",
"strippedAccount",
"[",
"property",
"]",
"[",
"subProperty",
"]",
";",
"}",
"if",
"(",
"subProperty",
".",
"match",
"(",
"'stormpathApiKey'",
")",
")",
"{",
"delete",
"strippedAccount",
"[",
"property",
"]",
"[",
"subProperty",
"]",
";",
"}",
"}",
")",
";",
"}",
"else",
"{",
"delete",
"strippedAccount",
".",
"customData",
";",
"}",
"}",
"}",
")",
";",
"return",
"strippedAccount",
";",
"}"
] |
Returns an account object, but strips all of the linked resources and sensitive properties.
@function
@param {Object} account - The stormpath account object.
|
[
"Returns",
"an",
"account",
"object",
"but",
"strips",
"all",
"of",
"the",
"linked",
"resources",
"and",
"sensitive",
"properties",
"."
] |
aed8d26ba51272755ea4eab706b4417e4bbeed99
|
https://github.com/stormpath/express-stormpath/blob/aed8d26ba51272755ea4eab706b4417e4bbeed99/lib/helpers/stripped-account-response.js#L12-L53
|
train
|
jesstelford/node-MarkerWithLabel
|
index.js
|
MarkerLabel_
|
function MarkerLabel_(marker, crossURL, handCursorURL) {
this.marker_ = marker;
this.handCursorURL_ = marker.handCursorURL;
this.labelDiv_ = document.createElement("div");
this.labelDiv_.style.cssText = "position: absolute; overflow: hidden;";
// Set up the DIV for handling mouse events in the label. This DIV forms a transparent veil
// in the "overlayMouseTarget" pane, a veil that covers just the label. This is done so that
// events can be captured even if the label is in the shadow of a google.maps.InfoWindow.
// Code is included here to ensure the veil is always exactly the same size as the label.
this.eventDiv_ = document.createElement("div");
this.eventDiv_.style.cssText = this.labelDiv_.style.cssText;
// This is needed for proper behavior on MSIE:
this.eventDiv_.addEventListener('selectstart', function() { return false; });
this.eventDiv_.addEventListener('dragstart', function() { return false; });
// Get the DIV for the "X" to be displayed when the marker is raised.
this.crossDiv_ = MarkerLabel_.getSharedCross(crossURL);
}
|
javascript
|
function MarkerLabel_(marker, crossURL, handCursorURL) {
this.marker_ = marker;
this.handCursorURL_ = marker.handCursorURL;
this.labelDiv_ = document.createElement("div");
this.labelDiv_.style.cssText = "position: absolute; overflow: hidden;";
// Set up the DIV for handling mouse events in the label. This DIV forms a transparent veil
// in the "overlayMouseTarget" pane, a veil that covers just the label. This is done so that
// events can be captured even if the label is in the shadow of a google.maps.InfoWindow.
// Code is included here to ensure the veil is always exactly the same size as the label.
this.eventDiv_ = document.createElement("div");
this.eventDiv_.style.cssText = this.labelDiv_.style.cssText;
// This is needed for proper behavior on MSIE:
this.eventDiv_.addEventListener('selectstart', function() { return false; });
this.eventDiv_.addEventListener('dragstart', function() { return false; });
// Get the DIV for the "X" to be displayed when the marker is raised.
this.crossDiv_ = MarkerLabel_.getSharedCross(crossURL);
}
|
[
"function",
"MarkerLabel_",
"(",
"marker",
",",
"crossURL",
",",
"handCursorURL",
")",
"{",
"this",
".",
"marker_",
"=",
"marker",
";",
"this",
".",
"handCursorURL_",
"=",
"marker",
".",
"handCursorURL",
";",
"this",
".",
"labelDiv_",
"=",
"document",
".",
"createElement",
"(",
"\"div\"",
")",
";",
"this",
".",
"labelDiv_",
".",
"style",
".",
"cssText",
"=",
"\"position: absolute; overflow: hidden;\"",
";",
"this",
".",
"eventDiv_",
"=",
"document",
".",
"createElement",
"(",
"\"div\"",
")",
";",
"this",
".",
"eventDiv_",
".",
"style",
".",
"cssText",
"=",
"this",
".",
"labelDiv_",
".",
"style",
".",
"cssText",
";",
"this",
".",
"eventDiv_",
".",
"addEventListener",
"(",
"'selectstart'",
",",
"function",
"(",
")",
"{",
"return",
"false",
";",
"}",
")",
";",
"this",
".",
"eventDiv_",
".",
"addEventListener",
"(",
"'dragstart'",
",",
"function",
"(",
")",
"{",
"return",
"false",
";",
"}",
")",
";",
"this",
".",
"crossDiv_",
"=",
"MarkerLabel_",
".",
"getSharedCross",
"(",
"crossURL",
")",
";",
"}"
] |
This constructor creates a label and associates it with a marker.
It is for the private use of the MarkerWithLabel class.
@constructor
@param {Marker} marker The marker with which the label is to be associated.
@param {string} crossURL The URL of the cross image =.
@param {string} handCursor The URL of the hand cursor.
@private
|
[
"This",
"constructor",
"creates",
"a",
"label",
"and",
"associates",
"it",
"with",
"a",
"marker",
".",
"It",
"is",
"for",
"the",
"private",
"use",
"of",
"the",
"MarkerWithLabel",
"class",
"."
] |
54e0eb0fde830b591b0550a921420ef566bdbc0b
|
https://github.com/jesstelford/node-MarkerWithLabel/blob/54e0eb0fde830b591b0550a921420ef566bdbc0b/index.js#L67-L87
|
train
|
perry-mitchell/webdav-fs
|
source/index.js
|
function(filePath, options) {
var clientOptions = {};
if (options && options !== null) {
if (typeof options.headers === "object") {
clientOptions.headers = options.headers;
}
}
return client.createWriteStream(filePath, clientOptions);
}
|
javascript
|
function(filePath, options) {
var clientOptions = {};
if (options && options !== null) {
if (typeof options.headers === "object") {
clientOptions.headers = options.headers;
}
}
return client.createWriteStream(filePath, clientOptions);
}
|
[
"function",
"(",
"filePath",
",",
"options",
")",
"{",
"var",
"clientOptions",
"=",
"{",
"}",
";",
"if",
"(",
"options",
"&&",
"options",
"!==",
"null",
")",
"{",
"if",
"(",
"typeof",
"options",
".",
"headers",
"===",
"\"object\"",
")",
"{",
"clientOptions",
".",
"headers",
"=",
"options",
".",
"headers",
";",
"}",
"}",
"return",
"client",
".",
"createWriteStream",
"(",
"filePath",
",",
"clientOptions",
")",
";",
"}"
] |
Create a write stream for a remote file
@param {String} filePath The remote path
@param {CreateWriteStreamOptions=} options Options for the stream
@returns {Writeable} A writeable stream
|
[
"Create",
"a",
"write",
"stream",
"for",
"a",
"remote",
"file"
] |
b41794aae460df6d24ea6eaa1d833f8465b26606
|
https://github.com/perry-mitchell/webdav-fs/blob/b41794aae460df6d24ea6eaa1d833f8465b26606/source/index.js#L93-L101
|
train
|
|
perry-mitchell/webdav-fs
|
source/index.js
|
function(dirPath, callback) {
client
.createDirectory(dirPath)
.then(function() {
__executeCallbackAsync(callback, [null]);
})
.catch(callback);
}
|
javascript
|
function(dirPath, callback) {
client
.createDirectory(dirPath)
.then(function() {
__executeCallbackAsync(callback, [null]);
})
.catch(callback);
}
|
[
"function",
"(",
"dirPath",
",",
"callback",
")",
"{",
"client",
".",
"createDirectory",
"(",
"dirPath",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"__executeCallbackAsync",
"(",
"callback",
",",
"[",
"null",
"]",
")",
";",
"}",
")",
".",
"catch",
"(",
"callback",
")",
";",
"}"
] |
Create a remote directory
@param {String} dirPath The remote path to create
@param {Function} callback Callback: function(error)
|
[
"Create",
"a",
"remote",
"directory"
] |
b41794aae460df6d24ea6eaa1d833f8465b26606
|
https://github.com/perry-mitchell/webdav-fs/blob/b41794aae460df6d24ea6eaa1d833f8465b26606/source/index.js#L108-L115
|
train
|
|
perry-mitchell/webdav-fs
|
source/index.js
|
function(/* dirPath[, mode], callback */) {
var args = Array.prototype.slice.call(arguments),
argc = args.length;
if (argc <= 1) {
throw new Error("Invalid number of arguments");
}
var dirPath = args[0],
mode = (typeof args[1] === "string") ? args[1] : "node",
callback = function() {};
if (typeof args[1] === "function") {
callback = args[1];
} else if (argc >= 3 && typeof args[2] === "function") {
callback = args[2];
}
client
.getDirectoryContents(dirPath)
.then(function(contents) {
var results;
if (mode === "node") {
results = contents.map(function(statItem) {
return statItem.basename;
});
} else if (mode === "stat") {
results = contents.map(__convertStat);
} else {
throw new Error("Unknown mode: " + mode);
}
__executeCallbackAsync(callback, [null, results]);
})
.catch(callback);
}
|
javascript
|
function(/* dirPath[, mode], callback */) {
var args = Array.prototype.slice.call(arguments),
argc = args.length;
if (argc <= 1) {
throw new Error("Invalid number of arguments");
}
var dirPath = args[0],
mode = (typeof args[1] === "string") ? args[1] : "node",
callback = function() {};
if (typeof args[1] === "function") {
callback = args[1];
} else if (argc >= 3 && typeof args[2] === "function") {
callback = args[2];
}
client
.getDirectoryContents(dirPath)
.then(function(contents) {
var results;
if (mode === "node") {
results = contents.map(function(statItem) {
return statItem.basename;
});
} else if (mode === "stat") {
results = contents.map(__convertStat);
} else {
throw new Error("Unknown mode: " + mode);
}
__executeCallbackAsync(callback, [null, results]);
})
.catch(callback);
}
|
[
"function",
"(",
")",
"{",
"var",
"args",
"=",
"Array",
".",
"prototype",
".",
"slice",
".",
"call",
"(",
"arguments",
")",
",",
"argc",
"=",
"args",
".",
"length",
";",
"if",
"(",
"argc",
"<=",
"1",
")",
"{",
"throw",
"new",
"Error",
"(",
"\"Invalid number of arguments\"",
")",
";",
"}",
"var",
"dirPath",
"=",
"args",
"[",
"0",
"]",
",",
"mode",
"=",
"(",
"typeof",
"args",
"[",
"1",
"]",
"===",
"\"string\"",
")",
"?",
"args",
"[",
"1",
"]",
":",
"\"node\"",
",",
"callback",
"=",
"function",
"(",
")",
"{",
"}",
";",
"if",
"(",
"typeof",
"args",
"[",
"1",
"]",
"===",
"\"function\"",
")",
"{",
"callback",
"=",
"args",
"[",
"1",
"]",
";",
"}",
"else",
"if",
"(",
"argc",
">=",
"3",
"&&",
"typeof",
"args",
"[",
"2",
"]",
"===",
"\"function\"",
")",
"{",
"callback",
"=",
"args",
"[",
"2",
"]",
";",
"}",
"client",
".",
"getDirectoryContents",
"(",
"dirPath",
")",
".",
"then",
"(",
"function",
"(",
"contents",
")",
"{",
"var",
"results",
";",
"if",
"(",
"mode",
"===",
"\"node\"",
")",
"{",
"results",
"=",
"contents",
".",
"map",
"(",
"function",
"(",
"statItem",
")",
"{",
"return",
"statItem",
".",
"basename",
";",
"}",
")",
";",
"}",
"else",
"if",
"(",
"mode",
"===",
"\"stat\"",
")",
"{",
"results",
"=",
"contents",
".",
"map",
"(",
"__convertStat",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"\"Unknown mode: \"",
"+",
"mode",
")",
";",
"}",
"__executeCallbackAsync",
"(",
"callback",
",",
"[",
"null",
",",
"results",
"]",
")",
";",
"}",
")",
".",
"catch",
"(",
"callback",
")",
";",
"}"
] |
Readdir processing mode.
When set to 'node', readdir will return an array of strings like Node's
fs.readdir does. When set to 'stat', readdir will return an array of stat
objects.
@see stat
@typedef {('node'|'stat')} ReadDirMode
Read a directory synchronously.
Maps -> fs.readdir
@see https://nodejs.org/api/fs.html#fs_fs_readdir_path_callback
@param {String} path The path to read at
@param {String=} mode The readdir processing mode (default 'node')
@param {Function} callback Callback: function(error, files)
|
[
"Readdir",
"processing",
"mode",
".",
"When",
"set",
"to",
"node",
"readdir",
"will",
"return",
"an",
"array",
"of",
"strings",
"like",
"Node",
"s",
"fs",
".",
"readdir",
"does",
".",
"When",
"set",
"to",
"stat",
"readdir",
"will",
"return",
"an",
"array",
"of",
"stat",
"objects",
"."
] |
b41794aae460df6d24ea6eaa1d833f8465b26606
|
https://github.com/perry-mitchell/webdav-fs/blob/b41794aae460df6d24ea6eaa1d833f8465b26606/source/index.js#L134-L164
|
train
|
|
perry-mitchell/webdav-fs
|
source/index.js
|
function(filePath, targetPath, callback) {
client
.moveFile(filePath, targetPath)
.then(function() {
__executeCallbackAsync(callback, [null]);
})
.catch(callback);
}
|
javascript
|
function(filePath, targetPath, callback) {
client
.moveFile(filePath, targetPath)
.then(function() {
__executeCallbackAsync(callback, [null]);
})
.catch(callback);
}
|
[
"function",
"(",
"filePath",
",",
"targetPath",
",",
"callback",
")",
"{",
"client",
".",
"moveFile",
"(",
"filePath",
",",
"targetPath",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"__executeCallbackAsync",
"(",
"callback",
",",
"[",
"null",
"]",
")",
";",
"}",
")",
".",
"catch",
"(",
"callback",
")",
";",
"}"
] |
Rename a remote item
@param {String} filePath The remote path to rename
@param {String} targetPath The new path name of the item
@param {Function} callback Callback: function(error)
|
[
"Rename",
"a",
"remote",
"item"
] |
b41794aae460df6d24ea6eaa1d833f8465b26606
|
https://github.com/perry-mitchell/webdav-fs/blob/b41794aae460df6d24ea6eaa1d833f8465b26606/source/index.js#L201-L208
|
train
|
|
perry-mitchell/webdav-fs
|
source/index.js
|
function(targetPath, callback) {
client
.deleteFile(targetPath)
.then(function() {
__executeCallbackAsync(callback, [null]);
})
.catch(callback);
}
|
javascript
|
function(targetPath, callback) {
client
.deleteFile(targetPath)
.then(function() {
__executeCallbackAsync(callback, [null]);
})
.catch(callback);
}
|
[
"function",
"(",
"targetPath",
",",
"callback",
")",
"{",
"client",
".",
"deleteFile",
"(",
"targetPath",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"__executeCallbackAsync",
"(",
"callback",
",",
"[",
"null",
"]",
")",
";",
"}",
")",
".",
"catch",
"(",
"callback",
")",
";",
"}"
] |
Remote remote directory
@todo Check if remote is a directory before removing
@param {String} targetPath Directory to remove
@param {Function} callback Callback: function(error)
|
[
"Remote",
"remote",
"directory"
] |
b41794aae460df6d24ea6eaa1d833f8465b26606
|
https://github.com/perry-mitchell/webdav-fs/blob/b41794aae460df6d24ea6eaa1d833f8465b26606/source/index.js#L216-L223
|
train
|
|
perry-mitchell/webdav-fs
|
source/index.js
|
function(remotePath, callback) {
client
.stat(remotePath)
.then(function(stat) {
__executeCallbackAsync(callback, [null, __convertStat(stat)]);
})
.catch(callback);
}
|
javascript
|
function(remotePath, callback) {
client
.stat(remotePath)
.then(function(stat) {
__executeCallbackAsync(callback, [null, __convertStat(stat)]);
})
.catch(callback);
}
|
[
"function",
"(",
"remotePath",
",",
"callback",
")",
"{",
"client",
".",
"stat",
"(",
"remotePath",
")",
".",
"then",
"(",
"function",
"(",
"stat",
")",
"{",
"__executeCallbackAsync",
"(",
"callback",
",",
"[",
"null",
",",
"__convertStat",
"(",
"stat",
")",
"]",
")",
";",
"}",
")",
".",
"catch",
"(",
"callback",
")",
";",
"}"
] |
Stat a remote item
@param {String} remotePath The remote item to stat
@param {Function} callback Callback: function(error, stat)
|
[
"Stat",
"a",
"remote",
"item"
] |
b41794aae460df6d24ea6eaa1d833f8465b26606
|
https://github.com/perry-mitchell/webdav-fs/blob/b41794aae460df6d24ea6eaa1d833f8465b26606/source/index.js#L230-L237
|
train
|
|
perry-mitchell/webdav-fs
|
source/index.js
|
function(/* filename, data[, encoding], callback */) {
var args = Array.prototype.slice.call(arguments),
argc = args.length;
if (argc <= 2) {
throw new Error("Invalid number of arguments");
}
var filePath = args[0],
data = args[1],
encoding = (argc >= 3 && typeof args[2] === "string") ? args[2] : "text",
callback = function() {};
if (typeof args[2] === "function") {
callback = args[2];
} else if (argc >= 4 && typeof args[3] === "function") {
callback = args[3];
}
encoding = (encoding === "utf8") ? "text" : encoding;
client
.putFileContents(filePath, data, { format: encoding })
.then(function() {
__executeCallbackAsync(callback, [null]);
})
.catch(callback);
}
|
javascript
|
function(/* filename, data[, encoding], callback */) {
var args = Array.prototype.slice.call(arguments),
argc = args.length;
if (argc <= 2) {
throw new Error("Invalid number of arguments");
}
var filePath = args[0],
data = args[1],
encoding = (argc >= 3 && typeof args[2] === "string") ? args[2] : "text",
callback = function() {};
if (typeof args[2] === "function") {
callback = args[2];
} else if (argc >= 4 && typeof args[3] === "function") {
callback = args[3];
}
encoding = (encoding === "utf8") ? "text" : encoding;
client
.putFileContents(filePath, data, { format: encoding })
.then(function() {
__executeCallbackAsync(callback, [null]);
})
.catch(callback);
}
|
[
"function",
"(",
")",
"{",
"var",
"args",
"=",
"Array",
".",
"prototype",
".",
"slice",
".",
"call",
"(",
"arguments",
")",
",",
"argc",
"=",
"args",
".",
"length",
";",
"if",
"(",
"argc",
"<=",
"2",
")",
"{",
"throw",
"new",
"Error",
"(",
"\"Invalid number of arguments\"",
")",
";",
"}",
"var",
"filePath",
"=",
"args",
"[",
"0",
"]",
",",
"data",
"=",
"args",
"[",
"1",
"]",
",",
"encoding",
"=",
"(",
"argc",
">=",
"3",
"&&",
"typeof",
"args",
"[",
"2",
"]",
"===",
"\"string\"",
")",
"?",
"args",
"[",
"2",
"]",
":",
"\"text\"",
",",
"callback",
"=",
"function",
"(",
")",
"{",
"}",
";",
"if",
"(",
"typeof",
"args",
"[",
"2",
"]",
"===",
"\"function\"",
")",
"{",
"callback",
"=",
"args",
"[",
"2",
"]",
";",
"}",
"else",
"if",
"(",
"argc",
">=",
"4",
"&&",
"typeof",
"args",
"[",
"3",
"]",
"===",
"\"function\"",
")",
"{",
"callback",
"=",
"args",
"[",
"3",
"]",
";",
"}",
"encoding",
"=",
"(",
"encoding",
"===",
"\"utf8\"",
")",
"?",
"\"text\"",
":",
"encoding",
";",
"client",
".",
"putFileContents",
"(",
"filePath",
",",
"data",
",",
"{",
"format",
":",
"encoding",
"}",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"__executeCallbackAsync",
"(",
"callback",
",",
"[",
"null",
"]",
")",
";",
"}",
")",
".",
"catch",
"(",
"callback",
")",
";",
"}"
] |
Write data to a remote file
@param {String} filename The remote file path to write to
@param {Buffer|String} data The data to write
@param {String=} encoding Optional encoding to write as (utf8/binary) (default: utf8)
@param {Function} callback Callback: function(error)
|
[
"Write",
"data",
"to",
"a",
"remote",
"file"
] |
b41794aae460df6d24ea6eaa1d833f8465b26606
|
https://github.com/perry-mitchell/webdav-fs/blob/b41794aae460df6d24ea6eaa1d833f8465b26606/source/index.js#L260-L282
|
train
|
|
JamesMessinger/swagger-server
|
samples/sample3/handlers/employees.js
|
loadMockData
|
function loadMockData(server, next) {
// Create REST resources for each employee
var resources = data.employees.map(function(employee) {
return new swagger.Resource('/employees', employee.username, employee);
});
// Save the resources to the mock data store
server.dataStore.save(resources, next);
}
|
javascript
|
function loadMockData(server, next) {
// Create REST resources for each employee
var resources = data.employees.map(function(employee) {
return new swagger.Resource('/employees', employee.username, employee);
});
// Save the resources to the mock data store
server.dataStore.save(resources, next);
}
|
[
"function",
"loadMockData",
"(",
"server",
",",
"next",
")",
"{",
"var",
"resources",
"=",
"data",
".",
"employees",
".",
"map",
"(",
"function",
"(",
"employee",
")",
"{",
"return",
"new",
"swagger",
".",
"Resource",
"(",
"'/employees'",
",",
"employee",
".",
"username",
",",
"employee",
")",
";",
"}",
")",
";",
"server",
".",
"dataStore",
".",
"save",
"(",
"resources",
",",
"next",
")",
";",
"}"
] |
Loads mock employee data
@param {SwaggerServer} server
@param {function} next
|
[
"Loads",
"mock",
"employee",
"data"
] |
7afa6bdb159022a9bed1efaa2997a6d5f993c7e4
|
https://github.com/JamesMessinger/swagger-server/blob/7afa6bdb159022a9bed1efaa2997a6d5f993c7e4/samples/sample3/handlers/employees.js#L34-L42
|
train
|
JamesMessinger/swagger-server
|
samples/sample3/handlers/employees.js
|
verifyUsernameDoesNotExist
|
function verifyUsernameDoesNotExist(req, res, next) {
var username = req.body.username;
var dataStore = req.app.dataStore;
// Check for an existing employee REST resource - /employees/{username}
var resource = new swagger.Resource('/employees', username, null);
dataStore.get(resource, function(err, resource) {
if (resource) {
// The username already exists, so send an HTTP 409 (Conflict)
res.sendStatus(409);
}
else {
next();
}
});
}
|
javascript
|
function verifyUsernameDoesNotExist(req, res, next) {
var username = req.body.username;
var dataStore = req.app.dataStore;
// Check for an existing employee REST resource - /employees/{username}
var resource = new swagger.Resource('/employees', username, null);
dataStore.get(resource, function(err, resource) {
if (resource) {
// The username already exists, so send an HTTP 409 (Conflict)
res.sendStatus(409);
}
else {
next();
}
});
}
|
[
"function",
"verifyUsernameDoesNotExist",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"var",
"username",
"=",
"req",
".",
"body",
".",
"username",
";",
"var",
"dataStore",
"=",
"req",
".",
"app",
".",
"dataStore",
";",
"var",
"resource",
"=",
"new",
"swagger",
".",
"Resource",
"(",
"'/employees'",
",",
"username",
",",
"null",
")",
";",
"dataStore",
".",
"get",
"(",
"resource",
",",
"function",
"(",
"err",
",",
"resource",
")",
"{",
"if",
"(",
"resource",
")",
"{",
"res",
".",
"sendStatus",
"(",
"409",
")",
";",
"}",
"else",
"{",
"next",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
] |
Verifies that the new employee's username isn't the same as any existing username.
|
[
"Verifies",
"that",
"the",
"new",
"employee",
"s",
"username",
"isn",
"t",
"the",
"same",
"as",
"any",
"existing",
"username",
"."
] |
7afa6bdb159022a9bed1efaa2997a6d5f993c7e4
|
https://github.com/JamesMessinger/swagger-server/blob/7afa6bdb159022a9bed1efaa2997a6d5f993c7e4/samples/sample3/handlers/employees.js#L47-L62
|
train
|
JamesMessinger/swagger-server
|
lib/server.js
|
SwaggerServer
|
function SwaggerServer(app) {
app = app || express();
// Event Emitter
_.extend(this, EventEmitter.prototype);
EventEmitter.call(this);
/**
* @type {Middleware}
* @protected
*/
this.__middleware = new SwaggerMiddleware(app);
/**
* @type {SwaggerParser}
* @protected
*/
this.__parser = new SwaggerParser(this);
/**
*
* @type {Handlers|exports|module.exports}
* @private
*/
this.__handlers = new Handlers(this);
/**
* @type {SwaggerWatcher}
* @protected
*/
this.__watcher = new SwaggerWatcher(this);
/**
* The Express Application.
* @type {e.application}
*/
this.app = app;
/**
* The {@link DataStore} object that's used by the mock middleware.
* See https://github.com/BigstickCarpet/swagger-express-middleware/blob/master/docs/exports/DataStore.md
*
* @type {DataStore}
*/
Object.defineProperty(this, 'dataStore', {
configurable: true,
enumerable: true,
get: function() {
return app.get('mock data store');
},
set: function(value) {
app.set('mock data store', value);
}
});
/**
* Parses the given Swagger API.
*
* @param {string|object} swagger
* The file path or URL of a Swagger 2.0 API spec, in YAML or JSON format.
* Or a valid Swagger API object (see https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#swagger-object).
*
* @param {function} [callback]
* function(err, api, parser)
*/
this.parse = function(swagger, callback) {
this.__parser.parse(swagger);
if (_.isFunction(callback)) {
this.__parser.whenParsed(callback);
}
};
/**
* Adds the Swaggerize Express handlers to the Express Instance
* (see https://github.com/krakenjs/swaggerize-express for info and acceptable formats)
*/
this.addHandlers = function() {
this.__handlers.setupHandlers();
};
// Patch the Express app to support Swagger
application.patch(this);
// For convenience, expose many of the Express app's methods directly on the Swagger Server object
var server = this;
swaggerMethods.concat(['enable', 'disable', 'set', 'listen', 'use', 'route', 'all'])
.forEach(function(method) {
server[method] = app[method].bind(app);
});
}
|
javascript
|
function SwaggerServer(app) {
app = app || express();
// Event Emitter
_.extend(this, EventEmitter.prototype);
EventEmitter.call(this);
/**
* @type {Middleware}
* @protected
*/
this.__middleware = new SwaggerMiddleware(app);
/**
* @type {SwaggerParser}
* @protected
*/
this.__parser = new SwaggerParser(this);
/**
*
* @type {Handlers|exports|module.exports}
* @private
*/
this.__handlers = new Handlers(this);
/**
* @type {SwaggerWatcher}
* @protected
*/
this.__watcher = new SwaggerWatcher(this);
/**
* The Express Application.
* @type {e.application}
*/
this.app = app;
/**
* The {@link DataStore} object that's used by the mock middleware.
* See https://github.com/BigstickCarpet/swagger-express-middleware/blob/master/docs/exports/DataStore.md
*
* @type {DataStore}
*/
Object.defineProperty(this, 'dataStore', {
configurable: true,
enumerable: true,
get: function() {
return app.get('mock data store');
},
set: function(value) {
app.set('mock data store', value);
}
});
/**
* Parses the given Swagger API.
*
* @param {string|object} swagger
* The file path or URL of a Swagger 2.0 API spec, in YAML or JSON format.
* Or a valid Swagger API object (see https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#swagger-object).
*
* @param {function} [callback]
* function(err, api, parser)
*/
this.parse = function(swagger, callback) {
this.__parser.parse(swagger);
if (_.isFunction(callback)) {
this.__parser.whenParsed(callback);
}
};
/**
* Adds the Swaggerize Express handlers to the Express Instance
* (see https://github.com/krakenjs/swaggerize-express for info and acceptable formats)
*/
this.addHandlers = function() {
this.__handlers.setupHandlers();
};
// Patch the Express app to support Swagger
application.patch(this);
// For convenience, expose many of the Express app's methods directly on the Swagger Server object
var server = this;
swaggerMethods.concat(['enable', 'disable', 'set', 'listen', 'use', 'route', 'all'])
.forEach(function(method) {
server[method] = app[method].bind(app);
});
}
|
[
"function",
"SwaggerServer",
"(",
"app",
")",
"{",
"app",
"=",
"app",
"||",
"express",
"(",
")",
";",
"_",
".",
"extend",
"(",
"this",
",",
"EventEmitter",
".",
"prototype",
")",
";",
"EventEmitter",
".",
"call",
"(",
"this",
")",
";",
"this",
".",
"__middleware",
"=",
"new",
"SwaggerMiddleware",
"(",
"app",
")",
";",
"this",
".",
"__parser",
"=",
"new",
"SwaggerParser",
"(",
"this",
")",
";",
"this",
".",
"__handlers",
"=",
"new",
"Handlers",
"(",
"this",
")",
";",
"this",
".",
"__watcher",
"=",
"new",
"SwaggerWatcher",
"(",
"this",
")",
";",
"this",
".",
"app",
"=",
"app",
";",
"Object",
".",
"defineProperty",
"(",
"this",
",",
"'dataStore'",
",",
"{",
"configurable",
":",
"true",
",",
"enumerable",
":",
"true",
",",
"get",
":",
"function",
"(",
")",
"{",
"return",
"app",
".",
"get",
"(",
"'mock data store'",
")",
";",
"}",
",",
"set",
":",
"function",
"(",
"value",
")",
"{",
"app",
".",
"set",
"(",
"'mock data store'",
",",
"value",
")",
";",
"}",
"}",
")",
";",
"this",
".",
"parse",
"=",
"function",
"(",
"swagger",
",",
"callback",
")",
"{",
"this",
".",
"__parser",
".",
"parse",
"(",
"swagger",
")",
";",
"if",
"(",
"_",
".",
"isFunction",
"(",
"callback",
")",
")",
"{",
"this",
".",
"__parser",
".",
"whenParsed",
"(",
"callback",
")",
";",
"}",
"}",
";",
"this",
".",
"addHandlers",
"=",
"function",
"(",
")",
"{",
"this",
".",
"__handlers",
".",
"setupHandlers",
"(",
")",
";",
"}",
";",
"application",
".",
"patch",
"(",
"this",
")",
";",
"var",
"server",
"=",
"this",
";",
"swaggerMethods",
".",
"concat",
"(",
"[",
"'enable'",
",",
"'disable'",
",",
"'set'",
",",
"'listen'",
",",
"'use'",
",",
"'route'",
",",
"'all'",
"]",
")",
".",
"forEach",
"(",
"function",
"(",
"method",
")",
"{",
"server",
"[",
"method",
"]",
"=",
"app",
"[",
"method",
"]",
".",
"bind",
"(",
"app",
")",
";",
"}",
")",
";",
"}"
] |
The Swagger Server class, which wraps an Express Application and extends it.
@param {e.application} [app] An Express Application. If not provided, a new app is created.
@constructor
@extends EventEmitter
|
[
"The",
"Swagger",
"Server",
"class",
"which",
"wraps",
"an",
"Express",
"Application",
"and",
"extends",
"it",
"."
] |
7afa6bdb159022a9bed1efaa2997a6d5f993c7e4
|
https://github.com/JamesMessinger/swagger-server/blob/7afa6bdb159022a9bed1efaa2997a6d5f993c7e4/lib/server.js#L22-L112
|
train
|
JamesMessinger/swagger-server
|
lib/index.js
|
createRouter
|
function createRouter() {
var rtr = express.Router.apply(express, arguments);
router.patch(rtr);
return rtr;
}
|
javascript
|
function createRouter() {
var rtr = express.Router.apply(express, arguments);
router.patch(rtr);
return rtr;
}
|
[
"function",
"createRouter",
"(",
")",
"{",
"var",
"rtr",
"=",
"express",
".",
"Router",
".",
"apply",
"(",
"express",
",",
"arguments",
")",
";",
"router",
".",
"patch",
"(",
"rtr",
")",
";",
"return",
"rtr",
";",
"}"
] |
Creates an Express Router and patches it to support Swagger.
@returns {e.Router}
|
[
"Creates",
"an",
"Express",
"Router",
"and",
"patches",
"it",
"to",
"support",
"Swagger",
"."
] |
7afa6bdb159022a9bed1efaa2997a6d5f993c7e4
|
https://github.com/JamesMessinger/swagger-server/blob/7afa6bdb159022a9bed1efaa2997a6d5f993c7e4/lib/index.js#L40-L44
|
train
|
JamesMessinger/swagger-server
|
lib/index.js
|
Route
|
function Route(path) {
// Convert Swagger-style path to Express-style path
path = path.replace(util.swaggerParamRegExp, ':$1');
express.Route.call(this, path);
}
|
javascript
|
function Route(path) {
// Convert Swagger-style path to Express-style path
path = path.replace(util.swaggerParamRegExp, ':$1');
express.Route.call(this, path);
}
|
[
"function",
"Route",
"(",
"path",
")",
"{",
"path",
"=",
"path",
".",
"replace",
"(",
"util",
".",
"swaggerParamRegExp",
",",
"':$1'",
")",
";",
"express",
".",
"Route",
".",
"call",
"(",
"this",
",",
"path",
")",
";",
"}"
] |
Extends the Express Route class to support Swagger.
@param {string} path
@constructor
@extends {e.Route}
|
[
"Extends",
"the",
"Express",
"Route",
"class",
"to",
"support",
"Swagger",
"."
] |
7afa6bdb159022a9bed1efaa2997a6d5f993c7e4
|
https://github.com/JamesMessinger/swagger-server/blob/7afa6bdb159022a9bed1efaa2997a6d5f993c7e4/lib/index.js#L52-L56
|
train
|
JamesMessinger/swagger-server
|
lib/router.js
|
function(router, target) {
// By default, just patch the router's own methods.
// If a target is given, then patch the router to call the target's methods
target = target || router;
// get(setting), which is different than get(path, fn)
var get = router.get;
// Wrap all of these methods to convert Swagger-style paths to Express-style paths
var fns = {};
['use', 'route', 'all'].concat(swaggerMethods).forEach(function(method) {
fns[method] = target[method];
router[method] = function(path) {
var args = _.drop(arguments, 0);
// Special-case for `app.get(setting)`
if (args.length === 1 && method === 'get') {
return get.call(router, path);
}
// Convert Swagger-style path to Express-style path
if (_.isString(path)) {
args[0] = path.replace(util.swaggerParamRegExp, ':$1');
}
// Pass-through to the corresponding Express method
var ret = fns[method].apply(target, args);
if (router.__sortMiddleWare) {
router.__sortMiddleWare();
}
return ret;
};
});
}
|
javascript
|
function(router, target) {
// By default, just patch the router's own methods.
// If a target is given, then patch the router to call the target's methods
target = target || router;
// get(setting), which is different than get(path, fn)
var get = router.get;
// Wrap all of these methods to convert Swagger-style paths to Express-style paths
var fns = {};
['use', 'route', 'all'].concat(swaggerMethods).forEach(function(method) {
fns[method] = target[method];
router[method] = function(path) {
var args = _.drop(arguments, 0);
// Special-case for `app.get(setting)`
if (args.length === 1 && method === 'get') {
return get.call(router, path);
}
// Convert Swagger-style path to Express-style path
if (_.isString(path)) {
args[0] = path.replace(util.swaggerParamRegExp, ':$1');
}
// Pass-through to the corresponding Express method
var ret = fns[method].apply(target, args);
if (router.__sortMiddleWare) {
router.__sortMiddleWare();
}
return ret;
};
});
}
|
[
"function",
"(",
"router",
",",
"target",
")",
"{",
"target",
"=",
"target",
"||",
"router",
";",
"var",
"get",
"=",
"router",
".",
"get",
";",
"var",
"fns",
"=",
"{",
"}",
";",
"[",
"'use'",
",",
"'route'",
",",
"'all'",
"]",
".",
"concat",
"(",
"swaggerMethods",
")",
".",
"forEach",
"(",
"function",
"(",
"method",
")",
"{",
"fns",
"[",
"method",
"]",
"=",
"target",
"[",
"method",
"]",
";",
"router",
"[",
"method",
"]",
"=",
"function",
"(",
"path",
")",
"{",
"var",
"args",
"=",
"_",
".",
"drop",
"(",
"arguments",
",",
"0",
")",
";",
"if",
"(",
"args",
".",
"length",
"===",
"1",
"&&",
"method",
"===",
"'get'",
")",
"{",
"return",
"get",
".",
"call",
"(",
"router",
",",
"path",
")",
";",
"}",
"if",
"(",
"_",
".",
"isString",
"(",
"path",
")",
")",
"{",
"args",
"[",
"0",
"]",
"=",
"path",
".",
"replace",
"(",
"util",
".",
"swaggerParamRegExp",
",",
"':$1'",
")",
";",
"}",
"var",
"ret",
"=",
"fns",
"[",
"method",
"]",
".",
"apply",
"(",
"target",
",",
"args",
")",
";",
"if",
"(",
"router",
".",
"__sortMiddleWare",
")",
"{",
"router",
".",
"__sortMiddleWare",
"(",
")",
";",
"}",
"return",
"ret",
";",
"}",
";",
"}",
")",
";",
"}"
] |
Patches an Express Router to support Swagger.
@param {e.Router|e.application} router
@param {e.Router|e.application} [target]
|
[
"Patches",
"an",
"Express",
"Router",
"to",
"support",
"Swagger",
"."
] |
7afa6bdb159022a9bed1efaa2997a6d5f993c7e4
|
https://github.com/JamesMessinger/swagger-server/blob/7afa6bdb159022a9bed1efaa2997a6d5f993c7e4/lib/router.js#L13-L48
|
train
|
|
JamesMessinger/swagger-server
|
lib/handlers.js
|
Handlers
|
function Handlers(server) {
var self = this;
this.server = server;
//Store the most recently parsed swagger data for when only the handlers get re-attached.
this.server.on('parsed', function(err, api, parser, basePath) {
self.api = api;
self.parser = parser;
self.basePath = basePath;
self.setupHandlers();
});
}
|
javascript
|
function Handlers(server) {
var self = this;
this.server = server;
//Store the most recently parsed swagger data for when only the handlers get re-attached.
this.server.on('parsed', function(err, api, parser, basePath) {
self.api = api;
self.parser = parser;
self.basePath = basePath;
self.setupHandlers();
});
}
|
[
"function",
"Handlers",
"(",
"server",
")",
"{",
"var",
"self",
"=",
"this",
";",
"this",
".",
"server",
"=",
"server",
";",
"this",
".",
"server",
".",
"on",
"(",
"'parsed'",
",",
"function",
"(",
"err",
",",
"api",
",",
"parser",
",",
"basePath",
")",
"{",
"self",
".",
"api",
"=",
"api",
";",
"self",
".",
"parser",
"=",
"parser",
";",
"self",
".",
"basePath",
"=",
"basePath",
";",
"self",
".",
"setupHandlers",
"(",
")",
";",
"}",
")",
";",
"}"
] |
The Handler class, correlates the swagger paths with the handlers directory structure and adds the d
custom logic to the Express instance.
@param server
@constructor
|
[
"The",
"Handler",
"class",
"correlates",
"the",
"swagger",
"paths",
"with",
"the",
"handlers",
"directory",
"structure",
"and",
"adds",
"the",
"d",
"custom",
"logic",
"to",
"the",
"Express",
"instance",
"."
] |
7afa6bdb159022a9bed1efaa2997a6d5f993c7e4
|
https://github.com/JamesMessinger/swagger-server/blob/7afa6bdb159022a9bed1efaa2997a6d5f993c7e4/lib/handlers.js#L19-L30
|
train
|
JamesMessinger/swagger-server
|
lib/handlers.js
|
addPathToExpress
|
function addPathToExpress(handlerObj, handlePath) {
var self = handlerObj;
//Check to make sure that the module exists and will load properly to what node expects
if (moduleExists.call(self, handlePath)) {
//retrieve the http verbs defined in the handler files and then add to the swagger server
var handleVerbs = require(handlePath);
//Get the route path by removing the ./handlers and the .js file extension
//TODO: Use path names to get these
var routePath = handlePath.replace(/.*\/handlers/, '');
routePath = routePath.replace(/\.js/, '');
swaggerMethods.forEach(function(method) {
if (handleVerbs[method] && validSwaggerize(self, handleVerbs[method])) {
self.server[method](routePath, handleVerbs[method]);
}
});
}
}
|
javascript
|
function addPathToExpress(handlerObj, handlePath) {
var self = handlerObj;
//Check to make sure that the module exists and will load properly to what node expects
if (moduleExists.call(self, handlePath)) {
//retrieve the http verbs defined in the handler files and then add to the swagger server
var handleVerbs = require(handlePath);
//Get the route path by removing the ./handlers and the .js file extension
//TODO: Use path names to get these
var routePath = handlePath.replace(/.*\/handlers/, '');
routePath = routePath.replace(/\.js/, '');
swaggerMethods.forEach(function(method) {
if (handleVerbs[method] && validSwaggerize(self, handleVerbs[method])) {
self.server[method](routePath, handleVerbs[method]);
}
});
}
}
|
[
"function",
"addPathToExpress",
"(",
"handlerObj",
",",
"handlePath",
")",
"{",
"var",
"self",
"=",
"handlerObj",
";",
"if",
"(",
"moduleExists",
".",
"call",
"(",
"self",
",",
"handlePath",
")",
")",
"{",
"var",
"handleVerbs",
"=",
"require",
"(",
"handlePath",
")",
";",
"var",
"routePath",
"=",
"handlePath",
".",
"replace",
"(",
"/",
".*\\/handlers",
"/",
",",
"''",
")",
";",
"routePath",
"=",
"routePath",
".",
"replace",
"(",
"/",
"\\.js",
"/",
",",
"''",
")",
";",
"swaggerMethods",
".",
"forEach",
"(",
"function",
"(",
"method",
")",
"{",
"if",
"(",
"handleVerbs",
"[",
"method",
"]",
"&&",
"validSwaggerize",
"(",
"self",
",",
"handleVerbs",
"[",
"method",
"]",
")",
")",
"{",
"self",
".",
"server",
"[",
"method",
"]",
"(",
"routePath",
",",
"handleVerbs",
"[",
"method",
"]",
")",
";",
"}",
"}",
")",
";",
"}",
"}"
] |
Add the handlePath to the Swagger Express server if valid
@param handlePath
|
[
"Add",
"the",
"handlePath",
"to",
"the",
"Swagger",
"Express",
"server",
"if",
"valid"
] |
7afa6bdb159022a9bed1efaa2997a6d5f993c7e4
|
https://github.com/JamesMessinger/swagger-server/blob/7afa6bdb159022a9bed1efaa2997a6d5f993c7e4/lib/handlers.js#L69-L87
|
train
|
JamesMessinger/swagger-server
|
lib/handlers.js
|
moduleExists
|
function moduleExists(name) {
//TODO: Check that the file exists before trying to require it.
try {
require.resolve(name);
}
catch (err) {
this.server.emit('error', err);
return false;
}
return true;
}
|
javascript
|
function moduleExists(name) {
//TODO: Check that the file exists before trying to require it.
try {
require.resolve(name);
}
catch (err) {
this.server.emit('error', err);
return false;
}
return true;
}
|
[
"function",
"moduleExists",
"(",
"name",
")",
"{",
"try",
"{",
"require",
".",
"resolve",
"(",
"name",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"this",
".",
"server",
".",
"emit",
"(",
"'error'",
",",
"err",
")",
";",
"return",
"false",
";",
"}",
"return",
"true",
";",
"}"
] |
Check to see if the provided name is a valid node module.
@param name
@returns {boolean}
|
[
"Check",
"to",
"see",
"if",
"the",
"provided",
"name",
"is",
"a",
"valid",
"node",
"module",
"."
] |
7afa6bdb159022a9bed1efaa2997a6d5f993c7e4
|
https://github.com/JamesMessinger/swagger-server/blob/7afa6bdb159022a9bed1efaa2997a6d5f993c7e4/lib/handlers.js#L119-L129
|
train
|
JamesMessinger/swagger-server
|
samples/sample3/handlers/employees/{username}/photos/{photoType}.js
|
loadMockData
|
function loadMockData(server, next) {
// Create REST resources for each employee photo
var resources = [];
data.employees.forEach(function(employee) {
var collectionPath = '/employees/' + employee.username + '/photos';
resources.push(new swagger.Resource(collectionPath, 'portrait', {path: employee.portrait}));
resources.push(new swagger.Resource(collectionPath, 'thumbnail', {path: employee.thumbnail}));
});
// Save the resources to the mock data store
server.dataStore.save(resources, next);
}
|
javascript
|
function loadMockData(server, next) {
// Create REST resources for each employee photo
var resources = [];
data.employees.forEach(function(employee) {
var collectionPath = '/employees/' + employee.username + '/photos';
resources.push(new swagger.Resource(collectionPath, 'portrait', {path: employee.portrait}));
resources.push(new swagger.Resource(collectionPath, 'thumbnail', {path: employee.thumbnail}));
});
// Save the resources to the mock data store
server.dataStore.save(resources, next);
}
|
[
"function",
"loadMockData",
"(",
"server",
",",
"next",
")",
"{",
"var",
"resources",
"=",
"[",
"]",
";",
"data",
".",
"employees",
".",
"forEach",
"(",
"function",
"(",
"employee",
")",
"{",
"var",
"collectionPath",
"=",
"'/employees/'",
"+",
"employee",
".",
"username",
"+",
"'/photos'",
";",
"resources",
".",
"push",
"(",
"new",
"swagger",
".",
"Resource",
"(",
"collectionPath",
",",
"'portrait'",
",",
"{",
"path",
":",
"employee",
".",
"portrait",
"}",
")",
")",
";",
"resources",
".",
"push",
"(",
"new",
"swagger",
".",
"Resource",
"(",
"collectionPath",
",",
"'thumbnail'",
",",
"{",
"path",
":",
"employee",
".",
"thumbnail",
"}",
")",
")",
";",
"}",
")",
";",
"server",
".",
"dataStore",
".",
"save",
"(",
"resources",
",",
"next",
")",
";",
"}"
] |
Loads mock employee photo data
@param {SwaggerServer} server
@param {function} next
|
[
"Loads",
"mock",
"employee",
"photo",
"data"
] |
7afa6bdb159022a9bed1efaa2997a6d5f993c7e4
|
https://github.com/JamesMessinger/swagger-server/blob/7afa6bdb159022a9bed1efaa2997a6d5f993c7e4/samples/sample3/handlers/employees/{username}/photos/{photoType}.js#L41-L52
|
train
|
JamesMessinger/swagger-server
|
lib/watcher.js
|
SwaggerWatcher
|
function SwaggerWatcher(server) {
var self = this;
self.server = server;
/**
* The Swagger API files that are being watched.
* @type {FSWatcher[]}
*/
self.watchedSwaggerFiles = [];
/**
* The Handler files that are being watched.
* @type {FSWatcher[]}
*/
self.watchedHandlerFiles = [];
// Watch Swagger API files
server.on('parsed', function(err, api, parser) {
// Watch all the files that were parsed
self.unwatchSwaggerFiles();
self.watchSwaggerFiles(parser.$refs.paths('fs'));
});
// Watch Handler Files
server.on('handled', function(err, filePaths) {
self.unwatchHandlerFiles(filePaths);
self.watchHandlerFiles(filePaths);
});
}
|
javascript
|
function SwaggerWatcher(server) {
var self = this;
self.server = server;
/**
* The Swagger API files that are being watched.
* @type {FSWatcher[]}
*/
self.watchedSwaggerFiles = [];
/**
* The Handler files that are being watched.
* @type {FSWatcher[]}
*/
self.watchedHandlerFiles = [];
// Watch Swagger API files
server.on('parsed', function(err, api, parser) {
// Watch all the files that were parsed
self.unwatchSwaggerFiles();
self.watchSwaggerFiles(parser.$refs.paths('fs'));
});
// Watch Handler Files
server.on('handled', function(err, filePaths) {
self.unwatchHandlerFiles(filePaths);
self.watchHandlerFiles(filePaths);
});
}
|
[
"function",
"SwaggerWatcher",
"(",
"server",
")",
"{",
"var",
"self",
"=",
"this",
";",
"self",
".",
"server",
"=",
"server",
";",
"self",
".",
"watchedSwaggerFiles",
"=",
"[",
"]",
";",
"self",
".",
"watchedHandlerFiles",
"=",
"[",
"]",
";",
"server",
".",
"on",
"(",
"'parsed'",
",",
"function",
"(",
"err",
",",
"api",
",",
"parser",
")",
"{",
"self",
".",
"unwatchSwaggerFiles",
"(",
")",
";",
"self",
".",
"watchSwaggerFiles",
"(",
"parser",
".",
"$refs",
".",
"paths",
"(",
"'fs'",
")",
")",
";",
"}",
")",
";",
"server",
".",
"on",
"(",
"'handled'",
",",
"function",
"(",
"err",
",",
"filePaths",
")",
"{",
"self",
".",
"unwatchHandlerFiles",
"(",
"filePaths",
")",
";",
"self",
".",
"watchHandlerFiles",
"(",
"filePaths",
")",
";",
"}",
")",
";",
"}"
] |
Watches files for changes and updates the server accordingly.
@param {SwaggerServer} server
@constructor
|
[
"Watches",
"files",
"for",
"changes",
"and",
"updates",
"the",
"server",
"accordingly",
"."
] |
7afa6bdb159022a9bed1efaa2997a6d5f993c7e4
|
https://github.com/JamesMessinger/swagger-server/blob/7afa6bdb159022a9bed1efaa2997a6d5f993c7e4/lib/watcher.js#L14-L42
|
train
|
JamesMessinger/swagger-server
|
lib/watcher.js
|
watchFile
|
function watchFile(path, onChange) {
try {
var oldStats = fs.statSync(path);
var watcher = fs.watch(path, {persistent: false});
watcher.on('error', watchError);
watcher.on('change', function(event) {
fs.stat(path, function(err, stats) {
if (err) {
/* istanbul ignore next: not easy to repro this error in tests */
watchError(err);
}
else if (stats.mtime > oldStats.mtime) {
oldStats = stats;
onChange(event, path);
}
else {
util.debug('Ignoring %s event for "%s" because %j <= %j', event, path, stats.mtime, oldStats.mtime);
}
});
});
return watcher;
}
catch (e) {
watchError(e);
}
function watchError(e) {
util.warn('Error watching file "%s": %s', path, e.stack);
}
}
|
javascript
|
function watchFile(path, onChange) {
try {
var oldStats = fs.statSync(path);
var watcher = fs.watch(path, {persistent: false});
watcher.on('error', watchError);
watcher.on('change', function(event) {
fs.stat(path, function(err, stats) {
if (err) {
/* istanbul ignore next: not easy to repro this error in tests */
watchError(err);
}
else if (stats.mtime > oldStats.mtime) {
oldStats = stats;
onChange(event, path);
}
else {
util.debug('Ignoring %s event for "%s" because %j <= %j', event, path, stats.mtime, oldStats.mtime);
}
});
});
return watcher;
}
catch (e) {
watchError(e);
}
function watchError(e) {
util.warn('Error watching file "%s": %s', path, e.stack);
}
}
|
[
"function",
"watchFile",
"(",
"path",
",",
"onChange",
")",
"{",
"try",
"{",
"var",
"oldStats",
"=",
"fs",
".",
"statSync",
"(",
"path",
")",
";",
"var",
"watcher",
"=",
"fs",
".",
"watch",
"(",
"path",
",",
"{",
"persistent",
":",
"false",
"}",
")",
";",
"watcher",
".",
"on",
"(",
"'error'",
",",
"watchError",
")",
";",
"watcher",
".",
"on",
"(",
"'change'",
",",
"function",
"(",
"event",
")",
"{",
"fs",
".",
"stat",
"(",
"path",
",",
"function",
"(",
"err",
",",
"stats",
")",
"{",
"if",
"(",
"err",
")",
"{",
"watchError",
"(",
"err",
")",
";",
"}",
"else",
"if",
"(",
"stats",
".",
"mtime",
">",
"oldStats",
".",
"mtime",
")",
"{",
"oldStats",
"=",
"stats",
";",
"onChange",
"(",
"event",
",",
"path",
")",
";",
"}",
"else",
"{",
"util",
".",
"debug",
"(",
"'Ignoring %s event for \"%s\" because %j <= %j'",
",",
"event",
",",
"path",
",",
"stats",
".",
"mtime",
",",
"oldStats",
".",
"mtime",
")",
";",
"}",
"}",
")",
";",
"}",
")",
";",
"return",
"watcher",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"watchError",
"(",
"e",
")",
";",
"}",
"function",
"watchError",
"(",
"e",
")",
"{",
"util",
".",
"warn",
"(",
"'Error watching file \"%s\": %s'",
",",
"path",
",",
"e",
".",
"stack",
")",
";",
"}",
"}"
] |
Watches a file, and calls the given callback whenever the file changes.
@param {string} path
The full path of the file.
@param {function} onChange
Callback signature is `function(event, filename)`. The event param will be "change", "delete", "move", etc.
The filename param is the full path of the file, and it is guaranteed to be present (unlike Node's FSWatcher).
@returns {FSWatcher|undefined}
Returns the file watcher, unless the path does not exist.
|
[
"Watches",
"a",
"file",
"and",
"calls",
"the",
"given",
"callback",
"whenever",
"the",
"file",
"changes",
"."
] |
7afa6bdb159022a9bed1efaa2997a6d5f993c7e4
|
https://github.com/JamesMessinger/swagger-server/blob/7afa6bdb159022a9bed1efaa2997a6d5f993c7e4/lib/watcher.js#L134-L165
|
train
|
JamesMessinger/swagger-server
|
samples/sample3/handlers/sessions.js
|
authenticate
|
function authenticate(req, res, next) {
var username = req.body.username,
password = req.body.password;
if (req.session && req.session.user.username === username) {
// This user is already logged in
next();
return;
}
// Get the employee REST resource - /employees/{username}
var dataStore = req.app.dataStore;
var resource = new swagger.Resource('/employees', username, null);
dataStore.get(resource, function(err, resource) {
// Check the login credentials
if (resource && resource.data.password === password) {
// Login is valid, so create a new session object
var sessionId = Math.random().toString(36).substr(2);
req.session = {
id: sessionId,
created: new Date(),
user: resource.data
};
// Save the session REST resource
resource = new swagger.Resource('/sessions', req.session.id, req.session);
dataStore.save(resource, next);
}
else {
// Login failed
res.sendStatus(401);
}
});
}
|
javascript
|
function authenticate(req, res, next) {
var username = req.body.username,
password = req.body.password;
if (req.session && req.session.user.username === username) {
// This user is already logged in
next();
return;
}
// Get the employee REST resource - /employees/{username}
var dataStore = req.app.dataStore;
var resource = new swagger.Resource('/employees', username, null);
dataStore.get(resource, function(err, resource) {
// Check the login credentials
if (resource && resource.data.password === password) {
// Login is valid, so create a new session object
var sessionId = Math.random().toString(36).substr(2);
req.session = {
id: sessionId,
created: new Date(),
user: resource.data
};
// Save the session REST resource
resource = new swagger.Resource('/sessions', req.session.id, req.session);
dataStore.save(resource, next);
}
else {
// Login failed
res.sendStatus(401);
}
});
}
|
[
"function",
"authenticate",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"var",
"username",
"=",
"req",
".",
"body",
".",
"username",
",",
"password",
"=",
"req",
".",
"body",
".",
"password",
";",
"if",
"(",
"req",
".",
"session",
"&&",
"req",
".",
"session",
".",
"user",
".",
"username",
"===",
"username",
")",
"{",
"next",
"(",
")",
";",
"return",
";",
"}",
"var",
"dataStore",
"=",
"req",
".",
"app",
".",
"dataStore",
";",
"var",
"resource",
"=",
"new",
"swagger",
".",
"Resource",
"(",
"'/employees'",
",",
"username",
",",
"null",
")",
";",
"dataStore",
".",
"get",
"(",
"resource",
",",
"function",
"(",
"err",
",",
"resource",
")",
"{",
"if",
"(",
"resource",
"&&",
"resource",
".",
"data",
".",
"password",
"===",
"password",
")",
"{",
"var",
"sessionId",
"=",
"Math",
".",
"random",
"(",
")",
".",
"toString",
"(",
"36",
")",
".",
"substr",
"(",
"2",
")",
";",
"req",
".",
"session",
"=",
"{",
"id",
":",
"sessionId",
",",
"created",
":",
"new",
"Date",
"(",
")",
",",
"user",
":",
"resource",
".",
"data",
"}",
";",
"resource",
"=",
"new",
"swagger",
".",
"Resource",
"(",
"'/sessions'",
",",
"req",
".",
"session",
".",
"id",
",",
"req",
".",
"session",
")",
";",
"dataStore",
".",
"save",
"(",
"resource",
",",
"next",
")",
";",
"}",
"else",
"{",
"res",
".",
"sendStatus",
"(",
"401",
")",
";",
"}",
"}",
")",
";",
"}"
] |
Authenticates the user's login credentials and creates a new user session.
|
[
"Authenticates",
"the",
"user",
"s",
"login",
"credentials",
"and",
"creates",
"a",
"new",
"user",
"session",
"."
] |
7afa6bdb159022a9bed1efaa2997a6d5f993c7e4
|
https://github.com/JamesMessinger/swagger-server/blob/7afa6bdb159022a9bed1efaa2997a6d5f993c7e4/samples/sample3/handlers/sessions.js#L35-L68
|
train
|
JamesMessinger/swagger-server
|
samples/sample3/handlers/sessions.js
|
sendSessionResponse
|
function sendSessionResponse(req, res, next) {
// Set the session cookie
res.cookie('session', req.session.id);
// Set the Location HTTP header
res.location('/sessions/' + req.session.id);
// Send the response
res.status(201).json(req.session);
}
|
javascript
|
function sendSessionResponse(req, res, next) {
// Set the session cookie
res.cookie('session', req.session.id);
// Set the Location HTTP header
res.location('/sessions/' + req.session.id);
// Send the response
res.status(201).json(req.session);
}
|
[
"function",
"sendSessionResponse",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"res",
".",
"cookie",
"(",
"'session'",
",",
"req",
".",
"session",
".",
"id",
")",
";",
"res",
".",
"location",
"(",
"'/sessions/'",
"+",
"req",
".",
"session",
".",
"id",
")",
";",
"res",
".",
"status",
"(",
"201",
")",
".",
"json",
"(",
"req",
".",
"session",
")",
";",
"}"
] |
Sends the session data and session cookie.
|
[
"Sends",
"the",
"session",
"data",
"and",
"session",
"cookie",
"."
] |
7afa6bdb159022a9bed1efaa2997a6d5f993c7e4
|
https://github.com/JamesMessinger/swagger-server/blob/7afa6bdb159022a9bed1efaa2997a6d5f993c7e4/samples/sample3/handlers/sessions.js#L73-L82
|
train
|
JamesMessinger/swagger-server
|
samples/sample3/handlers/sessions.js
|
identifyUser
|
function identifyUser(req, res, next) {
// Get the session ID from the session cookie
var sessionId = req.cookies.session;
req.session = null;
if (sessionId) {
// Get the session REST resource
var resource = new swagger.Resource('/sessions', sessionId, null);
req.app.dataStore.get(resource, function(err, resource) {
if (resource) {
// Add the session to the request, so other middleware can use it
req.session = resource.data;
console.log('Current User: %s', req.session.user.username);
}
else {
console.warn('INVALID SESSION ID: ' + sessionId);
}
next();
});
}
else {
console.log('Current User: ANONYMOUS');
next();
}
}
|
javascript
|
function identifyUser(req, res, next) {
// Get the session ID from the session cookie
var sessionId = req.cookies.session;
req.session = null;
if (sessionId) {
// Get the session REST resource
var resource = new swagger.Resource('/sessions', sessionId, null);
req.app.dataStore.get(resource, function(err, resource) {
if (resource) {
// Add the session to the request, so other middleware can use it
req.session = resource.data;
console.log('Current User: %s', req.session.user.username);
}
else {
console.warn('INVALID SESSION ID: ' + sessionId);
}
next();
});
}
else {
console.log('Current User: ANONYMOUS');
next();
}
}
|
[
"function",
"identifyUser",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"var",
"sessionId",
"=",
"req",
".",
"cookies",
".",
"session",
";",
"req",
".",
"session",
"=",
"null",
";",
"if",
"(",
"sessionId",
")",
"{",
"var",
"resource",
"=",
"new",
"swagger",
".",
"Resource",
"(",
"'/sessions'",
",",
"sessionId",
",",
"null",
")",
";",
"req",
".",
"app",
".",
"dataStore",
".",
"get",
"(",
"resource",
",",
"function",
"(",
"err",
",",
"resource",
")",
"{",
"if",
"(",
"resource",
")",
"{",
"req",
".",
"session",
"=",
"resource",
".",
"data",
";",
"console",
".",
"log",
"(",
"'Current User: %s'",
",",
"req",
".",
"session",
".",
"user",
".",
"username",
")",
";",
"}",
"else",
"{",
"console",
".",
"warn",
"(",
"'INVALID SESSION ID: '",
"+",
"sessionId",
")",
";",
"}",
"next",
"(",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"console",
".",
"log",
"(",
"'Current User: ANONYMOUS'",
")",
";",
"next",
"(",
")",
";",
"}",
"}"
] |
Identifies the user via the session cookie on the request.
`req.session` is set to the user's session, so it can be used by subsequent middleware.
|
[
"Identifies",
"the",
"user",
"via",
"the",
"session",
"cookie",
"on",
"the",
"request",
".",
"req",
".",
"session",
"is",
"set",
"to",
"the",
"user",
"s",
"session",
"so",
"it",
"can",
"be",
"used",
"by",
"subsequent",
"middleware",
"."
] |
7afa6bdb159022a9bed1efaa2997a6d5f993c7e4
|
https://github.com/JamesMessinger/swagger-server/blob/7afa6bdb159022a9bed1efaa2997a6d5f993c7e4/samples/sample3/handlers/sessions.js#L88-L112
|
train
|
JamesMessinger/swagger-server
|
samples/sample3/handlers/sessions.js
|
mustBeLoggedIn
|
function mustBeLoggedIn(req, res, next) {
if (req.session && req.session.user) {
next();
}
else {
res.status(401).send('You must be logged-in to access this resource');
}
}
|
javascript
|
function mustBeLoggedIn(req, res, next) {
if (req.session && req.session.user) {
next();
}
else {
res.status(401).send('You must be logged-in to access this resource');
}
}
|
[
"function",
"mustBeLoggedIn",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"if",
"(",
"req",
".",
"session",
"&&",
"req",
".",
"session",
".",
"user",
")",
"{",
"next",
"(",
")",
";",
"}",
"else",
"{",
"res",
".",
"status",
"(",
"401",
")",
".",
"send",
"(",
"'You must be logged-in to access this resource'",
")",
";",
"}",
"}"
] |
Prevents access to anonymous users.
|
[
"Prevents",
"access",
"to",
"anonymous",
"users",
"."
] |
7afa6bdb159022a9bed1efaa2997a6d5f993c7e4
|
https://github.com/JamesMessinger/swagger-server/blob/7afa6bdb159022a9bed1efaa2997a6d5f993c7e4/samples/sample3/handlers/sessions.js#L117-L124
|
train
|
JamesMessinger/swagger-server
|
samples/sample3/handlers/sessions.js
|
adminsOnly
|
function adminsOnly(req, res, next) {
if (req.session && _.contains(req.session.user.roles, 'admin')) {
next();
}
else {
res.status(401).send('Only administrators can access this resource');
}
}
|
javascript
|
function adminsOnly(req, res, next) {
if (req.session && _.contains(req.session.user.roles, 'admin')) {
next();
}
else {
res.status(401).send('Only administrators can access this resource');
}
}
|
[
"function",
"adminsOnly",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"if",
"(",
"req",
".",
"session",
"&&",
"_",
".",
"contains",
"(",
"req",
".",
"session",
".",
"user",
".",
"roles",
",",
"'admin'",
")",
")",
"{",
"next",
"(",
")",
";",
"}",
"else",
"{",
"res",
".",
"status",
"(",
"401",
")",
".",
"send",
"(",
"'Only administrators can access this resource'",
")",
";",
"}",
"}"
] |
Prevents access to anyone who is not in the "admin" role.
|
[
"Prevents",
"access",
"to",
"anyone",
"who",
"is",
"not",
"in",
"the",
"admin",
"role",
"."
] |
7afa6bdb159022a9bed1efaa2997a6d5f993c7e4
|
https://github.com/JamesMessinger/swagger-server/blob/7afa6bdb159022a9bed1efaa2997a6d5f993c7e4/samples/sample3/handlers/sessions.js#L129-L136
|
train
|
JamesMessinger/swagger-server
|
samples/sample3/handlers/sessions.js
|
yourselfOnly
|
function yourselfOnly(req, res, next) {
// Get the username or sessionId from the URL
var username = req.params.username;
var sessionId = req.params.sessionId;
if (!req.session) {
res.status(401).send('You must be logged-in to access this resource');
}
else if (_.contains(req.session.user.roles, 'admin') ||
(username && req.session.user.username === username) ||
(sessionId && req.session.id === sessionId)) {
next();
}
else {
res.status(401).send('You can only perform this operation on your own account');
}
}
|
javascript
|
function yourselfOnly(req, res, next) {
// Get the username or sessionId from the URL
var username = req.params.username;
var sessionId = req.params.sessionId;
if (!req.session) {
res.status(401).send('You must be logged-in to access this resource');
}
else if (_.contains(req.session.user.roles, 'admin') ||
(username && req.session.user.username === username) ||
(sessionId && req.session.id === sessionId)) {
next();
}
else {
res.status(401).send('You can only perform this operation on your own account');
}
}
|
[
"function",
"yourselfOnly",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"var",
"username",
"=",
"req",
".",
"params",
".",
"username",
";",
"var",
"sessionId",
"=",
"req",
".",
"params",
".",
"sessionId",
";",
"if",
"(",
"!",
"req",
".",
"session",
")",
"{",
"res",
".",
"status",
"(",
"401",
")",
".",
"send",
"(",
"'You must be logged-in to access this resource'",
")",
";",
"}",
"else",
"if",
"(",
"_",
".",
"contains",
"(",
"req",
".",
"session",
".",
"user",
".",
"roles",
",",
"'admin'",
")",
"||",
"(",
"username",
"&&",
"req",
".",
"session",
".",
"user",
".",
"username",
"===",
"username",
")",
"||",
"(",
"sessionId",
"&&",
"req",
".",
"session",
".",
"id",
"===",
"sessionId",
")",
")",
"{",
"next",
"(",
")",
";",
"}",
"else",
"{",
"res",
".",
"status",
"(",
"401",
")",
".",
"send",
"(",
"'You can only perform this operation on your own account'",
")",
";",
"}",
"}"
] |
Prevents users from accessing another user's account.
Except for "admins", who can access any account.
|
[
"Prevents",
"users",
"from",
"accessing",
"another",
"user",
"s",
"account",
".",
"Except",
"for",
"admins",
"who",
"can",
"access",
"any",
"account",
"."
] |
7afa6bdb159022a9bed1efaa2997a6d5f993c7e4
|
https://github.com/JamesMessinger/swagger-server/blob/7afa6bdb159022a9bed1efaa2997a6d5f993c7e4/samples/sample3/handlers/sessions.js#L142-L158
|
train
|
JamesMessinger/swagger-server
|
samples/sample3/handlers/projects.js
|
loadMockData
|
function loadMockData(server, next) {
// Create REST resources for each project
var resources = data.projects.map(function(project) {
return new swagger.Resource('/projects', project.id, project);
});
// Save the resources to the mock data store
server.dataStore.save(resources, next);
}
|
javascript
|
function loadMockData(server, next) {
// Create REST resources for each project
var resources = data.projects.map(function(project) {
return new swagger.Resource('/projects', project.id, project);
});
// Save the resources to the mock data store
server.dataStore.save(resources, next);
}
|
[
"function",
"loadMockData",
"(",
"server",
",",
"next",
")",
"{",
"var",
"resources",
"=",
"data",
".",
"projects",
".",
"map",
"(",
"function",
"(",
"project",
")",
"{",
"return",
"new",
"swagger",
".",
"Resource",
"(",
"'/projects'",
",",
"project",
".",
"id",
",",
"project",
")",
";",
"}",
")",
";",
"server",
".",
"dataStore",
".",
"save",
"(",
"resources",
",",
"next",
")",
";",
"}"
] |
Loads mock project data
@param {SwaggerServer} server
@param {function} next
|
[
"Loads",
"mock",
"project",
"data"
] |
7afa6bdb159022a9bed1efaa2997a6d5f993c7e4
|
https://github.com/JamesMessinger/swagger-server/blob/7afa6bdb159022a9bed1efaa2997a6d5f993c7e4/samples/sample3/handlers/projects.js#L35-L43
|
train
|
JamesMessinger/swagger-server
|
samples/sample3/handlers/projects.js
|
verifyProjectIdDoesNotExist
|
function verifyProjectIdDoesNotExist(req, res, next) {
var projectId = req.body.id;
var dataStore = req.app.dataStore;
// Check for an existing project REST resource - /projects/{projectId}
var resource = new swagger.Resource('/projects', projectId, null);
dataStore.get(resource, function(err, resource) {
if (resource) {
// The ID already exists, so send an HTTP 409 (Conflict)
res.sendStatus(409);
}
else {
next();
}
});
}
|
javascript
|
function verifyProjectIdDoesNotExist(req, res, next) {
var projectId = req.body.id;
var dataStore = req.app.dataStore;
// Check for an existing project REST resource - /projects/{projectId}
var resource = new swagger.Resource('/projects', projectId, null);
dataStore.get(resource, function(err, resource) {
if (resource) {
// The ID already exists, so send an HTTP 409 (Conflict)
res.sendStatus(409);
}
else {
next();
}
});
}
|
[
"function",
"verifyProjectIdDoesNotExist",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"var",
"projectId",
"=",
"req",
".",
"body",
".",
"id",
";",
"var",
"dataStore",
"=",
"req",
".",
"app",
".",
"dataStore",
";",
"var",
"resource",
"=",
"new",
"swagger",
".",
"Resource",
"(",
"'/projects'",
",",
"projectId",
",",
"null",
")",
";",
"dataStore",
".",
"get",
"(",
"resource",
",",
"function",
"(",
"err",
",",
"resource",
")",
"{",
"if",
"(",
"resource",
")",
"{",
"res",
".",
"sendStatus",
"(",
"409",
")",
";",
"}",
"else",
"{",
"next",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
] |
Verifies that the new project's ID isn't the same as any existing ID.
|
[
"Verifies",
"that",
"the",
"new",
"project",
"s",
"ID",
"isn",
"t",
"the",
"same",
"as",
"any",
"existing",
"ID",
"."
] |
7afa6bdb159022a9bed1efaa2997a6d5f993c7e4
|
https://github.com/JamesMessinger/swagger-server/blob/7afa6bdb159022a9bed1efaa2997a6d5f993c7e4/samples/sample3/handlers/projects.js#L48-L63
|
train
|
JamesMessinger/swagger-server
|
samples/sample3/handlers/projects.js
|
verifyProjectNameDoesNotExist
|
function verifyProjectNameDoesNotExist(req, res, next) {
var projectName = req.body.name.toLowerCase();
var dataStore = req.app.dataStore;
// Get all project REST resources
dataStore.getCollection('/projects', function(err, resources) {
var alreadyExists = resources.some(function(resource) {
return resource.data.name.toLowerCase() === projectName;
});
if (alreadyExists) {
// The ID already exists, so send an HTTP 409 (Conflict)
res.sendStatus(409);
}
else {
next();
}
});
}
|
javascript
|
function verifyProjectNameDoesNotExist(req, res, next) {
var projectName = req.body.name.toLowerCase();
var dataStore = req.app.dataStore;
// Get all project REST resources
dataStore.getCollection('/projects', function(err, resources) {
var alreadyExists = resources.some(function(resource) {
return resource.data.name.toLowerCase() === projectName;
});
if (alreadyExists) {
// The ID already exists, so send an HTTP 409 (Conflict)
res.sendStatus(409);
}
else {
next();
}
});
}
|
[
"function",
"verifyProjectNameDoesNotExist",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"var",
"projectName",
"=",
"req",
".",
"body",
".",
"name",
".",
"toLowerCase",
"(",
")",
";",
"var",
"dataStore",
"=",
"req",
".",
"app",
".",
"dataStore",
";",
"dataStore",
".",
"getCollection",
"(",
"'/projects'",
",",
"function",
"(",
"err",
",",
"resources",
")",
"{",
"var",
"alreadyExists",
"=",
"resources",
".",
"some",
"(",
"function",
"(",
"resource",
")",
"{",
"return",
"resource",
".",
"data",
".",
"name",
".",
"toLowerCase",
"(",
")",
"===",
"projectName",
";",
"}",
")",
";",
"if",
"(",
"alreadyExists",
")",
"{",
"res",
".",
"sendStatus",
"(",
"409",
")",
";",
"}",
"else",
"{",
"next",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
] |
Verifies that the new project's name isn't the same as any existing name.
|
[
"Verifies",
"that",
"the",
"new",
"project",
"s",
"name",
"isn",
"t",
"the",
"same",
"as",
"any",
"existing",
"name",
"."
] |
7afa6bdb159022a9bed1efaa2997a6d5f993c7e4
|
https://github.com/JamesMessinger/swagger-server/blob/7afa6bdb159022a9bed1efaa2997a6d5f993c7e4/samples/sample3/handlers/projects.js#L68-L86
|
train
|
keycloak/keycloak-admin-client
|
lib/role-mappings.js
|
find
|
function find (client) {
return function find (realmName, userId) {
return new Promise((resolve, reject) => {
const req = {
auth: {
bearer: privates.get(client).accessToken
},
json: true
};
req.url = `${client.baseUrl}/admin/realms/${realmName}/users/${userId}/role-mappings`;
request(req, (err, resp, body) => {
if (err) {
return reject(err);
}
if (resp.statusCode !== 200) {
return reject(body);
}
return resolve(body);
});
});
};
}
|
javascript
|
function find (client) {
return function find (realmName, userId) {
return new Promise((resolve, reject) => {
const req = {
auth: {
bearer: privates.get(client).accessToken
},
json: true
};
req.url = `${client.baseUrl}/admin/realms/${realmName}/users/${userId}/role-mappings`;
request(req, (err, resp, body) => {
if (err) {
return reject(err);
}
if (resp.statusCode !== 200) {
return reject(body);
}
return resolve(body);
});
});
};
}
|
[
"function",
"find",
"(",
"client",
")",
"{",
"return",
"function",
"find",
"(",
"realmName",
",",
"userId",
")",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"const",
"req",
"=",
"{",
"auth",
":",
"{",
"bearer",
":",
"privates",
".",
"get",
"(",
"client",
")",
".",
"accessToken",
"}",
",",
"json",
":",
"true",
"}",
";",
"req",
".",
"url",
"=",
"`",
"${",
"client",
".",
"baseUrl",
"}",
"${",
"realmName",
"}",
"${",
"userId",
"}",
"`",
";",
"request",
"(",
"req",
",",
"(",
"err",
",",
"resp",
",",
"body",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"reject",
"(",
"err",
")",
";",
"}",
"if",
"(",
"resp",
".",
"statusCode",
"!==",
"200",
")",
"{",
"return",
"reject",
"(",
"body",
")",
";",
"}",
"return",
"resolve",
"(",
"body",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}",
";",
"}"
] |
A function to get the all the role mappings of an user
@param {string} realmName - The name of the realm (not the realmID) where the client roles exist - ex: master
@param {string} userId - The id of the user whose role mappings should be found
@returns {Promise} A promise that will resolve with the Array of role mappings
@example
keycloakAdminClient(settings)
.then((client) => {
client.users.roleMappings.find(realmName, userId)
.then((userRoleMappings) => {
console.log(userRoleMappings)
})
})
|
[
"A",
"function",
"to",
"get",
"the",
"all",
"the",
"role",
"mappings",
"of",
"an",
"user"
] |
eb75ad219dfc6aa14fe8c976647b9c017502458d
|
https://github.com/keycloak/keycloak-admin-client/blob/eb75ad219dfc6aa14fe8c976647b9c017502458d/lib/role-mappings.js#L28-L53
|
train
|
keycloak/keycloak-admin-client
|
lib/users.js
|
find
|
function find (client) {
return function find (realm, options) {
return new Promise((resolve, reject) => {
options = options || {};
const req = {
auth: {
bearer: privates.get(client).accessToken
},
json: true
};
if (options.userId) {
req.url = `${client.baseUrl}/admin/realms/${realm}/users/${options.userId}`;
} else {
req.url = `${client.baseUrl}/admin/realms/${realm}/users`;
req.qs = options;
}
request(req, (err, resp, body) => {
if (err) {
return reject(err);
}
if (resp.statusCode !== 200) {
return reject(body);
}
return resolve(body);
});
});
};
}
|
javascript
|
function find (client) {
return function find (realm, options) {
return new Promise((resolve, reject) => {
options = options || {};
const req = {
auth: {
bearer: privates.get(client).accessToken
},
json: true
};
if (options.userId) {
req.url = `${client.baseUrl}/admin/realms/${realm}/users/${options.userId}`;
} else {
req.url = `${client.baseUrl}/admin/realms/${realm}/users`;
req.qs = options;
}
request(req, (err, resp, body) => {
if (err) {
return reject(err);
}
if (resp.statusCode !== 200) {
return reject(body);
}
return resolve(body);
});
});
};
}
|
[
"function",
"find",
"(",
"client",
")",
"{",
"return",
"function",
"find",
"(",
"realm",
",",
"options",
")",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"const",
"req",
"=",
"{",
"auth",
":",
"{",
"bearer",
":",
"privates",
".",
"get",
"(",
"client",
")",
".",
"accessToken",
"}",
",",
"json",
":",
"true",
"}",
";",
"if",
"(",
"options",
".",
"userId",
")",
"{",
"req",
".",
"url",
"=",
"`",
"${",
"client",
".",
"baseUrl",
"}",
"${",
"realm",
"}",
"${",
"options",
".",
"userId",
"}",
"`",
";",
"}",
"else",
"{",
"req",
".",
"url",
"=",
"`",
"${",
"client",
".",
"baseUrl",
"}",
"${",
"realm",
"}",
"`",
";",
"req",
".",
"qs",
"=",
"options",
";",
"}",
"request",
"(",
"req",
",",
"(",
"err",
",",
"resp",
",",
"body",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"reject",
"(",
"err",
")",
";",
"}",
"if",
"(",
"resp",
".",
"statusCode",
"!==",
"200",
")",
"{",
"return",
"reject",
"(",
"body",
")",
";",
"}",
"return",
"resolve",
"(",
"body",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}",
";",
"}"
] |
A function to get the list of users or a user for a realm.
@param {string} realmName - The name of the realm(not the realmID) - ex: master
@param {object} [options] - The options object
@param {string} [options.userId] - use this options to get a user by an id. If this value is populated, it overrides the querystring param options
@param {string} [options.username] - the querystring param to search based on username
@param {string} [options.firstName] - the querystring param to search based on firstName
@param {string} [options.lastName] - the querystring param to search based on lastName
@param {string} [options.email] - the querystring param to search based on email
@returns {Promise} A promise that will resolve with an Array of user objects or just the 1 user object if userId is used
@example
keycloakAdminClient(settings)
.then((client) => {
client.users.find(realmName)
.then((userList) => {
console.log(userList) // [{...},{...}, ...]
})
})
|
[
"A",
"function",
"to",
"get",
"the",
"list",
"of",
"users",
"or",
"a",
"user",
"for",
"a",
"realm",
"."
] |
eb75ad219dfc6aa14fe8c976647b9c017502458d
|
https://github.com/keycloak/keycloak-admin-client/blob/eb75ad219dfc6aa14fe8c976647b9c017502458d/lib/users.js#L43-L74
|
train
|
keycloak/keycloak-admin-client
|
lib/users.js
|
create
|
function create (client) {
return function create (realm, user) {
return new Promise((resolve, reject) => {
const req = {
url: `${client.baseUrl}/admin/realms/${realm}/users`,
auth: {
bearer: privates.get(client).accessToken
},
body: user,
method: 'POST',
json: true
};
request(req, (err, resp, body) => {
if (err) {
return reject(err);
}
if (resp.statusCode !== 201) {
return reject(body);
}
// eg "location":"https://<url>/auth/admin/realms/<realm>/users/499b7073-fe1f-4b7a-a8ab-f401d9b6b8ec"
const uid = resp.headers.location.replace(/.*\/(.*)$/, '$1');
// Since the create Endpoint returns an empty body, go get what we just imported.
// *** Body is empty but location header contains user id ***
// We need to search based on the userid, since it will be unique
return resolve(client.users.find(realm, {
userId: uid
}));
});
});
};
}
|
javascript
|
function create (client) {
return function create (realm, user) {
return new Promise((resolve, reject) => {
const req = {
url: `${client.baseUrl}/admin/realms/${realm}/users`,
auth: {
bearer: privates.get(client).accessToken
},
body: user,
method: 'POST',
json: true
};
request(req, (err, resp, body) => {
if (err) {
return reject(err);
}
if (resp.statusCode !== 201) {
return reject(body);
}
// eg "location":"https://<url>/auth/admin/realms/<realm>/users/499b7073-fe1f-4b7a-a8ab-f401d9b6b8ec"
const uid = resp.headers.location.replace(/.*\/(.*)$/, '$1');
// Since the create Endpoint returns an empty body, go get what we just imported.
// *** Body is empty but location header contains user id ***
// We need to search based on the userid, since it will be unique
return resolve(client.users.find(realm, {
userId: uid
}));
});
});
};
}
|
[
"function",
"create",
"(",
"client",
")",
"{",
"return",
"function",
"create",
"(",
"realm",
",",
"user",
")",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"const",
"req",
"=",
"{",
"url",
":",
"`",
"${",
"client",
".",
"baseUrl",
"}",
"${",
"realm",
"}",
"`",
",",
"auth",
":",
"{",
"bearer",
":",
"privates",
".",
"get",
"(",
"client",
")",
".",
"accessToken",
"}",
",",
"body",
":",
"user",
",",
"method",
":",
"'POST'",
",",
"json",
":",
"true",
"}",
";",
"request",
"(",
"req",
",",
"(",
"err",
",",
"resp",
",",
"body",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"reject",
"(",
"err",
")",
";",
"}",
"if",
"(",
"resp",
".",
"statusCode",
"!==",
"201",
")",
"{",
"return",
"reject",
"(",
"body",
")",
";",
"}",
"const",
"uid",
"=",
"resp",
".",
"headers",
".",
"location",
".",
"replace",
"(",
"/",
".*\\/(.*)$",
"/",
",",
"'$1'",
")",
";",
"return",
"resolve",
"(",
"client",
".",
"users",
".",
"find",
"(",
"realm",
",",
"{",
"userId",
":",
"uid",
"}",
")",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}",
";",
"}"
] |
A function to create a new user for a realm.
@param {string} realmName - The name of the realm(not the realmID) - ex: master
@param {object} user - The JSON representation of a user - http://keycloak.github.io/docs/rest-api/index.html#_userrepresentation - username must be unique
@returns {Promise} A promise that will resolve with the user object
@example
keycloakAdminClient(settings)
.then((client) => {
client.users.create(realmName, user)
.then((createdUser) => {
console.log(createdUser) // [{...}]
})
})
|
[
"A",
"function",
"to",
"create",
"a",
"new",
"user",
"for",
"a",
"realm",
"."
] |
eb75ad219dfc6aa14fe8c976647b9c017502458d
|
https://github.com/keycloak/keycloak-admin-client/blob/eb75ad219dfc6aa14fe8c976647b9c017502458d/lib/users.js#L90-L124
|
train
|
keycloak/keycloak-admin-client
|
lib/users.js
|
update
|
function update (client) {
return function update (realmName, user) {
return new Promise((resolve, reject) => {
user = user || {};
const req = {
url: `${client.baseUrl}/admin/realms/${realmName}/users/${user.id}`,
auth: {
bearer: privates.get(client).accessToken
},
json: true,
method: 'PUT',
body: user
};
request(req, (err, resp, body) => {
if (err) {
return reject(err);
}
// Check that the status cod
if (resp.statusCode !== 204) {
return reject(body);
}
return resolve(body);
});
});
};
}
|
javascript
|
function update (client) {
return function update (realmName, user) {
return new Promise((resolve, reject) => {
user = user || {};
const req = {
url: `${client.baseUrl}/admin/realms/${realmName}/users/${user.id}`,
auth: {
bearer: privates.get(client).accessToken
},
json: true,
method: 'PUT',
body: user
};
request(req, (err, resp, body) => {
if (err) {
return reject(err);
}
// Check that the status cod
if (resp.statusCode !== 204) {
return reject(body);
}
return resolve(body);
});
});
};
}
|
[
"function",
"update",
"(",
"client",
")",
"{",
"return",
"function",
"update",
"(",
"realmName",
",",
"user",
")",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"user",
"=",
"user",
"||",
"{",
"}",
";",
"const",
"req",
"=",
"{",
"url",
":",
"`",
"${",
"client",
".",
"baseUrl",
"}",
"${",
"realmName",
"}",
"${",
"user",
".",
"id",
"}",
"`",
",",
"auth",
":",
"{",
"bearer",
":",
"privates",
".",
"get",
"(",
"client",
")",
".",
"accessToken",
"}",
",",
"json",
":",
"true",
",",
"method",
":",
"'PUT'",
",",
"body",
":",
"user",
"}",
";",
"request",
"(",
"req",
",",
"(",
"err",
",",
"resp",
",",
"body",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"reject",
"(",
"err",
")",
";",
"}",
"if",
"(",
"resp",
".",
"statusCode",
"!==",
"204",
")",
"{",
"return",
"reject",
"(",
"body",
")",
";",
"}",
"return",
"resolve",
"(",
"body",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}",
";",
"}"
] |
A function to update a user for a realm
@param {string} realmName - The name of the realm(not the realmID) - ex: master,
@param {object} user - The JSON representation of the fields to update for the user - This must include the user.id field.
@returns {Promise} A promise that resolves.
@example
keycloakAdminClient(settings)
.then((client) => {
client.users.update(realmName, user)
.then(() => {
console.log('success')
})
})
|
[
"A",
"function",
"to",
"update",
"a",
"user",
"for",
"a",
"realm"
] |
eb75ad219dfc6aa14fe8c976647b9c017502458d
|
https://github.com/keycloak/keycloak-admin-client/blob/eb75ad219dfc6aa14fe8c976647b9c017502458d/lib/users.js#L140-L168
|
train
|
keycloak/keycloak-admin-client
|
lib/users.js
|
resetPassword
|
function resetPassword (c) {
return function resetPassword (realmName, userId, payload) {
return new Promise((resolve, reject) => {
payload = payload || {};
payload.type = 'password';
if (!userId) {
return reject(new Error('userId is missing'));
}
if (!payload.value) {
return reject(new Error('value for the new password is missing'));
}
const req = {
url: `${c.baseUrl}/admin/realms/${realmName}/users/${userId}/reset-password`,
auth: {
bearer: privates.get(c).accessToken
},
json: true,
method: 'PUT',
body: payload
};
request(req, (err, resp, body) => {
if (err) {
return reject(err);
}
// Check that the status cod
if (resp.statusCode !== 204) {
return reject(body);
}
return resolve(body);
});
});
};
}
|
javascript
|
function resetPassword (c) {
return function resetPassword (realmName, userId, payload) {
return new Promise((resolve, reject) => {
payload = payload || {};
payload.type = 'password';
if (!userId) {
return reject(new Error('userId is missing'));
}
if (!payload.value) {
return reject(new Error('value for the new password is missing'));
}
const req = {
url: `${c.baseUrl}/admin/realms/${realmName}/users/${userId}/reset-password`,
auth: {
bearer: privates.get(c).accessToken
},
json: true,
method: 'PUT',
body: payload
};
request(req, (err, resp, body) => {
if (err) {
return reject(err);
}
// Check that the status cod
if (resp.statusCode !== 204) {
return reject(body);
}
return resolve(body);
});
});
};
}
|
[
"function",
"resetPassword",
"(",
"c",
")",
"{",
"return",
"function",
"resetPassword",
"(",
"realmName",
",",
"userId",
",",
"payload",
")",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"payload",
"=",
"payload",
"||",
"{",
"}",
";",
"payload",
".",
"type",
"=",
"'password'",
";",
"if",
"(",
"!",
"userId",
")",
"{",
"return",
"reject",
"(",
"new",
"Error",
"(",
"'userId is missing'",
")",
")",
";",
"}",
"if",
"(",
"!",
"payload",
".",
"value",
")",
"{",
"return",
"reject",
"(",
"new",
"Error",
"(",
"'value for the new password is missing'",
")",
")",
";",
"}",
"const",
"req",
"=",
"{",
"url",
":",
"`",
"${",
"c",
".",
"baseUrl",
"}",
"${",
"realmName",
"}",
"${",
"userId",
"}",
"`",
",",
"auth",
":",
"{",
"bearer",
":",
"privates",
".",
"get",
"(",
"c",
")",
".",
"accessToken",
"}",
",",
"json",
":",
"true",
",",
"method",
":",
"'PUT'",
",",
"body",
":",
"payload",
"}",
";",
"request",
"(",
"req",
",",
"(",
"err",
",",
"resp",
",",
"body",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"reject",
"(",
"err",
")",
";",
"}",
"if",
"(",
"resp",
".",
"statusCode",
"!==",
"204",
")",
"{",
"return",
"reject",
"(",
"body",
")",
";",
"}",
"return",
"resolve",
"(",
"body",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}",
";",
"}"
] |
A function to reset a user password for a realm
@param {string} realmName - The name of the realm(not the realmID) - ex: master,
@param {string} userId - The id of user
@param {object} payload { temporary: boolean , value : string } - The JSON representation of the fields to update for the password
@returns {Promise} A promise that resolves.
@example
keycloakAdminClient(settings)
.then((client) => {
client.users.resetPassword(realmName, userId, { temporary: boolean , value : string})
.then(() => {
console.log('success')
})
})
|
[
"A",
"function",
"to",
"reset",
"a",
"user",
"password",
"for",
"a",
"realm"
] |
eb75ad219dfc6aa14fe8c976647b9c017502458d
|
https://github.com/keycloak/keycloak-admin-client/blob/eb75ad219dfc6aa14fe8c976647b9c017502458d/lib/users.js#L226-L264
|
train
|
keycloak/keycloak-admin-client
|
lib/users.js
|
count
|
function count (client) {
return function count (realm) {
return new Promise((resolve, reject) => {
const req = {
auth: {
bearer: privates.get(client).accessToken
},
json: true,
url: `${client.baseUrl}/admin/realms/${realm}/users/count`
};
request(req, (err, resp, body) => {
if (err) {
return reject(err);
}
if (resp.statusCode !== 200) {
return reject(body);
}
return resolve(body);
});
});
};
}
|
javascript
|
function count (client) {
return function count (realm) {
return new Promise((resolve, reject) => {
const req = {
auth: {
bearer: privates.get(client).accessToken
},
json: true,
url: `${client.baseUrl}/admin/realms/${realm}/users/count`
};
request(req, (err, resp, body) => {
if (err) {
return reject(err);
}
if (resp.statusCode !== 200) {
return reject(body);
}
return resolve(body);
});
});
};
}
|
[
"function",
"count",
"(",
"client",
")",
"{",
"return",
"function",
"count",
"(",
"realm",
")",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"const",
"req",
"=",
"{",
"auth",
":",
"{",
"bearer",
":",
"privates",
".",
"get",
"(",
"client",
")",
".",
"accessToken",
"}",
",",
"json",
":",
"true",
",",
"url",
":",
"`",
"${",
"client",
".",
"baseUrl",
"}",
"${",
"realm",
"}",
"`",
"}",
";",
"request",
"(",
"req",
",",
"(",
"err",
",",
"resp",
",",
"body",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"reject",
"(",
"err",
")",
";",
"}",
"if",
"(",
"resp",
".",
"statusCode",
"!==",
"200",
")",
"{",
"return",
"reject",
"(",
"body",
")",
";",
"}",
"return",
"resolve",
"(",
"body",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}",
";",
"}"
] |
A function to get the number of users in a realm.
@param {string} realmName - The name of the realm(not the realmID) - ex: master
@returns {Promise} A promise that will resolve with an integer - the number of users in the realm
@example
keycloakAdminClient(settings)
.then((client) => {
client.users.count(realmName)
.then((numberOfUsers) => {
console.log(numberOfUsers) // integer
})
})
|
[
"A",
"function",
"to",
"get",
"the",
"number",
"of",
"users",
"in",
"a",
"realm",
"."
] |
eb75ad219dfc6aa14fe8c976647b9c017502458d
|
https://github.com/keycloak/keycloak-admin-client/blob/eb75ad219dfc6aa14fe8c976647b9c017502458d/lib/users.js#L362-L386
|
train
|
marklogic/node-client-api
|
lib/values-builder.js
|
copyFromValueBuilder
|
function copyFromValueBuilder(otherValueBuilder) {
var tb = new ValueBuilder();
// TODO: share with QueryBuilder
if (otherValueBuilder != null) {
var clauseKeys = [
'fromIndexesClause', 'whereClause', 'aggregatesClause',
'sliceClause', 'withOptionsClause'
];
var isString = (typeof otherValueBuilder === 'string' || otherValueBuilder instanceof String);
var other = isString ?
JSON.parse(otherValueBuilder) : otherValueBuilder;
for (var i=0; i < clauseKeys.length; i++){
var key = clauseKeys[i];
var value = other[key];
if (value != null) {
// deepcopy instead of clone to avoid preserving prototype
tb[key] = isString ? value : deepcopy(value);
}
}
}
return tb;
}
|
javascript
|
function copyFromValueBuilder(otherValueBuilder) {
var tb = new ValueBuilder();
// TODO: share with QueryBuilder
if (otherValueBuilder != null) {
var clauseKeys = [
'fromIndexesClause', 'whereClause', 'aggregatesClause',
'sliceClause', 'withOptionsClause'
];
var isString = (typeof otherValueBuilder === 'string' || otherValueBuilder instanceof String);
var other = isString ?
JSON.parse(otherValueBuilder) : otherValueBuilder;
for (var i=0; i < clauseKeys.length; i++){
var key = clauseKeys[i];
var value = other[key];
if (value != null) {
// deepcopy instead of clone to avoid preserving prototype
tb[key] = isString ? value : deepcopy(value);
}
}
}
return tb;
}
|
[
"function",
"copyFromValueBuilder",
"(",
"otherValueBuilder",
")",
"{",
"var",
"tb",
"=",
"new",
"ValueBuilder",
"(",
")",
";",
"if",
"(",
"otherValueBuilder",
"!=",
"null",
")",
"{",
"var",
"clauseKeys",
"=",
"[",
"'fromIndexesClause'",
",",
"'whereClause'",
",",
"'aggregatesClause'",
",",
"'sliceClause'",
",",
"'withOptionsClause'",
"]",
";",
"var",
"isString",
"=",
"(",
"typeof",
"otherValueBuilder",
"===",
"'string'",
"||",
"otherValueBuilder",
"instanceof",
"String",
")",
";",
"var",
"other",
"=",
"isString",
"?",
"JSON",
".",
"parse",
"(",
"otherValueBuilder",
")",
":",
"otherValueBuilder",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"clauseKeys",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"key",
"=",
"clauseKeys",
"[",
"i",
"]",
";",
"var",
"value",
"=",
"other",
"[",
"key",
"]",
";",
"if",
"(",
"value",
"!=",
"null",
")",
"{",
"tb",
"[",
"key",
"]",
"=",
"isString",
"?",
"value",
":",
"deepcopy",
"(",
"value",
")",
";",
"}",
"}",
"}",
"return",
"tb",
";",
"}"
] |
Initializes a new values builder by copying the from indexes clause
and any where, aggregates, slice, or withOptions clause defined in
the built query.
@method valuesBuilder#copyFrom
@since 1.0
@param {valuesBuilder.BuiltQuery} query - an existing values query
with clauses to copy
@returns {valuesBuilder.BuiltQuery} a built query
|
[
"Initializes",
"a",
"new",
"values",
"builder",
"by",
"copying",
"the",
"from",
"indexes",
"clause",
"and",
"any",
"where",
"aggregates",
"slice",
"or",
"withOptions",
"clause",
"defined",
"in",
"the",
"built",
"query",
"."
] |
368be82f377eb4178ece35d9491dac6672bd1288
|
https://github.com/marklogic/node-client-api/blob/368be82f377eb4178ece35d9491dac6672bd1288/lib/values-builder.js#L408-L431
|
train
|
marklogic/node-client-api
|
lib/query-builder.js
|
checkQueryArray
|
function checkQueryArray(queryArray) {
if (queryArray == null) {
return queryArray;
}
var max = queryArray.length;
if (max === 0) {
return queryArray;
}
var i = 0;
for (; i < max; i++) {
checkQuery(queryArray[i]);
}
return queryArray;
}
|
javascript
|
function checkQueryArray(queryArray) {
if (queryArray == null) {
return queryArray;
}
var max = queryArray.length;
if (max === 0) {
return queryArray;
}
var i = 0;
for (; i < max; i++) {
checkQuery(queryArray[i]);
}
return queryArray;
}
|
[
"function",
"checkQueryArray",
"(",
"queryArray",
")",
"{",
"if",
"(",
"queryArray",
"==",
"null",
")",
"{",
"return",
"queryArray",
";",
"}",
"var",
"max",
"=",
"queryArray",
".",
"length",
";",
"if",
"(",
"max",
"===",
"0",
")",
"{",
"return",
"queryArray",
";",
"}",
"var",
"i",
"=",
"0",
";",
"for",
"(",
";",
"i",
"<",
"max",
";",
"i",
"++",
")",
"{",
"checkQuery",
"(",
"queryArray",
"[",
"i",
"]",
")",
";",
"}",
"return",
"queryArray",
";",
"}"
] |
A composable query.
@typedef {object} queryBuilder.Query
@since 1.0
An indexed name such as a JSON property, {@link queryBuilder#element} or
{@link queryBuilder#attribute}, {@link queryBuilder#field},
or {@link queryBuilder#pathIndex}.
@typedef {object} queryBuilder.IndexedName
@since 1.0
An indexed name such as a JSON property, XML element, or path that
represents a geospatial location for matched by a geospatial query.
@typedef {object} queryBuilder.GeoLocation
@since 1.0
The specification of a point or an area (such as a box, circle, or polygon)
for use as criteria in a geospatial query.
@typedef {object} queryBuilder.Region
@since 1.0
The specification of the latitude and longitude
returned by the {@link queryBuilder#latlon} function
for a coordinate of a {@link queryBuilder.Region}.
@typedef {object} queryBuilder.LatLon
@since 1.0
The specification of the coordinate system
returned by the {@link queryBuilder#coordSystem} function
for a geospatial path index
@typedef {object} queryBuilder.CoordSystem
@since 1.0
@ignore
|
[
"A",
"composable",
"query",
"."
] |
368be82f377eb4178ece35d9491dac6672bd1288
|
https://github.com/marklogic/node-client-api/blob/368be82f377eb4178ece35d9491dac6672bd1288/lib/query-builder.js#L119-L135
|
train
|
marklogic/node-client-api
|
lib/query-builder.js
|
and
|
function and() {
var args = mlutil.asArray.apply(null, arguments);
var queries = [];
var ordered = null;
var arg = null;
for (var i=0; i < args.length; i++) {
arg = args[i];
if (ordered === null) {
if (arg instanceof OrderedDef) {
ordered = arg.ordered;
continue;
} else if (typeof arg === 'boolean') {
ordered = arg;
continue;
}
}
if (arg instanceof Array){
Array.prototype.push.apply(queries, arg);
} else {
queries.push(arg);
}
}
return new AndDef(new QueryListDef(queries, ordered, null, null));
}
|
javascript
|
function and() {
var args = mlutil.asArray.apply(null, arguments);
var queries = [];
var ordered = null;
var arg = null;
for (var i=0; i < args.length; i++) {
arg = args[i];
if (ordered === null) {
if (arg instanceof OrderedDef) {
ordered = arg.ordered;
continue;
} else if (typeof arg === 'boolean') {
ordered = arg;
continue;
}
}
if (arg instanceof Array){
Array.prototype.push.apply(queries, arg);
} else {
queries.push(arg);
}
}
return new AndDef(new QueryListDef(queries, ordered, null, null));
}
|
[
"function",
"and",
"(",
")",
"{",
"var",
"args",
"=",
"mlutil",
".",
"asArray",
".",
"apply",
"(",
"null",
",",
"arguments",
")",
";",
"var",
"queries",
"=",
"[",
"]",
";",
"var",
"ordered",
"=",
"null",
";",
"var",
"arg",
"=",
"null",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"args",
".",
"length",
";",
"i",
"++",
")",
"{",
"arg",
"=",
"args",
"[",
"i",
"]",
";",
"if",
"(",
"ordered",
"===",
"null",
")",
"{",
"if",
"(",
"arg",
"instanceof",
"OrderedDef",
")",
"{",
"ordered",
"=",
"arg",
".",
"ordered",
";",
"continue",
";",
"}",
"else",
"if",
"(",
"typeof",
"arg",
"===",
"'boolean'",
")",
"{",
"ordered",
"=",
"arg",
";",
"continue",
";",
"}",
"}",
"if",
"(",
"arg",
"instanceof",
"Array",
")",
"{",
"Array",
".",
"prototype",
".",
"push",
".",
"apply",
"(",
"queries",
",",
"arg",
")",
";",
"}",
"else",
"{",
"queries",
".",
"push",
"(",
"arg",
")",
";",
"}",
"}",
"return",
"new",
"AndDef",
"(",
"new",
"QueryListDef",
"(",
"queries",
",",
"ordered",
",",
"null",
",",
"null",
")",
")",
";",
"}"
] |
Builds a query for the intersection of the subqueries.
@method
@since 1.0
@memberof queryBuilder#
@param {...queryBuilder.Query} subquery - a word, value, range, geospatial,
or other query or a composer such as an or query.
@param {queryBuilder.OrderParam} [ordering] - the ordering on the subqueries
returned from {@link queryBuilder#ordered}
@returns {queryBuilder.Query} a composable query
|
[
"Builds",
"a",
"query",
"for",
"the",
"intersection",
"of",
"the",
"subqueries",
"."
] |
368be82f377eb4178ece35d9491dac6672bd1288
|
https://github.com/marklogic/node-client-api/blob/368be82f377eb4178ece35d9491dac6672bd1288/lib/query-builder.js#L182-L207
|
train
|
marklogic/node-client-api
|
lib/query-builder.js
|
andNot
|
function andNot() {
var args = mlutil.asArray.apply(null, arguments);
switch(args.length) {
case 0:
throw new Error('missing positive and negative queries');
case 1:
throw new Error('has positive but missing negative query: '+mlutil.identify(args[0], true));
case 2:
return new AndNotDef(new PositiveNegativeDef(args[0], args[1]));
default:
throw new Error('more than two arguments for andNot(): '+args.length);
}
}
|
javascript
|
function andNot() {
var args = mlutil.asArray.apply(null, arguments);
switch(args.length) {
case 0:
throw new Error('missing positive and negative queries');
case 1:
throw new Error('has positive but missing negative query: '+mlutil.identify(args[0], true));
case 2:
return new AndNotDef(new PositiveNegativeDef(args[0], args[1]));
default:
throw new Error('more than two arguments for andNot(): '+args.length);
}
}
|
[
"function",
"andNot",
"(",
")",
"{",
"var",
"args",
"=",
"mlutil",
".",
"asArray",
".",
"apply",
"(",
"null",
",",
"arguments",
")",
";",
"switch",
"(",
"args",
".",
"length",
")",
"{",
"case",
"0",
":",
"throw",
"new",
"Error",
"(",
"'missing positive and negative queries'",
")",
";",
"case",
"1",
":",
"throw",
"new",
"Error",
"(",
"'has positive but missing negative query: '",
"+",
"mlutil",
".",
"identify",
"(",
"args",
"[",
"0",
"]",
",",
"true",
")",
")",
";",
"case",
"2",
":",
"return",
"new",
"AndNotDef",
"(",
"new",
"PositiveNegativeDef",
"(",
"args",
"[",
"0",
"]",
",",
"args",
"[",
"1",
"]",
")",
")",
";",
"default",
":",
"throw",
"new",
"Error",
"(",
"'more than two arguments for andNot(): '",
"+",
"args",
".",
"length",
")",
";",
"}",
"}"
] |
Builds a query with positive and negative subqueries.
@method
@since 1.0
@memberof queryBuilder#
@param {queryBuilder.Query} positiveQuery - a query that must match
the result documents
@param {queryBuilder.Query} negativeQuery - a query that must not match
the result documents
@returns {queryBuilder.Query} a composable query
|
[
"Builds",
"a",
"query",
"with",
"positive",
"and",
"negative",
"subqueries",
"."
] |
368be82f377eb4178ece35d9491dac6672bd1288
|
https://github.com/marklogic/node-client-api/blob/368be82f377eb4178ece35d9491dac6672bd1288/lib/query-builder.js#L272-L284
|
train
|
marklogic/node-client-api
|
lib/query-builder.js
|
boost
|
function boost() {
var args = mlutil.asArray.apply(null, arguments);
switch(args.length) {
case 0:
throw new Error('missing matching and boosting queries');
case 1:
throw new Error('has matching but missing boosting query: '+mlutil.identify(args[0], true));
case 2:
return new BoostDef(new MatchingBoostingDef(args[0], args[1]));
default:
throw new Error('too many arguments for boost(): '+args.length);
}
}
|
javascript
|
function boost() {
var args = mlutil.asArray.apply(null, arguments);
switch(args.length) {
case 0:
throw new Error('missing matching and boosting queries');
case 1:
throw new Error('has matching but missing boosting query: '+mlutil.identify(args[0], true));
case 2:
return new BoostDef(new MatchingBoostingDef(args[0], args[1]));
default:
throw new Error('too many arguments for boost(): '+args.length);
}
}
|
[
"function",
"boost",
"(",
")",
"{",
"var",
"args",
"=",
"mlutil",
".",
"asArray",
".",
"apply",
"(",
"null",
",",
"arguments",
")",
";",
"switch",
"(",
"args",
".",
"length",
")",
"{",
"case",
"0",
":",
"throw",
"new",
"Error",
"(",
"'missing matching and boosting queries'",
")",
";",
"case",
"1",
":",
"throw",
"new",
"Error",
"(",
"'has matching but missing boosting query: '",
"+",
"mlutil",
".",
"identify",
"(",
"args",
"[",
"0",
"]",
",",
"true",
")",
")",
";",
"case",
"2",
":",
"return",
"new",
"BoostDef",
"(",
"new",
"MatchingBoostingDef",
"(",
"args",
"[",
"0",
"]",
",",
"args",
"[",
"1",
"]",
")",
")",
";",
"default",
":",
"throw",
"new",
"Error",
"(",
"'too many arguments for boost(): '",
"+",
"args",
".",
"length",
")",
";",
"}",
"}"
] |
Builds a query with matching and boosting subqueries.
@method
@since 1.0
@memberof queryBuilder#
@param {queryBuilder.Query} matchingQuery - a query that must match
the result documents
@param {queryBuilder.Query} boostingQuery - a query that increases
the ranking when qualifying result documents
@returns {queryBuilder.Query} a composable query
|
[
"Builds",
"a",
"query",
"with",
"matching",
"and",
"boosting",
"subqueries",
"."
] |
368be82f377eb4178ece35d9491dac6672bd1288
|
https://github.com/marklogic/node-client-api/blob/368be82f377eb4178ece35d9491dac6672bd1288/lib/query-builder.js#L405-L417
|
train
|
marklogic/node-client-api
|
lib/query-builder.js
|
directory
|
function directory() {
var args = mlutil.asArray.apply(null, arguments);
var uris = [];
var infinite = null;
var arg = null;
for (var i=0; i < args.length; i++) {
arg = args[i];
if (infinite === null && (typeof arg === 'boolean')) {
infinite = arg;
} else if (arg instanceof Array){
Array.prototype.push.apply(uris, arg);
} else {
uris.push(arg);
}
}
return new DirectoryQueryDef(
new UrisDef(uris, infinite)
);
}
|
javascript
|
function directory() {
var args = mlutil.asArray.apply(null, arguments);
var uris = [];
var infinite = null;
var arg = null;
for (var i=0; i < args.length; i++) {
arg = args[i];
if (infinite === null && (typeof arg === 'boolean')) {
infinite = arg;
} else if (arg instanceof Array){
Array.prototype.push.apply(uris, arg);
} else {
uris.push(arg);
}
}
return new DirectoryQueryDef(
new UrisDef(uris, infinite)
);
}
|
[
"function",
"directory",
"(",
")",
"{",
"var",
"args",
"=",
"mlutil",
".",
"asArray",
".",
"apply",
"(",
"null",
",",
"arguments",
")",
";",
"var",
"uris",
"=",
"[",
"]",
";",
"var",
"infinite",
"=",
"null",
";",
"var",
"arg",
"=",
"null",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"args",
".",
"length",
";",
"i",
"++",
")",
"{",
"arg",
"=",
"args",
"[",
"i",
"]",
";",
"if",
"(",
"infinite",
"===",
"null",
"&&",
"(",
"typeof",
"arg",
"===",
"'boolean'",
")",
")",
"{",
"infinite",
"=",
"arg",
";",
"}",
"else",
"if",
"(",
"arg",
"instanceof",
"Array",
")",
"{",
"Array",
".",
"prototype",
".",
"push",
".",
"apply",
"(",
"uris",
",",
"arg",
")",
";",
"}",
"else",
"{",
"uris",
".",
"push",
"(",
"arg",
")",
";",
"}",
"}",
"return",
"new",
"DirectoryQueryDef",
"(",
"new",
"UrisDef",
"(",
"uris",
",",
"infinite",
")",
")",
";",
"}"
] |
Builds a query matching documents in one or more database directories.
@method
@since 1.0
@memberof queryBuilder#
@param {string|string[]} uris - one or more directory uris
to match
@param {boolean} [infinite] - whether to match documents at the top level or
at any level of depth within the specified directories
@returns {queryBuilder.Query} a composable query
|
[
"Builds",
"a",
"query",
"matching",
"documents",
"in",
"one",
"or",
"more",
"database",
"directories",
"."
] |
368be82f377eb4178ece35d9491dac6672bd1288
|
https://github.com/marklogic/node-client-api/blob/368be82f377eb4178ece35d9491dac6672bd1288/lib/query-builder.js#L999-L1019
|
train
|
marklogic/node-client-api
|
lib/query-builder.js
|
field
|
function field() {
var args = mlutil.asArray.apply(null, arguments);
switch(args.length) {
case 0:
throw new Error('missing field name');
case 1:
return new FieldDef(new FieldNameDef(args[0]));
case 2:
return new FieldDef(new FieldNameDef(args[0], args[1]));
default:
throw new Error('too many arguments for field identifier: '+args.length);
}
}
|
javascript
|
function field() {
var args = mlutil.asArray.apply(null, arguments);
switch(args.length) {
case 0:
throw new Error('missing field name');
case 1:
return new FieldDef(new FieldNameDef(args[0]));
case 2:
return new FieldDef(new FieldNameDef(args[0], args[1]));
default:
throw new Error('too many arguments for field identifier: '+args.length);
}
}
|
[
"function",
"field",
"(",
")",
"{",
"var",
"args",
"=",
"mlutil",
".",
"asArray",
".",
"apply",
"(",
"null",
",",
"arguments",
")",
";",
"switch",
"(",
"args",
".",
"length",
")",
"{",
"case",
"0",
":",
"throw",
"new",
"Error",
"(",
"'missing field name'",
")",
";",
"case",
"1",
":",
"return",
"new",
"FieldDef",
"(",
"new",
"FieldNameDef",
"(",
"args",
"[",
"0",
"]",
")",
")",
";",
"case",
"2",
":",
"return",
"new",
"FieldDef",
"(",
"new",
"FieldNameDef",
"(",
"args",
"[",
"0",
"]",
",",
"args",
"[",
"1",
"]",
")",
")",
";",
"default",
":",
"throw",
"new",
"Error",
"(",
"'too many arguments for field identifier: '",
"+",
"args",
".",
"length",
")",
";",
"}",
"}"
] |
Specifies a field for a query.
@method
@since 1.0
@memberof queryBuilder#
@param {string} name - the name of the field
@param {string} [collation] - the collation of a field over strings
@returns {queryBuilder.IndexedName} an indexed name for specifying a query
|
[
"Specifies",
"a",
"field",
"for",
"a",
"query",
"."
] |
368be82f377eb4178ece35d9491dac6672bd1288
|
https://github.com/marklogic/node-client-api/blob/368be82f377eb4178ece35d9491dac6672bd1288/lib/query-builder.js#L1156-L1168
|
train
|
marklogic/node-client-api
|
lib/query-builder.js
|
heatmap
|
function heatmap() {
var args = mlutil.asArray.apply(null, arguments);
var argLen = args.length;
if (argLen < 1) {
throw new Error('no region or divisions for heat map');
}
var hmap = {};
switch(argLen) {
case 3:
var first = args[0];
var second = args[1];
var third = args[2];
var region = null;
if (typeof first === 'object' && first !== null) {
region = first;
hmap.latdivs = second;
hmap.londivs = third;
} else if (typeof third === 'object' && third !== null) {
region = third;
hmap.latdivs = first;
hmap.londivs = second;
} else {
throw new Error('no first or last region for heat map');
}
var keys = ['s', 'w', 'n', 'e'];
for (var i=0; i < keys.length; i++) {
var key = keys[i];
var value = region[key];
if (value != null) {
hmap[key] = value;
continue;
} else {
var altKey = null;
switch(key) {
case 's':
altKey = 'south';
break;
case 'w':
altKey = 'west';
break;
case 'n':
altKey = 'north';
break;
case 'e':
altKey = 'east';
break;
}
value = (altKey !== null) ? region[altKey] : null;
if (value != null) {
hmap[key] = value;
continue;
}
}
throw new Error('heat map does not have '+key+' key');
}
break;
case 6:
hmap.latdivs = args[0];
hmap.londivs = args[1];
hmap.s = args[2];
hmap.w = args[3];
hmap.n = args[4];
hmap.e = args[5];
break;
default:
throw new Error('could not assign parameters to heat map');
}
return {'heatmap': hmap};
}
|
javascript
|
function heatmap() {
var args = mlutil.asArray.apply(null, arguments);
var argLen = args.length;
if (argLen < 1) {
throw new Error('no region or divisions for heat map');
}
var hmap = {};
switch(argLen) {
case 3:
var first = args[0];
var second = args[1];
var third = args[2];
var region = null;
if (typeof first === 'object' && first !== null) {
region = first;
hmap.latdivs = second;
hmap.londivs = third;
} else if (typeof third === 'object' && third !== null) {
region = third;
hmap.latdivs = first;
hmap.londivs = second;
} else {
throw new Error('no first or last region for heat map');
}
var keys = ['s', 'w', 'n', 'e'];
for (var i=0; i < keys.length; i++) {
var key = keys[i];
var value = region[key];
if (value != null) {
hmap[key] = value;
continue;
} else {
var altKey = null;
switch(key) {
case 's':
altKey = 'south';
break;
case 'w':
altKey = 'west';
break;
case 'n':
altKey = 'north';
break;
case 'e':
altKey = 'east';
break;
}
value = (altKey !== null) ? region[altKey] : null;
if (value != null) {
hmap[key] = value;
continue;
}
}
throw new Error('heat map does not have '+key+' key');
}
break;
case 6:
hmap.latdivs = args[0];
hmap.londivs = args[1];
hmap.s = args[2];
hmap.w = args[3];
hmap.n = args[4];
hmap.e = args[5];
break;
default:
throw new Error('could not assign parameters to heat map');
}
return {'heatmap': hmap};
}
|
[
"function",
"heatmap",
"(",
")",
"{",
"var",
"args",
"=",
"mlutil",
".",
"asArray",
".",
"apply",
"(",
"null",
",",
"arguments",
")",
";",
"var",
"argLen",
"=",
"args",
".",
"length",
";",
"if",
"(",
"argLen",
"<",
"1",
")",
"{",
"throw",
"new",
"Error",
"(",
"'no region or divisions for heat map'",
")",
";",
"}",
"var",
"hmap",
"=",
"{",
"}",
";",
"switch",
"(",
"argLen",
")",
"{",
"case",
"3",
":",
"var",
"first",
"=",
"args",
"[",
"0",
"]",
";",
"var",
"second",
"=",
"args",
"[",
"1",
"]",
";",
"var",
"third",
"=",
"args",
"[",
"2",
"]",
";",
"var",
"region",
"=",
"null",
";",
"if",
"(",
"typeof",
"first",
"===",
"'object'",
"&&",
"first",
"!==",
"null",
")",
"{",
"region",
"=",
"first",
";",
"hmap",
".",
"latdivs",
"=",
"second",
";",
"hmap",
".",
"londivs",
"=",
"third",
";",
"}",
"else",
"if",
"(",
"typeof",
"third",
"===",
"'object'",
"&&",
"third",
"!==",
"null",
")",
"{",
"region",
"=",
"third",
";",
"hmap",
".",
"latdivs",
"=",
"first",
";",
"hmap",
".",
"londivs",
"=",
"second",
";",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"'no first or last region for heat map'",
")",
";",
"}",
"var",
"keys",
"=",
"[",
"'s'",
",",
"'w'",
",",
"'n'",
",",
"'e'",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"keys",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"key",
"=",
"keys",
"[",
"i",
"]",
";",
"var",
"value",
"=",
"region",
"[",
"key",
"]",
";",
"if",
"(",
"value",
"!=",
"null",
")",
"{",
"hmap",
"[",
"key",
"]",
"=",
"value",
";",
"continue",
";",
"}",
"else",
"{",
"var",
"altKey",
"=",
"null",
";",
"switch",
"(",
"key",
")",
"{",
"case",
"'s'",
":",
"altKey",
"=",
"'south'",
";",
"break",
";",
"case",
"'w'",
":",
"altKey",
"=",
"'west'",
";",
"break",
";",
"case",
"'n'",
":",
"altKey",
"=",
"'north'",
";",
"break",
";",
"case",
"'e'",
":",
"altKey",
"=",
"'east'",
";",
"break",
";",
"}",
"value",
"=",
"(",
"altKey",
"!==",
"null",
")",
"?",
"region",
"[",
"altKey",
"]",
":",
"null",
";",
"if",
"(",
"value",
"!=",
"null",
")",
"{",
"hmap",
"[",
"key",
"]",
"=",
"value",
";",
"continue",
";",
"}",
"}",
"throw",
"new",
"Error",
"(",
"'heat map does not have '",
"+",
"key",
"+",
"' key'",
")",
";",
"}",
"break",
";",
"case",
"6",
":",
"hmap",
".",
"latdivs",
"=",
"args",
"[",
"0",
"]",
";",
"hmap",
".",
"londivs",
"=",
"args",
"[",
"1",
"]",
";",
"hmap",
".",
"s",
"=",
"args",
"[",
"2",
"]",
";",
"hmap",
".",
"w",
"=",
"args",
"[",
"3",
"]",
";",
"hmap",
".",
"n",
"=",
"args",
"[",
"4",
"]",
";",
"hmap",
".",
"e",
"=",
"args",
"[",
"5",
"]",
";",
"break",
";",
"default",
":",
"throw",
"new",
"Error",
"(",
"'could not assign parameters to heat map'",
")",
";",
"}",
"return",
"{",
"'heatmap'",
":",
"hmap",
"}",
";",
"}"
] |
Specifies the buckets for a geospatial facet.
@typedef {object} queryBuilder.HeatMapParam
@since 1.0
Divides a geospatial box into a two-dimensional grid for calculating facets
based on document counts for each cell within the grid.
The coordinates of the box can be specified either by passing the return value
from the {@link queryBuilder#southWestNorthEast} function or as a list
of {queryBuilder.LatLon} coordinates in South, West, North, and East order.
@method
@since 1.0
@memberof queryBuilder#
@param {number} latdivs - the number of latitude divisions in the grid
@param {number} londivs - the number of longitude divisions in the grid
@param {queryBuilder.LatLon} south - the south coordinate of the box
@param {queryBuilder.LatLon} west - the west coordinate for the box
@param {queryBuilder.LatLon} north - the north coordinate for the box
@param {queryBuilder.LatLon} east - the east coordinate for the box
@returns {queryBuilder.HeatMapParam} the buckets for a geospatial facet
|
[
"Specifies",
"the",
"buckets",
"for",
"a",
"geospatial",
"facet",
"."
] |
368be82f377eb4178ece35d9491dac6672bd1288
|
https://github.com/marklogic/node-client-api/blob/368be82f377eb4178ece35d9491dac6672bd1288/lib/query-builder.js#L1742-L1813
|
train
|
marklogic/node-client-api
|
lib/query-builder.js
|
latlon
|
function latlon() {
var args = mlutil.asArray.apply(null, arguments);
switch(args.length) {
case 0:
throw new Error('missing latitude and longitude for latlon coordinate');
case 1:
throw new Error('missing longitude for latlon coordinate');
case 2:
return new LatLongDef(args[0], args[1]);
default:
throw new Error('too many arguments for latlon coordinate: '+args.length);
}
}
|
javascript
|
function latlon() {
var args = mlutil.asArray.apply(null, arguments);
switch(args.length) {
case 0:
throw new Error('missing latitude and longitude for latlon coordinate');
case 1:
throw new Error('missing longitude for latlon coordinate');
case 2:
return new LatLongDef(args[0], args[1]);
default:
throw new Error('too many arguments for latlon coordinate: '+args.length);
}
}
|
[
"function",
"latlon",
"(",
")",
"{",
"var",
"args",
"=",
"mlutil",
".",
"asArray",
".",
"apply",
"(",
"null",
",",
"arguments",
")",
";",
"switch",
"(",
"args",
".",
"length",
")",
"{",
"case",
"0",
":",
"throw",
"new",
"Error",
"(",
"'missing latitude and longitude for latlon coordinate'",
")",
";",
"case",
"1",
":",
"throw",
"new",
"Error",
"(",
"'missing longitude for latlon coordinate'",
")",
";",
"case",
"2",
":",
"return",
"new",
"LatLongDef",
"(",
"args",
"[",
"0",
"]",
",",
"args",
"[",
"1",
"]",
")",
";",
"default",
":",
"throw",
"new",
"Error",
"(",
"'too many arguments for latlon coordinate: '",
"+",
"args",
".",
"length",
")",
";",
"}",
"}"
] |
Specifies the latitude and longitude for a coordinate of the region
criteria for a geospatial query. The latitude and longitude can be
passed as individual numeric parameters or wrapped in an array
@method
@since 1.0
@memberof queryBuilder#
@param {number} latitude - the north-south location
@param {number} longitude - the east-west location
@returns {queryBuilder.LatLon} a coordinate for a {queryBuilder.Region}
|
[
"Specifies",
"the",
"latitude",
"and",
"longitude",
"for",
"a",
"coordinate",
"of",
"the",
"region",
"criteria",
"for",
"a",
"geospatial",
"query",
".",
"The",
"latitude",
"and",
"longitude",
"can",
"be",
"passed",
"as",
"individual",
"numeric",
"parameters",
"or",
"wrapped",
"in",
"an",
"array"
] |
368be82f377eb4178ece35d9491dac6672bd1288
|
https://github.com/marklogic/node-client-api/blob/368be82f377eb4178ece35d9491dac6672bd1288/lib/query-builder.js#L1857-L1869
|
train
|
marklogic/node-client-api
|
lib/query-builder.js
|
notIn
|
function notIn() {
var args = mlutil.asArray.apply(null, arguments);
switch(args.length) {
case 0:
throw new Error('missing positive and negative queries');
case 1:
throw new Error('has positive query but missing negative query: '+mlutil.identify(args[0], true));
case 2:
return new NotInDef(new PositiveNegativeDef(args[0], args[1]));
default:
throw new Error('too many arguments for notIn() query: '+args.length);
}
}
|
javascript
|
function notIn() {
var args = mlutil.asArray.apply(null, arguments);
switch(args.length) {
case 0:
throw new Error('missing positive and negative queries');
case 1:
throw new Error('has positive query but missing negative query: '+mlutil.identify(args[0], true));
case 2:
return new NotInDef(new PositiveNegativeDef(args[0], args[1]));
default:
throw new Error('too many arguments for notIn() query: '+args.length);
}
}
|
[
"function",
"notIn",
"(",
")",
"{",
"var",
"args",
"=",
"mlutil",
".",
"asArray",
".",
"apply",
"(",
"null",
",",
"arguments",
")",
";",
"switch",
"(",
"args",
".",
"length",
")",
"{",
"case",
"0",
":",
"throw",
"new",
"Error",
"(",
"'missing positive and negative queries'",
")",
";",
"case",
"1",
":",
"throw",
"new",
"Error",
"(",
"'has positive query but missing negative query: '",
"+",
"mlutil",
".",
"identify",
"(",
"args",
"[",
"0",
"]",
",",
"true",
")",
")",
";",
"case",
"2",
":",
"return",
"new",
"NotInDef",
"(",
"new",
"PositiveNegativeDef",
"(",
"args",
"[",
"0",
"]",
",",
"args",
"[",
"1",
"]",
")",
")",
";",
"default",
":",
"throw",
"new",
"Error",
"(",
"'too many arguments for notIn() query: '",
"+",
"args",
".",
"length",
")",
";",
"}",
"}"
] |
Builds a query where the matching content qualifies for the positive query
and does not qualify for the negative query. Positions must be enabled for indexes.
@method
@since 1.0
@memberof queryBuilder#
@param {queryBuilder.Query} positiveQuery - a query that must match
the content
@param {queryBuilder.Query} negativeQuery - a query that must not match
the same content
@returns {queryBuilder.Query} a composable query
|
[
"Builds",
"a",
"query",
"where",
"the",
"matching",
"content",
"qualifies",
"for",
"the",
"positive",
"query",
"and",
"does",
"not",
"qualify",
"for",
"the",
"negative",
"query",
".",
"Positions",
"must",
"be",
"enabled",
"for",
"indexes",
"."
] |
368be82f377eb4178ece35d9491dac6672bd1288
|
https://github.com/marklogic/node-client-api/blob/368be82f377eb4178ece35d9491dac6672bd1288/lib/query-builder.js#L2069-L2081
|
train
|
marklogic/node-client-api
|
lib/query-builder.js
|
pathIndex
|
function pathIndex() {
var args = mlutil.asArray.apply(null, arguments);
switch(args.length) {
case 0:
throw new Error('missing path for path index identifier');
case 1:
return new PathIndexDef(new PathDef(args[0]));
case 2:
return new PathIndexDef(new PathDef(args[0], args[1]));
default:
throw new Error('too many arguments for path index identifier: '+args.length);
}
}
|
javascript
|
function pathIndex() {
var args = mlutil.asArray.apply(null, arguments);
switch(args.length) {
case 0:
throw new Error('missing path for path index identifier');
case 1:
return new PathIndexDef(new PathDef(args[0]));
case 2:
return new PathIndexDef(new PathDef(args[0], args[1]));
default:
throw new Error('too many arguments for path index identifier: '+args.length);
}
}
|
[
"function",
"pathIndex",
"(",
")",
"{",
"var",
"args",
"=",
"mlutil",
".",
"asArray",
".",
"apply",
"(",
"null",
",",
"arguments",
")",
";",
"switch",
"(",
"args",
".",
"length",
")",
"{",
"case",
"0",
":",
"throw",
"new",
"Error",
"(",
"'missing path for path index identifier'",
")",
";",
"case",
"1",
":",
"return",
"new",
"PathIndexDef",
"(",
"new",
"PathDef",
"(",
"args",
"[",
"0",
"]",
")",
")",
";",
"case",
"2",
":",
"return",
"new",
"PathIndexDef",
"(",
"new",
"PathDef",
"(",
"args",
"[",
"0",
"]",
",",
"args",
"[",
"1",
"]",
")",
")",
";",
"default",
":",
"throw",
"new",
"Error",
"(",
"'too many arguments for path index identifier: '",
"+",
"args",
".",
"length",
")",
";",
"}",
"}"
] |
Specifies a path configured as an index over JSON or XML documents on the server.
@method
@since 1.0
@memberof queryBuilder#
@param {string} pathExpression - the indexed path
@param {object} namespaces - bindings between the prefixes in the path and
namespace URIs
@returns {queryBuilder.IndexedName} an indexed name for specifying a query
|
[
"Specifies",
"a",
"path",
"configured",
"as",
"an",
"index",
"over",
"JSON",
"or",
"XML",
"documents",
"on",
"the",
"server",
"."
] |
368be82f377eb4178ece35d9491dac6672bd1288
|
https://github.com/marklogic/node-client-api/blob/368be82f377eb4178ece35d9491dac6672bd1288/lib/query-builder.js#L2163-L2175
|
train
|
marklogic/node-client-api
|
lib/query-builder.js
|
coordSystem
|
function coordSystem() {
var args = mlutil.asArray.apply(null, arguments);
switch(args.length) {
case 0:
throw new Error('missing identifier for coordinate system');
case 1:
return new CoordSystemDef(args[0]);
default:
throw new Error('too many arguments for coordinate system identifier: '+args.length);
}
}
|
javascript
|
function coordSystem() {
var args = mlutil.asArray.apply(null, arguments);
switch(args.length) {
case 0:
throw new Error('missing identifier for coordinate system');
case 1:
return new CoordSystemDef(args[0]);
default:
throw new Error('too many arguments for coordinate system identifier: '+args.length);
}
}
|
[
"function",
"coordSystem",
"(",
")",
"{",
"var",
"args",
"=",
"mlutil",
".",
"asArray",
".",
"apply",
"(",
"null",
",",
"arguments",
")",
";",
"switch",
"(",
"args",
".",
"length",
")",
"{",
"case",
"0",
":",
"throw",
"new",
"Error",
"(",
"'missing identifier for coordinate system'",
")",
";",
"case",
"1",
":",
"return",
"new",
"CoordSystemDef",
"(",
"args",
"[",
"0",
"]",
")",
";",
"default",
":",
"throw",
"new",
"Error",
"(",
"'too many arguments for coordinate system identifier: '",
"+",
"args",
".",
"length",
")",
";",
"}",
"}"
] |
Identifies the coordinate system used by a geospatial path index.
@method
@since 1.0
@memberof queryBuilder#
@param {string} coord - the name of the coordinate system
@returns {queryBuilder.CoordSystem} a coordinate system identifier
|
[
"Identifies",
"the",
"coordinate",
"system",
"used",
"by",
"a",
"geospatial",
"path",
"index",
"."
] |
368be82f377eb4178ece35d9491dac6672bd1288
|
https://github.com/marklogic/node-client-api/blob/368be82f377eb4178ece35d9491dac6672bd1288/lib/query-builder.js#L2214-L2224
|
train
|
marklogic/node-client-api
|
lib/query-builder.js
|
property
|
function property() {
var args = mlutil.asArray.apply(null, arguments);
switch(args.length) {
case 0:
throw new Error('missing JSON property name');
case 1:
return new JSONPropertyDef(args[0]);
default:
throw new Error('too many arguments for JSON property identifier: '+args.length);
}
}
|
javascript
|
function property() {
var args = mlutil.asArray.apply(null, arguments);
switch(args.length) {
case 0:
throw new Error('missing JSON property name');
case 1:
return new JSONPropertyDef(args[0]);
default:
throw new Error('too many arguments for JSON property identifier: '+args.length);
}
}
|
[
"function",
"property",
"(",
")",
"{",
"var",
"args",
"=",
"mlutil",
".",
"asArray",
".",
"apply",
"(",
"null",
",",
"arguments",
")",
";",
"switch",
"(",
"args",
".",
"length",
")",
"{",
"case",
"0",
":",
"throw",
"new",
"Error",
"(",
"'missing JSON property name'",
")",
";",
"case",
"1",
":",
"return",
"new",
"JSONPropertyDef",
"(",
"args",
"[",
"0",
"]",
")",
";",
"default",
":",
"throw",
"new",
"Error",
"(",
"'too many arguments for JSON property identifier: '",
"+",
"args",
".",
"length",
")",
";",
"}",
"}"
] |
Specifies a JSON property for a query. As a shortcut, a JSON property
can also be specified with a string instead of calling this function.
@method
@since 1.0
@memberof queryBuilder#
@param {string} name - the name of the property
@returns {queryBuilder.IndexedName} an indexed name for specifying a query
|
[
"Specifies",
"a",
"JSON",
"property",
"for",
"a",
"query",
".",
"As",
"a",
"shortcut",
"a",
"JSON",
"property",
"can",
"also",
"be",
"specified",
"with",
"a",
"string",
"instead",
"of",
"calling",
"this",
"function",
"."
] |
368be82f377eb4178ece35d9491dac6672bd1288
|
https://github.com/marklogic/node-client-api/blob/368be82f377eb4178ece35d9491dac6672bd1288/lib/query-builder.js#L2357-L2367
|
train
|
marklogic/node-client-api
|
lib/query-builder.js
|
term
|
function term() {
var args = mlutil.asArray.apply(null, arguments);
var text = [];
var weight = null;
var termOptions = null;
var arg = null;
for (var i=0; i < args.length; i++) {
arg = args[i];
if (weight === null && arg instanceof WeightDef) {
weight = arg.weight;
continue;
}
if (termOptions === null && arg instanceof TermOptionsDef) {
termOptions = arg['term-option'];
continue;
}
if (arg instanceof Array){
Array.prototype.push.apply(text, arg);
} else {
text.push(arg);
}
}
return new TermDef(new TextDef(null, null, text, weight, termOptions, null));
}
|
javascript
|
function term() {
var args = mlutil.asArray.apply(null, arguments);
var text = [];
var weight = null;
var termOptions = null;
var arg = null;
for (var i=0; i < args.length; i++) {
arg = args[i];
if (weight === null && arg instanceof WeightDef) {
weight = arg.weight;
continue;
}
if (termOptions === null && arg instanceof TermOptionsDef) {
termOptions = arg['term-option'];
continue;
}
if (arg instanceof Array){
Array.prototype.push.apply(text, arg);
} else {
text.push(arg);
}
}
return new TermDef(new TextDef(null, null, text, weight, termOptions, null));
}
|
[
"function",
"term",
"(",
")",
"{",
"var",
"args",
"=",
"mlutil",
".",
"asArray",
".",
"apply",
"(",
"null",
",",
"arguments",
")",
";",
"var",
"text",
"=",
"[",
"]",
";",
"var",
"weight",
"=",
"null",
";",
"var",
"termOptions",
"=",
"null",
";",
"var",
"arg",
"=",
"null",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"args",
".",
"length",
";",
"i",
"++",
")",
"{",
"arg",
"=",
"args",
"[",
"i",
"]",
";",
"if",
"(",
"weight",
"===",
"null",
"&&",
"arg",
"instanceof",
"WeightDef",
")",
"{",
"weight",
"=",
"arg",
".",
"weight",
";",
"continue",
";",
"}",
"if",
"(",
"termOptions",
"===",
"null",
"&&",
"arg",
"instanceof",
"TermOptionsDef",
")",
"{",
"termOptions",
"=",
"arg",
"[",
"'term-option'",
"]",
";",
"continue",
";",
"}",
"if",
"(",
"arg",
"instanceof",
"Array",
")",
"{",
"Array",
".",
"prototype",
".",
"push",
".",
"apply",
"(",
"text",
",",
"arg",
")",
";",
"}",
"else",
"{",
"text",
".",
"push",
"(",
"arg",
")",
";",
"}",
"}",
"return",
"new",
"TermDef",
"(",
"new",
"TextDef",
"(",
"null",
",",
"null",
",",
"text",
",",
"weight",
",",
"termOptions",
",",
"null",
")",
")",
";",
"}"
] |
Builds a query for matching words in a JSON, text, or XML document.
@method
@since 1.0
@memberof queryBuilder#
@param {string} [...text] - one or more words to match
@param {queryBuilder.WeightParam} [weight] - a weight returned
by {@link queryBuilder#weight} to increase or decrease the score
of the query relative to other queries in the complete search
@param {queryBuilder.TermOptionsParam} [options] - options
from {@link queryBuilder#termOptions} modifying the default behavior
@returns {queryBuilder.Query} a composable query
|
[
"Builds",
"a",
"query",
"for",
"matching",
"words",
"in",
"a",
"JSON",
"text",
"or",
"XML",
"document",
"."
] |
368be82f377eb4178ece35d9491dac6672bd1288
|
https://github.com/marklogic/node-client-api/blob/368be82f377eb4178ece35d9491dac6672bd1288/lib/query-builder.js#L3104-L3128
|
train
|
marklogic/node-client-api
|
lib/query-builder.js
|
calculate
|
function calculate() {
/*jshint validthis:true */
var self = (this instanceof QueryBuilder) ? this : new QueryBuilder();
var args = mlutil.asArray.apply(null, arguments);
// TODO: distinguish facets and values
var calculateClause = {
constraint: args
};
self.calculateClause = calculateClause;
return self;
}
|
javascript
|
function calculate() {
/*jshint validthis:true */
var self = (this instanceof QueryBuilder) ? this : new QueryBuilder();
var args = mlutil.asArray.apply(null, arguments);
// TODO: distinguish facets and values
var calculateClause = {
constraint: args
};
self.calculateClause = calculateClause;
return self;
}
|
[
"function",
"calculate",
"(",
")",
"{",
"var",
"self",
"=",
"(",
"this",
"instanceof",
"QueryBuilder",
")",
"?",
"this",
":",
"new",
"QueryBuilder",
"(",
")",
";",
"var",
"args",
"=",
"mlutil",
".",
"asArray",
".",
"apply",
"(",
"null",
",",
"arguments",
")",
";",
"var",
"calculateClause",
"=",
"{",
"constraint",
":",
"args",
"}",
";",
"self",
".",
"calculateClause",
"=",
"calculateClause",
";",
"return",
"self",
";",
"}"
] |
Sets the calculate clause of a built query, specifying JSON properties,
XML elements or attributes, fields, or paths with a range index for
value frequency or other aggregate calculation.
@method
@since 1.0
@memberof queryBuilder#
@param {queryBuilder.Facet} ...facets - the facets to calculate
over the documents in the result set as returned by
the {@link queryBuilder#facet} function.
@returns {queryBuilder.BuiltQuery} a built query
|
[
"Sets",
"the",
"calculate",
"clause",
"of",
"a",
"built",
"query",
"specifying",
"JSON",
"properties",
"XML",
"elements",
"or",
"attributes",
"fields",
"or",
"paths",
"with",
"a",
"range",
"index",
"for",
"value",
"frequency",
"or",
"other",
"aggregate",
"calculation",
"."
] |
368be82f377eb4178ece35d9491dac6672bd1288
|
https://github.com/marklogic/node-client-api/blob/368be82f377eb4178ece35d9491dac6672bd1288/lib/query-builder.js#L3918-L3932
|
train
|
marklogic/node-client-api
|
lib/query-builder.js
|
extract
|
function extract() {
var args = mlutil.asArray.apply(null, arguments);
var argLen = args.length;
if (argLen < 1) {
throw new Error('must specify paths to extract');
}
var extractdef = {};
var arg = args[0];
if (typeof arg === 'string' || arg instanceof String) {
extractdef['extract-path'] = args;
} else {
var paths = arg.paths;
if (typeof paths === 'string' || paths instanceof String) {
extractdef['extract-path'] = [paths];
} else if (Array.isArray(paths)) {
extractdef['extract-path'] = paths;
} else if (paths === void 0) {
throw new Error('first argument does not have key for paths to extract');
}
var namespaces = arg.namespaces;
if (namespaces !== void 0) {
extractdef.namespaces = namespaces;
}
var selected = arg.selected;
if (selected !== void 0) {
extractdef.selected = selected;
}
}
return {'extract-document-data': extractdef};
}
|
javascript
|
function extract() {
var args = mlutil.asArray.apply(null, arguments);
var argLen = args.length;
if (argLen < 1) {
throw new Error('must specify paths to extract');
}
var extractdef = {};
var arg = args[0];
if (typeof arg === 'string' || arg instanceof String) {
extractdef['extract-path'] = args;
} else {
var paths = arg.paths;
if (typeof paths === 'string' || paths instanceof String) {
extractdef['extract-path'] = [paths];
} else if (Array.isArray(paths)) {
extractdef['extract-path'] = paths;
} else if (paths === void 0) {
throw new Error('first argument does not have key for paths to extract');
}
var namespaces = arg.namespaces;
if (namespaces !== void 0) {
extractdef.namespaces = namespaces;
}
var selected = arg.selected;
if (selected !== void 0) {
extractdef.selected = selected;
}
}
return {'extract-document-data': extractdef};
}
|
[
"function",
"extract",
"(",
")",
"{",
"var",
"args",
"=",
"mlutil",
".",
"asArray",
".",
"apply",
"(",
"null",
",",
"arguments",
")",
";",
"var",
"argLen",
"=",
"args",
".",
"length",
";",
"if",
"(",
"argLen",
"<",
"1",
")",
"{",
"throw",
"new",
"Error",
"(",
"'must specify paths to extract'",
")",
";",
"}",
"var",
"extractdef",
"=",
"{",
"}",
";",
"var",
"arg",
"=",
"args",
"[",
"0",
"]",
";",
"if",
"(",
"typeof",
"arg",
"===",
"'string'",
"||",
"arg",
"instanceof",
"String",
")",
"{",
"extractdef",
"[",
"'extract-path'",
"]",
"=",
"args",
";",
"}",
"else",
"{",
"var",
"paths",
"=",
"arg",
".",
"paths",
";",
"if",
"(",
"typeof",
"paths",
"===",
"'string'",
"||",
"paths",
"instanceof",
"String",
")",
"{",
"extractdef",
"[",
"'extract-path'",
"]",
"=",
"[",
"paths",
"]",
";",
"}",
"else",
"if",
"(",
"Array",
".",
"isArray",
"(",
"paths",
")",
")",
"{",
"extractdef",
"[",
"'extract-path'",
"]",
"=",
"paths",
";",
"}",
"else",
"if",
"(",
"paths",
"===",
"void",
"0",
")",
"{",
"throw",
"new",
"Error",
"(",
"'first argument does not have key for paths to extract'",
")",
";",
"}",
"var",
"namespaces",
"=",
"arg",
".",
"namespaces",
";",
"if",
"(",
"namespaces",
"!==",
"void",
"0",
")",
"{",
"extractdef",
".",
"namespaces",
"=",
"namespaces",
";",
"}",
"var",
"selected",
"=",
"arg",
".",
"selected",
";",
"if",
"(",
"selected",
"!==",
"void",
"0",
")",
"{",
"extractdef",
".",
"selected",
"=",
"selected",
";",
"}",
"}",
"return",
"{",
"'extract-document-data'",
":",
"extractdef",
"}",
";",
"}"
] |
Specifies JSON properties or XML elements to project from the
documents returned by a query.
@method
@since 1.0
@memberof queryBuilder#
@param {string|string[]} paths - restricted XPaths (valid for
the cts:valid-index-path() function) to match in documents
@param {object} [namespaces] - for XPaths using namespaces,
an object whose properties specify the prefix as the key and
the uri as the value
@param {string} [selected] - specifies how to process
the selected JSON properties or XML elements where
include (the default) lists the selections,
include-ancestors projects a sparse document with
the selections and their ancesors, and
exclude suppresses the selections to projects a sparse document
with the sibilings and ancestors of the selections.
@returns {object} a extract definition
for the {@link queryBuilder#slice} function
|
[
"Specifies",
"JSON",
"properties",
"or",
"XML",
"elements",
"to",
"project",
"from",
"the",
"documents",
"returned",
"by",
"a",
"query",
"."
] |
368be82f377eb4178ece35d9491dac6672bd1288
|
https://github.com/marklogic/node-client-api/blob/368be82f377eb4178ece35d9491dac6672bd1288/lib/query-builder.js#L4998-L5032
|
train
|
marklogic/node-client-api
|
lib/query-builder.js
|
withOptions
|
function withOptions() {
/*jshint validthis:true */
var self = (this instanceof QueryBuilder) ? this : new QueryBuilder();
// TODO: share with documents.js
var optionKeyMapping = {
search:'search-option', weight:'quality-weight',
forestNames:'forest', similarDocs:'return-similar',
metrics:'return-metrics', queryPlan:'return-plan',
debug:'debug', concurrencyLevel:'concurrency-level',
categories:true, txid:true
};
var withOptionsClause = {};
if (0 < arguments.length) {
var arg = arguments[0];
var argKeys = Object.keys(arg);
for (var i=0; i < argKeys.length; i++) {
var key = argKeys[i];
if (optionKeyMapping[key] !== void 0) {
var value = arg[key];
if (value !== void 0) {
withOptionsClause[key] = value;
} else {
throw new Error('empty options value for '+key);
}
} else {
throw new Error('unknown option '+key);
}
}
}
self.withOptionsClause = withOptionsClause;
return self;
}
|
javascript
|
function withOptions() {
/*jshint validthis:true */
var self = (this instanceof QueryBuilder) ? this : new QueryBuilder();
// TODO: share with documents.js
var optionKeyMapping = {
search:'search-option', weight:'quality-weight',
forestNames:'forest', similarDocs:'return-similar',
metrics:'return-metrics', queryPlan:'return-plan',
debug:'debug', concurrencyLevel:'concurrency-level',
categories:true, txid:true
};
var withOptionsClause = {};
if (0 < arguments.length) {
var arg = arguments[0];
var argKeys = Object.keys(arg);
for (var i=0; i < argKeys.length; i++) {
var key = argKeys[i];
if (optionKeyMapping[key] !== void 0) {
var value = arg[key];
if (value !== void 0) {
withOptionsClause[key] = value;
} else {
throw new Error('empty options value for '+key);
}
} else {
throw new Error('unknown option '+key);
}
}
}
self.withOptionsClause = withOptionsClause;
return self;
}
|
[
"function",
"withOptions",
"(",
")",
"{",
"var",
"self",
"=",
"(",
"this",
"instanceof",
"QueryBuilder",
")",
"?",
"this",
":",
"new",
"QueryBuilder",
"(",
")",
";",
"var",
"optionKeyMapping",
"=",
"{",
"search",
":",
"'search-option'",
",",
"weight",
":",
"'quality-weight'",
",",
"forestNames",
":",
"'forest'",
",",
"similarDocs",
":",
"'return-similar'",
",",
"metrics",
":",
"'return-metrics'",
",",
"queryPlan",
":",
"'return-plan'",
",",
"debug",
":",
"'debug'",
",",
"concurrencyLevel",
":",
"'concurrency-level'",
",",
"categories",
":",
"true",
",",
"txid",
":",
"true",
"}",
";",
"var",
"withOptionsClause",
"=",
"{",
"}",
";",
"if",
"(",
"0",
"<",
"arguments",
".",
"length",
")",
"{",
"var",
"arg",
"=",
"arguments",
"[",
"0",
"]",
";",
"var",
"argKeys",
"=",
"Object",
".",
"keys",
"(",
"arg",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"argKeys",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"key",
"=",
"argKeys",
"[",
"i",
"]",
";",
"if",
"(",
"optionKeyMapping",
"[",
"key",
"]",
"!==",
"void",
"0",
")",
"{",
"var",
"value",
"=",
"arg",
"[",
"key",
"]",
";",
"if",
"(",
"value",
"!==",
"void",
"0",
")",
"{",
"withOptionsClause",
"[",
"key",
"]",
"=",
"value",
";",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"'empty options value for '",
"+",
"key",
")",
";",
"}",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"'unknown option '",
"+",
"key",
")",
";",
"}",
"}",
"}",
"self",
".",
"withOptionsClause",
"=",
"withOptionsClause",
";",
"return",
"self",
";",
"}"
] |
Sets the withOptions clause of a built query to configure the query;
takes a configuration object with the following named parameters.
This function may be called on the result of building a query. When the
'debug', 'metrics', 'queryPlan', or 'similarDocs' parameter is set, a
search summary object will be returned along with the result documents.
When 'categories' is set to 'none', only a search summary is returned.
@method
@since 1.0
@memberof queryBuilder#
@param {documents.categories} [categories] - the categories of information
to retrieve for the result documents
@param {number} [concurrencyLevel] - the maximum number of threads to use to calculate facets
@param {string|string[]} [forestNames] - the ids of forests providing documents
for the result set
@param {...string} [search] - <a href="https://docs.marklogic.com/guide/search-dev/appendixa#id_77801">options</a>
modifying the default behaviour of the query
@param {string|transactions.Transaction} [txid] - a string
transaction id or Transaction object identifying an open
multi-statement transaction
@param {number} [weight] - a weighting factor between -16 and 64
@param {boolean} [debug] - whether to return query debugging
@param {boolean} [metrics] - whether to return metrics for the query performance
@param {boolean} [queryPlan] - whether to return a plan for the execution of the query
@param {boolean} [similarDocs] - whether to return a list of URIs for documents
similar to each result
@returns {queryBuilder.BuiltQuery} a built query
|
[
"Sets",
"the",
"withOptions",
"clause",
"of",
"a",
"built",
"query",
"to",
"configure",
"the",
"query",
";",
"takes",
"a",
"configuration",
"object",
"with",
"the",
"following",
"named",
"parameters",
".",
"This",
"function",
"may",
"be",
"called",
"on",
"the",
"result",
"of",
"building",
"a",
"query",
".",
"When",
"the",
"debug",
"metrics",
"queryPlan",
"or",
"similarDocs",
"parameter",
"is",
"set",
"a",
"search",
"summary",
"object",
"will",
"be",
"returned",
"along",
"with",
"the",
"result",
"documents",
".",
"When",
"categories",
"is",
"set",
"to",
"none",
"only",
"a",
"search",
"summary",
"is",
"returned",
"."
] |
368be82f377eb4178ece35d9491dac6672bd1288
|
https://github.com/marklogic/node-client-api/blob/368be82f377eb4178ece35d9491dac6672bd1288/lib/query-builder.js#L5125-L5159
|
train
|
marklogic/node-client-api
|
lib/patch-builder.js
|
remove
|
function remove() {
var select = null;
var cardinality = null;
var argLen = arguments.length;
for (var i=0; i < argLen; i++) {
var arg = arguments[i];
if (i === 0) {
select = arg;
continue;
}
if (cardinality === null && /^[?.*+]$/.test(arg)) {
cardinality = arg;
continue;
}
break;
}
if (select === null) {
throw new Error('remove takes select and optional cardinality');
}
var operation = {
select: select
};
if (cardinality !== null) {
operation.cardinality = cardinality;
}
return {'delete': operation};
}
|
javascript
|
function remove() {
var select = null;
var cardinality = null;
var argLen = arguments.length;
for (var i=0; i < argLen; i++) {
var arg = arguments[i];
if (i === 0) {
select = arg;
continue;
}
if (cardinality === null && /^[?.*+]$/.test(arg)) {
cardinality = arg;
continue;
}
break;
}
if (select === null) {
throw new Error('remove takes select and optional cardinality');
}
var operation = {
select: select
};
if (cardinality !== null) {
operation.cardinality = cardinality;
}
return {'delete': operation};
}
|
[
"function",
"remove",
"(",
")",
"{",
"var",
"select",
"=",
"null",
";",
"var",
"cardinality",
"=",
"null",
";",
"var",
"argLen",
"=",
"arguments",
".",
"length",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"argLen",
";",
"i",
"++",
")",
"{",
"var",
"arg",
"=",
"arguments",
"[",
"i",
"]",
";",
"if",
"(",
"i",
"===",
"0",
")",
"{",
"select",
"=",
"arg",
";",
"continue",
";",
"}",
"if",
"(",
"cardinality",
"===",
"null",
"&&",
"/",
"^[?.*+]$",
"/",
".",
"test",
"(",
"arg",
")",
")",
"{",
"cardinality",
"=",
"arg",
";",
"continue",
";",
"}",
"break",
";",
"}",
"if",
"(",
"select",
"===",
"null",
")",
"{",
"throw",
"new",
"Error",
"(",
"'remove takes select and optional cardinality'",
")",
";",
"}",
"var",
"operation",
"=",
"{",
"select",
":",
"select",
"}",
";",
"if",
"(",
"cardinality",
"!==",
"null",
")",
"{",
"operation",
".",
"cardinality",
"=",
"cardinality",
";",
"}",
"return",
"{",
"'delete'",
":",
"operation",
"}",
";",
"}"
] |
An operation as part of a document patch request.
@typedef {object} patchBuilder.PatchOperation
@since 1.0
Builds an operation to remove a JSON property or XML element or attribute.
@method
@since 1.0
@memberof patchBuilder#
@param {string} select - the path to select the fragment to remove
@param {string} [cardinality] - a specification from the ?|.|*|+
enumeration controlling whether the select path must match zero-or-one
fragment, exactly one fragment, any number of fragments (the default), or
one-or-more fragments.
@returns {patchBuilder.PatchOperation} a patch operation
|
[
"An",
"operation",
"as",
"part",
"of",
"a",
"document",
"patch",
"request",
"."
] |
368be82f377eb4178ece35d9491dac6672bd1288
|
https://github.com/marklogic/node-client-api/blob/368be82f377eb4178ece35d9491dac6672bd1288/lib/patch-builder.js#L47-L77
|
train
|
marklogic/node-client-api
|
lib/patch-builder.js
|
insert
|
function insert() {
var context = null;
var position = null;
var content = void 0;
var cardinality = null;
var argLen = arguments.length;
for (var i=0; i < argLen; i++) {
var arg = arguments[i];
if (i === 0) {
context = arg;
continue;
}
if (arg === null && content === void 0) {
content = arg;
continue;
}
var isString = (typeof arg === 'string' || arg instanceof String);
if (isString) {
if (position === null && /^(before|after|last-child)$/.test(arg)) {
position = arg;
continue;
}
if (cardinality === null && /^[?.*+]$/.test(arg)) {
cardinality = arg;
continue;
}
}
if (content === void 0) {
content = arg;
continue;
}
break;
}
if (context === null || position === null || content === void 0) {
throw new Error(
'insert takes context, position, content, and optional cardinality'
);
}
var operation = {
context: context,
position: position,
content: content
};
if (cardinality !== null) {
operation.cardinality = cardinality;
}
return {insert: operation};
}
|
javascript
|
function insert() {
var context = null;
var position = null;
var content = void 0;
var cardinality = null;
var argLen = arguments.length;
for (var i=0; i < argLen; i++) {
var arg = arguments[i];
if (i === 0) {
context = arg;
continue;
}
if (arg === null && content === void 0) {
content = arg;
continue;
}
var isString = (typeof arg === 'string' || arg instanceof String);
if (isString) {
if (position === null && /^(before|after|last-child)$/.test(arg)) {
position = arg;
continue;
}
if (cardinality === null && /^[?.*+]$/.test(arg)) {
cardinality = arg;
continue;
}
}
if (content === void 0) {
content = arg;
continue;
}
break;
}
if (context === null || position === null || content === void 0) {
throw new Error(
'insert takes context, position, content, and optional cardinality'
);
}
var operation = {
context: context,
position: position,
content: content
};
if (cardinality !== null) {
operation.cardinality = cardinality;
}
return {insert: operation};
}
|
[
"function",
"insert",
"(",
")",
"{",
"var",
"context",
"=",
"null",
";",
"var",
"position",
"=",
"null",
";",
"var",
"content",
"=",
"void",
"0",
";",
"var",
"cardinality",
"=",
"null",
";",
"var",
"argLen",
"=",
"arguments",
".",
"length",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"argLen",
";",
"i",
"++",
")",
"{",
"var",
"arg",
"=",
"arguments",
"[",
"i",
"]",
";",
"if",
"(",
"i",
"===",
"0",
")",
"{",
"context",
"=",
"arg",
";",
"continue",
";",
"}",
"if",
"(",
"arg",
"===",
"null",
"&&",
"content",
"===",
"void",
"0",
")",
"{",
"content",
"=",
"arg",
";",
"continue",
";",
"}",
"var",
"isString",
"=",
"(",
"typeof",
"arg",
"===",
"'string'",
"||",
"arg",
"instanceof",
"String",
")",
";",
"if",
"(",
"isString",
")",
"{",
"if",
"(",
"position",
"===",
"null",
"&&",
"/",
"^(before|after|last-child)$",
"/",
".",
"test",
"(",
"arg",
")",
")",
"{",
"position",
"=",
"arg",
";",
"continue",
";",
"}",
"if",
"(",
"cardinality",
"===",
"null",
"&&",
"/",
"^[?.*+]$",
"/",
".",
"test",
"(",
"arg",
")",
")",
"{",
"cardinality",
"=",
"arg",
";",
"continue",
";",
"}",
"}",
"if",
"(",
"content",
"===",
"void",
"0",
")",
"{",
"content",
"=",
"arg",
";",
"continue",
";",
"}",
"break",
";",
"}",
"if",
"(",
"context",
"===",
"null",
"||",
"position",
"===",
"null",
"||",
"content",
"===",
"void",
"0",
")",
"{",
"throw",
"new",
"Error",
"(",
"'insert takes context, position, content, and optional cardinality'",
")",
";",
"}",
"var",
"operation",
"=",
"{",
"context",
":",
"context",
",",
"position",
":",
"position",
",",
"content",
":",
"content",
"}",
";",
"if",
"(",
"cardinality",
"!==",
"null",
")",
"{",
"operation",
".",
"cardinality",
"=",
"cardinality",
";",
"}",
"return",
"{",
"insert",
":",
"operation",
"}",
";",
"}"
] |
Builds an operation to insert content.
@method
@since 1.0
@memberof patchBuilder#
@param {string} context - the path to the container of the inserted content
@param {string} position - a specification from the before|after|last-child
enumeration controlling where the content will be inserted relative to the context
@param content - the inserted object or value
@param {string} [cardinality] - a specification from the ?|.|*|+
enumeration controlling whether the context path must match zero-or-one
fragment, exactly one fragment, any number of fragments (the default), or
one-or-more fragments.
@returns {patchBuilder.PatchOperation} a patch operation
|
[
"Builds",
"an",
"operation",
"to",
"insert",
"content",
"."
] |
368be82f377eb4178ece35d9491dac6672bd1288
|
https://github.com/marklogic/node-client-api/blob/368be82f377eb4178ece35d9491dac6672bd1288/lib/patch-builder.js#L94-L145
|
train
|
marklogic/node-client-api
|
lib/patch-builder.js
|
replace
|
function replace() {
var select = null;
var content = void 0;
var cardinality = null;
var apply = null;
var argLen = arguments.length;
for (var i=0; i < argLen; i++) {
var arg = arguments[i];
if (i === 0) {
select = arg;
continue;
}
if (arg === null && content === void 0) {
content = arg;
continue;
}
var isString = (typeof arg === 'string' || arg instanceof String);
if (isString && cardinality === null && /^[?.*+]$/.test(arg)) {
cardinality = arg;
continue;
}
if (apply === null || apply === undefined) {
apply = arg.apply;
if (apply != null) {
content = arg.content;
continue;
}
}
if (content === void 0) {
content = arg;
continue;
}
break;
}
if (select === null) {
throw new Error(
'replace takes a select path, content or an apply function, and optional cardinality'
);
}
var operation = {
select: select,
content: content
};
if (cardinality != null) {
operation.cardinality = cardinality;
}
if (apply != null) {
operation.apply = apply;
}
return {replace: operation};
}
|
javascript
|
function replace() {
var select = null;
var content = void 0;
var cardinality = null;
var apply = null;
var argLen = arguments.length;
for (var i=0; i < argLen; i++) {
var arg = arguments[i];
if (i === 0) {
select = arg;
continue;
}
if (arg === null && content === void 0) {
content = arg;
continue;
}
var isString = (typeof arg === 'string' || arg instanceof String);
if (isString && cardinality === null && /^[?.*+]$/.test(arg)) {
cardinality = arg;
continue;
}
if (apply === null || apply === undefined) {
apply = arg.apply;
if (apply != null) {
content = arg.content;
continue;
}
}
if (content === void 0) {
content = arg;
continue;
}
break;
}
if (select === null) {
throw new Error(
'replace takes a select path, content or an apply function, and optional cardinality'
);
}
var operation = {
select: select,
content: content
};
if (cardinality != null) {
operation.cardinality = cardinality;
}
if (apply != null) {
operation.apply = apply;
}
return {replace: operation};
}
|
[
"function",
"replace",
"(",
")",
"{",
"var",
"select",
"=",
"null",
";",
"var",
"content",
"=",
"void",
"0",
";",
"var",
"cardinality",
"=",
"null",
";",
"var",
"apply",
"=",
"null",
";",
"var",
"argLen",
"=",
"arguments",
".",
"length",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"argLen",
";",
"i",
"++",
")",
"{",
"var",
"arg",
"=",
"arguments",
"[",
"i",
"]",
";",
"if",
"(",
"i",
"===",
"0",
")",
"{",
"select",
"=",
"arg",
";",
"continue",
";",
"}",
"if",
"(",
"arg",
"===",
"null",
"&&",
"content",
"===",
"void",
"0",
")",
"{",
"content",
"=",
"arg",
";",
"continue",
";",
"}",
"var",
"isString",
"=",
"(",
"typeof",
"arg",
"===",
"'string'",
"||",
"arg",
"instanceof",
"String",
")",
";",
"if",
"(",
"isString",
"&&",
"cardinality",
"===",
"null",
"&&",
"/",
"^[?.*+]$",
"/",
".",
"test",
"(",
"arg",
")",
")",
"{",
"cardinality",
"=",
"arg",
";",
"continue",
";",
"}",
"if",
"(",
"apply",
"===",
"null",
"||",
"apply",
"===",
"undefined",
")",
"{",
"apply",
"=",
"arg",
".",
"apply",
";",
"if",
"(",
"apply",
"!=",
"null",
")",
"{",
"content",
"=",
"arg",
".",
"content",
";",
"continue",
";",
"}",
"}",
"if",
"(",
"content",
"===",
"void",
"0",
")",
"{",
"content",
"=",
"arg",
";",
"continue",
";",
"}",
"break",
";",
"}",
"if",
"(",
"select",
"===",
"null",
")",
"{",
"throw",
"new",
"Error",
"(",
"'replace takes a select path, content or an apply function, and optional cardinality'",
")",
";",
"}",
"var",
"operation",
"=",
"{",
"select",
":",
"select",
",",
"content",
":",
"content",
"}",
";",
"if",
"(",
"cardinality",
"!=",
"null",
")",
"{",
"operation",
".",
"cardinality",
"=",
"cardinality",
";",
"}",
"if",
"(",
"apply",
"!=",
"null",
")",
"{",
"operation",
".",
"apply",
"=",
"apply",
";",
"}",
"return",
"{",
"replace",
":",
"operation",
"}",
";",
"}"
] |
Builds an operation to replace a JSON property or XML element or attribute.
@method
@since 1.0
@memberof patchBuilder#
@param {string} select - the path to select the fragment to replace
@param [content] - the object or value replacing the selected fragment or
an {@link patchBuilder.ApplyDefinition} specifying a function to apply to the selected
fragment to produce the replacement
@param {string} [cardinality] - a specification from the ?|.|*|+
enumeration controlling whether the select path must match zero-or-one
fragment, exactly one fragment, any number of fragments (the default), or
one-or-more fragments.
@returns {patchBuilder.PatchOperation} a patch operation
|
[
"Builds",
"an",
"operation",
"to",
"replace",
"a",
"JSON",
"property",
"or",
"XML",
"element",
"or",
"attribute",
"."
] |
368be82f377eb4178ece35d9491dac6672bd1288
|
https://github.com/marklogic/node-client-api/blob/368be82f377eb4178ece35d9491dac6672bd1288/lib/patch-builder.js#L419-L473
|
train
|
marklogic/node-client-api
|
lib/patch-builder.js
|
addPermission
|
function addPermission() {
var permission = getPermission(
mlutil.asArray.apply(null, arguments)
);
if (permission === null) {
throw new Error('permissions.add() takes the role name and one or more insert|update|read|execute capabilities');
}
return insert('/array-node("permissions")', 'last-child', permission);
}
|
javascript
|
function addPermission() {
var permission = getPermission(
mlutil.asArray.apply(null, arguments)
);
if (permission === null) {
throw new Error('permissions.add() takes the role name and one or more insert|update|read|execute capabilities');
}
return insert('/array-node("permissions")', 'last-child', permission);
}
|
[
"function",
"addPermission",
"(",
")",
"{",
"var",
"permission",
"=",
"getPermission",
"(",
"mlutil",
".",
"asArray",
".",
"apply",
"(",
"null",
",",
"arguments",
")",
")",
";",
"if",
"(",
"permission",
"===",
"null",
")",
"{",
"throw",
"new",
"Error",
"(",
"'permissions.add() takes the role name and one or more insert|update|read|execute capabilities'",
")",
";",
"}",
"return",
"insert",
"(",
"'/array-node(\"permissions\")'",
",",
"'last-child'",
",",
"permission",
")",
";",
"}"
] |
Specifies operations to patch the permissions of a document.
@namespace patchBuilderPermissions
Specifies a role to add to a document's permissions; takes a configuration
object with the following named parameters or, as a shortcut,
a role string and capabilities string or array.
@method patchBuilderPermissions#add
@since 1.0
@param {string} role - the name of a role defined in the server configuration
@param {string|string[]} capabilities - the capability or an array of
capabilities from the insert|update|read|execute enumeration
@returns {patchBuilder.PatchOperation} a patch operation
|
[
"Specifies",
"operations",
"to",
"patch",
"the",
"permissions",
"of",
"a",
"document",
"."
] |
368be82f377eb4178ece35d9491dac6672bd1288
|
https://github.com/marklogic/node-client-api/blob/368be82f377eb4178ece35d9491dac6672bd1288/lib/patch-builder.js#L647-L655
|
train
|
marklogic/node-client-api
|
lib/patch-builder.js
|
replacePermission
|
function replacePermission() {
var permission = getPermission(
mlutil.asArray.apply(null, arguments)
);
if (permission === null) {
throw new Error('permissions.replace() takes the role name and one or more insert|update|read|execute capabilities');
}
return replace(
'/permissions[node("role-name") eq "'+permission['role-name']+'"]',
permission
);
}
|
javascript
|
function replacePermission() {
var permission = getPermission(
mlutil.asArray.apply(null, arguments)
);
if (permission === null) {
throw new Error('permissions.replace() takes the role name and one or more insert|update|read|execute capabilities');
}
return replace(
'/permissions[node("role-name") eq "'+permission['role-name']+'"]',
permission
);
}
|
[
"function",
"replacePermission",
"(",
")",
"{",
"var",
"permission",
"=",
"getPermission",
"(",
"mlutil",
".",
"asArray",
".",
"apply",
"(",
"null",
",",
"arguments",
")",
")",
";",
"if",
"(",
"permission",
"===",
"null",
")",
"{",
"throw",
"new",
"Error",
"(",
"'permissions.replace() takes the role name and one or more insert|update|read|execute capabilities'",
")",
";",
"}",
"return",
"replace",
"(",
"'/permissions[node(\"role-name\") eq \"'",
"+",
"permission",
"[",
"'role-name'",
"]",
"+",
"'\"]'",
",",
"permission",
")",
";",
"}"
] |
Specifies different capabilities for a role with permissions on a document;
takes a configuration object with the following named parameters or,
as a shortcut, a role string and capabilities string or array.
@method patchBuilderPermissions#replace
@since 1.0
@param {string} role - the name of an existing role with permissions
on the document
@param {string|string[]} capabilities - the role's modified capability or
capabilities from the insert|update|read|execute enumeration
|
[
"Specifies",
"different",
"capabilities",
"for",
"a",
"role",
"with",
"permissions",
"on",
"a",
"document",
";",
"takes",
"a",
"configuration",
"object",
"with",
"the",
"following",
"named",
"parameters",
"or",
"as",
"a",
"shortcut",
"a",
"role",
"string",
"and",
"capabilities",
"string",
"or",
"array",
"."
] |
368be82f377eb4178ece35d9491dac6672bd1288
|
https://github.com/marklogic/node-client-api/blob/368be82f377eb4178ece35d9491dac6672bd1288/lib/patch-builder.js#L667-L678
|
train
|
marklogic/node-client-api
|
lib/patch-builder.js
|
addProperty
|
function addProperty(name, value) {
if (typeof name !== 'string' || value == null) {
throw new Error('properties.add() takes a string name and a value');
}
var prop = {};
prop[name] = value;
return insert('/object-node("properties")', 'last-child', prop);
}
|
javascript
|
function addProperty(name, value) {
if (typeof name !== 'string' || value == null) {
throw new Error('properties.add() takes a string name and a value');
}
var prop = {};
prop[name] = value;
return insert('/object-node("properties")', 'last-child', prop);
}
|
[
"function",
"addProperty",
"(",
"name",
",",
"value",
")",
"{",
"if",
"(",
"typeof",
"name",
"!==",
"'string'",
"||",
"value",
"==",
"null",
")",
"{",
"throw",
"new",
"Error",
"(",
"'properties.add() takes a string name and a value'",
")",
";",
"}",
"var",
"prop",
"=",
"{",
"}",
";",
"prop",
"[",
"name",
"]",
"=",
"value",
";",
"return",
"insert",
"(",
"'/object-node(\"properties\")'",
",",
"'last-child'",
",",
"prop",
")",
";",
"}"
] |
Specifies operations to patch the metadata properties of a document.
@namespace patchBuilderProperties
Specifies a new property to add to a document's metadata.
@method patchBuilderProperties#add
@since 1.0
@param {string} name - the name of the new metadata property
@param value - the value of the new metadata property
@returns {patchBuilder.PatchOperation} a patch operation
|
[
"Specifies",
"operations",
"to",
"patch",
"the",
"metadata",
"properties",
"of",
"a",
"document",
"."
] |
368be82f377eb4178ece35d9491dac6672bd1288
|
https://github.com/marklogic/node-client-api/blob/368be82f377eb4178ece35d9491dac6672bd1288/lib/patch-builder.js#L756-L763
|
train
|
marklogic/node-client-api
|
lib/patch-builder.js
|
replaceProperty
|
function replaceProperty(name, value) {
if (typeof name !== 'string' || value == null) {
throw new Error('properties.replace() takes a string name and a value');
}
return replace('/properties/node("'+name+'")', value);
}
|
javascript
|
function replaceProperty(name, value) {
if (typeof name !== 'string' || value == null) {
throw new Error('properties.replace() takes a string name and a value');
}
return replace('/properties/node("'+name+'")', value);
}
|
[
"function",
"replaceProperty",
"(",
"name",
",",
"value",
")",
"{",
"if",
"(",
"typeof",
"name",
"!==",
"'string'",
"||",
"value",
"==",
"null",
")",
"{",
"throw",
"new",
"Error",
"(",
"'properties.replace() takes a string name and a value'",
")",
";",
"}",
"return",
"replace",
"(",
"'/properties/node(\"'",
"+",
"name",
"+",
"'\")'",
",",
"value",
")",
";",
"}"
] |
Specifies a different value for a property in a document's metadata.
@method patchBuilderProperties#replace
@since 1.0
@param {string} name - the name of the existing metadata property
@param value - the modified value of the metadata property
@returns {patchBuilder.PatchOperation} a patch operation
|
[
"Specifies",
"a",
"different",
"value",
"for",
"a",
"property",
"in",
"a",
"document",
"s",
"metadata",
"."
] |
368be82f377eb4178ece35d9491dac6672bd1288
|
https://github.com/marklogic/node-client-api/blob/368be82f377eb4178ece35d9491dac6672bd1288/lib/patch-builder.js#L772-L777
|
train
|
marklogic/node-client-api
|
lib/patch-builder.js
|
addMetadataValue
|
function addMetadataValue(name, value) {
if (typeof name !== 'string' || typeof value !== 'string' ) {
throw new Error('metadataValues.add() takes a string name and string value');
}
var metaVal = {};
metaVal[name] = value;
return insert('/object-node("metadataValues")', 'last-child', metaVal);
}
|
javascript
|
function addMetadataValue(name, value) {
if (typeof name !== 'string' || typeof value !== 'string' ) {
throw new Error('metadataValues.add() takes a string name and string value');
}
var metaVal = {};
metaVal[name] = value;
return insert('/object-node("metadataValues")', 'last-child', metaVal);
}
|
[
"function",
"addMetadataValue",
"(",
"name",
",",
"value",
")",
"{",
"if",
"(",
"typeof",
"name",
"!==",
"'string'",
"||",
"typeof",
"value",
"!==",
"'string'",
")",
"{",
"throw",
"new",
"Error",
"(",
"'metadataValues.add() takes a string name and string value'",
")",
";",
"}",
"var",
"metaVal",
"=",
"{",
"}",
";",
"metaVal",
"[",
"name",
"]",
"=",
"value",
";",
"return",
"insert",
"(",
"'/object-node(\"metadataValues\")'",
",",
"'last-child'",
",",
"metaVal",
")",
";",
"}"
] |
Specifies operations to patch the metadata values of a document.
@namespace patchBuilderMetadataValues
@since 2.0.1
Specifies a new metadata value to add to a document.
@method patchBuilderMetadataValues#add
@since 2.0.1
@param {string} name - the name of the new metadata value
@param value - the value of the new metadata value
@returns {patchBuilder.PatchOperation} a patch operation
|
[
"Specifies",
"operations",
"to",
"patch",
"the",
"metadata",
"values",
"of",
"a",
"document",
"."
] |
368be82f377eb4178ece35d9491dac6672bd1288
|
https://github.com/marklogic/node-client-api/blob/368be82f377eb4178ece35d9491dac6672bd1288/lib/patch-builder.js#L824-L831
|
train
|
marklogic/node-client-api
|
lib/mlutil.js
|
asArray
|
function asArray() {
var argLen = arguments.length;
switch(argLen) {
// No arguments returns an empty array
case 0:
return [];
// Single array argument returns that array
case 1:
var arg = arguments[0];
if (Array.isArray(arg)) {
return arg;
}
// Single object argument returns an array with object as only element
return [arg];
// List of arguments returns an array with arguments as elements
default:
var args = new Array(argLen);
for(var i=0; i < argLen; ++i) {
args[i] = arguments[i];
}
return args;
}
}
|
javascript
|
function asArray() {
var argLen = arguments.length;
switch(argLen) {
// No arguments returns an empty array
case 0:
return [];
// Single array argument returns that array
case 1:
var arg = arguments[0];
if (Array.isArray(arg)) {
return arg;
}
// Single object argument returns an array with object as only element
return [arg];
// List of arguments returns an array with arguments as elements
default:
var args = new Array(argLen);
for(var i=0; i < argLen; ++i) {
args[i] = arguments[i];
}
return args;
}
}
|
[
"function",
"asArray",
"(",
")",
"{",
"var",
"argLen",
"=",
"arguments",
".",
"length",
";",
"switch",
"(",
"argLen",
")",
"{",
"case",
"0",
":",
"return",
"[",
"]",
";",
"case",
"1",
":",
"var",
"arg",
"=",
"arguments",
"[",
"0",
"]",
";",
"if",
"(",
"Array",
".",
"isArray",
"(",
"arg",
")",
")",
"{",
"return",
"arg",
";",
"}",
"return",
"[",
"arg",
"]",
";",
"default",
":",
"var",
"args",
"=",
"new",
"Array",
"(",
"argLen",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"argLen",
";",
"++",
"i",
")",
"{",
"args",
"[",
"i",
"]",
"=",
"arguments",
"[",
"i",
"]",
";",
"}",
"return",
"args",
";",
"}",
"}"
] |
Normalize arguments by returning them as an array.
|
[
"Normalize",
"arguments",
"by",
"returning",
"them",
"as",
"an",
"array",
"."
] |
368be82f377eb4178ece35d9491dac6672bd1288
|
https://github.com/marklogic/node-client-api/blob/368be82f377eb4178ece35d9491dac6672bd1288/lib/mlutil.js#L23-L45
|
train
|
marklogic/node-client-api
|
lib/transactions.js
|
openOutputTransform
|
function openOutputTransform(headers/*, data*/) {
/*jshint validthis:true */
var operation = this;
var txid = headers.location.substring('/v1/transactions/'.length);
if (operation.withState === true) {
return new mlutil.Transaction(txid, operation.rawHeaders['set-cookie']);
}
return {txid: txid};
}
|
javascript
|
function openOutputTransform(headers/*, data*/) {
/*jshint validthis:true */
var operation = this;
var txid = headers.location.substring('/v1/transactions/'.length);
if (operation.withState === true) {
return new mlutil.Transaction(txid, operation.rawHeaders['set-cookie']);
}
return {txid: txid};
}
|
[
"function",
"openOutputTransform",
"(",
"headers",
")",
"{",
"var",
"operation",
"=",
"this",
";",
"var",
"txid",
"=",
"headers",
".",
"location",
".",
"substring",
"(",
"'/v1/transactions/'",
".",
"length",
")",
";",
"if",
"(",
"operation",
".",
"withState",
"===",
"true",
")",
"{",
"return",
"new",
"mlutil",
".",
"Transaction",
"(",
"txid",
",",
"operation",
".",
"rawHeaders",
"[",
"'set-cookie'",
"]",
")",
";",
"}",
"return",
"{",
"txid",
":",
"txid",
"}",
";",
"}"
] |
Provides functions to open, commit, or rollback multi-statement
transactions. The client must have been created for a user with
the rest-writer role.
@namespace transactions
@ignore
|
[
"Provides",
"functions",
"to",
"open",
"commit",
"or",
"rollback",
"multi",
"-",
"statement",
"transactions",
".",
"The",
"client",
"must",
"have",
"been",
"created",
"for",
"a",
"user",
"with",
"the",
"rest",
"-",
"writer",
"role",
"."
] |
368be82f377eb4178ece35d9491dac6672bd1288
|
https://github.com/marklogic/node-client-api/blob/368be82f377eb4178ece35d9491dac6672bd1288/lib/transactions.js#L29-L40
|
train
|
marklogic/node-client-api
|
lib/documents.js
|
probeOutputTransform
|
function probeOutputTransform(/*headers, data*/) {
/*jshint validthis:true */
var operation = this;
var statusCode = operation.responseStatusCode;
var exists = (statusCode === 200) ? true : false;
if (operation.contentOnly === true) {
return exists;
}
var output = exists ? operation.responseHeaders : {};
output.uri = operation.uri;
output.exists = exists;
return output;
}
|
javascript
|
function probeOutputTransform(/*headers, data*/) {
/*jshint validthis:true */
var operation = this;
var statusCode = operation.responseStatusCode;
var exists = (statusCode === 200) ? true : false;
if (operation.contentOnly === true) {
return exists;
}
var output = exists ? operation.responseHeaders : {};
output.uri = operation.uri;
output.exists = exists;
return output;
}
|
[
"function",
"probeOutputTransform",
"(",
")",
"{",
"var",
"operation",
"=",
"this",
";",
"var",
"statusCode",
"=",
"operation",
".",
"responseStatusCode",
";",
"var",
"exists",
"=",
"(",
"statusCode",
"===",
"200",
")",
"?",
"true",
":",
"false",
";",
"if",
"(",
"operation",
".",
"contentOnly",
"===",
"true",
")",
"{",
"return",
"exists",
";",
"}",
"var",
"output",
"=",
"exists",
"?",
"operation",
".",
"responseHeaders",
":",
"{",
"}",
";",
"output",
".",
"uri",
"=",
"operation",
".",
"uri",
";",
"output",
".",
"exists",
"=",
"exists",
";",
"return",
"output",
";",
"}"
] |
Provides functions to write, read, query, or perform other operations
on documents in the database. For operations that modify the database,
the client must have been created for a user with the rest-writer role.
For operations that read or query the database, the user need only have
the rest-reader role.
@namespace documents
@ignore
|
[
"Provides",
"functions",
"to",
"write",
"read",
"query",
"or",
"perform",
"other",
"operations",
"on",
"documents",
"in",
"the",
"database",
".",
"For",
"operations",
"that",
"modify",
"the",
"database",
"the",
"client",
"must",
"have",
"been",
"created",
"for",
"a",
"user",
"with",
"the",
"rest",
"-",
"writer",
"role",
".",
"For",
"operations",
"that",
"read",
"or",
"query",
"the",
"database",
"the",
"user",
"need",
"only",
"have",
"the",
"rest",
"-",
"reader",
"role",
"."
] |
368be82f377eb4178ece35d9491dac6672bd1288
|
https://github.com/marklogic/node-client-api/blob/368be82f377eb4178ece35d9491dac6672bd1288/lib/documents.js#L81-L96
|
train
|
marklogic/node-client-api
|
lib/marklogic.js
|
ExtlibsWrapper
|
function ExtlibsWrapper(extlibs, name, dir) {
if (!(this instanceof ExtlibsWrapper)) {
return new ExtlibsWrapper(extlibs, name, dir);
}
this.extlibs = extlibs;
this.name = name;
this.dir = dir;
}
|
javascript
|
function ExtlibsWrapper(extlibs, name, dir) {
if (!(this instanceof ExtlibsWrapper)) {
return new ExtlibsWrapper(extlibs, name, dir);
}
this.extlibs = extlibs;
this.name = name;
this.dir = dir;
}
|
[
"function",
"ExtlibsWrapper",
"(",
"extlibs",
",",
"name",
",",
"dir",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"ExtlibsWrapper",
")",
")",
"{",
"return",
"new",
"ExtlibsWrapper",
"(",
"extlibs",
",",
"name",
",",
"dir",
")",
";",
"}",
"this",
".",
"extlibs",
"=",
"extlibs",
";",
"this",
".",
"name",
"=",
"name",
";",
"this",
".",
"dir",
"=",
"dir",
";",
"}"
] |
Provides functions that maintain query snippet extensions
on the REST server. The client must have been created for a user with the
rest-admin role.
@namespace config.query.snippet
Reads a query snippet library installed on the server.
@method config.query.snippet#read
@since 1.0
@param {string} moduleName - the filename without a path for the query snippet library
@returns {ResultProvider} an object whose result() function takes
a success callback that receives the source code for the library
Installs a query snippet library on the server.
@method config.query.snippet#write
@since 1.0
@param {string} moduleName - the filename without a path for the query snippet library;
the filename must end in an extension registered in the server's mime type mapping table
for the mime type of the source code format; at present, the extension should be ".xqy"
@param {object[]} [permissions] - the permissions controlling which users can read, update, or
execute the query snippet library
@param {string} source - the source code for the query snippet library; at present,
the source code must be XQuery
Deletes a query snippet library from the server.
@method config.query.snippet#remove
@since 1.0
@param {string} moduleName - the filename without a path for the query snippet library
Lists the custom query libraries installed on the server.
@method config.query.snippet#list
@since 1.0
@returns {ResultProvider} an object whose result() function takes
a success callback that receives the list of replacement libraries
|
[
"Provides",
"functions",
"that",
"maintain",
"query",
"snippet",
"extensions",
"on",
"the",
"REST",
"server",
".",
"The",
"client",
"must",
"have",
"been",
"created",
"for",
"a",
"user",
"with",
"the",
"rest",
"-",
"admin",
"role",
"."
] |
368be82f377eb4178ece35d9491dac6672bd1288
|
https://github.com/marklogic/node-client-api/blob/368be82f377eb4178ece35d9491dac6672bd1288/lib/marklogic.js#L166-L173
|
train
|
pvdlg/ncat
|
src/index.js
|
concatBanner
|
function concatBanner() {
if (typeof argv.banner !== 'undefined') {
if (argv.banner) {
return Promise.resolve().then(() => {
concat.add(null, require(path.join(process.cwd(), argv.banner)));
return log('banner', argv.banner);
});
}
return readPkg().then(pkg => {
concat.add(null, getDefaultBanner(pkg.pkg));
return log('dbanner', pkg.path);
});
}
return Promise.resolve();
}
|
javascript
|
function concatBanner() {
if (typeof argv.banner !== 'undefined') {
if (argv.banner) {
return Promise.resolve().then(() => {
concat.add(null, require(path.join(process.cwd(), argv.banner)));
return log('banner', argv.banner);
});
}
return readPkg().then(pkg => {
concat.add(null, getDefaultBanner(pkg.pkg));
return log('dbanner', pkg.path);
});
}
return Promise.resolve();
}
|
[
"function",
"concatBanner",
"(",
")",
"{",
"if",
"(",
"typeof",
"argv",
".",
"banner",
"!==",
"'undefined'",
")",
"{",
"if",
"(",
"argv",
".",
"banner",
")",
"{",
"return",
"Promise",
".",
"resolve",
"(",
")",
".",
"then",
"(",
"(",
")",
"=>",
"{",
"concat",
".",
"add",
"(",
"null",
",",
"require",
"(",
"path",
".",
"join",
"(",
"process",
".",
"cwd",
"(",
")",
",",
"argv",
".",
"banner",
")",
")",
")",
";",
"return",
"log",
"(",
"'banner'",
",",
"argv",
".",
"banner",
")",
";",
"}",
")",
";",
"}",
"return",
"readPkg",
"(",
")",
".",
"then",
"(",
"pkg",
"=>",
"{",
"concat",
".",
"add",
"(",
"null",
",",
"getDefaultBanner",
"(",
"pkg",
".",
"pkg",
")",
")",
";",
"return",
"log",
"(",
"'dbanner'",
",",
"pkg",
".",
"path",
")",
";",
"}",
")",
";",
"}",
"return",
"Promise",
".",
"resolve",
"(",
")",
";",
"}"
] |
Concatenate a default or custom banner.
@return {Promise<Any>} Promise that resolve once the banner has been generated and concatenated.
|
[
"Concatenate",
"a",
"default",
"or",
"custom",
"banner",
"."
] |
7a7bdacf4cd6a97482964814ecb8dddc6c21b0c4
|
https://github.com/pvdlg/ncat/blob/7a7bdacf4cd6a97482964814ecb8dddc6c21b0c4/src/index.js#L127-L141
|
train
|
pvdlg/ncat
|
src/index.js
|
concatFooter
|
function concatFooter() {
if (argv.footer) {
return Promise.resolve().then(() => {
concat.add(null, require(path.join(process.cwd(), argv.footer)));
return log('footer', `Concat footer from ${argv.footer}`);
});
}
return Promise.resolve();
}
|
javascript
|
function concatFooter() {
if (argv.footer) {
return Promise.resolve().then(() => {
concat.add(null, require(path.join(process.cwd(), argv.footer)));
return log('footer', `Concat footer from ${argv.footer}`);
});
}
return Promise.resolve();
}
|
[
"function",
"concatFooter",
"(",
")",
"{",
"if",
"(",
"argv",
".",
"footer",
")",
"{",
"return",
"Promise",
".",
"resolve",
"(",
")",
".",
"then",
"(",
"(",
")",
"=>",
"{",
"concat",
".",
"add",
"(",
"null",
",",
"require",
"(",
"path",
".",
"join",
"(",
"process",
".",
"cwd",
"(",
")",
",",
"argv",
".",
"footer",
")",
")",
")",
";",
"return",
"log",
"(",
"'footer'",
",",
"`",
"${",
"argv",
".",
"footer",
"}",
"`",
")",
";",
"}",
")",
";",
"}",
"return",
"Promise",
".",
"resolve",
"(",
")",
";",
"}"
] |
Concatenate a custom banner.
@return {Promise<Any>} Promise that resolve once the footer has been generated and concatenated.
|
[
"Concatenate",
"a",
"custom",
"banner",
"."
] |
7a7bdacf4cd6a97482964814ecb8dddc6c21b0c4
|
https://github.com/pvdlg/ncat/blob/7a7bdacf4cd6a97482964814ecb8dddc6c21b0c4/src/index.js#L148-L156
|
train
|
pvdlg/ncat
|
src/index.js
|
concatFiles
|
function concatFiles() {
return Promise.all(argv._.map(handleGlob)).then(globs => {
const files = globs.reduce((acc, cur) => acc.concat(cur), []);
if (
(files.length < 2 && typeof argv.banner === 'undefined' && !argv.footer) ||
(files.length === 0 && (typeof argv.banner === 'undefined' || !argv.footer))
) {
throw new Error(
chalk.bold.red('Require at least 2 file, banner or footer to concatenate. ("ncat --help" for help)\n')
);
}
return files.forEach(file => {
concat.add(file.file, file.content, file.map);
});
});
}
|
javascript
|
function concatFiles() {
return Promise.all(argv._.map(handleGlob)).then(globs => {
const files = globs.reduce((acc, cur) => acc.concat(cur), []);
if (
(files.length < 2 && typeof argv.banner === 'undefined' && !argv.footer) ||
(files.length === 0 && (typeof argv.banner === 'undefined' || !argv.footer))
) {
throw new Error(
chalk.bold.red('Require at least 2 file, banner or footer to concatenate. ("ncat --help" for help)\n')
);
}
return files.forEach(file => {
concat.add(file.file, file.content, file.map);
});
});
}
|
[
"function",
"concatFiles",
"(",
")",
"{",
"return",
"Promise",
".",
"all",
"(",
"argv",
".",
"_",
".",
"map",
"(",
"handleGlob",
")",
")",
".",
"then",
"(",
"globs",
"=>",
"{",
"const",
"files",
"=",
"globs",
".",
"reduce",
"(",
"(",
"acc",
",",
"cur",
")",
"=>",
"acc",
".",
"concat",
"(",
"cur",
")",
",",
"[",
"]",
")",
";",
"if",
"(",
"(",
"files",
".",
"length",
"<",
"2",
"&&",
"typeof",
"argv",
".",
"banner",
"===",
"'undefined'",
"&&",
"!",
"argv",
".",
"footer",
")",
"||",
"(",
"files",
".",
"length",
"===",
"0",
"&&",
"(",
"typeof",
"argv",
".",
"banner",
"===",
"'undefined'",
"||",
"!",
"argv",
".",
"footer",
")",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"chalk",
".",
"bold",
".",
"red",
"(",
"'Require at least 2 file, banner or footer to concatenate. (\"ncat --help\" for help)\\n'",
")",
")",
";",
"}",
"\\n",
"}",
")",
";",
"}"
] |
Concatenate the files in order.
Exit process with error if there is less than two files, banner or footer to concatenate.
@return {Promise<Any>} Promise that resolve once the files have been read/created and concatenated.
|
[
"Concatenate",
"the",
"files",
"in",
"order",
".",
"Exit",
"process",
"with",
"error",
"if",
"there",
"is",
"less",
"than",
"two",
"files",
"banner",
"or",
"footer",
"to",
"concatenate",
"."
] |
7a7bdacf4cd6a97482964814ecb8dddc6c21b0c4
|
https://github.com/pvdlg/ncat/blob/7a7bdacf4cd6a97482964814ecb8dddc6c21b0c4/src/index.js#L164-L180
|
train
|
pvdlg/ncat
|
src/index.js
|
handleGlob
|
function handleGlob(glob) {
if (glob === '-') {
return stdinCache.then(stdin => [{content: stdin}]);
}
return globby(glob.split(' '), {nodir: true}).then(files => Promise.all(files.map(handleFile)));
}
|
javascript
|
function handleGlob(glob) {
if (glob === '-') {
return stdinCache.then(stdin => [{content: stdin}]);
}
return globby(glob.split(' '), {nodir: true}).then(files => Promise.all(files.map(handleFile)));
}
|
[
"function",
"handleGlob",
"(",
"glob",
")",
"{",
"if",
"(",
"glob",
"===",
"'-'",
")",
"{",
"return",
"stdinCache",
".",
"then",
"(",
"stdin",
"=>",
"[",
"{",
"content",
":",
"stdin",
"}",
"]",
")",
";",
"}",
"return",
"globby",
"(",
"glob",
".",
"split",
"(",
"' '",
")",
",",
"{",
"nodir",
":",
"true",
"}",
")",
".",
"then",
"(",
"files",
"=>",
"Promise",
".",
"all",
"(",
"files",
".",
"map",
"(",
"handleFile",
")",
")",
")",
";",
"}"
] |
FileToConcat describe the filename, content and sourcemap to concatenate.
@typedef {Object} FileToConcat
@property {String} file
@property {String} content
@property {Object} sourcemap
Retrieve files matched by the gloc and call {@link handleFile} for each one found.
If the glob is '-' return one FileToConcat with stdin as its content.
@param {String} glob the glob expression for which to retrive files.
@return {Promise<FileToConcat[]>} a Promise that resolve to an Array of FileToConcat.
|
[
"FileToConcat",
"describe",
"the",
"filename",
"content",
"and",
"sourcemap",
"to",
"concatenate",
"."
] |
7a7bdacf4cd6a97482964814ecb8dddc6c21b0c4
|
https://github.com/pvdlg/ncat/blob/7a7bdacf4cd6a97482964814ecb8dddc6c21b0c4/src/index.js#L198-L203
|
train
|
pvdlg/ncat
|
src/index.js
|
getSourceMappingURL
|
function getSourceMappingURL() {
if (path.extname(argv.output) === '.css') {
return `\n/*# sourceMappingURL=${path.basename(argv.output)}.map */`;
}
return `\n//# sourceMappingURL=${path.basename(argv.output)}.map`;
}
|
javascript
|
function getSourceMappingURL() {
if (path.extname(argv.output) === '.css') {
return `\n/*# sourceMappingURL=${path.basename(argv.output)}.map */`;
}
return `\n//# sourceMappingURL=${path.basename(argv.output)}.map`;
}
|
[
"function",
"getSourceMappingURL",
"(",
")",
"{",
"if",
"(",
"path",
".",
"extname",
"(",
"argv",
".",
"output",
")",
"===",
"'.css'",
")",
"{",
"return",
"`",
"\\n",
"${",
"path",
".",
"basename",
"(",
"argv",
".",
"output",
")",
"}",
"`",
";",
"}",
"return",
"`",
"\\n",
"${",
"path",
".",
"basename",
"(",
"argv",
".",
"output",
")",
"}",
"`",
";",
"}"
] |
Return a source mapping URL comment based on the output file extension.
@return {String} the sourceMappingURL comment.
|
[
"Return",
"a",
"source",
"mapping",
"URL",
"comment",
"based",
"on",
"the",
"output",
"file",
"extension",
"."
] |
7a7bdacf4cd6a97482964814ecb8dddc6c21b0c4
|
https://github.com/pvdlg/ncat/blob/7a7bdacf4cd6a97482964814ecb8dddc6c21b0c4/src/index.js#L310-L315
|
train
|
strongloop/strongloop
|
lib/commands/env.js
|
resolvePaths
|
function resolvePaths(paths) {
var exec = {};
var originalWd = process.cwd();
for (var name in paths) {
process.chdir(originalWd);
exec[name] = resolveLink(paths[name]);
process.chdir(originalWd);
}
process.chdir(originalWd);
return exec;
}
|
javascript
|
function resolvePaths(paths) {
var exec = {};
var originalWd = process.cwd();
for (var name in paths) {
process.chdir(originalWd);
exec[name] = resolveLink(paths[name]);
process.chdir(originalWd);
}
process.chdir(originalWd);
return exec;
}
|
[
"function",
"resolvePaths",
"(",
"paths",
")",
"{",
"var",
"exec",
"=",
"{",
"}",
";",
"var",
"originalWd",
"=",
"process",
".",
"cwd",
"(",
")",
";",
"for",
"(",
"var",
"name",
"in",
"paths",
")",
"{",
"process",
".",
"chdir",
"(",
"originalWd",
")",
";",
"exec",
"[",
"name",
"]",
"=",
"resolveLink",
"(",
"paths",
"[",
"name",
"]",
")",
";",
"process",
".",
"chdir",
"(",
"originalWd",
")",
";",
"}",
"process",
".",
"chdir",
"(",
"originalWd",
")",
";",
"return",
"exec",
";",
"}"
] |
resolve symlinks of all paths to eventual targets
|
[
"resolve",
"symlinks",
"of",
"all",
"paths",
"to",
"eventual",
"targets"
] |
aa519ec2fd151f3816d224dfd8dac27958dd14ca
|
https://github.com/strongloop/strongloop/blob/aa519ec2fd151f3816d224dfd8dac27958dd14ca/lib/commands/env.js#L109-L119
|
train
|
strongloop/strongloop
|
lib/commands/env.js
|
resolveLink
|
function resolveLink(path) {
var links = readLinkRecursive(path);
var resolved = p.resolve.apply(null, links);
trace('links', links, 'resolves to', resolved);
return resolved;
}
|
javascript
|
function resolveLink(path) {
var links = readLinkRecursive(path);
var resolved = p.resolve.apply(null, links);
trace('links', links, 'resolves to', resolved);
return resolved;
}
|
[
"function",
"resolveLink",
"(",
"path",
")",
"{",
"var",
"links",
"=",
"readLinkRecursive",
"(",
"path",
")",
";",
"var",
"resolved",
"=",
"p",
".",
"resolve",
".",
"apply",
"(",
"null",
",",
"links",
")",
";",
"trace",
"(",
"'links'",
",",
"links",
",",
"'resolves to'",
",",
"resolved",
")",
";",
"return",
"resolved",
";",
"}"
] |
resolve link to absolute path
|
[
"resolve",
"link",
"to",
"absolute",
"path"
] |
aa519ec2fd151f3816d224dfd8dac27958dd14ca
|
https://github.com/strongloop/strongloop/blob/aa519ec2fd151f3816d224dfd8dac27958dd14ca/lib/commands/env.js#L122-L129
|
train
|
strongloop/strongloop
|
lib/commands/env.js
|
readLinkRecursive
|
function readLinkRecursive(path, seen) {
seen = seen || [];
seen.push(p.dirname(path));
var next = readLink(path);
trace('recur', seen, next);
if (!next) {
seen.push(p.basename(path));
return seen;
}
return readLinkRecursive(next, seen);
}
|
javascript
|
function readLinkRecursive(path, seen) {
seen = seen || [];
seen.push(p.dirname(path));
var next = readLink(path);
trace('recur', seen, next);
if (!next) {
seen.push(p.basename(path));
return seen;
}
return readLinkRecursive(next, seen);
}
|
[
"function",
"readLinkRecursive",
"(",
"path",
",",
"seen",
")",
"{",
"seen",
"=",
"seen",
"||",
"[",
"]",
";",
"seen",
".",
"push",
"(",
"p",
".",
"dirname",
"(",
"path",
")",
")",
";",
"var",
"next",
"=",
"readLink",
"(",
"path",
")",
";",
"trace",
"(",
"'recur'",
",",
"seen",
",",
"next",
")",
";",
"if",
"(",
"!",
"next",
")",
"{",
"seen",
".",
"push",
"(",
"p",
".",
"basename",
"(",
"path",
")",
")",
";",
"return",
"seen",
";",
"}",
"return",
"readLinkRecursive",
"(",
"next",
",",
"seen",
")",
";",
"}"
] |
read link, recursively, return array of links seen up to final path
|
[
"read",
"link",
"recursively",
"return",
"array",
"of",
"links",
"seen",
"up",
"to",
"final",
"path"
] |
aa519ec2fd151f3816d224dfd8dac27958dd14ca
|
https://github.com/strongloop/strongloop/blob/aa519ec2fd151f3816d224dfd8dac27958dd14ca/lib/commands/env.js#L132-L146
|
train
|
nodemailer/nodemailer-smtp-transport
|
lib/smtp-transport.js
|
SMTPTransport
|
function SMTPTransport(options) {
EventEmitter.call(this);
options = options || {};
if (typeof options === 'string') {
options = {
url: options
};
}
var urlData;
var service = options.service;
if (typeof options.getSocket === 'function') {
this.getSocket = options.getSocket;
}
if (options.url) {
urlData = shared.parseConnectionUrl(options.url);
service = service || urlData.service;
}
this.options = assign(
false, // create new object
options, // regular options
urlData, // url options
service && wellknown(service) // wellknown options
);
this.logger = shared.getLogger(this.options);
// temporary object
var connection = new SMTPConnection(this.options);
this.name = 'SMTP';
this.version = packageData.version + '[client:' + connection.version + ']';
}
|
javascript
|
function SMTPTransport(options) {
EventEmitter.call(this);
options = options || {};
if (typeof options === 'string') {
options = {
url: options
};
}
var urlData;
var service = options.service;
if (typeof options.getSocket === 'function') {
this.getSocket = options.getSocket;
}
if (options.url) {
urlData = shared.parseConnectionUrl(options.url);
service = service || urlData.service;
}
this.options = assign(
false, // create new object
options, // regular options
urlData, // url options
service && wellknown(service) // wellknown options
);
this.logger = shared.getLogger(this.options);
// temporary object
var connection = new SMTPConnection(this.options);
this.name = 'SMTP';
this.version = packageData.version + '[client:' + connection.version + ']';
}
|
[
"function",
"SMTPTransport",
"(",
"options",
")",
"{",
"EventEmitter",
".",
"call",
"(",
"this",
")",
";",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"if",
"(",
"typeof",
"options",
"===",
"'string'",
")",
"{",
"options",
"=",
"{",
"url",
":",
"options",
"}",
";",
"}",
"var",
"urlData",
";",
"var",
"service",
"=",
"options",
".",
"service",
";",
"if",
"(",
"typeof",
"options",
".",
"getSocket",
"===",
"'function'",
")",
"{",
"this",
".",
"getSocket",
"=",
"options",
".",
"getSocket",
";",
"}",
"if",
"(",
"options",
".",
"url",
")",
"{",
"urlData",
"=",
"shared",
".",
"parseConnectionUrl",
"(",
"options",
".",
"url",
")",
";",
"service",
"=",
"service",
"||",
"urlData",
".",
"service",
";",
"}",
"this",
".",
"options",
"=",
"assign",
"(",
"false",
",",
"options",
",",
"urlData",
",",
"service",
"&&",
"wellknown",
"(",
"service",
")",
")",
";",
"this",
".",
"logger",
"=",
"shared",
".",
"getLogger",
"(",
"this",
".",
"options",
")",
";",
"var",
"connection",
"=",
"new",
"SMTPConnection",
"(",
"this",
".",
"options",
")",
";",
"this",
".",
"name",
"=",
"'SMTP'",
";",
"this",
".",
"version",
"=",
"packageData",
".",
"version",
"+",
"'[client:'",
"+",
"connection",
".",
"version",
"+",
"']'",
";",
"}"
] |
Creates a SMTP transport object for Nodemailer
@constructor
@param {Object} options Connection options
|
[
"Creates",
"a",
"SMTP",
"transport",
"object",
"for",
"Nodemailer"
] |
d854aa0e4e7b22cd921ae3e4e04ab7b6e02761e6
|
https://github.com/nodemailer/nodemailer-smtp-transport/blob/d854aa0e4e7b22cd921ae3e4e04ab7b6e02761e6/lib/smtp-transport.js#L22-L58
|
train
|
nodemailer/nodemailer-smtp-transport
|
lib/smtp-transport.js
|
assign
|
function assign( /* target, ... sources */ ) {
var args = Array.prototype.slice.call(arguments);
var target = args.shift() || {};
args.forEach(function (source) {
Object.keys(source || {}).forEach(function (key) {
if (['tls', 'auth'].indexOf(key) >= 0 && source[key] && typeof source[key] === 'object') {
// tls and auth are special keys that need to be enumerated separately
// other objects are passed as is
if (!target[key]) {
// esnure that target has this key
target[key] = {};
}
Object.keys(source[key]).forEach(function (subKey) {
target[key][subKey] = source[key][subKey];
});
} else {
target[key] = source[key];
}
});
});
return target;
}
|
javascript
|
function assign( /* target, ... sources */ ) {
var args = Array.prototype.slice.call(arguments);
var target = args.shift() || {};
args.forEach(function (source) {
Object.keys(source || {}).forEach(function (key) {
if (['tls', 'auth'].indexOf(key) >= 0 && source[key] && typeof source[key] === 'object') {
// tls and auth are special keys that need to be enumerated separately
// other objects are passed as is
if (!target[key]) {
// esnure that target has this key
target[key] = {};
}
Object.keys(source[key]).forEach(function (subKey) {
target[key][subKey] = source[key][subKey];
});
} else {
target[key] = source[key];
}
});
});
return target;
}
|
[
"function",
"assign",
"(",
")",
"{",
"var",
"args",
"=",
"Array",
".",
"prototype",
".",
"slice",
".",
"call",
"(",
"arguments",
")",
";",
"var",
"target",
"=",
"args",
".",
"shift",
"(",
")",
"||",
"{",
"}",
";",
"args",
".",
"forEach",
"(",
"function",
"(",
"source",
")",
"{",
"Object",
".",
"keys",
"(",
"source",
"||",
"{",
"}",
")",
".",
"forEach",
"(",
"function",
"(",
"key",
")",
"{",
"if",
"(",
"[",
"'tls'",
",",
"'auth'",
"]",
".",
"indexOf",
"(",
"key",
")",
">=",
"0",
"&&",
"source",
"[",
"key",
"]",
"&&",
"typeof",
"source",
"[",
"key",
"]",
"===",
"'object'",
")",
"{",
"if",
"(",
"!",
"target",
"[",
"key",
"]",
")",
"{",
"target",
"[",
"key",
"]",
"=",
"{",
"}",
";",
"}",
"Object",
".",
"keys",
"(",
"source",
"[",
"key",
"]",
")",
".",
"forEach",
"(",
"function",
"(",
"subKey",
")",
"{",
"target",
"[",
"key",
"]",
"[",
"subKey",
"]",
"=",
"source",
"[",
"key",
"]",
"[",
"subKey",
"]",
";",
"}",
")",
";",
"}",
"else",
"{",
"target",
"[",
"key",
"]",
"=",
"source",
"[",
"key",
"]",
";",
"}",
"}",
")",
";",
"}",
")",
";",
"return",
"target",
";",
"}"
] |
Copies properties from source objects to target objects
|
[
"Copies",
"properties",
"from",
"source",
"objects",
"to",
"target",
"objects"
] |
d854aa0e4e7b22cd921ae3e4e04ab7b6e02761e6
|
https://github.com/nodemailer/nodemailer-smtp-transport/blob/d854aa0e4e7b22cd921ae3e4e04ab7b6e02761e6/lib/smtp-transport.js#L259-L281
|
train
|
fmarcia/UglifyCSS
|
uglifycss-lib.js
|
collectComments
|
function collectComments(content, comments) {
const table = []
let from = 0
let end
while (true) {
let start = content.indexOf('/*', from)
if (start > -1) {
end = content.indexOf('*/', start + 2)
if (end > -1) {
comments.push(content.slice(start + 2, end))
table.push(content.slice(from, start))
table.push('/*___PRESERVE_CANDIDATE_COMMENT_' + (comments.length - 1) + '___*/')
from = end + 2
} else {
// unterminated comment
end = -2
break
}
} else {
break
}
}
table.push(content.slice(end + 2))
return table.join('')
}
|
javascript
|
function collectComments(content, comments) {
const table = []
let from = 0
let end
while (true) {
let start = content.indexOf('/*', from)
if (start > -1) {
end = content.indexOf('*/', start + 2)
if (end > -1) {
comments.push(content.slice(start + 2, end))
table.push(content.slice(from, start))
table.push('/*___PRESERVE_CANDIDATE_COMMENT_' + (comments.length - 1) + '___*/')
from = end + 2
} else {
// unterminated comment
end = -2
break
}
} else {
break
}
}
table.push(content.slice(end + 2))
return table.join('')
}
|
[
"function",
"collectComments",
"(",
"content",
",",
"comments",
")",
"{",
"const",
"table",
"=",
"[",
"]",
"let",
"from",
"=",
"0",
"let",
"end",
"while",
"(",
"true",
")",
"{",
"let",
"start",
"=",
"content",
".",
"indexOf",
"(",
"'/*'",
",",
"from",
")",
"if",
"(",
"start",
">",
"-",
"1",
")",
"{",
"end",
"=",
"content",
".",
"indexOf",
"(",
"'*/'",
",",
"start",
"+",
"2",
")",
"if",
"(",
"end",
">",
"-",
"1",
")",
"{",
"comments",
".",
"push",
"(",
"content",
".",
"slice",
"(",
"start",
"+",
"2",
",",
"end",
")",
")",
"table",
".",
"push",
"(",
"content",
".",
"slice",
"(",
"from",
",",
"start",
")",
")",
"table",
".",
"push",
"(",
"'/*",
"PRESERVE_CANDIDATE_COMMENT_'",
"+",
"(",
"comments",
".",
"length",
"-",
"1",
")",
"+",
"'",
"*/'",
")",
"from",
"=",
"end",
"+",
"2",
"}",
"else",
"{",
"end",
"=",
"-",
"2",
"break",
"}",
"}",
"else",
"{",
"break",
"}",
"}",
"table",
".",
"push",
"(",
"content",
".",
"slice",
"(",
"end",
"+",
"2",
")",
")",
"return",
"table",
".",
"join",
"(",
"''",
")",
"}"
] |
collectComments collects all comment blocks and return new content with comment placeholders
@param {string} content - CSS content
@param {string[]} comments - Global array of extracted comments
@return {string} Processed CSS
|
[
"collectComments",
"collects",
"all",
"comment",
"blocks",
"and",
"return",
"new",
"content",
"with",
"comment",
"placeholders"
] |
3a4312ef9a321643ab27cf7438b85c92498af19b
|
https://github.com/fmarcia/UglifyCSS/blob/3a4312ef9a321643ab27cf7438b85c92498af19b/uglifycss-lib.js#L425-L460
|
train
|
fmarcia/UglifyCSS
|
uglifycss-lib.js
|
processFiles
|
function processFiles(filenames = [], options = defaultOptions) {
if (options.convertUrls) {
options.target = resolve(process.cwd(), options.convertUrls).split(PATH_SEP)
}
const uglies = []
// process files
filenames.forEach(filename => {
try {
const content = readFileSync(filename, 'utf8')
if (content.length) {
if (options.convertUrls) {
options.source = resolve(process.cwd(), filename).split(PATH_SEP)
options.source.pop()
}
uglies.push(processString(content, options))
}
} catch (e) {
if (options.debug) {
console.error(`uglifycss: unable to process "${filename}"\n${e.stack}`)
} else {
console.error(`uglifycss: unable to process "${filename}"\n\t${e}`)
}
process.exit(1)
}
})
// return concat'd results
return uglies.join('')
}
|
javascript
|
function processFiles(filenames = [], options = defaultOptions) {
if (options.convertUrls) {
options.target = resolve(process.cwd(), options.convertUrls).split(PATH_SEP)
}
const uglies = []
// process files
filenames.forEach(filename => {
try {
const content = readFileSync(filename, 'utf8')
if (content.length) {
if (options.convertUrls) {
options.source = resolve(process.cwd(), filename).split(PATH_SEP)
options.source.pop()
}
uglies.push(processString(content, options))
}
} catch (e) {
if (options.debug) {
console.error(`uglifycss: unable to process "${filename}"\n${e.stack}`)
} else {
console.error(`uglifycss: unable to process "${filename}"\n\t${e}`)
}
process.exit(1)
}
})
// return concat'd results
return uglies.join('')
}
|
[
"function",
"processFiles",
"(",
"filenames",
"=",
"[",
"]",
",",
"options",
"=",
"defaultOptions",
")",
"{",
"if",
"(",
"options",
".",
"convertUrls",
")",
"{",
"options",
".",
"target",
"=",
"resolve",
"(",
"process",
".",
"cwd",
"(",
")",
",",
"options",
".",
"convertUrls",
")",
".",
"split",
"(",
"PATH_SEP",
")",
"}",
"const",
"uglies",
"=",
"[",
"]",
"filenames",
".",
"forEach",
"(",
"filename",
"=>",
"{",
"try",
"{",
"const",
"content",
"=",
"readFileSync",
"(",
"filename",
",",
"'utf8'",
")",
"if",
"(",
"content",
".",
"length",
")",
"{",
"if",
"(",
"options",
".",
"convertUrls",
")",
"{",
"options",
".",
"source",
"=",
"resolve",
"(",
"process",
".",
"cwd",
"(",
")",
",",
"filename",
")",
".",
"split",
"(",
"PATH_SEP",
")",
"options",
".",
"source",
".",
"pop",
"(",
")",
"}",
"uglies",
".",
"push",
"(",
"processString",
"(",
"content",
",",
"options",
")",
")",
"}",
"}",
"catch",
"(",
"e",
")",
"{",
"if",
"(",
"options",
".",
"debug",
")",
"{",
"console",
".",
"error",
"(",
"`",
"${",
"filename",
"}",
"\\n",
"${",
"e",
".",
"stack",
"}",
"`",
")",
"}",
"else",
"{",
"console",
".",
"error",
"(",
"`",
"${",
"filename",
"}",
"\\n",
"\\t",
"${",
"e",
"}",
"`",
")",
"}",
"process",
".",
"exit",
"(",
"1",
")",
"}",
"}",
")",
"return",
"uglies",
".",
"join",
"(",
"''",
")",
"}"
] |
processFiles uglifies a set of CSS files
@param {string[]} filenames - List of filenames
@param {options} options - UglifyCSS options
@return {string} Uglified result
|
[
"processFiles",
"uglifies",
"a",
"set",
"of",
"CSS",
"files"
] |
3a4312ef9a321643ab27cf7438b85c92498af19b
|
https://github.com/fmarcia/UglifyCSS/blob/3a4312ef9a321643ab27cf7438b85c92498af19b/uglifycss-lib.js#L820-L851
|
train
|
blackbaud/skyux2
|
config/karma/ci-ie.karma.conf.js
|
getSpecsRegex
|
function getSpecsRegex() {
const argv = minimist(process.argv.slice(2));
/**
* The command line argument `--ieBatch` is a string representing
* the current batch to run, of total batches.
* For example, `npm run test:unit:ci:ie -- --ieBatch 1of3`
*/
const [
currentRun,
totalRuns
] = argv.ieBatch.split('of');
if (!currentRun || !totalRuns) {
throw 'Invalid IE 11 batch request! Please provide a command line argument in the format of `--ieBatch 1of3`.';
}
const moduleDirectories = getDirectories(path.resolve('src/modules'));
const totalModules = moduleDirectories.length;
const modulesPerRun = Math.ceil(moduleDirectories.length / totalRuns);
const startAtIndex = modulesPerRun * (currentRun - 1);
const modules = moduleDirectories.splice(startAtIndex, modulesPerRun);
if (modules.length === 0) {
return;
}
console.log(`[Batch ${currentRun} of ${totalRuns}]`);
console.log(`--> Running specs for ${modules.length} modules...`);
console.log(`--> Starting at module ${startAtIndex}, ending at module ${startAtIndex + modules.length}, of ${totalModules} total modules\n`);
console.log(modules.join(',\n'));
return [
String.raw`\\/`,
'\(',
...modules.join('|'),
')\\/'
].join('').replace(/\-/g, '\\-');
}
|
javascript
|
function getSpecsRegex() {
const argv = minimist(process.argv.slice(2));
/**
* The command line argument `--ieBatch` is a string representing
* the current batch to run, of total batches.
* For example, `npm run test:unit:ci:ie -- --ieBatch 1of3`
*/
const [
currentRun,
totalRuns
] = argv.ieBatch.split('of');
if (!currentRun || !totalRuns) {
throw 'Invalid IE 11 batch request! Please provide a command line argument in the format of `--ieBatch 1of3`.';
}
const moduleDirectories = getDirectories(path.resolve('src/modules'));
const totalModules = moduleDirectories.length;
const modulesPerRun = Math.ceil(moduleDirectories.length / totalRuns);
const startAtIndex = modulesPerRun * (currentRun - 1);
const modules = moduleDirectories.splice(startAtIndex, modulesPerRun);
if (modules.length === 0) {
return;
}
console.log(`[Batch ${currentRun} of ${totalRuns}]`);
console.log(`--> Running specs for ${modules.length} modules...`);
console.log(`--> Starting at module ${startAtIndex}, ending at module ${startAtIndex + modules.length}, of ${totalModules} total modules\n`);
console.log(modules.join(',\n'));
return [
String.raw`\\/`,
'\(',
...modules.join('|'),
')\\/'
].join('').replace(/\-/g, '\\-');
}
|
[
"function",
"getSpecsRegex",
"(",
")",
"{",
"const",
"argv",
"=",
"minimist",
"(",
"process",
".",
"argv",
".",
"slice",
"(",
"2",
")",
")",
";",
"const",
"[",
"currentRun",
",",
"totalRuns",
"]",
"=",
"argv",
".",
"ieBatch",
".",
"split",
"(",
"'of'",
")",
";",
"if",
"(",
"!",
"currentRun",
"||",
"!",
"totalRuns",
")",
"{",
"throw",
"'Invalid IE 11 batch request! Please provide a command line argument in the format of `--ieBatch 1of3`.'",
";",
"}",
"const",
"moduleDirectories",
"=",
"getDirectories",
"(",
"path",
".",
"resolve",
"(",
"'src/modules'",
")",
")",
";",
"const",
"totalModules",
"=",
"moduleDirectories",
".",
"length",
";",
"const",
"modulesPerRun",
"=",
"Math",
".",
"ceil",
"(",
"moduleDirectories",
".",
"length",
"/",
"totalRuns",
")",
";",
"const",
"startAtIndex",
"=",
"modulesPerRun",
"*",
"(",
"currentRun",
"-",
"1",
")",
";",
"const",
"modules",
"=",
"moduleDirectories",
".",
"splice",
"(",
"startAtIndex",
",",
"modulesPerRun",
")",
";",
"if",
"(",
"modules",
".",
"length",
"===",
"0",
")",
"{",
"return",
";",
"}",
"console",
".",
"log",
"(",
"`",
"${",
"currentRun",
"}",
"${",
"totalRuns",
"}",
"`",
")",
";",
"console",
".",
"log",
"(",
"`",
"${",
"modules",
".",
"length",
"}",
"`",
")",
";",
"console",
".",
"log",
"(",
"`",
"${",
"startAtIndex",
"}",
"${",
"startAtIndex",
"+",
"modules",
".",
"length",
"}",
"${",
"totalModules",
"}",
"\\n",
"`",
")",
";",
"console",
".",
"log",
"(",
"modules",
".",
"join",
"(",
"',\\n'",
")",
")",
";",
"\\n",
"}"
] |
Run only a few modules' specs
|
[
"Run",
"only",
"a",
"few",
"modules",
"specs"
] |
f4d70d718f718e6136e2262103e9b1eb7a295c18
|
https://github.com/blackbaud/skyux2/blob/f4d70d718f718e6136e2262103e9b1eb7a295c18/config/karma/ci-ie.karma.conf.js#L13-L51
|
train
|
wswebcreation/protractor-multiple-cucumber-html-reporter-plugin
|
index.js
|
setup
|
function setup() {
return browser.getProcessedConfig()
.then((configuration) => {
let cucumberFormat = configuration.cucumberOpts.format;
IS_JSON_FORMAT = cucumberFormat && cucumberFormat.includes('json');
if (Array.isArray(cucumberFormat)) {
IS_JSON_FORMAT = cucumberFormat.find((format) => {
cucumberFormat = format;
return format.includes('json')
});
}
if (IS_JSON_FORMAT) {
/**
* If options are provided override the values to the PLUGIN_CONFIG object
*/
if (this.config.options) {
Object.assign(PLUGIN_CONFIG, this.config.options);
}
/**
* Get the JSON folder path and file name if they are still empty
*/
const formatPathMatch = cucumberFormat.match(/(.+):(.+)/);
const filePathMatch = formatPathMatch[2].match(/(.*)\/(.*)\.json/);
// Get the cucumber results path
PLUGIN_CONFIG.cucumberResultsPath = filePathMatch[1];
// Get the cucumber report name
PLUGIN_CONFIG.cucumberReportName = filePathMatch[2];
/**
* If the json output folder is still default, then create a new one
*/
if (PLUGIN_CONFIG.jsonOutputPath === JSON_OUTPUT_FOLDER) {
PLUGIN_CONFIG.jsonOutputPath = path.join(PLUGIN_CONFIG.cucumberResultsPath, JSON_OUTPUT_FOLDER);
}
/**
* Check whether the file name need to be unique
*/
PLUGIN_CONFIG.uniqueReportFileName = (Array.isArray(configuration.multiCapabilities)
&& configuration.multiCapabilities.length > 0)
|| typeof configuration.getMultiCapabilities === 'function'
|| configuration.capabilities.shardTestFiles;
/**
* Prepare the PID_INSTANCE_DATA
*/
const metadata = {
browser: {
name: '',
version: ''
},
device: '',
platform: {
name: '',
version: ''
}
};
PID_INSTANCE_DATA = {
pid: process.pid,
metadata: Object.assign(metadata, configuration.capabilities[PLUGIN_CONFIG.metadataKey] || {})
};
/**
* Create the needed folders if they are not present
*/
fs.ensureDirSync(PLUGIN_CONFIG.cucumberResultsPath);
fs.ensureDirSync(PLUGIN_CONFIG.jsonOutputPath);
} else {
console.warn('\n### NO `JSON` FORMAT IS SPECIFIED IN THE PROTRACTOR CONF FILE UNDER `cucumberOpts.format ###`\n');
}
});
}
|
javascript
|
function setup() {
return browser.getProcessedConfig()
.then((configuration) => {
let cucumberFormat = configuration.cucumberOpts.format;
IS_JSON_FORMAT = cucumberFormat && cucumberFormat.includes('json');
if (Array.isArray(cucumberFormat)) {
IS_JSON_FORMAT = cucumberFormat.find((format) => {
cucumberFormat = format;
return format.includes('json')
});
}
if (IS_JSON_FORMAT) {
/**
* If options are provided override the values to the PLUGIN_CONFIG object
*/
if (this.config.options) {
Object.assign(PLUGIN_CONFIG, this.config.options);
}
/**
* Get the JSON folder path and file name if they are still empty
*/
const formatPathMatch = cucumberFormat.match(/(.+):(.+)/);
const filePathMatch = formatPathMatch[2].match(/(.*)\/(.*)\.json/);
// Get the cucumber results path
PLUGIN_CONFIG.cucumberResultsPath = filePathMatch[1];
// Get the cucumber report name
PLUGIN_CONFIG.cucumberReportName = filePathMatch[2];
/**
* If the json output folder is still default, then create a new one
*/
if (PLUGIN_CONFIG.jsonOutputPath === JSON_OUTPUT_FOLDER) {
PLUGIN_CONFIG.jsonOutputPath = path.join(PLUGIN_CONFIG.cucumberResultsPath, JSON_OUTPUT_FOLDER);
}
/**
* Check whether the file name need to be unique
*/
PLUGIN_CONFIG.uniqueReportFileName = (Array.isArray(configuration.multiCapabilities)
&& configuration.multiCapabilities.length > 0)
|| typeof configuration.getMultiCapabilities === 'function'
|| configuration.capabilities.shardTestFiles;
/**
* Prepare the PID_INSTANCE_DATA
*/
const metadata = {
browser: {
name: '',
version: ''
},
device: '',
platform: {
name: '',
version: ''
}
};
PID_INSTANCE_DATA = {
pid: process.pid,
metadata: Object.assign(metadata, configuration.capabilities[PLUGIN_CONFIG.metadataKey] || {})
};
/**
* Create the needed folders if they are not present
*/
fs.ensureDirSync(PLUGIN_CONFIG.cucumberResultsPath);
fs.ensureDirSync(PLUGIN_CONFIG.jsonOutputPath);
} else {
console.warn('\n### NO `JSON` FORMAT IS SPECIFIED IN THE PROTRACTOR CONF FILE UNDER `cucumberOpts.format ###`\n');
}
});
}
|
[
"function",
"setup",
"(",
")",
"{",
"return",
"browser",
".",
"getProcessedConfig",
"(",
")",
".",
"then",
"(",
"(",
"configuration",
")",
"=>",
"{",
"let",
"cucumberFormat",
"=",
"configuration",
".",
"cucumberOpts",
".",
"format",
";",
"IS_JSON_FORMAT",
"=",
"cucumberFormat",
"&&",
"cucumberFormat",
".",
"includes",
"(",
"'json'",
")",
";",
"if",
"(",
"Array",
".",
"isArray",
"(",
"cucumberFormat",
")",
")",
"{",
"IS_JSON_FORMAT",
"=",
"cucumberFormat",
".",
"find",
"(",
"(",
"format",
")",
"=>",
"{",
"cucumberFormat",
"=",
"format",
";",
"return",
"format",
".",
"includes",
"(",
"'json'",
")",
"}",
")",
";",
"}",
"if",
"(",
"IS_JSON_FORMAT",
")",
"{",
"if",
"(",
"this",
".",
"config",
".",
"options",
")",
"{",
"Object",
".",
"assign",
"(",
"PLUGIN_CONFIG",
",",
"this",
".",
"config",
".",
"options",
")",
";",
"}",
"const",
"formatPathMatch",
"=",
"cucumberFormat",
".",
"match",
"(",
"/",
"(.+):(.+)",
"/",
")",
";",
"const",
"filePathMatch",
"=",
"formatPathMatch",
"[",
"2",
"]",
".",
"match",
"(",
"/",
"(.*)\\/(.*)\\.json",
"/",
")",
";",
"PLUGIN_CONFIG",
".",
"cucumberResultsPath",
"=",
"filePathMatch",
"[",
"1",
"]",
";",
"PLUGIN_CONFIG",
".",
"cucumberReportName",
"=",
"filePathMatch",
"[",
"2",
"]",
";",
"if",
"(",
"PLUGIN_CONFIG",
".",
"jsonOutputPath",
"===",
"JSON_OUTPUT_FOLDER",
")",
"{",
"PLUGIN_CONFIG",
".",
"jsonOutputPath",
"=",
"path",
".",
"join",
"(",
"PLUGIN_CONFIG",
".",
"cucumberResultsPath",
",",
"JSON_OUTPUT_FOLDER",
")",
";",
"}",
"PLUGIN_CONFIG",
".",
"uniqueReportFileName",
"=",
"(",
"Array",
".",
"isArray",
"(",
"configuration",
".",
"multiCapabilities",
")",
"&&",
"configuration",
".",
"multiCapabilities",
".",
"length",
">",
"0",
")",
"||",
"typeof",
"configuration",
".",
"getMultiCapabilities",
"===",
"'function'",
"||",
"configuration",
".",
"capabilities",
".",
"shardTestFiles",
";",
"const",
"metadata",
"=",
"{",
"browser",
":",
"{",
"name",
":",
"''",
",",
"version",
":",
"''",
"}",
",",
"device",
":",
"''",
",",
"platform",
":",
"{",
"name",
":",
"''",
",",
"version",
":",
"''",
"}",
"}",
";",
"PID_INSTANCE_DATA",
"=",
"{",
"pid",
":",
"process",
".",
"pid",
",",
"metadata",
":",
"Object",
".",
"assign",
"(",
"metadata",
",",
"configuration",
".",
"capabilities",
"[",
"PLUGIN_CONFIG",
".",
"metadataKey",
"]",
"||",
"{",
"}",
")",
"}",
";",
"fs",
".",
"ensureDirSync",
"(",
"PLUGIN_CONFIG",
".",
"cucumberResultsPath",
")",
";",
"fs",
".",
"ensureDirSync",
"(",
"PLUGIN_CONFIG",
".",
"jsonOutputPath",
")",
";",
"}",
"else",
"{",
"console",
".",
"warn",
"(",
"'\\n### NO `JSON` FORMAT IS SPECIFIED IN THE PROTRACTOR CONF FILE UNDER `cucumberOpts.format ###`\\n'",
")",
";",
"}",
"}",
")",
";",
"}"
] |
Configures the plugin with the correct data
@see docs/plugins.md
@returns {Promise} A promise which resolves into a configured setup
@public
|
[
"Configures",
"the",
"plugin",
"with",
"the",
"correct",
"data"
] |
d01dc9f9660d7bec1ef47c007b429cebe58e3ff4
|
https://github.com/wswebcreation/protractor-multiple-cucumber-html-reporter-plugin/blob/d01dc9f9660d7bec1ef47c007b429cebe58e3ff4/index.js#L49-L127
|
train
|
wswebcreation/protractor-multiple-cucumber-html-reporter-plugin
|
index.js
|
onPrepare
|
function onPrepare() {
if (IS_JSON_FORMAT) {
return browser.getCapabilities()
.then((capabilities) => {
PID_INSTANCE_DATA.metadata.browser.name = PID_INSTANCE_DATA.metadata.browser.name === ''
? capabilities.get('browserName').toLowerCase()
: PID_INSTANCE_DATA.metadata.browser.name;
PID_INSTANCE_DATA.metadata.browser.version = (capabilities.get('version') || capabilities.get('browserVersion'))
|| PID_INSTANCE_DATA.metadata.browser.version;
});
}
}
|
javascript
|
function onPrepare() {
if (IS_JSON_FORMAT) {
return browser.getCapabilities()
.then((capabilities) => {
PID_INSTANCE_DATA.metadata.browser.name = PID_INSTANCE_DATA.metadata.browser.name === ''
? capabilities.get('browserName').toLowerCase()
: PID_INSTANCE_DATA.metadata.browser.name;
PID_INSTANCE_DATA.metadata.browser.version = (capabilities.get('version') || capabilities.get('browserVersion'))
|| PID_INSTANCE_DATA.metadata.browser.version;
});
}
}
|
[
"function",
"onPrepare",
"(",
")",
"{",
"if",
"(",
"IS_JSON_FORMAT",
")",
"{",
"return",
"browser",
".",
"getCapabilities",
"(",
")",
".",
"then",
"(",
"(",
"capabilities",
")",
"=>",
"{",
"PID_INSTANCE_DATA",
".",
"metadata",
".",
"browser",
".",
"name",
"=",
"PID_INSTANCE_DATA",
".",
"metadata",
".",
"browser",
".",
"name",
"===",
"''",
"?",
"capabilities",
".",
"get",
"(",
"'browserName'",
")",
".",
"toLowerCase",
"(",
")",
":",
"PID_INSTANCE_DATA",
".",
"metadata",
".",
"browser",
".",
"name",
";",
"PID_INSTANCE_DATA",
".",
"metadata",
".",
"browser",
".",
"version",
"=",
"(",
"capabilities",
".",
"get",
"(",
"'version'",
")",
"||",
"capabilities",
".",
"get",
"(",
"'browserVersion'",
")",
")",
"||",
"PID_INSTANCE_DATA",
".",
"metadata",
".",
"browser",
".",
"version",
";",
"}",
")",
";",
"}",
"}"
] |
Enrich the instance data
@see docs/plugins.md
@returns {Promise} A promise which resolves in a enriched instance data object
@public
|
[
"Enrich",
"the",
"instance",
"data"
] |
d01dc9f9660d7bec1ef47c007b429cebe58e3ff4
|
https://github.com/wswebcreation/protractor-multiple-cucumber-html-reporter-plugin/blob/d01dc9f9660d7bec1ef47c007b429cebe58e3ff4/index.js#L136-L147
|
train
|
olegskl/gulp-stylelint
|
src/index.js
|
passLintResultsThroughReporters
|
function passLintResultsThroughReporters(lintResults) {
const warnings = lintResults
.reduce((accumulated, res) => accumulated.concat(res.results), []);
return Promise
.all(reporters.map(reporter => reporter(warnings)))
.then(() => lintResults);
}
|
javascript
|
function passLintResultsThroughReporters(lintResults) {
const warnings = lintResults
.reduce((accumulated, res) => accumulated.concat(res.results), []);
return Promise
.all(reporters.map(reporter => reporter(warnings)))
.then(() => lintResults);
}
|
[
"function",
"passLintResultsThroughReporters",
"(",
"lintResults",
")",
"{",
"const",
"warnings",
"=",
"lintResults",
".",
"reduce",
"(",
"(",
"accumulated",
",",
"res",
")",
"=>",
"accumulated",
".",
"concat",
"(",
"res",
".",
"results",
")",
",",
"[",
"]",
")",
";",
"return",
"Promise",
".",
"all",
"(",
"reporters",
".",
"map",
"(",
"reporter",
"=>",
"reporter",
"(",
"warnings",
")",
")",
")",
".",
"then",
"(",
"(",
")",
"=>",
"lintResults",
")",
";",
"}"
] |
Provides Stylelint result to reporters.
@param {[Object]} lintResults - Stylelint results.
@return {Promise} Resolved with original lint results.
|
[
"Provides",
"Stylelint",
"result",
"to",
"reporters",
"."
] |
bc79cfc11c87c95a1d1f0fd727e2e2c33a8f3fba
|
https://github.com/olegskl/gulp-stylelint/blob/bc79cfc11c87c95a1d1f0fd727e2e2c33a8f3fba/src/index.js#L126-L133
|
train
|
ajhsu/node-wget-promise
|
src/lib/wget.js
|
download
|
function download(source, { verbose, output, onStart, onProgress } = {}) {
return new Promise(function(y, n) {
if (typeof output === 'undefined') {
output = path.basename(url.parse(source).pathname) || 'unknown';
}
/**
* Parse the source url into parts
*/
const sourceUrl = url.parse(source);
/**
* Determine to use https or http request depends on source url
*/
let request = null;
if (sourceUrl.protocol === 'https:') {
request = https.request;
} else if (sourceUrl.protocol === 'http:') {
request = http.request;
} else {
throw new Error('protocol should be http or https');
}
/**
* Issue the request
*/
const req = request(
{
method: 'GET',
protocol: sourceUrl.protocol,
host: sourceUrl.hostname,
port: sourceUrl.port,
path: sourceUrl.pathname + (sourceUrl.search || '')
},
function(res) {
if (res.statusCode === 200) {
const fileSize = Number.isInteger(res.headers['content-length'] - 0)
? parseInt(res.headers['content-length'])
: 0;
let downloadedSize = 0;
/**
* Create write stream
*/
var writeStream = fs.createWriteStream(output, {
flags: 'w+',
encoding: 'binary'
});
res.pipe(writeStream);
/**
* Invoke `onStartCallback` function
*/
if (onStart) {
onStart(res.headers);
}
res.on('data', function(chunk) {
downloadedSize += chunk.length;
if (onProgress) {
onProgress({
fileSize,
downloadedSize,
percentage: fileSize > 0 ? downloadedSize / fileSize : 0
});
}
});
res.on('error', function(err) {
writeStream.end();
n(err);
});
writeStream.on('finish', function() {
writeStream.end();
req.end('finished');
y({ headers: res.headers, fileSize });
});
} else if (
res.statusCode === 301 ||
res.statusCode === 302 ||
res.statusCode === 307
) {
const redirectLocation = res.headers.location;
if (verbose) {
console.log('node-wget-promise: Redirected to:', redirectLocation);
}
/**
* Call download function recursively
*/
download(redirectLocation, {
output,
onStart,
onProgress
})
.then(y)
.catch(n);
} else {
n('Server responded with unhandled status: ' + res.statusCode);
}
}
);
req.end('done');
req.on('error', err => n(err));
});
}
|
javascript
|
function download(source, { verbose, output, onStart, onProgress } = {}) {
return new Promise(function(y, n) {
if (typeof output === 'undefined') {
output = path.basename(url.parse(source).pathname) || 'unknown';
}
/**
* Parse the source url into parts
*/
const sourceUrl = url.parse(source);
/**
* Determine to use https or http request depends on source url
*/
let request = null;
if (sourceUrl.protocol === 'https:') {
request = https.request;
} else if (sourceUrl.protocol === 'http:') {
request = http.request;
} else {
throw new Error('protocol should be http or https');
}
/**
* Issue the request
*/
const req = request(
{
method: 'GET',
protocol: sourceUrl.protocol,
host: sourceUrl.hostname,
port: sourceUrl.port,
path: sourceUrl.pathname + (sourceUrl.search || '')
},
function(res) {
if (res.statusCode === 200) {
const fileSize = Number.isInteger(res.headers['content-length'] - 0)
? parseInt(res.headers['content-length'])
: 0;
let downloadedSize = 0;
/**
* Create write stream
*/
var writeStream = fs.createWriteStream(output, {
flags: 'w+',
encoding: 'binary'
});
res.pipe(writeStream);
/**
* Invoke `onStartCallback` function
*/
if (onStart) {
onStart(res.headers);
}
res.on('data', function(chunk) {
downloadedSize += chunk.length;
if (onProgress) {
onProgress({
fileSize,
downloadedSize,
percentage: fileSize > 0 ? downloadedSize / fileSize : 0
});
}
});
res.on('error', function(err) {
writeStream.end();
n(err);
});
writeStream.on('finish', function() {
writeStream.end();
req.end('finished');
y({ headers: res.headers, fileSize });
});
} else if (
res.statusCode === 301 ||
res.statusCode === 302 ||
res.statusCode === 307
) {
const redirectLocation = res.headers.location;
if (verbose) {
console.log('node-wget-promise: Redirected to:', redirectLocation);
}
/**
* Call download function recursively
*/
download(redirectLocation, {
output,
onStart,
onProgress
})
.then(y)
.catch(n);
} else {
n('Server responded with unhandled status: ' + res.statusCode);
}
}
);
req.end('done');
req.on('error', err => n(err));
});
}
|
[
"function",
"download",
"(",
"source",
",",
"{",
"verbose",
",",
"output",
",",
"onStart",
",",
"onProgress",
"}",
"=",
"{",
"}",
")",
"{",
"return",
"new",
"Promise",
"(",
"function",
"(",
"y",
",",
"n",
")",
"{",
"if",
"(",
"typeof",
"output",
"===",
"'undefined'",
")",
"{",
"output",
"=",
"path",
".",
"basename",
"(",
"url",
".",
"parse",
"(",
"source",
")",
".",
"pathname",
")",
"||",
"'unknown'",
";",
"}",
"const",
"sourceUrl",
"=",
"url",
".",
"parse",
"(",
"source",
")",
";",
"let",
"request",
"=",
"null",
";",
"if",
"(",
"sourceUrl",
".",
"protocol",
"===",
"'https:'",
")",
"{",
"request",
"=",
"https",
".",
"request",
";",
"}",
"else",
"if",
"(",
"sourceUrl",
".",
"protocol",
"===",
"'http:'",
")",
"{",
"request",
"=",
"http",
".",
"request",
";",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"'protocol should be http or https'",
")",
";",
"}",
"const",
"req",
"=",
"request",
"(",
"{",
"method",
":",
"'GET'",
",",
"protocol",
":",
"sourceUrl",
".",
"protocol",
",",
"host",
":",
"sourceUrl",
".",
"hostname",
",",
"port",
":",
"sourceUrl",
".",
"port",
",",
"path",
":",
"sourceUrl",
".",
"pathname",
"+",
"(",
"sourceUrl",
".",
"search",
"||",
"''",
")",
"}",
",",
"function",
"(",
"res",
")",
"{",
"if",
"(",
"res",
".",
"statusCode",
"===",
"200",
")",
"{",
"const",
"fileSize",
"=",
"Number",
".",
"isInteger",
"(",
"res",
".",
"headers",
"[",
"'content-length'",
"]",
"-",
"0",
")",
"?",
"parseInt",
"(",
"res",
".",
"headers",
"[",
"'content-length'",
"]",
")",
":",
"0",
";",
"let",
"downloadedSize",
"=",
"0",
";",
"var",
"writeStream",
"=",
"fs",
".",
"createWriteStream",
"(",
"output",
",",
"{",
"flags",
":",
"'w+'",
",",
"encoding",
":",
"'binary'",
"}",
")",
";",
"res",
".",
"pipe",
"(",
"writeStream",
")",
";",
"if",
"(",
"onStart",
")",
"{",
"onStart",
"(",
"res",
".",
"headers",
")",
";",
"}",
"res",
".",
"on",
"(",
"'data'",
",",
"function",
"(",
"chunk",
")",
"{",
"downloadedSize",
"+=",
"chunk",
".",
"length",
";",
"if",
"(",
"onProgress",
")",
"{",
"onProgress",
"(",
"{",
"fileSize",
",",
"downloadedSize",
",",
"percentage",
":",
"fileSize",
">",
"0",
"?",
"downloadedSize",
"/",
"fileSize",
":",
"0",
"}",
")",
";",
"}",
"}",
")",
";",
"res",
".",
"on",
"(",
"'error'",
",",
"function",
"(",
"err",
")",
"{",
"writeStream",
".",
"end",
"(",
")",
";",
"n",
"(",
"err",
")",
";",
"}",
")",
";",
"writeStream",
".",
"on",
"(",
"'finish'",
",",
"function",
"(",
")",
"{",
"writeStream",
".",
"end",
"(",
")",
";",
"req",
".",
"end",
"(",
"'finished'",
")",
";",
"y",
"(",
"{",
"headers",
":",
"res",
".",
"headers",
",",
"fileSize",
"}",
")",
";",
"}",
")",
";",
"}",
"else",
"if",
"(",
"res",
".",
"statusCode",
"===",
"301",
"||",
"res",
".",
"statusCode",
"===",
"302",
"||",
"res",
".",
"statusCode",
"===",
"307",
")",
"{",
"const",
"redirectLocation",
"=",
"res",
".",
"headers",
".",
"location",
";",
"if",
"(",
"verbose",
")",
"{",
"console",
".",
"log",
"(",
"'node-wget-promise: Redirected to:'",
",",
"redirectLocation",
")",
";",
"}",
"download",
"(",
"redirectLocation",
",",
"{",
"output",
",",
"onStart",
",",
"onProgress",
"}",
")",
".",
"then",
"(",
"y",
")",
".",
"catch",
"(",
"n",
")",
";",
"}",
"else",
"{",
"n",
"(",
"'Server responded with unhandled status: '",
"+",
"res",
".",
"statusCode",
")",
";",
"}",
"}",
")",
";",
"req",
".",
"end",
"(",
"'done'",
")",
";",
"req",
".",
"on",
"(",
"'error'",
",",
"err",
"=>",
"n",
"(",
"err",
")",
")",
";",
"}",
")",
";",
"}"
] |
Downloads a file using http get and request
@param {string} source - The http URL to download from
@param {object} options - Options object
@returns {Promise}
|
[
"Downloads",
"a",
"file",
"using",
"http",
"get",
"and",
"request"
] |
6b6f2c31b4adca89c8e4a0a743ea2fb2ba797c4c
|
https://github.com/ajhsu/node-wget-promise/blob/6b6f2c31b4adca89c8e4a0a743ea2fb2ba797c4c/src/lib/wget.js#L13-L122
|
train
|
jaredhanson/passport-oauth2-client-password
|
lib/strategy.js
|
Strategy
|
function Strategy(options, verify) {
if (typeof options == 'function') {
verify = options;
options = {};
}
if (!verify) throw new Error('OAuth 2.0 client password strategy requires a verify function');
passport.Strategy.call(this);
this.name = 'oauth2-client-password';
this._verify = verify;
this._passReqToCallback = options.passReqToCallback;
}
|
javascript
|
function Strategy(options, verify) {
if (typeof options == 'function') {
verify = options;
options = {};
}
if (!verify) throw new Error('OAuth 2.0 client password strategy requires a verify function');
passport.Strategy.call(this);
this.name = 'oauth2-client-password';
this._verify = verify;
this._passReqToCallback = options.passReqToCallback;
}
|
[
"function",
"Strategy",
"(",
"options",
",",
"verify",
")",
"{",
"if",
"(",
"typeof",
"options",
"==",
"'function'",
")",
"{",
"verify",
"=",
"options",
";",
"options",
"=",
"{",
"}",
";",
"}",
"if",
"(",
"!",
"verify",
")",
"throw",
"new",
"Error",
"(",
"'OAuth 2.0 client password strategy requires a verify function'",
")",
";",
"passport",
".",
"Strategy",
".",
"call",
"(",
"this",
")",
";",
"this",
".",
"name",
"=",
"'oauth2-client-password'",
";",
"this",
".",
"_verify",
"=",
"verify",
";",
"this",
".",
"_passReqToCallback",
"=",
"options",
".",
"passReqToCallback",
";",
"}"
] |
`ClientPasswordStrategy` constructor.
@api protected
|
[
"ClientPasswordStrategy",
"constructor",
"."
] |
0cf29e3f2dfd945dd710e2d1d24f298842204742
|
https://github.com/jaredhanson/passport-oauth2-client-password/blob/0cf29e3f2dfd945dd710e2d1d24f298842204742/lib/strategy.js#L13-L24
|
train
|
poppinss/youch
|
bin/compile.js
|
bundleJsFiles
|
function bundleJsFiles () {
return concat(jsFiles)
.then((output) => {
const uglified = UglifyJS.minify(output)
if (uglified.error) {
throw new Error(uglified.error)
}
return uglified.code
})
}
|
javascript
|
function bundleJsFiles () {
return concat(jsFiles)
.then((output) => {
const uglified = UglifyJS.minify(output)
if (uglified.error) {
throw new Error(uglified.error)
}
return uglified.code
})
}
|
[
"function",
"bundleJsFiles",
"(",
")",
"{",
"return",
"concat",
"(",
"jsFiles",
")",
".",
"then",
"(",
"(",
"output",
")",
"=>",
"{",
"const",
"uglified",
"=",
"UglifyJS",
".",
"minify",
"(",
"output",
")",
"if",
"(",
"uglified",
".",
"error",
")",
"{",
"throw",
"new",
"Error",
"(",
"uglified",
".",
"error",
")",
"}",
"return",
"uglified",
".",
"code",
"}",
")",
"}"
] |
Bundling js files by concatenating them and then
uglifying them.
@method bundleJsFiles
@return {Promise<String>}
|
[
"Bundling",
"js",
"files",
"by",
"concatenating",
"them",
"and",
"then",
"uglifying",
"them",
"."
] |
f2db665c47b185c9ae0434af074644130a0f87aa
|
https://github.com/poppinss/youch/blob/f2db665c47b185c9ae0434af074644130a0f87aa/bin/compile.js#L59-L68
|
train
|
webgme/webgme-engine
|
src/client/gmeNodeSetter.js
|
addMember
|
function addMember(path, memberPath, setId, msg) {
// FIXME: This will have to break due to switched arguments
var node = _getNode(path),
memberNode = _getNode(memberPath);
if (node && memberNode) {
state.core.addMember(node, setId, memberNode);
saveRoot(typeof msg === 'string' ? msg : 'addMember(' + path + ',' + memberPath + ',' + setId + ')');
}
}
|
javascript
|
function addMember(path, memberPath, setId, msg) {
// FIXME: This will have to break due to switched arguments
var node = _getNode(path),
memberNode = _getNode(memberPath);
if (node && memberNode) {
state.core.addMember(node, setId, memberNode);
saveRoot(typeof msg === 'string' ? msg : 'addMember(' + path + ',' + memberPath + ',' + setId + ')');
}
}
|
[
"function",
"addMember",
"(",
"path",
",",
"memberPath",
",",
"setId",
",",
"msg",
")",
"{",
"var",
"node",
"=",
"_getNode",
"(",
"path",
")",
",",
"memberNode",
"=",
"_getNode",
"(",
"memberPath",
")",
";",
"if",
"(",
"node",
"&&",
"memberNode",
")",
"{",
"state",
".",
"core",
".",
"addMember",
"(",
"node",
",",
"setId",
",",
"memberNode",
")",
";",
"saveRoot",
"(",
"typeof",
"msg",
"===",
"'string'",
"?",
"msg",
":",
"'addMember('",
"+",
"path",
"+",
"','",
"+",
"memberPath",
"+",
"','",
"+",
"setId",
"+",
"')'",
")",
";",
"}",
"}"
] |
Mixed argument methods - START
|
[
"Mixed",
"argument",
"methods",
"-",
"START"
] |
f9af95d7bedd83cdfde9cca9c8c2d560c0222065
|
https://github.com/webgme/webgme-engine/blob/f9af95d7bedd83cdfde9cca9c8c2d560c0222065/src/client/gmeNodeSetter.js#L400-L409
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.