id
int32
0
58k
repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
list
docstring
stringlengths
4
11.8k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
86
226
25,500
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", ")", "{", "// 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", ";", "}" ]
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
25,501
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'", "}", ";", "// 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", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
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
25,502
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
25,503
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'", ")", ";", "// 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", ")", ";", "}" ]
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
25,504
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", ")", "{", "// 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'", ")", ";", "}", ")", ";", "}" ]
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
25,505
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
25,506
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'", "]", ";", "// 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", ";", "}" ]
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
25,507
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;\"", ";", "// 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", ")", ";", "}" ]
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
25,508
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
25,509
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
25,510
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", "(", "/* 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", ")", ";", "}" ]
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
25,511
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
25,512
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
25,513
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
25,514
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", "(", "/* 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", ")", ";", "}" ]
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
25,515
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", ")", "{", "// 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", ")", ";", "}" ]
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
25,516
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", ";", "// 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", "(", ")", ";", "}", "}", ")", ";", "}" ]
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
25,517
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", "(", ")", ";", "// Event Emitter", "_", ".", "extend", "(", "this", ",", "EventEmitter", ".", "prototype", ")", ";", "EventEmitter", ".", "call", "(", "this", ")", ";", "/**\n * @type {Middleware}\n * @protected\n */", "this", ".", "__middleware", "=", "new", "SwaggerMiddleware", "(", "app", ")", ";", "/**\n * @type {SwaggerParser}\n * @protected\n */", "this", ".", "__parser", "=", "new", "SwaggerParser", "(", "this", ")", ";", "/**\n *\n * @type {Handlers|exports|module.exports}\n * @private\n */", "this", ".", "__handlers", "=", "new", "Handlers", "(", "this", ")", ";", "/**\n * @type {SwaggerWatcher}\n * @protected\n */", "this", ".", "__watcher", "=", "new", "SwaggerWatcher", "(", "this", ")", ";", "/**\n * The Express Application.\n * @type {e.application}\n */", "this", ".", "app", "=", "app", ";", "/**\n * The {@link DataStore} object that's used by the mock middleware.\n * See https://github.com/BigstickCarpet/swagger-express-middleware/blob/master/docs/exports/DataStore.md\n *\n * @type {DataStore}\n */", "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", ")", ";", "}", "}", ")", ";", "/**\n * Parses the given Swagger API.\n *\n * @param {string|object} swagger\n * The file path or URL of a Swagger 2.0 API spec, in YAML or JSON format.\n * Or a valid Swagger API object (see https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#swagger-object).\n *\n * @param {function} [callback]\n * function(err, api, parser)\n */", "this", ".", "parse", "=", "function", "(", "swagger", ",", "callback", ")", "{", "this", ".", "__parser", ".", "parse", "(", "swagger", ")", ";", "if", "(", "_", ".", "isFunction", "(", "callback", ")", ")", "{", "this", ".", "__parser", ".", "whenParsed", "(", "callback", ")", ";", "}", "}", ";", "/**\n * Adds the Swaggerize Express handlers to the Express Instance\n * (see https://github.com/krakenjs/swaggerize-express for info and acceptable formats)\n */", "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", ")", ";", "}", ")", ";", "}" ]
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
25,518
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
25,519
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", ")", "{", "// Convert Swagger-style path to Express-style 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
25,520
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", ")", "{", "// 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", ";", "}", ";", "}", ")", ";", "}" ]
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
25,521
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", ";", "//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", "(", ")", ";", "}", ")", ";", "}" ]
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
25,522
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", ";", "//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", "]", ")", ";", "}", "}", ")", ";", "}", "}" ]
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
25,523
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", ")", "{", "//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", ";", "}" ]
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
25,524
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", ")", "{", "// 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", ")", ";", "}" ]
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
25,525
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", ";", "/**\n * The Swagger API files that are being watched.\n * @type {FSWatcher[]}\n */", "self", ".", "watchedSwaggerFiles", "=", "[", "]", ";", "/**\n * The Handler files that are being watched.\n * @type {FSWatcher[]}\n */", "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", ")", ";", "}", ")", ";", "}" ]
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
25,526
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", ")", "{", "/* 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", ")", ";", "}", "}" ]
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
25,527
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", ")", "{", "// 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", ")", ";", "}", "}", ")", ";", "}" ]
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
25,528
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", ")", "{", "// 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", ")", ";", "}" ]
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
25,529
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", ")", "{", "// 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", "(", ")", ";", "}", "}" ]
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
25,530
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
25,531
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
25,532
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", ")", "{", "// 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'", ")", ";", "}", "}" ]
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
25,533
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", ")", "{", "// 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", ")", ";", "}" ]
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
25,534
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", ";", "// 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", "(", ")", ";", "}", "}", ")", ";", "}" ]
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
25,535
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", ";", "// 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", "(", ")", ";", "}", "}", ")", ";", "}" ]
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
25,536
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
25,537
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
25,538
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", ")", ";", "}", "// 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", "}", ")", ")", ";", "}", ")", ";", "}", ")", ";", "}", ";", "}" ]
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
25,539
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", ")", ";", "}", "// Check that the status cod", "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
25,540
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", ")", ";", "}", "// Check that the status cod", "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
25,541
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
25,542
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", "(", ")", ";", "// 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", ";", "}" ]
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
25,543
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
25,544
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
25,545
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
25,546
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
25,547
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
25,548
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
25,549
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
25,550
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
25,551
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
25,552
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
25,553
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
25,554
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
25,555
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
25,556
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", "(", ")", "{", "/*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", ";", "}" ]
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
25,557
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
25,558
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", "(", ")", "{", "/*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", ";", "}" ]
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
25,559
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
25,560
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
25,561
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
25,562
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
25,563
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
25,564
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
25,565
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
25,566
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
25,567
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", ")", "{", "// 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", ";", "}", "}" ]
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
25,568
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", "/*, 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", "}", ";", "}" ]
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
25,569
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", "(", "/*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", ";", "}" ]
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
25,570
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
25,571
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
25,572
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
25,573
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'", ")", ")", ";", "}", "return", "files", ".", "forEach", "(", "file", "=>", "{", "concat", ".", "add", "(", "file", ".", "file", ",", "file", ".", "content", ",", "file", ".", "map", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
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
25,574
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
25,575
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
25,576
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
25,577
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
25,578
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
25,579
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", ",", "// 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", "+", "']'", ";", "}" ]
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
25,580
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", "(", "/* 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", ";", "}" ]
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
25,581
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", "{", "// unterminated comment", "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
25,582
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", "=", "[", "]", "// 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", "(", "`", "${", "filename", "}", "\\n", "${", "e", ".", "stack", "}", "`", ")", "}", "else", "{", "console", ".", "error", "(", "`", "${", "filename", "}", "\\n", "\\t", "${", "e", "}", "`", ")", "}", "process", ".", "exit", "(", "1", ")", "}", "}", ")", "// return concat'd results", "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
25,583
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", ")", ")", ";", "/**\n * The command line argument `--ieBatch` is a string representing\n * the current batch to run, of total batches.\n * For example, `npm run test:unit:ci:ie -- --ieBatch 1of3`\n */", "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'", ")", ")", ";", "return", "[", "String", ".", "raw", "`", "\\\\", "`", ",", "'\\('", ",", "...", "modules", ".", "join", "(", "'|'", ")", ",", "')\\\\/'", "]", ".", "join", "(", "''", ")", ".", "replace", "(", "/", "\\-", "/", "g", ",", "'\\\\-'", ")", ";", "}" ]
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
25,584
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", ")", "{", "/**\n * If options are provided override the values to the PLUGIN_CONFIG object\n */", "if", "(", "this", ".", "config", ".", "options", ")", "{", "Object", ".", "assign", "(", "PLUGIN_CONFIG", ",", "this", ".", "config", ".", "options", ")", ";", "}", "/**\n * Get the JSON folder path and file name if they are still empty\n */", "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", "]", ";", "/**\n * If the json output folder is still default, then create a new one\n */", "if", "(", "PLUGIN_CONFIG", ".", "jsonOutputPath", "===", "JSON_OUTPUT_FOLDER", ")", "{", "PLUGIN_CONFIG", ".", "jsonOutputPath", "=", "path", ".", "join", "(", "PLUGIN_CONFIG", ".", "cucumberResultsPath", ",", "JSON_OUTPUT_FOLDER", ")", ";", "}", "/**\n * Check whether the file name need to be unique\n */", "PLUGIN_CONFIG", ".", "uniqueReportFileName", "=", "(", "Array", ".", "isArray", "(", "configuration", ".", "multiCapabilities", ")", "&&", "configuration", ".", "multiCapabilities", ".", "length", ">", "0", ")", "||", "typeof", "configuration", ".", "getMultiCapabilities", "===", "'function'", "||", "configuration", ".", "capabilities", ".", "shardTestFiles", ";", "/**\n * Prepare the PID_INSTANCE_DATA\n */", "const", "metadata", "=", "{", "browser", ":", "{", "name", ":", "''", ",", "version", ":", "''", "}", ",", "device", ":", "''", ",", "platform", ":", "{", "name", ":", "''", ",", "version", ":", "''", "}", "}", ";", "PID_INSTANCE_DATA", "=", "{", "pid", ":", "process", ".", "pid", ",", "metadata", ":", "Object", ".", "assign", "(", "metadata", ",", "configuration", ".", "capabilities", "[", "PLUGIN_CONFIG", ".", "metadataKey", "]", "||", "{", "}", ")", "}", ";", "/**\n * Create the needed folders if they are not present\n */", "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
25,585
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
25,586
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
25,587
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'", ";", "}", "/**\n * Parse the source url into parts\n */", "const", "sourceUrl", "=", "url", ".", "parse", "(", "source", ")", ";", "/**\n * Determine to use https or http request depends on source url\n */", "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'", ")", ";", "}", "/**\n * Issue the request\n */", "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", ";", "/**\n * Create write stream\n */", "var", "writeStream", "=", "fs", ".", "createWriteStream", "(", "output", ",", "{", "flags", ":", "'w+'", ",", "encoding", ":", "'binary'", "}", ")", ";", "res", ".", "pipe", "(", "writeStream", ")", ";", "/**\n * Invoke `onStartCallback` function\n */", "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", ")", ";", "}", "/**\n * Call download function recursively\n */", "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
25,588
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
25,589
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
25,590
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", ")", "{", "// 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", "+", "')'", ")", ";", "}", "}" ]
Mixed argument methods - START
[ "Mixed", "argument", "methods", "-", "START" ]
f9af95d7bedd83cdfde9cca9c8c2d560c0222065
https://github.com/webgme/webgme-engine/blob/f9af95d7bedd83cdfde9cca9c8c2d560c0222065/src/client/gmeNodeSetter.js#L400-L409
25,591
webgme/webgme-engine
src/client/gmeNodeSetter.js
setSetAttribute
function setSetAttribute(path, setName, attrName, attrValue, msg) { var node = _getNode(path); if (node) { state.core.setSetAttribute(node, setName, attrName, attrValue); saveRoot(typeof msg === 'string' ? msg : 'setSetAttribute(' + path + ',' + setName + ',' + attrName + ',' + JSON.stringify(attrValue) + ')'); } }
javascript
function setSetAttribute(path, setName, attrName, attrValue, msg) { var node = _getNode(path); if (node) { state.core.setSetAttribute(node, setName, attrName, attrValue); saveRoot(typeof msg === 'string' ? msg : 'setSetAttribute(' + path + ',' + setName + ',' + attrName + ',' + JSON.stringify(attrValue) + ')'); } }
[ "function", "setSetAttribute", "(", "path", ",", "setName", ",", "attrName", ",", "attrValue", ",", "msg", ")", "{", "var", "node", "=", "_getNode", "(", "path", ")", ";", "if", "(", "node", ")", "{", "state", ".", "core", ".", "setSetAttribute", "(", "node", ",", "setName", ",", "attrName", ",", "attrValue", ")", ";", "saveRoot", "(", "typeof", "msg", "===", "'string'", "?", "msg", ":", "'setSetAttribute('", "+", "path", "+", "','", "+", "setName", "+", "','", "+", "attrName", "+", "','", "+", "JSON", ".", "stringify", "(", "attrValue", ")", "+", "')'", ")", ";", "}", "}" ]
Mixed argument methods - END
[ "Mixed", "argument", "methods", "-", "END" ]
f9af95d7bedd83cdfde9cca9c8c2d560c0222065
https://github.com/webgme/webgme-engine/blob/f9af95d7bedd83cdfde9cca9c8c2d560c0222065/src/client/gmeNodeSetter.js#L468-L477
25,592
webgme/webgme-engine
src/bin/blob_fs_clean_up.js
cleanUp
function cleanUp(options) { var BlobClient = require('../server/middleware/blob/BlobClientWithFSBackend'), blobClient, logger, gmeAuth, error, storage; if (options && options.env) { process.env.NODE_ENV = options.env; } gmeConfig = require(path.join(process.cwd(), 'config')); webgme.addToRequireJsPaths(gmeConfig); logger = webgme.Logger.create('clean_up', gmeConfig.bin.log, false); blobClient = new BlobClient(gmeConfig, logger); options = options || {}; return webgme.getGmeAuth(gmeConfig) .then(function (gmeAuth_) { gmeAuth = gmeAuth_; storage = webgme.getStorage(logger, gmeConfig, gmeAuth); return storage.openDatabase(); }) .then(function () { if (options.input) { return getInputHashes(options.input); } else { return getUnusedMetaHashes(blobClient, gmeAuth.metadataStorage, storage); } }) .then(function (unusedMetaHashes) { if (options.del !== true && !options.input) { console.log('The following metaDataHashes are unused:'); console.log(unusedMetaHashes); return null; } else { return removeBasedOnMetaHashes(blobClient, unusedMetaHashes); } }) .then(function (removals) { if (removals) { console.log('The following items were removed:'); console.log(JSON.stringify(removals, null, 2)); } }) .catch(function (err_) { error = err_; }) .finally(function () { logger.debug('Closing database connections...'); return Q.allSettled([storage.closeDatabase(), gmeAuth.unload()]) .finally(function () { logger.debug('Closed.'); if (error) { throw error; } }); }); }
javascript
function cleanUp(options) { var BlobClient = require('../server/middleware/blob/BlobClientWithFSBackend'), blobClient, logger, gmeAuth, error, storage; if (options && options.env) { process.env.NODE_ENV = options.env; } gmeConfig = require(path.join(process.cwd(), 'config')); webgme.addToRequireJsPaths(gmeConfig); logger = webgme.Logger.create('clean_up', gmeConfig.bin.log, false); blobClient = new BlobClient(gmeConfig, logger); options = options || {}; return webgme.getGmeAuth(gmeConfig) .then(function (gmeAuth_) { gmeAuth = gmeAuth_; storage = webgme.getStorage(logger, gmeConfig, gmeAuth); return storage.openDatabase(); }) .then(function () { if (options.input) { return getInputHashes(options.input); } else { return getUnusedMetaHashes(blobClient, gmeAuth.metadataStorage, storage); } }) .then(function (unusedMetaHashes) { if (options.del !== true && !options.input) { console.log('The following metaDataHashes are unused:'); console.log(unusedMetaHashes); return null; } else { return removeBasedOnMetaHashes(blobClient, unusedMetaHashes); } }) .then(function (removals) { if (removals) { console.log('The following items were removed:'); console.log(JSON.stringify(removals, null, 2)); } }) .catch(function (err_) { error = err_; }) .finally(function () { logger.debug('Closing database connections...'); return Q.allSettled([storage.closeDatabase(), gmeAuth.unload()]) .finally(function () { logger.debug('Closed.'); if (error) { throw error; } }); }); }
[ "function", "cleanUp", "(", "options", ")", "{", "var", "BlobClient", "=", "require", "(", "'../server/middleware/blob/BlobClientWithFSBackend'", ")", ",", "blobClient", ",", "logger", ",", "gmeAuth", ",", "error", ",", "storage", ";", "if", "(", "options", "&&", "options", ".", "env", ")", "{", "process", ".", "env", ".", "NODE_ENV", "=", "options", ".", "env", ";", "}", "gmeConfig", "=", "require", "(", "path", ".", "join", "(", "process", ".", "cwd", "(", ")", ",", "'config'", ")", ")", ";", "webgme", ".", "addToRequireJsPaths", "(", "gmeConfig", ")", ";", "logger", "=", "webgme", ".", "Logger", ".", "create", "(", "'clean_up'", ",", "gmeConfig", ".", "bin", ".", "log", ",", "false", ")", ";", "blobClient", "=", "new", "BlobClient", "(", "gmeConfig", ",", "logger", ")", ";", "options", "=", "options", "||", "{", "}", ";", "return", "webgme", ".", "getGmeAuth", "(", "gmeConfig", ")", ".", "then", "(", "function", "(", "gmeAuth_", ")", "{", "gmeAuth", "=", "gmeAuth_", ";", "storage", "=", "webgme", ".", "getStorage", "(", "logger", ",", "gmeConfig", ",", "gmeAuth", ")", ";", "return", "storage", ".", "openDatabase", "(", ")", ";", "}", ")", ".", "then", "(", "function", "(", ")", "{", "if", "(", "options", ".", "input", ")", "{", "return", "getInputHashes", "(", "options", ".", "input", ")", ";", "}", "else", "{", "return", "getUnusedMetaHashes", "(", "blobClient", ",", "gmeAuth", ".", "metadataStorage", ",", "storage", ")", ";", "}", "}", ")", ".", "then", "(", "function", "(", "unusedMetaHashes", ")", "{", "if", "(", "options", ".", "del", "!==", "true", "&&", "!", "options", ".", "input", ")", "{", "console", ".", "log", "(", "'The following metaDataHashes are unused:'", ")", ";", "console", ".", "log", "(", "unusedMetaHashes", ")", ";", "return", "null", ";", "}", "else", "{", "return", "removeBasedOnMetaHashes", "(", "blobClient", ",", "unusedMetaHashes", ")", ";", "}", "}", ")", ".", "then", "(", "function", "(", "removals", ")", "{", "if", "(", "removals", ")", "{", "console", ".", "log", "(", "'The following items were removed:'", ")", ";", "console", ".", "log", "(", "JSON", ".", "stringify", "(", "removals", ",", "null", ",", "2", ")", ")", ";", "}", "}", ")", ".", "catch", "(", "function", "(", "err_", ")", "{", "error", "=", "err_", ";", "}", ")", ".", "finally", "(", "function", "(", ")", "{", "logger", ".", "debug", "(", "'Closing database connections...'", ")", ";", "return", "Q", ".", "allSettled", "(", "[", "storage", ".", "closeDatabase", "(", ")", ",", "gmeAuth", ".", "unload", "(", ")", "]", ")", ".", "finally", "(", "function", "(", ")", "{", "logger", ".", "debug", "(", "'Closed.'", ")", ";", "if", "(", "error", ")", "{", "throw", "error", ";", "}", "}", ")", ";", "}", ")", ";", "}" ]
Lists and optionally deletes the unused data from file-system based Blob-storage. @param {object} [options] @param {bool} [options.del=false] - If true will do the deletion. @param {string} [options.env] - If given it will set the NODE_ENV environment variable. @param {string} [options.input] - Input JSON array file, that contains MetaDataHashes that needs to be removed.
[ "Lists", "and", "optionally", "deletes", "the", "unused", "data", "from", "file", "-", "system", "based", "Blob", "-", "storage", "." ]
f9af95d7bedd83cdfde9cca9c8c2d560c0222065
https://github.com/webgme/webgme-engine/blob/f9af95d7bedd83cdfde9cca9c8c2d560c0222065/src/bin/blob_fs_clean_up.js#L274-L334
25,593
webgme/webgme-engine
src/common/core/users/metarules.js
loadNode
function loadNode(core, rootNode, nodePath) { return core.loadByPath(rootNode, nodePath) .then(function (node) { if (node === null) { throw new Error('Given nodePath does not exist "' + nodePath + '"!'); } else { return node; } }); }
javascript
function loadNode(core, rootNode, nodePath) { return core.loadByPath(rootNode, nodePath) .then(function (node) { if (node === null) { throw new Error('Given nodePath does not exist "' + nodePath + '"!'); } else { return node; } }); }
[ "function", "loadNode", "(", "core", ",", "rootNode", ",", "nodePath", ")", "{", "return", "core", ".", "loadByPath", "(", "rootNode", ",", "nodePath", ")", ".", "then", "(", "function", "(", "node", ")", "{", "if", "(", "node", "===", "null", ")", "{", "throw", "new", "Error", "(", "'Given nodePath does not exist \"'", "+", "nodePath", "+", "'\"!'", ")", ";", "}", "else", "{", "return", "node", ";", "}", "}", ")", ";", "}" ]
Helper functions.
[ "Helper", "functions", "." ]
f9af95d7bedd83cdfde9cca9c8c2d560c0222065
https://github.com/webgme/webgme-engine/blob/f9af95d7bedd83cdfde9cca9c8c2d560c0222065/src/common/core/users/metarules.js#L13-L22
25,594
webgme/webgme-engine
src/common/core/users/metarules.js
checkPointerRules
function checkPointerRules(meta, core, node, callback) { var result = { hasViolation: false, messages: [] }, metaPointers = filterPointerRules(meta).pointers, checkPromises = [], pointerNames = core.getPointerNames(node); checkPromises = pointerNames.map(function (pointerName) { var metaPointer = metaPointers[pointerName], pointerPath, pointerPaths = []; if (!metaPointer) { if (pointerName === 'base') { return {hasViolation: false}; } else { return Q({ hasViolation: true, messages: ['Illegal pointer "' + pointerName + '".'] }); } } else { pointerPath = core.getPointerPath(node, pointerName); if (pointerPath !== null) { pointerPaths.push(pointerPath); } return loadNodes(core, node, pointerPaths) .then(function (nodes) { return checkNodeTypesAndCardinality(core, node, nodes, metaPointer, '"' + pointerName + '" target', true); }); } }); return Q.all(checkPromises) .then(function (results) { results.forEach(function (res) { if (res.hasViolation) { result.hasViolation = true; result.messages = result.messages.concat(res.messages); } }); return result; }).nodeify(callback); }
javascript
function checkPointerRules(meta, core, node, callback) { var result = { hasViolation: false, messages: [] }, metaPointers = filterPointerRules(meta).pointers, checkPromises = [], pointerNames = core.getPointerNames(node); checkPromises = pointerNames.map(function (pointerName) { var metaPointer = metaPointers[pointerName], pointerPath, pointerPaths = []; if (!metaPointer) { if (pointerName === 'base') { return {hasViolation: false}; } else { return Q({ hasViolation: true, messages: ['Illegal pointer "' + pointerName + '".'] }); } } else { pointerPath = core.getPointerPath(node, pointerName); if (pointerPath !== null) { pointerPaths.push(pointerPath); } return loadNodes(core, node, pointerPaths) .then(function (nodes) { return checkNodeTypesAndCardinality(core, node, nodes, metaPointer, '"' + pointerName + '" target', true); }); } }); return Q.all(checkPromises) .then(function (results) { results.forEach(function (res) { if (res.hasViolation) { result.hasViolation = true; result.messages = result.messages.concat(res.messages); } }); return result; }).nodeify(callback); }
[ "function", "checkPointerRules", "(", "meta", ",", "core", ",", "node", ",", "callback", ")", "{", "var", "result", "=", "{", "hasViolation", ":", "false", ",", "messages", ":", "[", "]", "}", ",", "metaPointers", "=", "filterPointerRules", "(", "meta", ")", ".", "pointers", ",", "checkPromises", "=", "[", "]", ",", "pointerNames", "=", "core", ".", "getPointerNames", "(", "node", ")", ";", "checkPromises", "=", "pointerNames", ".", "map", "(", "function", "(", "pointerName", ")", "{", "var", "metaPointer", "=", "metaPointers", "[", "pointerName", "]", ",", "pointerPath", ",", "pointerPaths", "=", "[", "]", ";", "if", "(", "!", "metaPointer", ")", "{", "if", "(", "pointerName", "===", "'base'", ")", "{", "return", "{", "hasViolation", ":", "false", "}", ";", "}", "else", "{", "return", "Q", "(", "{", "hasViolation", ":", "true", ",", "messages", ":", "[", "'Illegal pointer \"'", "+", "pointerName", "+", "'\".'", "]", "}", ")", ";", "}", "}", "else", "{", "pointerPath", "=", "core", ".", "getPointerPath", "(", "node", ",", "pointerName", ")", ";", "if", "(", "pointerPath", "!==", "null", ")", "{", "pointerPaths", ".", "push", "(", "pointerPath", ")", ";", "}", "return", "loadNodes", "(", "core", ",", "node", ",", "pointerPaths", ")", ".", "then", "(", "function", "(", "nodes", ")", "{", "return", "checkNodeTypesAndCardinality", "(", "core", ",", "node", ",", "nodes", ",", "metaPointer", ",", "'\"'", "+", "pointerName", "+", "'\" target'", ",", "true", ")", ";", "}", ")", ";", "}", "}", ")", ";", "return", "Q", ".", "all", "(", "checkPromises", ")", ".", "then", "(", "function", "(", "results", ")", "{", "results", ".", "forEach", "(", "function", "(", "res", ")", "{", "if", "(", "res", ".", "hasViolation", ")", "{", "result", ".", "hasViolation", "=", "true", ";", "result", ".", "messages", "=", "result", ".", "messages", ".", "concat", "(", "res", ".", "messages", ")", ";", "}", "}", ")", ";", "return", "result", ";", "}", ")", ".", "nodeify", "(", "callback", ")", ";", "}" ]
Checker functions for pointers, sets, containment and attributes.
[ "Checker", "functions", "for", "pointers", "sets", "containment", "and", "attributes", "." ]
f9af95d7bedd83cdfde9cca9c8c2d560c0222065
https://github.com/webgme/webgme-engine/blob/f9af95d7bedd83cdfde9cca9c8c2d560c0222065/src/common/core/users/metarules.js#L142-L189
25,595
webgme/webgme-engine
src/server/worker/workerrequests.js
_extractProjectJsonAndAddAssets
function _extractProjectJsonAndAddAssets(filenameOrBuffer, blobClient, callback) { var zip = new AdmZip(filenameOrBuffer), artifact = blobClient.createArtifact('files'), projectStr; return Q.all(zip.getEntries() .map(function (entry) { var entryName = entry.entryName; if (entryName === 'project.json') { projectStr = zip.readAsText(entry); } else { return artifact.addFileAsSoftLink(entryName, zip.readFile(entry)); } }) ) .then(function () { var metadata = artifact.descriptor; return blobUtil.addAssetsFromExportedProject(logger, blobClient, metadata); }) .then(function () { return JSON.parse(projectStr); }) .nodeify(callback); }
javascript
function _extractProjectJsonAndAddAssets(filenameOrBuffer, blobClient, callback) { var zip = new AdmZip(filenameOrBuffer), artifact = blobClient.createArtifact('files'), projectStr; return Q.all(zip.getEntries() .map(function (entry) { var entryName = entry.entryName; if (entryName === 'project.json') { projectStr = zip.readAsText(entry); } else { return artifact.addFileAsSoftLink(entryName, zip.readFile(entry)); } }) ) .then(function () { var metadata = artifact.descriptor; return blobUtil.addAssetsFromExportedProject(logger, blobClient, metadata); }) .then(function () { return JSON.parse(projectStr); }) .nodeify(callback); }
[ "function", "_extractProjectJsonAndAddAssets", "(", "filenameOrBuffer", ",", "blobClient", ",", "callback", ")", "{", "var", "zip", "=", "new", "AdmZip", "(", "filenameOrBuffer", ")", ",", "artifact", "=", "blobClient", ".", "createArtifact", "(", "'files'", ")", ",", "projectStr", ";", "return", "Q", ".", "all", "(", "zip", ".", "getEntries", "(", ")", ".", "map", "(", "function", "(", "entry", ")", "{", "var", "entryName", "=", "entry", ".", "entryName", ";", "if", "(", "entryName", "===", "'project.json'", ")", "{", "projectStr", "=", "zip", ".", "readAsText", "(", "entry", ")", ";", "}", "else", "{", "return", "artifact", ".", "addFileAsSoftLink", "(", "entryName", ",", "zip", ".", "readFile", "(", "entry", ")", ")", ";", "}", "}", ")", ")", ".", "then", "(", "function", "(", ")", "{", "var", "metadata", "=", "artifact", ".", "descriptor", ";", "return", "blobUtil", ".", "addAssetsFromExportedProject", "(", "logger", ",", "blobClient", ",", "metadata", ")", ";", "}", ")", ".", "then", "(", "function", "(", ")", "{", "return", "JSON", ".", "parse", "(", "projectStr", ")", ";", "}", ")", ".", "nodeify", "(", "callback", ")", ";", "}" ]
Extracts the exported zip file and adds the contained files to the blob using the import-part of ExportImport Plugin. @param {string|Buffer} filenameOrBuffer @param {BlobClient} blobClient @param function [callback] @returns {string} - The project json as a string @private
[ "Extracts", "the", "exported", "zip", "file", "and", "adds", "the", "contained", "files", "to", "the", "blob", "using", "the", "import", "-", "part", "of", "ExportImport", "Plugin", "." ]
f9af95d7bedd83cdfde9cca9c8c2d560c0222065
https://github.com/webgme/webgme-engine/blob/f9af95d7bedd83cdfde9cca9c8c2d560c0222065/src/server/worker/workerrequests.js#L308-L331
25,596
webgme/webgme-engine
src/server/worker/workerrequests.js
changeAttributeMeta
function changeAttributeMeta(webgmeToken, parameters, callback) { var storage, context, finish = function (err, result) { if (err) { err = err instanceof Error ? err : new Error(err); logger.error('changeAttributeMeta failed with error', err); } else { logger.debug('changeAttributeMeta completed'); } if (storage) { storage.close(function (closeErr) { callback(err || closeErr, result); }); } else { callback(err, result); } }; getConnectedStorage(webgmeToken) .then(function (storage_) { storage = storage_; storage.addEventListener(storage.CONSTANTS.NETWORK_STATUS_CHANGED, getNetworkStatusChangeHandler(finish)); return _getCoreAndRootNode(storage, parameters.projectId, parameters.commitHash, parameters.branchName, parameters.tagName); }) .then(function (context_) { context = context_; return context.core.loadByPath(context.rootNode, parameters.nodePath); }) .then(function (node) { context.core.renameAttributeMeta(node, parameters.oldName, parameters.newName); context.core.setAttributeMeta(node, parameters.newName, parameters.meta); parameters.excludeOriginNode = true; parameters.type = 'attribute'; return metaRename.propagateMetaDefinitionRename(context.core, node, parameters); }) .then(function () { var persisted = context.core.persist(context.rootNode); return context.project.makeCommit( parameters.branchName, [context.commitObject._id], persisted.rootHash, persisted.objects, 'rename attribute definition [' + parameters.oldName + '->' + parameters.newName + '] of [' + parameters.nodePath + ']'); }) .nodeify(finish); }
javascript
function changeAttributeMeta(webgmeToken, parameters, callback) { var storage, context, finish = function (err, result) { if (err) { err = err instanceof Error ? err : new Error(err); logger.error('changeAttributeMeta failed with error', err); } else { logger.debug('changeAttributeMeta completed'); } if (storage) { storage.close(function (closeErr) { callback(err || closeErr, result); }); } else { callback(err, result); } }; getConnectedStorage(webgmeToken) .then(function (storage_) { storage = storage_; storage.addEventListener(storage.CONSTANTS.NETWORK_STATUS_CHANGED, getNetworkStatusChangeHandler(finish)); return _getCoreAndRootNode(storage, parameters.projectId, parameters.commitHash, parameters.branchName, parameters.tagName); }) .then(function (context_) { context = context_; return context.core.loadByPath(context.rootNode, parameters.nodePath); }) .then(function (node) { context.core.renameAttributeMeta(node, parameters.oldName, parameters.newName); context.core.setAttributeMeta(node, parameters.newName, parameters.meta); parameters.excludeOriginNode = true; parameters.type = 'attribute'; return metaRename.propagateMetaDefinitionRename(context.core, node, parameters); }) .then(function () { var persisted = context.core.persist(context.rootNode); return context.project.makeCommit( parameters.branchName, [context.commitObject._id], persisted.rootHash, persisted.objects, 'rename attribute definition [' + parameters.oldName + '->' + parameters.newName + '] of [' + parameters.nodePath + ']'); }) .nodeify(finish); }
[ "function", "changeAttributeMeta", "(", "webgmeToken", ",", "parameters", ",", "callback", ")", "{", "var", "storage", ",", "context", ",", "finish", "=", "function", "(", "err", ",", "result", ")", "{", "if", "(", "err", ")", "{", "err", "=", "err", "instanceof", "Error", "?", "err", ":", "new", "Error", "(", "err", ")", ";", "logger", ".", "error", "(", "'changeAttributeMeta failed with error'", ",", "err", ")", ";", "}", "else", "{", "logger", ".", "debug", "(", "'changeAttributeMeta completed'", ")", ";", "}", "if", "(", "storage", ")", "{", "storage", ".", "close", "(", "function", "(", "closeErr", ")", "{", "callback", "(", "err", "||", "closeErr", ",", "result", ")", ";", "}", ")", ";", "}", "else", "{", "callback", "(", "err", ",", "result", ")", ";", "}", "}", ";", "getConnectedStorage", "(", "webgmeToken", ")", ".", "then", "(", "function", "(", "storage_", ")", "{", "storage", "=", "storage_", ";", "storage", ".", "addEventListener", "(", "storage", ".", "CONSTANTS", ".", "NETWORK_STATUS_CHANGED", ",", "getNetworkStatusChangeHandler", "(", "finish", ")", ")", ";", "return", "_getCoreAndRootNode", "(", "storage", ",", "parameters", ".", "projectId", ",", "parameters", ".", "commitHash", ",", "parameters", ".", "branchName", ",", "parameters", ".", "tagName", ")", ";", "}", ")", ".", "then", "(", "function", "(", "context_", ")", "{", "context", "=", "context_", ";", "return", "context", ".", "core", ".", "loadByPath", "(", "context", ".", "rootNode", ",", "parameters", ".", "nodePath", ")", ";", "}", ")", ".", "then", "(", "function", "(", "node", ")", "{", "context", ".", "core", ".", "renameAttributeMeta", "(", "node", ",", "parameters", ".", "oldName", ",", "parameters", ".", "newName", ")", ";", "context", ".", "core", ".", "setAttributeMeta", "(", "node", ",", "parameters", ".", "newName", ",", "parameters", ".", "meta", ")", ";", "parameters", ".", "excludeOriginNode", "=", "true", ";", "parameters", ".", "type", "=", "'attribute'", ";", "return", "metaRename", ".", "propagateMetaDefinitionRename", "(", "context", ".", "core", ",", "node", ",", "parameters", ")", ";", "}", ")", ".", "then", "(", "function", "(", ")", "{", "var", "persisted", "=", "context", ".", "core", ".", "persist", "(", "context", ".", "rootNode", ")", ";", "return", "context", ".", "project", ".", "makeCommit", "(", "parameters", ".", "branchName", ",", "[", "context", ".", "commitObject", ".", "_id", "]", ",", "persisted", ".", "rootHash", ",", "persisted", ".", "objects", ",", "'rename attribute definition ['", "+", "parameters", ".", "oldName", "+", "'->'", "+", "parameters", ".", "newName", "+", "'] of ['", "+", "parameters", ".", "nodePath", "+", "']'", ")", ";", "}", ")", ".", "nodeify", "(", "finish", ")", ";", "}" ]
Renames the given attribute definition and propagates the change throughout the whole project. @param {string} webgmeToken @param {object} parameters @param {string} parameters.projectId @param {string} parameters.branchName @param {string} parameters.nodePath - the starting meta node's path. @param {string} parameters.oldName - the current name of the attribute definition. @param {string} parameters.newName - the new name of the attribute definition. @param {function} callback
[ "Renames", "the", "given", "attribute", "definition", "and", "propagates", "the", "change", "throughout", "the", "whole", "project", "." ]
f9af95d7bedd83cdfde9cca9c8c2d560c0222065
https://github.com/webgme/webgme-engine/blob/f9af95d7bedd83cdfde9cca9c8c2d560c0222065/src/server/worker/workerrequests.js#L1323-L1374
25,597
webgme/webgme-engine
src/server/worker/workerrequests.js
renameMetaPointerTarget
function renameMetaPointerTarget(webgmeToken, parameters, callback) { var storage, context, finish = function (err, result) { if (err) { err = err instanceof Error ? err : new Error(err); logger.error('changeAttributeMeta failed with error', err); } else { logger.debug('changeAttributeMeta completed'); } if (storage) { storage.close(function (closeErr) { callback(err || closeErr, result); }); } else { callback(err, result); } }; getConnectedStorage(webgmeToken) .then(function (storage_) { storage = storage_; storage.addEventListener(storage.CONSTANTS.NETWORK_STATUS_CHANGED, getNetworkStatusChangeHandler(finish)); return _getCoreAndRootNode(storage, parameters.projectId, parameters.commitHash, parameters.branchName, parameters.tagName); }) .then(function (context_) { context = context_; return Q.all([context.core.loadByPath(context.rootNode, parameters.nodePath), context.core.loadByPath(context.rootNode, parameters.targetPath)]); }) .then(function (nodes) { context.core.movePointerMetaTarget(nodes[0], nodes[1], parameters.oldName, parameters.newName); return metaRename.propagateMetaDefinitionRename(context.core, nodes[0], parameters); }) .then(function () { var persisted = context.core.persist(context.rootNode); return context.project.makeCommit( parameters.branchName, [context.commitObject._id], persisted.rootHash, persisted.objects, 'rename pointer definition [' + parameters.oldName + '->' + parameters.newName + '] of [' + parameters.nodePath + '] regarding target [' + parameters.targetPath + ']'); }) .nodeify(finish); }
javascript
function renameMetaPointerTarget(webgmeToken, parameters, callback) { var storage, context, finish = function (err, result) { if (err) { err = err instanceof Error ? err : new Error(err); logger.error('changeAttributeMeta failed with error', err); } else { logger.debug('changeAttributeMeta completed'); } if (storage) { storage.close(function (closeErr) { callback(err || closeErr, result); }); } else { callback(err, result); } }; getConnectedStorage(webgmeToken) .then(function (storage_) { storage = storage_; storage.addEventListener(storage.CONSTANTS.NETWORK_STATUS_CHANGED, getNetworkStatusChangeHandler(finish)); return _getCoreAndRootNode(storage, parameters.projectId, parameters.commitHash, parameters.branchName, parameters.tagName); }) .then(function (context_) { context = context_; return Q.all([context.core.loadByPath(context.rootNode, parameters.nodePath), context.core.loadByPath(context.rootNode, parameters.targetPath)]); }) .then(function (nodes) { context.core.movePointerMetaTarget(nodes[0], nodes[1], parameters.oldName, parameters.newName); return metaRename.propagateMetaDefinitionRename(context.core, nodes[0], parameters); }) .then(function () { var persisted = context.core.persist(context.rootNode); return context.project.makeCommit( parameters.branchName, [context.commitObject._id], persisted.rootHash, persisted.objects, 'rename pointer definition [' + parameters.oldName + '->' + parameters.newName + '] of [' + parameters.nodePath + '] regarding target [' + parameters.targetPath + ']'); }) .nodeify(finish); }
[ "function", "renameMetaPointerTarget", "(", "webgmeToken", ",", "parameters", ",", "callback", ")", "{", "var", "storage", ",", "context", ",", "finish", "=", "function", "(", "err", ",", "result", ")", "{", "if", "(", "err", ")", "{", "err", "=", "err", "instanceof", "Error", "?", "err", ":", "new", "Error", "(", "err", ")", ";", "logger", ".", "error", "(", "'changeAttributeMeta failed with error'", ",", "err", ")", ";", "}", "else", "{", "logger", ".", "debug", "(", "'changeAttributeMeta completed'", ")", ";", "}", "if", "(", "storage", ")", "{", "storage", ".", "close", "(", "function", "(", "closeErr", ")", "{", "callback", "(", "err", "||", "closeErr", ",", "result", ")", ";", "}", ")", ";", "}", "else", "{", "callback", "(", "err", ",", "result", ")", ";", "}", "}", ";", "getConnectedStorage", "(", "webgmeToken", ")", ".", "then", "(", "function", "(", "storage_", ")", "{", "storage", "=", "storage_", ";", "storage", ".", "addEventListener", "(", "storage", ".", "CONSTANTS", ".", "NETWORK_STATUS_CHANGED", ",", "getNetworkStatusChangeHandler", "(", "finish", ")", ")", ";", "return", "_getCoreAndRootNode", "(", "storage", ",", "parameters", ".", "projectId", ",", "parameters", ".", "commitHash", ",", "parameters", ".", "branchName", ",", "parameters", ".", "tagName", ")", ";", "}", ")", ".", "then", "(", "function", "(", "context_", ")", "{", "context", "=", "context_", ";", "return", "Q", ".", "all", "(", "[", "context", ".", "core", ".", "loadByPath", "(", "context", ".", "rootNode", ",", "parameters", ".", "nodePath", ")", ",", "context", ".", "core", ".", "loadByPath", "(", "context", ".", "rootNode", ",", "parameters", ".", "targetPath", ")", "]", ")", ";", "}", ")", ".", "then", "(", "function", "(", "nodes", ")", "{", "context", ".", "core", ".", "movePointerMetaTarget", "(", "nodes", "[", "0", "]", ",", "nodes", "[", "1", "]", ",", "parameters", ".", "oldName", ",", "parameters", ".", "newName", ")", ";", "return", "metaRename", ".", "propagateMetaDefinitionRename", "(", "context", ".", "core", ",", "nodes", "[", "0", "]", ",", "parameters", ")", ";", "}", ")", ".", "then", "(", "function", "(", ")", "{", "var", "persisted", "=", "context", ".", "core", ".", "persist", "(", "context", ".", "rootNode", ")", ";", "return", "context", ".", "project", ".", "makeCommit", "(", "parameters", ".", "branchName", ",", "[", "context", ".", "commitObject", ".", "_id", "]", ",", "persisted", ".", "rootHash", ",", "persisted", ".", "objects", ",", "'rename pointer definition ['", "+", "parameters", ".", "oldName", "+", "'->'", "+", "parameters", ".", "newName", "+", "'] of ['", "+", "parameters", ".", "nodePath", "+", "'] regarding target ['", "+", "parameters", ".", "targetPath", "+", "']'", ")", ";", "}", ")", ".", "nodeify", "(", "finish", ")", ";", "}" ]
Renames the given pointer relation definitions and propagates the change throughout the whole project. @param {string} webgmeToken @param {object} parameters @param {string} parameters.projectId @param {string} parameters.branchName @param {string} parameters.type - the type of the relation ['pointer'|'set']. @param {string} parameters.nodePath - the starting meta node's path. @param {string} parameters.targetPath - the path of the meta node that is the target of the relationship definition. @param {string} parameters.oldName - the current name of the concept. @param {string} parameters.newName - the new name of the concept. @param {function} callback
[ "Renames", "the", "given", "pointer", "relation", "definitions", "and", "propagates", "the", "change", "throughout", "the", "whole", "project", "." ]
f9af95d7bedd83cdfde9cca9c8c2d560c0222065
https://github.com/webgme/webgme-engine/blob/f9af95d7bedd83cdfde9cca9c8c2d560c0222065/src/server/worker/workerrequests.js#L1390-L1440
25,598
webgme/webgme-engine
src/server/util/ensureDir.js
ensureDir
function ensureDir(dir, mode, callback) { var deferred = Q.defer(); if (mode && typeof mode === 'function') { callback = mode; mode = null; } mode = mode || parseInt('0777', 8) & (~process.umask()); _ensureDir(dir, mode, function (err) { if (err) { deferred.reject(err); } else { deferred.resolve(); } }); return deferred.promise.nodeify(callback); }
javascript
function ensureDir(dir, mode, callback) { var deferred = Q.defer(); if (mode && typeof mode === 'function') { callback = mode; mode = null; } mode = mode || parseInt('0777', 8) & (~process.umask()); _ensureDir(dir, mode, function (err) { if (err) { deferred.reject(err); } else { deferred.resolve(); } }); return deferred.promise.nodeify(callback); }
[ "function", "ensureDir", "(", "dir", ",", "mode", ",", "callback", ")", "{", "var", "deferred", "=", "Q", ".", "defer", "(", ")", ";", "if", "(", "mode", "&&", "typeof", "mode", "===", "'function'", ")", "{", "callback", "=", "mode", ";", "mode", "=", "null", ";", "}", "mode", "=", "mode", "||", "parseInt", "(", "'0777'", ",", "8", ")", "&", "(", "~", "process", ".", "umask", "(", ")", ")", ";", "_ensureDir", "(", "dir", ",", "mode", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "deferred", ".", "reject", "(", "err", ")", ";", "}", "else", "{", "deferred", ".", "resolve", "(", ")", ";", "}", "}", ")", ";", "return", "deferred", ".", "promise", ".", "nodeify", "(", "callback", ")", ";", "}" ]
ensure a directory exists, create it recursively if not. @param dir The directory you want to ensure it exists @param mode Refer to fs.mkdir() @param callback
[ "ensure", "a", "directory", "exists", "create", "it", "recursively", "if", "not", "." ]
f9af95d7bedd83cdfde9cca9c8c2d560c0222065
https://github.com/webgme/webgme-engine/blob/f9af95d7bedd83cdfde9cca9c8c2d560c0222065/src/server/util/ensureDir.js#L57-L77
25,599
webgme/webgme-engine
src/utils.js
requestWebGMEToken
function requestWebGMEToken(gmeConfig, userId, password, serverUrl, callback) { var deferred, req; if (gmeConfig.authentication.enable === false) { return Q().nodeify(callback); } if (!serverUrl) { serverUrl = 'http://localhost:' + gmeConfig.server.port; } req = superagent.get(serverUrl + '/api/v1/user/token'); if (gmeConfig.authentication.guestAccount !== userId) { if (!password) { return Q.reject(new Error('password was not provided!')); } req.set('Authorization', 'Basic ' + Buffer.from(userId + ':' + password).toString('base64')); } deferred = Q.defer(); req.end(function (err, res) { if (err) { deferred.reject(err); } else { deferred.resolve(res.body.webgmeToken); } }); return deferred.promise.nodeify(callback); }
javascript
function requestWebGMEToken(gmeConfig, userId, password, serverUrl, callback) { var deferred, req; if (gmeConfig.authentication.enable === false) { return Q().nodeify(callback); } if (!serverUrl) { serverUrl = 'http://localhost:' + gmeConfig.server.port; } req = superagent.get(serverUrl + '/api/v1/user/token'); if (gmeConfig.authentication.guestAccount !== userId) { if (!password) { return Q.reject(new Error('password was not provided!')); } req.set('Authorization', 'Basic ' + Buffer.from(userId + ':' + password).toString('base64')); } deferred = Q.defer(); req.end(function (err, res) { if (err) { deferred.reject(err); } else { deferred.resolve(res.body.webgmeToken); } }); return deferred.promise.nodeify(callback); }
[ "function", "requestWebGMEToken", "(", "gmeConfig", ",", "userId", ",", "password", ",", "serverUrl", ",", "callback", ")", "{", "var", "deferred", ",", "req", ";", "if", "(", "gmeConfig", ".", "authentication", ".", "enable", "===", "false", ")", "{", "return", "Q", "(", ")", ".", "nodeify", "(", "callback", ")", ";", "}", "if", "(", "!", "serverUrl", ")", "{", "serverUrl", "=", "'http://localhost:'", "+", "gmeConfig", ".", "server", ".", "port", ";", "}", "req", "=", "superagent", ".", "get", "(", "serverUrl", "+", "'/api/v1/user/token'", ")", ";", "if", "(", "gmeConfig", ".", "authentication", ".", "guestAccount", "!==", "userId", ")", "{", "if", "(", "!", "password", ")", "{", "return", "Q", ".", "reject", "(", "new", "Error", "(", "'password was not provided!'", ")", ")", ";", "}", "req", ".", "set", "(", "'Authorization'", ",", "'Basic '", "+", "Buffer", ".", "from", "(", "userId", "+", "':'", "+", "password", ")", ".", "toString", "(", "'base64'", ")", ")", ";", "}", "deferred", "=", "Q", ".", "defer", "(", ")", ";", "req", ".", "end", "(", "function", "(", "err", ",", "res", ")", "{", "if", "(", "err", ")", "{", "deferred", ".", "reject", "(", "err", ")", ";", "}", "else", "{", "deferred", ".", "resolve", "(", "res", ".", "body", ".", "webgmeToken", ")", ";", "}", "}", ")", ";", "return", "deferred", ".", "promise", ".", "nodeify", "(", "callback", ")", ";", "}" ]
Request a token for the user via the webgme server. If authentication is turned off it will resolve with undefined. @param {object} gmeConfig @param {string} userId - User to get token for. @param {string} [password] - Must be provided if userId is not the guestAccount. @param {string} [serverUrl='http://127.0.0.1:<gmeConfig.server.port>'] - Url of webgme server. @param [callback] - If not provided will return a promise. @returns {Promise}
[ "Request", "a", "token", "for", "the", "user", "via", "the", "webgme", "server", ".", "If", "authentication", "is", "turned", "off", "it", "will", "resolve", "with", "undefined", "." ]
f9af95d7bedd83cdfde9cca9c8c2d560c0222065
https://github.com/webgme/webgme-engine/blob/f9af95d7bedd83cdfde9cca9c8c2d560c0222065/src/utils.js#L30-L63