code stringlengths 28 313k | docstring stringlengths 25 85.3k | func_name stringlengths 1 74 | language stringclasses 1
value | repo stringlengths 5 60 | path stringlengths 4 172 | url stringlengths 44 218 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
function communityHubDownloadsEnabled(request, response, next) {
if (!("COMMUNITY_HUB_BUNDLE_DOWNLOADS_ENABLED" in process.env)) {
return response.status(422).json({
error:
"Community Hub bundle downloads are not enabled. The system administrator must enable this feature manually to allow this insta... | ### Must be called after `communityHubItem`
Checks if community hub bundle downloads are enabled. The reason this functionality is disabled
by default is that since AgentSkills, Workspaces, and DataConnectors are all imported from the
community hub via unzipping a bundle - it would be possible for a malicious user to c... | communityHubDownloadsEnabled | javascript | Mintplex-Labs/anything-llm | server/utils/middleware/communityHubDownloadsEnabled.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/middleware/communityHubDownloadsEnabled.js | MIT |
async function communityHubItem(request, response, next) {
const { importId } = reqBody(request);
if (!importId)
return response.status(500).json({
success: false,
error: "Import ID is required",
});
const {
url,
item,
error: fetchError,
} = await CommunityHub.getBundleItem(impo... | Fetch the bundle item from the community hub.
Sets `response.locals.bundleItem` and `response.locals.bundleUrl`. | communityHubItem | javascript | Mintplex-Labs/anything-llm | server/utils/middleware/communityHubDownloadsEnabled.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/middleware/communityHubDownloadsEnabled.js | MIT |
function strictMultiUserRoleValid(allowedRoles = DEFAULT_ROLES) {
return async (request, response, next) => {
// If the access-control is allowable for all - skip validations and continue;
if (allowedRoles.includes(ROLES.all)) {
next();
return;
}
const multiUserMode =
response.local... | Explicitly check that multi user mode is enabled as well as that the
requesting user has the appropriate role to modify or call the URL.
@param {string[]} allowedRoles - The roles that are allowed to access the route
@returns {function} | strictMultiUserRoleValid | javascript | Mintplex-Labs/anything-llm | server/utils/middleware/multiUserProtected.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/middleware/multiUserProtected.js | MIT |
function flexUserRoleValid(allowedRoles = DEFAULT_ROLES) {
return async (request, response, next) => {
// If the access-control is allowable for all - skip validations and continue;
// It does not matter if multi-user or not.
if (allowedRoles.includes(ROLES.all)) {
next();
return;
}
/... | Apply role permission checks IF the current system is in multi-user mode.
This is relevant for routes that are shared between MUM and single-user mode.
@param {string[]} allowedRoles - The roles that are allowed to access the route
@returns {function} | flexUserRoleValid | javascript | Mintplex-Labs/anything-llm | server/utils/middleware/multiUserProtected.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/middleware/multiUserProtected.js | MIT |
async function simpleSSOEnabled(_, response, next) {
if (!("SIMPLE_SSO_ENABLED" in process.env)) {
return response
.status(403)
.send(
"Simple SSO is not enabled. It must be enabled to validate or issue temporary auth tokens."
);
}
// If the multi-user mode response local is not set... | Checks if simple SSO is enabled for issuance of temporary auth tokens.
Note: This middleware must be called after `validApiKey`.
@param {import("express").Request} request
@param {import("express").Response} response
@param {import("express").NextFunction} next
@returns {void} | simpleSSOEnabled | javascript | Mintplex-Labs/anything-llm | server/utils/middleware/simpleSSOEnabled.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/middleware/simpleSSOEnabled.js | MIT |
function simpleSSOLoginDisabled() {
return (
"SIMPLE_SSO_ENABLED" in process.env && "SIMPLE_SSO_NO_LOGIN" in process.env
);
} | Checks if simple SSO login is disabled by checking if the
SIMPLE_SSO_NO_LOGIN environment variable is set as well as
SIMPLE_SSO_ENABLED is set.
This check should only be run when in multi-user mode when used.
@returns {boolean} | simpleSSOLoginDisabled | javascript | Mintplex-Labs/anything-llm | server/utils/middleware/simpleSSOEnabled.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/middleware/simpleSSOEnabled.js | MIT |
async function simpleSSOLoginDisabledMiddleware(_, response, next) {
if (!("multiUserMode" in response.locals)) {
const multiUserMode = await SystemSettings.isMultiUserMode();
response.locals.multiUserMode = multiUserMode;
}
if (response.locals.multiUserMode && simpleSSOLoginDisabled()) {
response.st... | Middleware that checks if simple SSO login is disabled by checking if the
SIMPLE_SSO_NO_LOGIN environment variable is set as well as
SIMPLE_SSO_ENABLED is set.
This middleware will 403 if SSO is enabled and no login is allowed and
the system is in multi-user mode. Otherwise, it will call next.
@param {import("express... | simpleSSOLoginDisabledMiddleware | javascript | Mintplex-Labs/anything-llm | server/utils/middleware/simpleSSOEnabled.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/middleware/simpleSSOEnabled.js | MIT |
function isNullOrNaN(value) {
if (value === null) return true;
return isNaN(value);
} | @typedef {object} DocumentMetadata
@property {string} id - eg; "123e4567-e89b-12d3-a456-426614174000"
@property {string} url - eg; "file://example.com/index.html"
@property {string} title - eg; "example.com/index.html"
@property {string} docAuthor - eg; "no author found"
@property {string} description - eg; "No descrip... | isNullOrNaN | javascript | Mintplex-Labs/anything-llm | server/utils/TextSplitter/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/TextSplitter/index.js | MIT |
static buildHeaderMeta(metadata = {}) {
if (!metadata || Object.keys(metadata).length === 0) return null;
const PLUCK_MAP = {
title: {
as: "sourceDocument",
pluck: (metadata) => {
return metadata?.title || null;
},
},
published: {
as: "published",
... | Creates a string of metadata to be prepended to each chunk.
@param {DocumentMetadata} metadata - Metadata to be prepended to each chunk.
@returns {{[key: ('title' | 'published' | 'source')]: string}} Object of metadata that will be prepended to each chunk. | buildHeaderMeta | javascript | Mintplex-Labs/anything-llm | server/utils/TextSplitter/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/TextSplitter/index.js | MIT |
stringifyHeader() {
if (!this.config.chunkHeaderMeta) return null;
let content = "";
Object.entries(this.config.chunkHeaderMeta).map(([key, value]) => {
if (!key || !value) return;
content += `${key}: ${value}\n`;
});
if (!content) return null;
return `<document_metadata>\n${content... | Creates a string of metadata to be prepended to each chunk. | stringifyHeader | javascript | Mintplex-Labs/anything-llm | server/utils/TextSplitter/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/TextSplitter/index.js | MIT |
async ttsBuffer(textInput) {
try {
const result = await this.openai.audio.speech.create({
model: "tts-1",
voice: this.voice,
input: textInput,
});
return Buffer.from(await result.arrayBuffer());
} catch (e) {
console.error(e);
}
return null;
} | Generates a buffer from the given text input using the OpenAI compatible TTS service.
@param {string} textInput - The text to be converted to audio.
@returns {Promise<Buffer>} A buffer containing the audio data. | ttsBuffer | javascript | Mintplex-Labs/anything-llm | server/utils/TextToSpeech/openAiGeneric/index.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/TextToSpeech/openAiGeneric/index.js | MIT |
async function resetAllVectorStores({ vectorDbKey }) {
try {
const workspaces = await Workspace.where();
purgeEntireVectorCache(); // Purges the entire vector-cache folder.
await DocumentVectors.delete(); // Deletes all document vectors from the database.
await Document.delete(); // Deletes all docume... | Resets all vector database and associated content:
- Purges the entire vector-cache folder.
- Deletes all document vectors from the database.
- Deletes all documents from the database.
- Deletes all vector db namespaces for each workspace.
- Logs an event indicating the reset.
@param {string} vectorDbKey - The _previou... | resetAllVectorStores | javascript | Mintplex-Labs/anything-llm | server/utils/vectorStore/resetAllVectorStores.js | https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/vectorStore/resetAllVectorStores.js | MIT |
constructor (path, name, options) {
super()
this.grpc = grpc
this.servers = []
this.ports = []
this.data = {}
// app options / settings
this.context = new Context()
this.env = process.env.NODE_ENV || 'development'
if (path) {
this.addService(path, name, options)
}
} | Create a gRPC service
@class
@param {String|Object} path - Optional path to the protocol buffer definition file
- Object specifying <code>root</code> directory and <code>file</code> to load
- Loaded grpc object
- The static service p... | constructor | javascript | malijs/mali | lib/app.js | https://github.com/malijs/mali/blob/master/lib/app.js | Apache-2.0 |
addService (path, name, options) {
const load = typeof path === 'string' || (_.isObject(path) && path.root && path.file)
let proto = path
if (load) {
let protoFilePath = path
const loadOptions = Object.assign({}, options)
if (typeof path === 'object' && path.root && path.file) {
... | Add the service and initialize the app with the proto.
Basically this can be used if you don't have the data at app construction time for some reason.
This is different than `grpc.Server.addService()`.
@param {String|Object} path - Path to the protocol buffer definition file
- Object specif... | addService | javascript | malijs/mali | lib/app.js | https://github.com/malijs/mali/blob/master/lib/app.js | Apache-2.0 |
use (service, name, ...fns) {
if (typeof service === 'function') {
const isFunction = typeof name === 'function'
for (const serviceName in this.data) {
const _service = this.data[serviceName]
if (isFunction) {
_service.middleware = _service.middleware.concat(service, name, fn... | Define middleware and handlers.
@param {String|Object} service Service name
@param {String|Function} name RPC name
@param {Function|Array} fns - Middleware and/or handler
@example <caption>Define handler for RPC function 'getUser' in first service we find that has that call name.</caption>
app.use('getUser', getUser)
... | use | javascript | malijs/mali | lib/app.js | https://github.com/malijs/mali/blob/master/lib/app.js | Apache-2.0 |
onerror (err, ctx) {
assert(err instanceof Error, `non-error thrown: ${err}`)
if (this.silent) return
const msg = err.stack || err.toString()
console.error()
console.error(msg.replace(/^/gm, ' '))
console.error()
} | Default error handler.
@param {Error} err | onerror | javascript | malijs/mali | lib/app.js | https://github.com/malijs/mali/blob/master/lib/app.js | Apache-2.0 |
async start (port, creds, options) {
if (_.isObject(port)) {
if (_.isObject(creds)) {
options = creds
}
creds = port
port = null
}
if (!port || typeof port !== 'string' || (typeof port === 'string' && port.length === 0)) {
port = '127.0.0.1:0'
}
if (!creds || ... | Start the service. All middleware and handlers have to be set up prior to calling <code>start</code>.
Throws in case we fail to bind to the given port.
@param {String} port - The hostport for the service. Default: <code>127.0.0.1:0</code>
@param {Object} creds - Credentials options. Default: <code>grpc.ServerCredential... | start | javascript | malijs/mali | lib/app.js | https://github.com/malijs/mali/blob/master/lib/app.js | Apache-2.0 |
async close () {
await Promise.all(this.servers.map(({ server }) => server.tryShutdownAsync()))
} | Close the service(s).
@example
app.close() | close | javascript | malijs/mali | lib/app.js | https://github.com/malijs/mali/blob/master/lib/app.js | Apache-2.0 |
_createContext (call, descriptor) {
const type = mu.getCallTypeFromCall(call) || mu.getCallTypeFromDescriptor(descriptor)
const { name, fullName, service } = descriptor
const pkgName = descriptor.package
const context = new Context()
Object.assign(context, this.context)
context.request = new Req... | @member {Boolean} silent Whether to supress logging errors in <code>onerror</code>. Default: <code>false</code>, that is errors will be logged to `stderr`.
@memberof Mali# | _createContext | javascript | malijs/mali | lib/app.js | https://github.com/malijs/mali/blob/master/lib/app.js | Apache-2.0 |
function create (metadata) {
if (typeof metadata !== 'object') {
return
}
if (metadata instanceof grpc.Metadata) {
return metadata
}
const meta = new grpc.Metadata()
for (const k in metadata) {
const v = metadata[k]
if (Buffer.isBuffer(v)) {
meta.set(k, v)
} else if (v !== null ... | Utility helper function to create <code>Metadata</code> object from plain Javascript object
This strictly just calls <code>Metadata.add</code> with the key / value map of objects.
If the value is a <code>Buffer</code> it's passed as is.
If the value is a <code>Sting</code> it's passed as is.
Else if the value defined a... | create | javascript | malijs/mali | lib/metadata.js | https://github.com/malijs/mali/blob/master/lib/metadata.js | Apache-2.0 |
constructor (call, type) {
this.call = call
this.type = type
if (call.metadata instanceof grpc.Metadata) {
this.metadata = call.metadata.getMap()
} else {
this.metadata = call.metadata
}
if (type === CallType.RESPONSE_STREAM ||
type === CallType.UNARY) {
this.req = call.... | Creates a Mali Request instance
@param {Object} call the grpc call instance
@param {String} type the call type. one of `@malijs/call-types` enums. | constructor | javascript | malijs/mali | lib/request.js | https://github.com/malijs/mali/blob/master/lib/request.js | Apache-2.0 |
getMetadata () {
return Metadata.create(this.metadata)
} | Gets the requests metadata as a `grpc.Metadata` object instance
@return {Object} request metadata | getMetadata | javascript | malijs/mali | lib/request.js | https://github.com/malijs/mali/blob/master/lib/request.js | Apache-2.0 |
get (field) {
let val
if (this.metadata) {
val = this.metadata[field]
}
return val
} | Gets specific request metadata field value
@param {*} field the metadata field name
@return {*} the metadata value for the field
@example
console.log(ctx.request.get('foo')) // 'bar' | get | javascript | malijs/mali | lib/request.js | https://github.com/malijs/mali/blob/master/lib/request.js | Apache-2.0 |
constructor (call, type) {
this.call = call
this.type = type
if (type === CallType.DUPLEX) {
this.res = call
}
} | Creates a Mali Response instance
@param {Object} call the grpc call instance
@param {String} type the call type. one of `@malijs/call-types` enums. | constructor | javascript | malijs/mali | lib/response.js | https://github.com/malijs/mali/blob/master/lib/response.js | Apache-2.0 |
set (field, val) {
if (arguments.length === 2) {
if (!this.metadata) {
this.metadata = {}
}
this.metadata[field] = val
} else {
const md = field instanceof grpc.Metadata ? field.getMap() : field
if (typeof md === 'object') {
for (const key in md) {
this.s... | Sets specific response header metadata field value
@param {String|Object} field the metadata field name or object for metadata
@param {*} [val] the value of the field
@example <caption>Using string field name and value</caption>
ctx.response.set('foo', 'bar')
@example <caption>Using object</caption>
ctx.response.set({
... | set | javascript | malijs/mali | lib/response.js | https://github.com/malijs/mali/blob/master/lib/response.js | Apache-2.0 |
sendMetadata (md) {
// if forcing send reset our metadata
if (md && (typeof md === 'object' || md instanceof grpc.Metadata)) {
this.metadata = null
this.set(md)
}
const data = this.getMetadata()
if (data) {
this.call.sendMetadata(data)
}
} | Sends the response header metadata. Optionally (re)sets the header metadata as well.
@param {Object} md optional header metadata object to set into the request before sending
if there is existing metadata in the response it is cleared
if param is not provided `sendMetadata` sends t... | sendMetadata | javascript | malijs/mali | lib/response.js | https://github.com/malijs/mali/blob/master/lib/response.js | Apache-2.0 |
getStatus (field) {
let val
if (this.status) {
val = this.status[field]
}
return val
} | Gets the response status / trailer metadata value
@param {String} field the field name
@return {*} the metadata field value
@example
console.log(ctx.response.getStatus('bar')) // 'baz' | getStatus | javascript | malijs/mali | lib/response.js | https://github.com/malijs/mali/blob/master/lib/response.js | Apache-2.0 |
setStatus (field, val) {
if (arguments.length === 2) {
if (!this.status) {
this.status = {}
}
this.status[field] = val
} else {
const md = field instanceof grpc.Metadata ? field.getMap() : field
if (typeof md === 'object') {
for (const key in md) {
this.s... | Sets specific response status / trailer metadata field value
@param {String|Object} field the metadata field name or object for metadata
@param {*} val the value of the field
@example <caption>Using string field name and value</caption>
ctx.response.setStatus('foo', 'bar')
@example <caption>Using object</caption>
ctx.r... | setStatus | javascript | malijs/mali | lib/response.js | https://github.com/malijs/mali/blob/master/lib/response.js | Apache-2.0 |
getStatusMetadata () {
return Metadata.create(this.status, { addEmpty: false })
} | Gets the response status / trailer metadata as a `grpc.Metadata` object instance
@return {Object} response status / trailer metadata | getStatusMetadata | javascript | malijs/mali | lib/response.js | https://github.com/malijs/mali/blob/master/lib/response.js | Apache-2.0 |
function isInt(n) {
return Number(n) === n && n % 1 === 0;
} | The scroll callback is called when the user scrolls
@callback ScrollCallback
@param {{x: Number, y: Number}} position
@param {string} direction | isInt | javascript | terwanerik/ScrollTrigger | dist/ScrollTrigger.js | https://github.com/terwanerik/ScrollTrigger/blob/master/dist/ScrollTrigger.js | MIT |
function Trigger(element, options) {
_classCallCheck(this, Trigger);
this.element = element;
options = extend_default()(new DefaultOptions().trigger, options);
this.offset = options.offset;
this.toggle = options.toggle;
this.once = options.once;
this.visible = null;
this.active = true;
... | Creates a new Trigger from the given element and options
@param {Element|HTMLElement} element
@param {DefaultOptions.trigger} [options=DefaultOptions.trigger] options | Trigger | javascript | terwanerik/ScrollTrigger | dist/ScrollTrigger.js | https://github.com/terwanerik/ScrollTrigger/blob/master/dist/ScrollTrigger.js | MIT |
function TriggerCollection(triggers) {
TriggerCollection_classCallCheck(this, TriggerCollection);
/**
* @member {Trigger[]}
*/
this.triggers = triggers instanceof Array ? triggers : [];
} | Initializes the collection
@param {Trigger[]} [triggers=[]] triggers A set of triggers to init with, optional | TriggerCollection | javascript | terwanerik/ScrollTrigger | dist/ScrollTrigger.js | https://github.com/terwanerik/ScrollTrigger/blob/master/dist/ScrollTrigger.js | MIT |
function ScrollAnimationLoop(options, callback) {
ScrollAnimationLoop_classCallCheck(this, ScrollAnimationLoop);
this._parseOptions(options);
if (typeof callback === 'function') {
this.callback = callback;
}
this.direction = 'none';
this.position = this.getPosition();
this.lastAction =... | ScrollAnimationLoop constructor.
Starts a requestAnimationFrame loop as long as the user has scrolled the scrollElement. Stops after a certain time.
@param {DefaultOptions.scroll} [options=DefaultOptions.scroll] options The options for the loop
@param {ScrollCallback} callback [loop=null] The loop callback | ScrollAnimationLoop | javascript | terwanerik/ScrollTrigger | dist/ScrollTrigger.js | https://github.com/terwanerik/ScrollTrigger/blob/master/dist/ScrollTrigger.js | MIT |
function ScrollTrigger(options) {
ScrollTrigger_classCallCheck(this, ScrollTrigger);
this._parseOptions(options);
this._initCollection();
this._initLoop();
} | Constructor for the scroll trigger
@param {DefaultOptions} [options=DefaultOptions] options | ScrollTrigger | javascript | terwanerik/ScrollTrigger | dist/ScrollTrigger.js | https://github.com/terwanerik/ScrollTrigger/blob/master/dist/ScrollTrigger.js | MIT |
_parseOptions(options) {
options = extend(new DefaultOptions(), options)
this.defaultTrigger = options.trigger
this.scrollOptions = options.scroll
} | Parses the options
@param {DefaultOptions} [options=DefaultOptions] options
@private | _parseOptions | javascript | terwanerik/ScrollTrigger | src/ScrollTrigger.js | https://github.com/terwanerik/ScrollTrigger/blob/master/src/ScrollTrigger.js | MIT |
_initCollection() {
const scrollAttributes = document.querySelectorAll('[data-scroll]')
let elements = []
if (scrollAttributes.length > 0) {
elements = this.createTriggers(scrollAttributes)
}
this.collection = new TriggerCollection(elements)
} | Initializes the collection, picks all [data-scroll] elements as initial elements
@private | _initCollection | javascript | terwanerik/ScrollTrigger | src/ScrollTrigger.js | https://github.com/terwanerik/ScrollTrigger/blob/master/src/ScrollTrigger.js | MIT |
_scrollCallback(position, direction) {
this.collection.call((trigger) => {
trigger.checkVisibility(this.scrollOptions.element, direction)
})
this.scrollOptions.callback(position, direction)
} | Callback for checking triggers
@param {{x: number, y: number}} position
@param {string} direction
@private | _scrollCallback | javascript | terwanerik/ScrollTrigger | src/ScrollTrigger.js | https://github.com/terwanerik/ScrollTrigger/blob/master/src/ScrollTrigger.js | MIT |
createTrigger(element, options) {
return new Trigger(element, extend(this.defaultTrigger, options))
} | Creates a Trigger object from a given element and optional option set
@param {HTMLElement} element
@param {DefaultOptions.trigger} [options=DefaultOptions.trigger] options
@returns Trigger | createTrigger | javascript | terwanerik/ScrollTrigger | src/ScrollTrigger.js | https://github.com/terwanerik/ScrollTrigger/blob/master/src/ScrollTrigger.js | MIT |
createTriggers(elements, options) {
let triggers = []
elements.each((element) => {
triggers.push(this.createTrigger(element, options))
})
return triggers
} | Creates an array of triggers
@param {HTMLElement[]|NodeList} elements
@param {Object} [options=null] options
@returns {Trigger[]} Array of triggers | createTriggers | javascript | terwanerik/ScrollTrigger | src/ScrollTrigger.js | https://github.com/terwanerik/ScrollTrigger/blob/master/src/ScrollTrigger.js | MIT |
add(objects, options) {
if (objects instanceof HTMLElement) {
this.collection.add(this.createTrigger(objects, options))
return this
}
if (objects instanceof Trigger) {
this.collection.add(objects)
return this
}
if (objects instanceof NodeList) {
this.collection.add(this.createTriggers(objec... | Adds triggers
@param {string|HTMLElement|NodeList|Trigger|Trigger[]} objects A list of objects or a query
@param {Object} [options=null] options
@returns {ScrollTrigger} | add | javascript | terwanerik/ScrollTrigger | src/ScrollTrigger.js | https://github.com/terwanerik/ScrollTrigger/blob/master/src/ScrollTrigger.js | MIT |
remove(objects) {
if (objects instanceof Trigger) {
this.collection.remove(objects)
return this
}
if (Array.isArray(objects) && objects.length && objects[0] instanceof Trigger) {
this.collection.remove(objects)
return this
}
if (objects instanceof HTMLElement) {
this.collection.remove(this.... | Removes triggers
@param {string|HTMLElement|NodeList|Trigger|Trigger[]} objects A list of objects or a query
@returns {ScrollTrigger} | remove | javascript | terwanerik/ScrollTrigger | src/ScrollTrigger.js | https://github.com/terwanerik/ScrollTrigger/blob/master/src/ScrollTrigger.js | MIT |
query(selector) {
return this.collection.query(selector)
} | Lookup one or multiple triggers by a query string
@param {string} selector
@returns {Trigger[]} | query | javascript | terwanerik/ScrollTrigger | src/ScrollTrigger.js | https://github.com/terwanerik/ScrollTrigger/blob/master/src/ScrollTrigger.js | MIT |
search(element) {
return this.collection.search(element)
} | Lookup one or multiple triggers by a certain HTMLElement or NodeList
@param {HTMLElement|HTMLElement[]|NodeList} element
@returns {Trigger|Trigger[]|null} | search | javascript | terwanerik/ScrollTrigger | src/ScrollTrigger.js | https://github.com/terwanerik/ScrollTrigger/blob/master/src/ScrollTrigger.js | MIT |
_parseOptions(options) {
let defaults = new DefaultOptions().scroll
if (typeof options != 'function') {
defaults.callback = () => {}
defaults = extend(defaults, options)
} else {
defaults.callback = options
}
this.element = defaults.element
this.sustain = defaults.sustain
this.callbac... | Parses the options
@param {DefaultOptions.scroll} [options=DefaultOptions.scroll] options The options for the loop
@private | _parseOptions | javascript | terwanerik/ScrollTrigger | src/scripts/ScrollAnimationLoop.js | https://github.com/terwanerik/ScrollTrigger/blob/master/src/scripts/ScrollAnimationLoop.js | MIT |
_didScroll() {
const newPosition = this.getPosition()
if (this.position !== newPosition) {
let newDirection = this.direction
if (newPosition.x !== this.position.x) {
newDirection = newPosition.x > this.position.x ? 'right' : 'left'
} else if (newPosition.y !== this.position.y) {
newDirection = ne... | Callback when the user scrolled the element
@private | _didScroll | javascript | terwanerik/ScrollTrigger | src/scripts/ScrollAnimationLoop.js | https://github.com/terwanerik/ScrollTrigger/blob/master/src/scripts/ScrollAnimationLoop.js | MIT |
_startRun() {
this.running = true
if (typeof this.startCallback === 'function') {
this.startCallback()
}
this._loop()
} | Starts the loop, calls the start callback
@private | _startRun | javascript | terwanerik/ScrollTrigger | src/scripts/ScrollAnimationLoop.js | https://github.com/terwanerik/ScrollTrigger/blob/master/src/scripts/ScrollAnimationLoop.js | MIT |
_stopRun() {
this.running = false
if (typeof this.stopCallback === 'function') {
this.stopCallback()
}
} | Stops the loop, calls the stop callback
@private | _stopRun | javascript | terwanerik/ScrollTrigger | src/scripts/ScrollAnimationLoop.js | https://github.com/terwanerik/ScrollTrigger/blob/master/src/scripts/ScrollAnimationLoop.js | MIT |
getPosition() {
const left = this.element.pageXOffset || this.element.scrollLeft || document.documentElement.scrollLeft || 0
const top = this.element.pageYOffset || this.element.scrollTop || document.documentElement.scrollTop || 0
return { x: left, y: top }
} | The current position of the element
@returns {{x: number, y: number}} | getPosition | javascript | terwanerik/ScrollTrigger | src/scripts/ScrollAnimationLoop.js | https://github.com/terwanerik/ScrollTrigger/blob/master/src/scripts/ScrollAnimationLoop.js | MIT |
_getTimestamp() {
return Number(Date.now())
} | The current timestamp in ms
@returns {number}
@private | _getTimestamp | javascript | terwanerik/ScrollTrigger | src/scripts/ScrollAnimationLoop.js | https://github.com/terwanerik/ScrollTrigger/blob/master/src/scripts/ScrollAnimationLoop.js | MIT |
_tick() {
this.callback(this.position, this.direction)
const now = this._getTimestamp()
if (now - this.lastAction > this.sustain) {
this._stopRun()
}
if (this.running) {
this._loop()
}
} | One single tick of the animation
@private | _tick | javascript | terwanerik/ScrollTrigger | src/scripts/ScrollAnimationLoop.js | https://github.com/terwanerik/ScrollTrigger/blob/master/src/scripts/ScrollAnimationLoop.js | MIT |
checkVisibility(parent, direction) {
if (!this.active) {
return this.visible
}
const parentWidth = parent.offsetWidth || parent.innerWidth || 0
const parentHeight = parent.offsetHeight || parent.innerHeight || 0
const parentFrame = { w: parentWidth, h: parentHeight }
const rect = this.getBounds()
co... | Checks if the Trigger is in the viewport, calls the callbacks and toggles the classes
@param {HTMLElement|HTMLDocument|Window} parent
@param {string} direction top, bottom, left, right
@returns {boolean} If the element is visible | checkVisibility | javascript | terwanerik/ScrollTrigger | src/scripts/Trigger.js | https://github.com/terwanerik/ScrollTrigger/blob/master/src/scripts/Trigger.js | MIT |
getBounds() {
return this.element.getBoundingClientRect()
} | Get the bounds of this element
@return {ClientRect | DOMRect} | getBounds | javascript | terwanerik/ScrollTrigger | src/scripts/Trigger.js | https://github.com/terwanerik/ScrollTrigger/blob/master/src/scripts/Trigger.js | MIT |
_getElementOffset(rect, direction) {
let offset = { x: 0, y: 0 }
if (typeof this.offset.element.x === 'function') {
offset.x = rect.width * this.offset.element.x(this, rect, direction)
} else if (isFloat(this.offset.element.x)) {
offset.x = rect.width * this.offset.element.x
} else if (isInt(this.offset.... | Get the calculated offset to place on the element
@param {ClientRect} rect
@param {string} direction top, bottom, left, right
@returns {{x: number, y: number}}
@private | _getElementOffset | javascript | terwanerik/ScrollTrigger | src/scripts/Trigger.js | https://github.com/terwanerik/ScrollTrigger/blob/master/src/scripts/Trigger.js | MIT |
_getViewportOffset(parent, direction) {
let offset = { x: 0, y: 0 }
if (typeof this.offset.viewport.x === 'function') {
offset.x = parent.w * this.offset.viewport.x(this, parent, direction)
} else if (isFloat(this.offset.viewport.x)) {
offset.x = parent.w * this.offset.viewport.x
} else if (isInt(this.of... | Get the calculated offset to place on the viewport
@param {{w: number, h: number}} parent
@param {string} direction top, bottom, left, right
@returns {{x: number, y: number}}
@private | _getViewportOffset | javascript | terwanerik/ScrollTrigger | src/scripts/Trigger.js | https://github.com/terwanerik/ScrollTrigger/blob/master/src/scripts/Trigger.js | MIT |
_checkVisibility(rect, parent, direction) {
const elementOffset = this._getElementOffset(rect, direction)
const viewportOffset = this._getViewportOffset(parent, direction)
let visible = true
if ((rect.left - viewportOffset.x) < -(rect.width - elementOffset.x)) {
visible = false
}
if ((rect.left + view... | Check the visibility of the trigger in the viewport, with offsets applied
@param {ClientRect} rect
@param {{w: number, h: number}} parent
@param {string} direction top, bottom, left, right
@returns {boolean}
@private | _checkVisibility | javascript | terwanerik/ScrollTrigger | src/scripts/Trigger.js | https://github.com/terwanerik/ScrollTrigger/blob/master/src/scripts/Trigger.js | MIT |
_toggleCallback() {
if (this.visible) {
if (typeof this.toggle.callback.in == 'function') {
return this.toggle.callback.in.call(this.element, this)
}
} else {
if (typeof this.toggle.callback.out == 'function') {
return this.toggle.callback.out.call(this.element, this)
}
}
} | Toggles the callback
@private
@return null|Promise | _toggleCallback | javascript | terwanerik/ScrollTrigger | src/scripts/Trigger.js | https://github.com/terwanerik/ScrollTrigger/blob/master/src/scripts/Trigger.js | MIT |
add(objects) {
if (objects instanceof Trigger) {
// single
return this.triggers.push(objects)
}
objects.each((trigger) => {
if (trigger instanceof Trigger) {
this.triggers.push(trigger)
} else {
console.error('Object added to TriggerCollection is not a Trigger. Object: ', trigger)
}
})
... | Adds one or multiple Trigger objects
@param {Trigger|Trigger[]} objects | add | javascript | terwanerik/ScrollTrigger | src/scripts/TriggerCollection.js | https://github.com/terwanerik/ScrollTrigger/blob/master/src/scripts/TriggerCollection.js | MIT |
remove(objects) {
if (objects instanceof Trigger) {
objects = [objects]
}
this.triggers = this.triggers.filter((trigger) => {
let hit = false
objects.each((object) => {
if (object == trigger) {
hit = true
}
})
return !hit
})
} | Removes one or multiple Trigger objects
@param {Trigger|Trigger[]} objects | remove | javascript | terwanerik/ScrollTrigger | src/scripts/TriggerCollection.js | https://github.com/terwanerik/ScrollTrigger/blob/master/src/scripts/TriggerCollection.js | MIT |
function iterate() {
fs.stat(paths[complete], function(err, stats) {
if (err) {
return callback(err);
}
var pathTime = stats.mtime.getTime();
var comparisonTime = time.getTime();
var difference = pathTime - comparisonTime;
if (difference > tolerance) {
return ca... | Determine if any of the given files are newer than the provided time.
@param {Array.<string>} paths List of file paths.
@param {Date} time The comparison time.
@param {number} tolerance Maximum time in milliseconds that the destination
file is allowed to be newer than the source file to compensate for
imprecisi... | iterate | javascript | tschaub/grunt-newer | lib/util.js | https://github.com/tschaub/grunt-newer/blob/master/lib/util.js | MIT |
function override(filePath, time, include) {
var details = {
task: taskName,
target: targetName,
path: filePath,
time: time
};
options.override(details, include);
} | Special handling for tasks that expect the `files` config to be a string
or array of string source paths. | override | javascript | tschaub/grunt-newer | tasks/newer.js | https://github.com/tschaub/grunt-newer/blob/master/tasks/newer.js | MIT |
function spawnGrunt(dir, done) {
var gruntfile = path.join(dir, 'gruntfile.js');
if (!fs.existsSync(gruntfile)) {
done(new Error('Cannot find gruntfile.js: ' + gruntfile));
} else {
var node = process.argv[0];
var grunt = process.argv[1]; // assumes grunt drives these tests
var child = cp.spawn(no... | Spawn a Grunt process.
@param {string} dir Directory with gruntfile.js.
@param {function(Error, Process)} done Callback. | spawnGrunt | javascript | tschaub/grunt-newer | test/helper.js | https://github.com/tschaub/grunt-newer/blob/master/test/helper.js | MIT |
function cloneFixture(name, done) {
var fixture = path.join(fixtures, name);
if (!fs.existsSync(tmpDir)) {
fs.mkdirSync(tmpDir);
}
tmp.dir({dir: tmpDir}, function(error, dir) {
if (error) {
return done(error);
}
var scratch = path.join(dir, name);
wrench.copyDirRecursive(fixture, scra... | Set up before running tests.
@param {string} name Fixture name.
@param {function} done Callback. | cloneFixture | javascript | tschaub/grunt-newer | test/helper.js | https://github.com/tschaub/grunt-newer/blob/master/test/helper.js | MIT |
function prune(obj) {
return {
src: obj.src,
dest: obj.dest
};
} | Create a clone of the object with just src and dest properties.
@param {Object} obj Source object.
@return {Object} Pruned clone. | prune | javascript | tschaub/grunt-newer | test/integration/tasks/index.js | https://github.com/tschaub/grunt-newer/blob/master/test/integration/tasks/index.js | MIT |
function filter(files) {
return files.map(prune).filter(function(obj) {
return obj.src && obj.src.length > 0;
});
} | Remove files config objects with no src files.
@param {Array} files Array of files config objects.
@return {Array} Filtered array of files config objects. | filter | javascript | tschaub/grunt-newer | test/integration/tasks/index.js | https://github.com/tschaub/grunt-newer/blob/master/test/integration/tasks/index.js | MIT |
match(path) {
return this.regexp.test(path);
} | Returns whether request `path` matches route.
@param {String} path
@returns {Boolean}
@private | match | javascript | koajs/router | lib/layer.js | https://github.com/koajs/router/blob/master/lib/layer.js | MIT |
params(path, captures, params = {}) {
for (let len = captures.length, i = 0; i < len; i++) {
if (this.paramNames[i]) {
const c = captures[i];
if (c && c.length > 0)
params[this.paramNames[i].name] = c ? safeDecodeURIComponent(c) : c;
}
}
return params;
} | Returns map of URL parameters for given `path` and `paramNames`.
@param {String} path
@param {Array.<String>} captures
@param {Object=} params
@returns {Object}
@private | params | javascript | koajs/router | lib/layer.js | https://github.com/koajs/router/blob/master/lib/layer.js | MIT |
captures(path) {
return this.opts.ignoreCaptures ? [] : path.match(this.regexp).slice(1);
} | Returns array of regexp url path captures.
@param {String} path
@returns {Array.<String>}
@private | captures | javascript | koajs/router | lib/layer.js | https://github.com/koajs/router/blob/master/lib/layer.js | MIT |
url(params, options) {
let args = params;
const url = this.path.replace(/\(\.\*\)/g, '');
if (typeof params !== 'object') {
args = Array.prototype.slice.call(arguments);
if (typeof args[args.length - 1] === 'object') {
options = args[args.length - 1];
args = args.slice(0, -1);
... | Generate URL for route using given `params`.
@example
```javascript
const route = new Layer('/users/:id', ['GET'], fn);
route.url({ id: 123 }); // => "/users/123"
```
@param {Object} params url parameters
@returns {String}
@private | url | javascript | koajs/router | lib/layer.js | https://github.com/koajs/router/blob/master/lib/layer.js | MIT |
param(param, fn) {
const { stack } = this;
const params = this.paramNames;
const middleware = function (ctx, next) {
return fn.call(this, ctx.params[param], ctx, next);
};
middleware.param = param;
const names = params.map(function (p) {
return p.name;
});
const x = names.... | Run validations on route named parameters.
@example
```javascript
router
.param('user', function (id, ctx, next) {
ctx.user = users[id];
if (!ctx.user) return ctx.status = 404;
next();
})
.get('/users/:user', function (ctx, next) {
ctx.body = ctx.user;
});
```
@param {String} param
@param {Fu... | param | javascript | koajs/router | lib/layer.js | https://github.com/koajs/router/blob/master/lib/layer.js | MIT |
setPrefix(prefix) {
if (this.path) {
this.path =
this.path !== '/' || this.opts.strict === true
? `${prefix}${this.path}`
: prefix;
this.paramNames = [];
this.regexp = pathToRegexp(this.path, this.paramNames, this.opts);
}
return this;
} | Prefix route path.
@param {String} prefix
@returns {Layer}
@private | setPrefix | javascript | koajs/router | lib/layer.js | https://github.com/koajs/router/blob/master/lib/layer.js | MIT |
constructor(opts = {}) {
if (!(this instanceof Router)) return new Router(opts); // eslint-disable-line no-constructor-return
this.opts = opts;
this.methods = this.opts.methods || [
'HEAD',
'OPTIONS',
'GET',
'PUT',
'PATCH',
'POST',
'DELETE'
];
this.exclusiv... | Create a new router.
@example
Basic usage:
```javascript
const Koa = require('koa');
const Router = require('@koa/router');
const app = new Koa();
const router = new Router();
router.get('/', (ctx, next) => {
// ctx.router available
});
app
.use(router.routes())
.use(router.allowedMethods());
```
@alias mo... | constructor | javascript | koajs/router | lib/router.js | https://github.com/koajs/router/blob/master/lib/router.js | MIT |
static url(path, ...args) {
return Layer.prototype.url.apply({ path }, args);
} | Generate URL from url pattern and given `params`.
@example
```javascript
const url = Router.url('/users/:id', {id: 1});
// => "/users/1"
```
@param {String} path url pattern
@param {Object} params url parameters
@returns {String} | url | javascript | koajs/router | lib/router.js | https://github.com/koajs/router/blob/master/lib/router.js | MIT |
use(...middleware) {
const router = this;
let path;
// support array of paths
if (Array.isArray(middleware[0]) && typeof middleware[0][0] === 'string') {
const arrPaths = middleware[0];
for (const p of arrPaths) {
router.use.apply(router, [p, ...middleware.slice(1)]);
}
... | Use given middleware.
Middleware run in the order they are defined by `.use()`. They are invoked
sequentially, requests start at the first middleware and work their way
"down" the middleware stack.
@example
```javascript
// session middleware will run before authorize
router
.use(session())
.use(authorize());
/... | use | javascript | koajs/router | lib/router.js | https://github.com/koajs/router/blob/master/lib/router.js | MIT |
prefix(prefix) {
prefix = prefix.replace(/\/$/, '');
this.opts.prefix = prefix;
for (let i = 0; i < this.stack.length; i++) {
const route = this.stack[i];
route.setPrefix(prefix);
}
return this;
} | Set the path prefix for a Router instance that was already initialized.
@example
```javascript
router.prefix('/things/:thing_id')
```
@param {String} prefix
@returns {Router} | prefix | javascript | koajs/router | lib/router.js | https://github.com/koajs/router/blob/master/lib/router.js | MIT |
allowedMethods(options = {}) {
const implemented = this.methods;
return (ctx, next) => {
return next().then(() => {
const allowed = {};
if (ctx.matched && (!ctx.status || ctx.status === 404)) {
for (let i = 0; i < ctx.matched.length; i++) {
const route = ctx.matched... | Returns separate middleware for responding to `OPTIONS` requests with
an `Allow` header containing the allowed methods, as well as responding
with `405 Method Not Allowed` and `501 Not Implemented` as appropriate.
@example
```javascript
const Koa = require('koa');
const Router = require('@koa/router');
const app = n... | allowedMethods | javascript | koajs/router | lib/router.js | https://github.com/koajs/router/blob/master/lib/router.js | MIT |
all(name, path, middleware) {
if (typeof path === 'string') {
middleware = Array.prototype.slice.call(arguments, 2);
} else {
middleware = Array.prototype.slice.call(arguments, 1);
path = name;
name = null;
}
// Sanity check to ensure we have a viable path candidate (eg: string|... | Register route with all methods.
@param {String} name Optional.
@param {String} path
@param {Function=} middleware You may also pass multiple middleware.
@param {Function} callback
@returns {Router} | all | javascript | koajs/router | lib/router.js | https://github.com/koajs/router/blob/master/lib/router.js | MIT |
redirect(source, destination, code) {
// lookup source route by name
if (typeof source === 'symbol' || source[0] !== '/') {
source = this.url(source);
if (source instanceof Error) throw source;
}
// lookup destination route by name
if (
typeof destination === 'symbol' ||
(de... | Redirect `source` to `destination` URL with optional 30x status `code`.
Both `source` and `destination` can be route names.
```javascript
router.redirect('/login', 'sign-in');
```
This is equivalent to:
```javascript
router.all('/login', ctx => {
ctx.redirect('/sign-in');
ctx.status = 301;
});
```
@param {Stri... | redirect | javascript | koajs/router | lib/router.js | https://github.com/koajs/router/blob/master/lib/router.js | MIT |
register(path, methods, middleware, opts = {}) {
const router = this;
const { stack } = this;
// support array of paths
if (Array.isArray(path)) {
for (const curPath of path) {
router.register.call(router, curPath, methods, middleware, opts);
}
return this;
}
// crea... | Create and register a route.
@param {String} path Path string.
@param {Array.<String>} methods Array of HTTP verbs.
@param {Function} middleware Multiple middleware also accepted.
@returns {Layer}
@private | register | javascript | koajs/router | lib/router.js | https://github.com/koajs/router/blob/master/lib/router.js | MIT |
route(name) {
const routes = this.stack;
for (let len = routes.length, i = 0; i < len; i++) {
if (routes[i].name && routes[i].name === name) return routes[i];
}
return false;
} | Lookup route with given `name`.
@param {String} name
@returns {Layer|false} | route | javascript | koajs/router | lib/router.js | https://github.com/koajs/router/blob/master/lib/router.js | MIT |
match(path, method) {
const layers = this.stack;
let layer;
const matched = {
path: [],
pathAndMethod: [],
route: false
};
for (let len = layers.length, i = 0; i < len; i++) {
layer = layers[i];
debug('test %s %s', layer.path, layer.regexp);
// eslint-disable-n... | Match given `path` and return corresponding routes.
@param {String} path
@param {String} method
@returns {Object.<path, pathAndMethod>} returns layers that matched path and
path and method.
@private | match | javascript | koajs/router | lib/router.js | https://github.com/koajs/router/blob/master/lib/router.js | MIT |
matchHost(input) {
const { host } = this;
if (!host) {
return true;
}
if (!input) {
return false;
}
if (typeof host === 'string') {
return input === host;
}
if (typeof host === 'object' && host instanceof RegExp) {
return host.test(input);
}
} | Match given `input` to allowed host
@param {String} input
@returns {boolean} | matchHost | javascript | koajs/router | lib/router.js | https://github.com/koajs/router/blob/master/lib/router.js | MIT |
param(param, middleware) {
this.params[param] = middleware;
for (let i = 0; i < this.stack.length; i++) {
const route = this.stack[i];
route.param(param, middleware);
}
return this;
} | Run middleware for named route parameters. Useful for auto-loading or
validation.
@example
```javascript
router
.param('user', (id, ctx, next) => {
ctx.user = users[id];
if (!ctx.user) return ctx.status = 404;
return next();
})
.get('/users/:user', ctx => {
ctx.body = ctx.user;
})
.get('/use... | param | javascript | koajs/router | lib/router.js | https://github.com/koajs/router/blob/master/lib/router.js | MIT |
function loadData(locations, response, callback) {
if (locations.length === 0) callback(null, response);
else $.get(locations.shift())
.fail(function(e) {
callback(e, null);
})
.done(function (data) {
if (response.length > 0) response += '\n\n';
respons... | File fetcher function.
Fetches a given `url` via AJAX.
See [Runner#run()] for a description of fetcher functions. | loadData | javascript | localForage/localForage | docs/scripts/flatdoc.js | https://github.com/localForage/localForage/blob/master/docs/scripts/flatdoc.js | Apache-2.0 |
function mkdir_p(level) {
cache.length = level + 1;
var obj = cache[level];
if (!obj) {
var parent = (level > 1) ? mkdir_p(level-1) : root;
obj = { items: [], level: level };
cache = cache.concat([obj, obj]);
parent.items.push(obj);
}
return obj;
} | Returns menu data for a given HTML.
menu = Flatdoc.transformer.getMenu($content);
menu == {
level: 0,
items: [{
section: "Getting started",
level: 1,
items: [...]}, ...]} | mkdir_p | javascript | localForage/localForage | docs/scripts/flatdoc.js | https://github.com/localForage/localForage/blob/master/docs/scripts/flatdoc.js | Apache-2.0 |
function getTextNodesIn(el) {
var exclude = 'iframe,pre,code';
return $(el).find(':not('+exclude+')').andSelf().contents().filter(function() {
return this.nodeType == 3 && $(this).closest(exclude).length === 0;
});
} | Fetches a given element from the DOM.
Returns a jQuery object.
@api private | getTextNodesIn | javascript | localForage/localForage | docs/scripts/flatdoc.js | https://github.com/localForage/localForage/blob/master/docs/scripts/flatdoc.js | Apache-2.0 |
function _init(stream) {
stream.setMaxListeners(0);
return stream;
} | /*.js')
.pipe(babel({
presets: ['es2015'],
ignore: 'src/ui/vendor/*'
}))
.pipe(gulp.dest(appConfig.buildPath));
});
/* ------------------------------------------------
Sym Links
------------------------------------------------ | _init | javascript | officert/mongotron | gulpfile.js | https://github.com/officert/mongotron/blob/master/gulpfile.js | MIT |
constructor(database, options) {
if (!(database instanceof MongoDb)) console.error('Collection ctor - database is not an instance of MongoDb');
options = options || {};
var _this = this;
_this.id = options.id;
_this.name = options.name;
_this.connection = options.connection;
_this.database... | @param {Object} database - MongoDb object
@param {Object} options
@param {String} options.name - name of the collection
@param {String} options.serverName - name of the server
@param {String} options.databaseName - name of the database | constructor | javascript | officert/mongotron | src/lib/entities/collection.js | https://github.com/officert/mongotron/blob/master/src/lib/entities/collection.js | MIT |
find(query, options) {
options = options || {};
let cursor = this._dbCollection.find(query, options);
if (options.skip) cursor.skip(Number(options.skip));
cursor.limit(options.limit ? Number(options.limit) : DEFAULT_PAGE_SIZE);
return new MongotronCursor(cursor);
} | @param {Object} [query] - mongo query
@param {Object} [options] - mongo query options | find | javascript | officert/mongotron | src/lib/entities/collection.js | https://github.com/officert/mongotron/blob/master/src/lib/entities/collection.js | MIT |
count(query, options) {
query = query || {};
options = options || {};
return this._dbCollection.count(query, options);
} | @param {Object} query - mongo query
@param {Object} [options] - mongo query options | count | javascript | officert/mongotron | src/lib/entities/collection.js | https://github.com/officert/mongotron/blob/master/src/lib/entities/collection.js | MIT |
distinct(field, query) {
if (!field) return Promise.reject(new errors.InvalidArugmentError('field is required'));
query = query || {};
return Promise.fromCallback(callback => {
this._dbCollection.distinct(field, query, callback);
});
} | @param {String} field - mongo field, including dot-notated fields
@param {Object} [query] - mongo query | distinct | javascript | officert/mongotron | src/lib/entities/collection.js | https://github.com/officert/mongotron/blob/master/src/lib/entities/collection.js | MIT |
aggregate(pipeline, options) {
if (!_.isArray(pipeline)) return Promise.reject('pipeline must be an array');
options = options || {};
let stream = options.stream;
delete options.stream;
//always return as a cursor
options.cursor = {};
let cursor = this._dbCollection.aggregate(pipeline, op... | @param {Object} [pipeline] - mongo pipeline
@param {Object} [options] - mongo pipeline options | aggregate | javascript | officert/mongotron | src/lib/entities/collection.js | https://github.com/officert/mongotron/blob/master/src/lib/entities/collection.js | MIT |
updateMany(query, updates, options) {
return new Promise((resolve, reject) => {
if (!query) return reject(new errors.InvalidArugmentError('query is required'));
if (!updates) return reject(new errors.InvalidArugmentError('updates is required'));
options = options || {};
this._dbCollection.u... | @param {Object} query - mongo query
@param {Object} updates - updates to apply
@param {Object} [options] - mongo query options | updateMany | javascript | officert/mongotron | src/lib/entities/collection.js | https://github.com/officert/mongotron/blob/master/src/lib/entities/collection.js | MIT |
updateById(objectId, updates, options) {
return new Promise((resolve, reject) => {
if (!objectId) return reject(new errors.InvalidArugmentError('objectId is required'));
if (!updates) return reject(new errors.InvalidArugmentError('updates is required'));
options = options || {};
this._dbCol... | @param {Object} Mongo ObjectId
@param {Object} updates - updates to apply
@param {Object} [options] - mongo query options | updateById | javascript | officert/mongotron | src/lib/entities/collection.js | https://github.com/officert/mongotron/blob/master/src/lib/entities/collection.js | MIT |
constructor(options) {
options = options || {};
var _this = this;
_this.id = options.id;
_this.name = options.name;
_this.host = options.host;
_this.port = options.port;
_this.replicaSet = options.replicaSet;
_this.databases = [];
if (options.databaseName && !mongoUtils.isLocalHost... | @param {Object} options
@param {String} options.name
@param {String} [options.host]
@param {String} [options.port]
@param {Object} [options.replicaSet]
@param {String} [options.replicaSet.name]
@param {Array<Object>} [options.replicaSet.servers] | constructor | javascript | officert/mongotron | src/lib/entities/connection.js | https://github.com/officert/mongotron/blob/master/src/lib/entities/connection.js | MIT |
addDatabase(options) {
options = options || {};
let existingDatabase = _.findWhere(this.databases, {
name: options.name
});
if (existingDatabase) return;
let database = new Database({
id: options.id,
name: options.name,
host: options.host,
port: options.port,
a... | Add a new database to the connection
@param {Object} options
@param {String} options.name | addDatabase | javascript | officert/mongotron | src/lib/entities/connection.js | https://github.com/officert/mongotron/blob/master/src/lib/entities/connection.js | MIT |
createDatabase(options) {
options = options || {};
return new Promise((resolve, reject) => {
if (!options) return reject(new Error('options is required'));
if (!options.name) return reject(new Error('options.name is required'));
let client = new MongoClient();
client.connect(this.conn... | Create a new database
@param {Object} options
@param {String} options.name
@return Promise | createDatabase | javascript | officert/mongotron | src/lib/entities/connection.js | https://github.com/officert/mongotron/blob/master/src/lib/entities/connection.js | MIT |
function _getDbsForLocalhostConnection(connection, next) {
if (!connection) return next(new Error('connection is required'));
if (!next) return next(new Error('next is required'));
if (!mongoUtils.isLocalHost(connection.host)) return next(new Error('cannot get local dbs for non localhost connection'));
var loc... | @function _getDbsForLocalhostConnection
@param {Function} next - callback function
@private | _getDbsForLocalhostConnection | javascript | officert/mongotron | src/lib/entities/connection.js | https://github.com/officert/mongotron/blob/master/src/lib/entities/connection.js | MIT |
constructor(options) {
options = options || {};
this.id = options.id;
this.name = options.name; //TODO: validate name doesn't contain spaces
this.host = options.host;
this.port = options.port;
this.auth = options.auth;
this.connection = options.connection;
this.collections = [];
i... | @param {Object} options
@param {String} options.name - name of the database
@param {String} options.host - host of the database, defaults to localhost
@param {String} options.port - port of the database, defaults to 27017
@param {Object} options.auth - database auth info
@param {String} options.auth.username - database... | constructor | javascript | officert/mongotron | src/lib/entities/database.js | https://github.com/officert/mongotron/blob/master/src/lib/entities/database.js | MIT |
findById(id) {
let _this = this;
return new Promise((resolve, reject) => {
if (!id) return reject(new errors.InvalidArugmentError('id is required'));
return _this.list()
.then((connections) => {
return findConnectionById(id, connections);
})
.then(resolve)
... | Find a connection by id
@param {string} id - Id of the connection to find | findById | javascript | officert/mongotron | src/lib/modules/connection/repository.js | https://github.com/officert/mongotron/blob/master/src/lib/modules/connection/repository.js | MIT |
create(options) {
let _this = this;
return new Promise((resolve, reject) => {
if (!options) return reject(new errors.InternalServiceError('options is required'));
let connections;
let newConnection;
options.id = uuid.v4(); //assign a "unique" id
return _this.list()
.the... | Create a new connection
@param {object} options
@param {string} options.name - Connection name
@param {string} options.host - Connection host
@param {string} options.port - Connection port
@param {string} [options.databaseName] - Database name
@param {object} [options.replicaSet] - Replica set config
@param {string} op... | create | javascript | officert/mongotron | src/lib/modules/connection/repository.js | https://github.com/officert/mongotron/blob/master/src/lib/modules/connection/repository.js | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.