From b599ee6c8264714420215d167c5b72f3ac42facd Mon Sep 17 00:00:00 2001 From: Benjamin Pannell Date: Thu, 9 Jun 2016 23:36:17 +0200 Subject: [PATCH] chore: Build latest changes --- dist/lib/Instance.js.map | 2 +- dist/lib/ModelSpecificInstance.js | 28 +- dist/lib/ModelSpecificInstance.js.map | 2 +- dist/main.d.ts | 5229 +++++++++++++------------ 4 files changed, 2642 insertions(+), 2619 deletions(-) diff --git a/dist/lib/Instance.js.map b/dist/lib/Instance.js.map index df34df9..f60860b 100644 --- a/dist/lib/Instance.js.map +++ b/dist/lib/Instance.js.map @@ -1 +1 @@ -{"version":3,"sources":["lib/Instance.ts"],"names":[],"mappings":";AASA,2BAAgC,cAAc,CAAC,CAAA;AAE/C,IAAY,CAAC,WAAM,QAAQ,CAAC,CAAA;AAE5B,IAAY,QAAQ,WAAM,UAAU,CAAC,CAAA;AAGrC;;;;;;;;;;;;;GAaG;AACH;IACI;;;;;;;OAOG;IACH,kBAAY,KAAkC,EAAE,QAAmB,EAAE,KAAqB,EAAE,SAA0B;QAT1H,iBAoWC;QA3VwE,qBAAqB,GAArB,YAAqB;QAAE,yBAA0B,GAA1B,iBAA0B;QAClH,IAAI,CAAC,MAAM,GAAG,KAAK,CAAC;QAEpB,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC,KAAK,CAAC;QACtB,IAAI,CAAC,UAAU,GAAG,SAAS,CAAC;QAC5B,IAAI,CAAC,SAAS,GAAG,QAAQ,CAAC;QAC1B,IAAI,CAAC,SAAS,GAAG,KAAK,CAAC,OAAO,CAAC,aAAa,CAAC,QAAQ,CAAC,CAAC;QAEvD,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,OAAO,EAAE,UAAC,MAAc;YACtC,EAAE,CAAC,CAAC,MAAM,CAAC,WAAW,CAAC;gBAAC,MAAM,CAAC,WAAW,CAAC,KAAI,EAAE,KAAK,CAAC,CAAC;QAC5D,CAAC,CAAC,CAAC;IACP,CAAC;IAWD,sB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AC,OAAO,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC;YAC9B,CAAC;QACL,CAAC,CAAC,CAAC;QAEH,MAAM,CAAC,OAAO,CAAC;IACnB,CAAC;IAED;;;OAGG;IACH,yBAAM,GAAN;QACI,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC;IACzB,CAAC;IAED;;;OAGG;IACH,2BAAQ,GAAR;QACI,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,QAAQ,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC;IAClD,CAAC;IA7RD;;OAEG;IACI,eAAM,GAAW;QACpB,GAAG,EAAE,KAAK;KACb,CAAC;IAEF;;OAEG;IACI,mBAAU,GAAuB,8BAAiB,EAAE,CAAC;IAE5D;;OAEG;IACI,mBAAU,GAAe,EAE/B,CAAC;IAOF;;OAEG;IACI,gBAAO,GAA+C,EAAE,CAAC;IAmQpE,eAAC;AAAD,CApWA,AAoWC,IAAA;AApWY,gBAAQ,WAoWpB,CAAA","file":"lib/Instance.js","sourcesContent":["import {Core} from \"./Core\";\r\nimport {Model} from \"./Model\";\r\nimport {Plugin} from \"./Plugins\";\r\nimport {CacheDirector} from \"./CacheDirector\";\r\nimport * as General from \"./General\";\r\nimport * as ModelInterfaces from \"./ModelInterfaces\";\r\nimport * as Index from \"./Index\";\r\nimport {Schema} from \"./Schema\";\r\nimport {Transforms} from \"./Transforms\";\r\nimport {DefaultValidators} from \"./Validators\";\r\n\r\nimport * as _ from \"lodash\";\r\nimport * as MongoDB from \"mongodb\";\r\nimport * as Bluebird from \"bluebird\";\r\nimport * as Skmatc from \"skmatc\";\r\n\r\n/**\r\n * The default Iridium Instance implementation which provides methods for saving, refreshing and\r\n * removing the wrapped document from the collection, as well as integrating with Omnom, our\r\n * built in document diff processor which allows clean, atomic, document updates to be performed\r\n * without needing to write the update queries yourself.\r\n *\r\n * @param TDocument The interface representing the structure of the documents in the collection.\r\n * @param TInstance The type of instance which wraps the documents, generally the subclass of this class.\r\n *\r\n * This class will be subclassed automatically by Iridium to create a model specific instance\r\n * which takes advantage of some of v8's optimizations to boost performance significantly.\r\n * The instance returned by the model, and all of this instance's methods, will be of type\r\n * TInstance - which should represent the merger of TSchema and IInstance for best results.\r\n */\r\nexport class Instance {\r\n /**\r\n * Creates a new instance which represents the given document as a type of model\r\n * @param model The model that dictates the collection the document originated from as well as how validations are performed.\r\n * @param document The document which should be wrapped by this instance\r\n * @param isNew Whether the document is new (doesn't exist in the database) or not\r\n * @param isPartial Whether the document has only a subset of its fields populated\r\n *\r\n */\r\n constructor(model: Model, document: TDocument, isNew: boolean = true, isPartial: boolean = false) {\r\n this._model = model;\r\n\r\n this._isNew = !!isNew;\r\n this._isPartial = isPartial;\r\n this._original = document;\r\n this._modified = model.helpers.cloneDocument(document);\r\n\r\n _.each(model.core.plugins, (plugin: Plugin) => {\r\n if (plugin.newInstance) plugin.newInstance(this, model);\r\n });\r\n }\r\n\r\n private _isNew: boolean;\r\n private _isPartial: boolean;\r\n private _model: Model;\r\n private _original: TDocument;\r\n private _modified: TDocument;\r\n\r\n /**\r\n * Gets the underlying document representation of this instance\r\n */\r\n get document(): TDocument {\r\n return this._modified;\r\n }\r\n\r\n [name: string]: any;\r\n\r\n /**\r\n * A function which is called whenever a new document is in the process of being inserted into the database.\r\n * @param document The document which will be inserted into the database.\r\n */\r\n static onCreating: (document: { _id?: any }) => Promise | void;\r\n\r\n /**\r\n * A function which is called whenever a document of this type is received from the database, prior to it being\r\n * wrapped by an Instance object.\r\n * @param document The document that was retrieved from the database.\r\n */\r\n static onRetrieved: (document: { _id?: any }) => Promise | void;\r\n\r\n /**\r\n * A function which is called whenever a new instance has been created to wrap a document.\r\n * @param instance The instance which has been created.\r\n */\r\n static onReady: (instance: Instance<{ _id?: any }, Instance<{ _id?: any }, any>>) => Promise | void;\r\n\r\n /**\r\n * A function which is called whenever an instance's save() method is called to allow you to interrogate and/or manipulate\r\n * the changes which are being made.\r\n *\r\n * @param instance The instance to which the changes are being made\r\n * @param changes The MongoDB change object describing the changes being made to the document.\r\n */\r\n static onSaving: (instance: Instance<{ _id?: any }, Instance<{ _id?: any }, any>>, changes: any) => Promise | void;\r\n\r\n /**\r\n * The name of the collection into which documents of this type are stored.\r\n */\r\n static collection: string;\r\n\r\n /**\r\n * The schema used to validate documents of this type before being stored in the database.\r\n */\r\n static schema: Schema = {\r\n _id: false\r\n };\r\n\r\n /**\r\n * Additional which should be made available for use in the schema definition for this instance.\r\n */\r\n static validators: Skmatc.Validator[] = DefaultValidators();\r\n\r\n /**\r\n * The transformations which should be applied to properties of documents of this type.\r\n */\r\n static transforms: Transforms = {\r\n\r\n };\r\n\r\n /**\r\n * The cache director used to derive unique cache keys for documents of this type.\r\n */\r\n static cache: CacheDirector;\r\n\r\n /**\r\n * The indexes which should be managed by Iridium for the collection used by this type.\r\n */\r\n static indexes: (Index.Index | Index.IndexSpecification)[] = [];\r\n\r\n /**\r\n * Saves any changes to this instance, using the built in diff algorithm to write the update query.\r\n * @param {function(Error, IInstance)} callback A callback which is triggered when the save operation completes\r\n * @returns {Promise}\r\n */\r\n save(callback?: General.Callback): Bluebird;\r\n /**\r\n * Saves the given changes to this instance and updates the instance to match the latest database document.\r\n * @param {Object} changes The MongoDB changes object to be used when updating this instance\r\n * @param {function(Error, IInstance)} callback A callback which is triggered when the save operation completes\r\n * @returns {Promise}\r\n */\r\n save(changes: Object, callback?: General.Callback): Bluebird;\r\n /**\r\n * Saves the given changes to this instance and updates the instance to match the latest database document.\r\n * @param {Object} conditions The conditions under which the update will take place - these will be merged with an _id query\r\n * @param {Object} changes The MongoDB changes object to be used when updating this instance\r\n * @param {function(Error, IInstance)} callback A callback which is triggered when the save operation completes\r\n * @returns {Promise}\r\n */\r\n save(conditions: Object, changes: Object, callback?: General.Callback): Bluebird;\r\n save(...args: any[]): Bluebird {\r\n let callback: General.Callback = null;\r\n let changes: any = null;\r\n let conditions: any = {};\r\n\r\n Array.prototype.slice.call(args, 0).reverse().forEach((arg) => {\r\n if (typeof arg == \"function\") callback = arg;\r\n else if (typeof arg == \"object\") {\r\n if (!changes) changes = arg;\r\n else conditions = arg;\r\n }\r\n });\r\n\r\n return Bluebird.resolve().then(() => {\r\n conditions = this._model.helpers.cloneConditions(conditions);\r\n _.merge(conditions, { _id: this._modified._id });\r\n\r\n if (!changes) {\r\n let validation = this._model.helpers.validate(this._modified);\r\n if (validation.failed) return Bluebird.reject(validation.error).bind(this).nodeify(callback);\r\n\r\n let original = this._model.helpers.cloneDocument(this._original);\r\n let modified = this._model.helpers.cloneDocument(this._modified);\r\n \r\n modified = this._model.helpers.transformToDB(modified, { document: true }); \r\n\r\n changes = this._model.helpers.diff(original, modified);\r\n }\r\n\r\n if (!_.keys(changes).length) return null;\r\n\r\n return changes;\r\n }).then((changes) => {\r\n if (!changes && !this._isNew) return changes;\r\n return this._model.handlers.savingDocument(this, changes).then(() => changes);\r\n }).then((changes) => {\r\n if (!changes && !this._isNew) return false;\r\n\r\n if (this._isNew) {\r\n return new Bluebird((resolve, reject) => {\r\n this._model.collection.insertOne(this._modified, { w: \"majority\" }, (err, doc) => {\r\n if (err) return reject(err);\r\n return resolve(!!doc);\r\n });\r\n });\r\n } else {\r\n return new Bluebird((resolve: (changed: boolean) => void, reject) => {\r\n this._model.collection.updateOne(conditions, changes, { w: \"majority\" }, (err, changed) => {\r\n if(err) {\r\n err[\"conditions\"] = conditions;\r\n err[\"changes\"] = changes;\r\n return reject(err);\r\n }\r\n\r\n return resolve(!!changed.modifiedCount);\r\n });\r\n });\r\n }\r\n }).catch(err => {\r\n err[\"original\"] = this._original;\r\n err[\"modified\"] = this._modified;\r\n return Bluebird.reject(err);\r\n }).then((changed: boolean) => {\r\n conditions = { _id: this._modified._id };\r\n if (!changed) return this._modified;\r\n\r\n return new Bluebird((resolve, reject) => {\r\n this._model.collection.find(conditions).limit(1).next((err: Error, latest) => {\r\n if (err) return reject(err);\r\n return resolve(latest);\r\n });\r\n });\r\n }).then((latest: TDocument) => {\r\n if(!latest) {\r\n this._isNew = true;\r\n this._original = this._model.helpers.cloneDocument(this._modified);\r\n return Bluebird.resolve(this);\r\n }\r\n\r\n return this._model.handlers.documentReceived(conditions, latest, (value) => {\r\n this._isPartial = false;\r\n this._isNew = false;\r\n this._modified = value;\r\n this._original = this._model.helpers.cloneDocument(value);\r\n return this;\r\n });\r\n }).nodeify(callback);\r\n }\r\n\r\n /**\r\n * Updates this instance to match the latest document available in the backing collection\r\n * @param {function(Error, IInstance)} callback A callback which is triggered when the update completes\r\n * @returns {Promise}\r\n */\r\n update(callback?: General.Callback): Bluebird {\r\n return this.refresh(callback);\r\n }\r\n\r\n /**\r\n * Updates this instance to match the latest document available in the backing collection\r\n * @param {function(Error, IInstance)} callback A callback which is triggered when the update completes\r\n * @returns {Promise}\r\n */\r\n refresh(callback?: General.Callback): Bluebird {\r\n let conditions = { _id: this._original._id };\r\n\r\n return Bluebird.resolve().then(() => {\r\n return new Bluebird((resolve, reject) => {\r\n this._model.collection.find(conditions).limit(1).next((err: Error, doc: any) => {\r\n if (err) return reject(err);\r\n return resolve(doc);\r\n });\r\n });\r\n }).then((newDocument) => {\r\n if (!newDocument) {\r\n this._isPartial = true;\r\n this._isNew = true;\r\n this._original = this._model.helpers.cloneDocument(this._modified);\r\n return >this;\r\n }\r\n\r\n return this._model.handlers.documentReceived(conditions, newDocument, (doc) => {\r\n this._isNew = false;\r\n this._isPartial = false;\r\n this._original = doc;\r\n this._modified = this._model.helpers.cloneDocument(doc);\r\n\r\n return this;\r\n });\r\n }).nodeify(callback);\r\n }\r\n\r\n /**\r\n * Removes this instance's document from the backing collection\r\n * @param {function(Error, IInstance)} callback A callback which is triggered when the operation completes\r\n * @returns {Promise}\r\n */\r\n delete(callback?: General.Callback): Bluebird {\r\n return this.remove(callback);\r\n }\r\n\r\n /**\r\n * Removes this instance's document from the backing collection\r\n * @param {function(Error, IInstance)} callback A callback which is triggered when the operation completes\r\n * @returns {Promise}\r\n */\r\n remove(callback?: General.Callback): Bluebird {\r\n let conditions = { _id: this._original._id };\r\n\r\n return Bluebird.resolve().then(() => {\r\n if (this._isNew) return 0;\r\n return new Bluebird((resolve, reject) => {\r\n this._model.collection.deleteOne(conditions, { w: \"majority\" }, (err: Error, removed?: any) => {\r\n if (err) return reject(err);\r\n return resolve(removed);\r\n });\r\n });\r\n }).then((removed) => {\r\n if (removed) return this._model.cache.clear(conditions);\r\n return false;\r\n }).then(() => {\r\n this._isNew = true;\r\n return this;\r\n }).nodeify(callback);\r\n }\r\n\r\n /**\r\n * Retrieves the first element in an enumerable collection which matches the predicate\r\n * @param collection The collection from which to retrieve the element\r\n * @param predicate The function which determines whether to select an element\r\n * @returns The first element in the array which matched the predicate.\r\n */\r\n first(collection: T[], predicate: General.Predicate): T;\r\n /**\r\n * Retrieves the first element in an enumerable collection which matches the predicate\r\n * @param collection The collection from which to retrieve the element\r\n * @param predicate The function which determines whether to select an element\r\n * @returns The first element in the object which matched the predicate.\r\n */\r\n first(collection: { [key: string]: T }, predicate: General.Predicate): T;\r\n first(collection: T[]| { [key: string]: T }, predicate: General.Predicate): T {\r\n let result = null;\r\n\r\n _.each(collection, (value: T, key) => {\r\n if (predicate.call(this, value, key)) {\r\n result = value;\r\n return false;\r\n }\r\n });\r\n\r\n return result;\r\n }\r\n\r\n /**\r\n * Retrieves a number of elements from an enumerable collection which match the predicate\r\n * @param collection The collection from which elements will be plucked\r\n * @param predicate The function which determines the elements to be plucked\r\n * @returns A new array containing the elements in the array which matched the predicate.\r\n */\r\n select(collection: T[], predicate: General.Predicate): T[];\r\n /**\r\n * Retrieves a number of elements from an enumerable collection which match the predicate\r\n * @param collection The collection from which elements will be plucked\r\n * @param predicate The function which determines the elements to be plucked\r\n * @returns An object with the properties from the collection which matched the predicate.\r\n */\r\n select(collection: { [key: string]: T }, predicate: General.Predicate): { [key: string]: T };\r\n select(collection: T[]| { [key: string]: T }, predicate: General.Predicate): any {\r\n let isArray = Array.isArray(collection);\r\n let results: any = isArray ? [] : {};\r\n\r\n _.each(collection, (value: T, key) => {\r\n if (predicate.call(this, value, key)) {\r\n if (isArray) results.push(value);\r\n else results[key] = value;\r\n }\r\n });\r\n\r\n return results;\r\n }\r\n\r\n /**\r\n * Gets the JSON representation of this instance\r\n * @returns {TDocument}\r\n */\r\n toJSON(): any {\r\n return this.document;\r\n }\r\n\r\n /**\r\n * Gets a string representation of this instance\r\n * @returns {String}\r\n */\r\n toString(): string {\r\n return JSON.stringify(this.document, null, 2);\r\n }\r\n}"],"sourceRoot":"/source/"} \ No newline at end of file +{"version":3,"sources":["lib/Instance.ts"],"names":[],"mappings":";AASA,2BAAgC,cAAc,CAAC,CAAA;AAE/C,IAAY,CAAC,WAAM,QAAQ,CAAC,CAAA;AAE5B,IAAY,QAAQ,WAAM,UAAU,CAAC,CAAA;AAGrC;;;;;;;;;;;;;GAaG;AACH;IACI;;;;;;;OAOG;IACH,kBAAY,KAAkC,EAAE,QAAmB,EAAE,KAAqB,EAAE,SAA0B;QAT1H,iBAoWC;QA3VwE,qBAAqB,GAArB,YAAqB;QAAE,yBAA0B,GAA1B,iBAA0B;QAClH,IAAI,CAAC,MAAM,GAAG,KAAK,CAAC;QAEpB,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC,KAAK,CAAC;QACtB,IAAI,CAAC,UAAU,GAAG,SAAS,CAAC;QAC5B,IAAI,CAAC,SAAS,GAAG,QAAQ,CAAC;QAC1B,IAAI,CAAC,SAAS,GAAG,KAAK,CAAC,OAAO,CAAC,aAAa,CAAC,QAAQ,CAAC,CAAC;QAEvD,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,OAAO,EAAE,UAAC,MAAc;YACtC,EAAE,CAAC,CAAC,MAAM,CAAC,WAAW,CAAC;gBAAC,MAAM,CAAC,WAAW,CAAC,KAAI,EAAE,KAAK,CAAC,CAAC;QAC5D,CAAC,CAAC,CAAC;IACP,CAAC;IAWD,sBAAI,8BAAQ;QAHZ;;WAEG;aACH;YACI,MAAM,CAAC,IA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,CAAC;QACL,CAAC,CAAC,CAAC;QAEH,MAAM,CAAC,OAAO,CAAC;IACnB,CAAC;IAED;;;OAGG;IACH,yBAAM,GAAN;QACI,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC;IACzB,CAAC;IAED;;;OAGG;IACH,2BAAQ,GAAR;QACI,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,QAAQ,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC;IAClD,CAAC;IA7RD;;OAEG;IACI,eAAM,GAAW;QACpB,GAAG,EAAE,KAAK;KACb,CAAC;IAEF;;OAEG;IACI,mBAAU,GAAuB,8BAAiB,EAAE,CAAC;IAE5D;;OAEG;IACI,mBAAU,GAAe,EAE/B,CAAC;IAOF;;OAEG;IACI,gBAAO,GAA+C,EAAE,CAAC;IAmQpE,eAAC;AAAD,CApWA,AAoWC,IAAA;AApWY,gBAAQ,WAoWpB,CAAA","file":"lib/Instance.js","sourcesContent":["import {Core} from \"./Core\";\r\nimport {Model} from \"./Model\";\r\nimport {Plugin} from \"./Plugins\";\r\nimport {CacheDirector} from \"./CacheDirector\";\r\nimport * as General from \"./General\";\r\nimport * as ModelInterfaces from \"./ModelInterfaces\";\r\nimport * as Index from \"./Index\";\r\nimport {Schema} from \"./Schema\";\r\nimport {Transforms} from \"./Transforms\";\r\nimport {DefaultValidators} from \"./Validators\";\r\n\r\nimport * as _ from \"lodash\";\r\nimport * as MongoDB from \"mongodb\";\r\nimport * as Bluebird from \"bluebird\";\r\nimport * as Skmatc from \"skmatc\";\r\n\r\n/**\r\n * The default Iridium Instance implementation which provides methods for saving, refreshing and\r\n * removing the wrapped document from the collection, as well as integrating with Omnom, our\r\n * built in document diff processor which allows clean, atomic, document updates to be performed\r\n * without needing to write the update queries yourself.\r\n *\r\n * @param TDocument The interface representing the structure of the documents in the collection.\r\n * @param TInstance The type of instance which wraps the documents, generally the subclass of this class.\r\n *\r\n * This class will be subclassed automatically by Iridium to create a model specific instance\r\n * which takes advantage of some of v8's optimizations to boost performance significantly.\r\n * The instance returned by the model, and all of this instance's methods, will be of type\r\n * TInstance - which should represent the merger of TSchema and IInstance for best results.\r\n */\r\nexport class Instance {\r\n /**\r\n * Creates a new instance which represents the given document as a type of model\r\n * @param model The model that dictates the collection the document originated from as well as how validations are performed.\r\n * @param document The document which should be wrapped by this instance\r\n * @param isNew Whether the document is new (doesn't exist in the database) or not\r\n * @param isPartial Whether the document has only a subset of its fields populated\r\n *\r\n */\r\n constructor(model: Model, document: TDocument, isNew: boolean = true, isPartial: boolean = false) {\r\n this._model = model;\r\n\r\n this._isNew = !!isNew;\r\n this._isPartial = isPartial;\r\n this._original = document;\r\n this._modified = model.helpers.cloneDocument(document);\r\n\r\n _.each(model.core.plugins, (plugin: Plugin) => {\r\n if (plugin.newInstance) plugin.newInstance(this, model);\r\n });\r\n }\r\n\r\n private _isNew: boolean;\r\n private _isPartial: boolean;\r\n private _model: Model;\r\n private _original: TDocument;\r\n private _modified: TDocument;\r\n\r\n /**\r\n * Gets the underlying document representation of this instance\r\n */\r\n get document(): TDocument {\r\n return this._modified;\r\n }\r\n\r\n [name: string]: any;\r\n\r\n /**\r\n * A function which is called whenever a new document is in the process of being inserted into the database.\r\n * @param document The document which will be inserted into the database.\r\n */\r\n static onCreating: (document: { _id?: any }) => Promise | PromiseLike | void;\r\n\r\n /**\r\n * A function which is called whenever a document of this type is received from the database, prior to it being\r\n * wrapped by an Instance object.\r\n * @param document The document that was retrieved from the database.\r\n */\r\n static onRetrieved: (document: { _id?: any }) => Promise | PromiseLike | void;\r\n\r\n /**\r\n * A function which is called whenever a new instance has been created to wrap a document.\r\n * @param instance The instance which has been created.\r\n */\r\n static onReady: (instance: Instance<{ _id?: any }, Instance<{ _id?: any }, any>>) => Promise | PromiseLike | void;\r\n\r\n /**\r\n * A function which is called whenever an instance's save() method is called to allow you to interrogate and/or manipulate\r\n * the changes which are being made.\r\n *\r\n * @param instance The instance to which the changes are being made\r\n * @param changes The MongoDB change object describing the changes being made to the document.\r\n */\r\n static onSaving: (instance: Instance<{ _id?: any }, Instance<{ _id?: any }, any>>, changes: any) => Promise | PromiseLike | void;\r\n\r\n /**\r\n * The name of the collection into which documents of this type are stored.\r\n */\r\n static collection: string;\r\n\r\n /**\r\n * The schema used to validate documents of this type before being stored in the database.\r\n */\r\n static schema: Schema = {\r\n _id: false\r\n };\r\n\r\n /**\r\n * Additional which should be made available for use in the schema definition for this instance.\r\n */\r\n static validators: Skmatc.Validator[] = DefaultValidators();\r\n\r\n /**\r\n * The transformations which should be applied to properties of documents of this type.\r\n */\r\n static transforms: Transforms = {\r\n\r\n };\r\n\r\n /**\r\n * The cache director used to derive unique cache keys for documents of this type.\r\n */\r\n static cache: CacheDirector;\r\n\r\n /**\r\n * The indexes which should be managed by Iridium for the collection used by this type.\r\n */\r\n static indexes: (Index.Index | Index.IndexSpecification)[] = [];\r\n\r\n /**\r\n * Saves any changes to this instance, using the built in diff algorithm to write the update query.\r\n * @param {function(Error, IInstance)} callback A callback which is triggered when the save operation completes\r\n * @returns {Promise}\r\n */\r\n save(callback?: General.Callback): Bluebird;\r\n /**\r\n * Saves the given changes to this instance and updates the instance to match the latest database document.\r\n * @param {Object} changes The MongoDB changes object to be used when updating this instance\r\n * @param {function(Error, IInstance)} callback A callback which is triggered when the save operation completes\r\n * @returns {Promise}\r\n */\r\n save(changes: Object, callback?: General.Callback): Bluebird;\r\n /**\r\n * Saves the given changes to this instance and updates the instance to match the latest database document.\r\n * @param {Object} conditions The conditions under which the update will take place - these will be merged with an _id query\r\n * @param {Object} changes The MongoDB changes object to be used when updating this instance\r\n * @param {function(Error, IInstance)} callback A callback which is triggered when the save operation completes\r\n * @returns {Promise}\r\n */\r\n save(conditions: Object, changes: Object, callback?: General.Callback): Bluebird;\r\n save(...args: any[]): Bluebird {\r\n let callback: General.Callback = null;\r\n let changes: any = null;\r\n let conditions: any = {};\r\n\r\n Array.prototype.slice.call(args, 0).reverse().forEach((arg) => {\r\n if (typeof arg == \"function\") callback = arg;\r\n else if (typeof arg == \"object\") {\r\n if (!changes) changes = arg;\r\n else conditions = arg;\r\n }\r\n });\r\n\r\n return Bluebird.resolve().then(() => {\r\n conditions = this._model.helpers.cloneConditions(conditions);\r\n _.merge(conditions, { _id: this._modified._id });\r\n\r\n if (!changes) {\r\n let validation = this._model.helpers.validate(this._modified);\r\n if (validation.failed) return Bluebird.reject(validation.error).bind(this).nodeify(callback);\r\n\r\n let original = this._model.helpers.cloneDocument(this._original);\r\n let modified = this._model.helpers.cloneDocument(this._modified);\r\n \r\n modified = this._model.helpers.transformToDB(modified, { document: true }); \r\n\r\n changes = this._model.helpers.diff(original, modified);\r\n }\r\n\r\n if (!_.keys(changes).length) return null;\r\n\r\n return changes;\r\n }).then((changes) => {\r\n if (!changes && !this._isNew) return changes;\r\n return this._model.handlers.savingDocument(this, changes).then(() => changes);\r\n }).then((changes) => {\r\n if (!changes && !this._isNew) return false;\r\n\r\n if (this._isNew) {\r\n return new Bluebird((resolve, reject) => {\r\n this._model.collection.insertOne(this._modified, { w: \"majority\" }, (err, doc) => {\r\n if (err) return reject(err);\r\n return resolve(!!doc);\r\n });\r\n });\r\n } else {\r\n return new Bluebird((resolve: (changed: boolean) => void, reject) => {\r\n this._model.collection.updateOne(conditions, changes, { w: \"majority\" }, (err, changed) => {\r\n if(err) {\r\n err[\"conditions\"] = conditions;\r\n err[\"changes\"] = changes;\r\n return reject(err);\r\n }\r\n\r\n return resolve(!!changed.modifiedCount);\r\n });\r\n });\r\n }\r\n }).catch(err => {\r\n err[\"original\"] = this._original;\r\n err[\"modified\"] = this._modified;\r\n return Bluebird.reject(err);\r\n }).then((changed: boolean) => {\r\n conditions = { _id: this._modified._id };\r\n if (!changed) return this._modified;\r\n\r\n return new Bluebird((resolve, reject) => {\r\n this._model.collection.find(conditions).limit(1).next((err: Error, latest) => {\r\n if (err) return reject(err);\r\n return resolve(latest);\r\n });\r\n });\r\n }).then((latest: TDocument) => {\r\n if(!latest) {\r\n this._isNew = true;\r\n this._original = this._model.helpers.cloneDocument(this._modified);\r\n return Bluebird.resolve(this);\r\n }\r\n\r\n return this._model.handlers.documentReceived(conditions, latest, (value) => {\r\n this._isPartial = false;\r\n this._isNew = false;\r\n this._modified = value;\r\n this._original = this._model.helpers.cloneDocument(value);\r\n return this;\r\n });\r\n }).nodeify(callback);\r\n }\r\n\r\n /**\r\n * Updates this instance to match the latest document available in the backing collection\r\n * @param {function(Error, IInstance)} callback A callback which is triggered when the update completes\r\n * @returns {Promise}\r\n */\r\n update(callback?: General.Callback): Bluebird {\r\n return this.refresh(callback);\r\n }\r\n\r\n /**\r\n * Updates this instance to match the latest document available in the backing collection\r\n * @param {function(Error, IInstance)} callback A callback which is triggered when the update completes\r\n * @returns {Promise}\r\n */\r\n refresh(callback?: General.Callback): Bluebird {\r\n let conditions = { _id: this._original._id };\r\n\r\n return Bluebird.resolve().then(() => {\r\n return new Bluebird((resolve, reject) => {\r\n this._model.collection.find(conditions).limit(1).next((err: Error, doc: any) => {\r\n if (err) return reject(err);\r\n return resolve(doc);\r\n });\r\n });\r\n }).then((newDocument) => {\r\n if (!newDocument) {\r\n this._isPartial = true;\r\n this._isNew = true;\r\n this._original = this._model.helpers.cloneDocument(this._modified);\r\n return >this;\r\n }\r\n\r\n return this._model.handlers.documentReceived(conditions, newDocument, (doc) => {\r\n this._isNew = false;\r\n this._isPartial = false;\r\n this._original = doc;\r\n this._modified = this._model.helpers.cloneDocument(doc);\r\n\r\n return this;\r\n });\r\n }).nodeify(callback);\r\n }\r\n\r\n /**\r\n * Removes this instance's document from the backing collection\r\n * @param {function(Error, IInstance)} callback A callback which is triggered when the operation completes\r\n * @returns {Promise}\r\n */\r\n delete(callback?: General.Callback): Bluebird {\r\n return this.remove(callback);\r\n }\r\n\r\n /**\r\n * Removes this instance's document from the backing collection\r\n * @param {function(Error, IInstance)} callback A callback which is triggered when the operation completes\r\n * @returns {Promise}\r\n */\r\n remove(callback?: General.Callback): Bluebird {\r\n let conditions = { _id: this._original._id };\r\n\r\n return Bluebird.resolve().then(() => {\r\n if (this._isNew) return 0;\r\n return new Bluebird((resolve, reject) => {\r\n this._model.collection.deleteOne(conditions, { w: \"majority\" }, (err: Error, removed?: any) => {\r\n if (err) return reject(err);\r\n return resolve(removed);\r\n });\r\n });\r\n }).then((removed) => {\r\n if (removed) return this._model.cache.clear(conditions);\r\n return false;\r\n }).then(() => {\r\n this._isNew = true;\r\n return this;\r\n }).nodeify(callback);\r\n }\r\n\r\n /**\r\n * Retrieves the first element in an enumerable collection which matches the predicate\r\n * @param collection The collection from which to retrieve the element\r\n * @param predicate The function which determines whether to select an element\r\n * @returns The first element in the array which matched the predicate.\r\n */\r\n first(collection: T[], predicate: General.Predicate): T;\r\n /**\r\n * Retrieves the first element in an enumerable collection which matches the predicate\r\n * @param collection The collection from which to retrieve the element\r\n * @param predicate The function which determines whether to select an element\r\n * @returns The first element in the object which matched the predicate.\r\n */\r\n first(collection: { [key: string]: T }, predicate: General.Predicate): T;\r\n first(collection: T[]| { [key: string]: T }, predicate: General.Predicate): T {\r\n let result = null;\r\n\r\n _.each(collection, (value: T, key) => {\r\n if (predicate.call(this, value, key)) {\r\n result = value;\r\n return false;\r\n }\r\n });\r\n\r\n return result;\r\n }\r\n\r\n /**\r\n * Retrieves a number of elements from an enumerable collection which match the predicate\r\n * @param collection The collection from which elements will be plucked\r\n * @param predicate The function which determines the elements to be plucked\r\n * @returns A new array containing the elements in the array which matched the predicate.\r\n */\r\n select(collection: T[], predicate: General.Predicate): T[];\r\n /**\r\n * Retrieves a number of elements from an enumerable collection which match the predicate\r\n * @param collection The collection from which elements will be plucked\r\n * @param predicate The function which determines the elements to be plucked\r\n * @returns An object with the properties from the collection which matched the predicate.\r\n */\r\n select(collection: { [key: string]: T }, predicate: General.Predicate): { [key: string]: T };\r\n select(collection: T[]| { [key: string]: T }, predicate: General.Predicate): any {\r\n let isArray = Array.isArray(collection);\r\n let results: any = isArray ? [] : {};\r\n\r\n _.each(collection, (value: T, key) => {\r\n if (predicate.call(this, value, key)) {\r\n if (isArray) results.push(value);\r\n else results[key] = value;\r\n }\r\n });\r\n\r\n return results;\r\n }\r\n\r\n /**\r\n * Gets the JSON representation of this instance\r\n * @returns {TDocument}\r\n */\r\n toJSON(): any {\r\n return this.document;\r\n }\r\n\r\n /**\r\n * Gets a string representation of this instance\r\n * @returns {String}\r\n */\r\n toString(): string {\r\n return JSON.stringify(this.document, null, 2);\r\n }\r\n}"],"sourceRoot":"/source/"} \ No newline at end of file diff --git a/dist/lib/ModelSpecificInstance.js b/dist/lib/ModelSpecificInstance.js index 146b055..65ecf02 100644 --- a/dist/lib/ModelSpecificInstance.js +++ b/dist/lib/ModelSpecificInstance.js @@ -1,5 +1,9 @@ "use strict"; -var util = require("util"); +var __extends = (this && this.__extends) || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +}; var _ = require("lodash"); /** * Creates a new subclass of the given instanceType which correctly performs property transforms @@ -14,13 +18,21 @@ var _ = require("lodash"); * @internal */ function ModelSpecificInstance(model, instanceType) { - var constructor = function (doc, isNew, isPartial) { - instanceType.call(this, model, doc, isNew, isPartial); - }; - util.inherits(constructor, instanceType); + var instanceTypeConstructor = instanceType; + var virtualClass = (function (_super) { + __extends(class_1, _super); + function class_1() { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i - 0] = arguments[_i]; + } + _super.apply(this, [model].concat(args)); + } + return class_1; + }(instanceTypeConstructor)); _.each(Object.keys(model.schema), function (property) { if (model.transforms.hasOwnProperty(property)) { - return Object.defineProperty(constructor.prototype, property, { + return Object.defineProperty(virtualClass.prototype, property, { get: function () { return model.transforms[property].fromDB(this._modified[property], property, model); }, @@ -31,7 +43,7 @@ function ModelSpecificInstance(model, instanceType) { configurable: true }); } - Object.defineProperty(constructor.prototype, property, { + Object.defineProperty(virtualClass.prototype, property, { get: function () { return this._modified[property]; }, @@ -41,7 +53,7 @@ function ModelSpecificInstance(model, instanceType) { enumerable: true }); }); - return constructor; + return virtualClass; } exports.ModelSpecificInstance = ModelSpecificInstance; diff --git a/dist/lib/ModelSpecificInstance.js.map b/dist/lib/ModelSpecificInstance.js.map index f61fdf8..d975ddb 100644 --- a/dist/lib/ModelSpecificInstance.js.map +++ b/dist/lib/ModelSpecificInstance.js.map @@ -1 +1 @@ -{"version":3,"sources":["lib/ModelSpecificInstance.ts"],"names":[],"mappings":";AAGA,IAAY,IAAI,WAAM,MAAM,CAAC,CAAA;AAC7B,IAAY,CAAC,WAAM,QAAQ,CAAC,CAAA;AAE5B;;;;;;;;;;;GAWG;AACH,+BAAkF,KAAkC,EAAE,YAA0D;IAC5K,IAAI,WAAW,GAAG,UAAU,GAAc,EAAE,KAAe,EAAE,SAAmB;QAC5E,YAAY,CAAC,IAAI,CAAC,IAAI,EAAE,KAAK,EAAE,GAAG,EAAE,KAAK,EAAE,SAAS,CAAC,CAAC;IAC1D,CAAC,CAAC;IAEF,IAAI,CAAC,QAAQ,CAAC,WAAW,EAAE,YAAY,CAAC,CAAC;IAEzC,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,EAAC,UAAC,QAAQ;QACtC,EAAE,CAAC,CAAC,KAAK,CAAC,UAAU,CAAC,cAAc,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC;YAC5C,MAAM,CAAC,MAAM,CAAC,cAAc,CAAC,WAAW,CAAC,SAAS,EAAE,QAAQ,EAAE;gBAC1D,GAAG,EAAE;oBACD,MAAM,CAAC,KAAK,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,EAAE,QAAQ,EAAE,KAAK,CAAC,CAAC;gBACxF,CAAC;gBACD,GAAG,EAAE,UAAU,KAAK;oBAChB,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,GAAG,KAAK,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC,IAAI,CAAC,KAAK,EAAE,QAAQ,EAAE,KAAK,CAAC,CAAC;gBACvF,CAAC;gBACD,UAAU,EAAE,IAAI;gBAChB,YAAY,EAAE,IAAI;aACrB,CAAC,CAAC;QACP,CAAC;QAED,MAAM,CAAC,cAAc,CAAC,WAAW,CAAC,SAAS,EAAE,QAAQ,EAAE;YACnD,GAAG,EAAE;gBACD,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAC;YACpC,CAAC;YACD,GAAG,EAAE,UAAU,KAAK;gBAChB,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,GAAG,KAAK,CAAC;YACrC,CAAC;YACD,UAAU,EAAE,IAAI;SACnB,CAAC,CAAC;IACP,CAAC,CAAC,CAAC;IAEH,MAAM,CAAM,WAAW,CAAC;AAC5B,CAAC;AAjCe,6BAAqB,wBAiCpC,CAAA","file":"lib/ModelSpecificInstance.js","sourcesContent":["import {Model} from \"./Model\";\r\nimport {InstanceImplementation} from \"./InstanceInterface\";\r\nimport {ModelSpecificInstanceConstructor} from \"./ModelInterfaces\";\r\nimport * as util from \"util\";\r\nimport * as _ from \"lodash\";\r\n\r\n/**\r\n * Creates a new subclass of the given instanceType which correctly performs property transforms\r\n * and associates the instance with the correct model when instantiated.\r\n *\r\n * @param TDocument The interface representing the structure of the documents found in the database.\r\n * @param TInstance The interface or class representing the documents after they have been wrapped in an instance.\r\n *\r\n * @param model The model which instances should be associated with when the resulting constructor is used.\r\n * @param instanceType The constructor used to create new instances of type TInstance.\r\n *\r\n * @internal\r\n */\r\nexport function ModelSpecificInstance(model: Model, instanceType: InstanceImplementation): ModelSpecificInstanceConstructor {\r\n let constructor = function (doc: TDocument, isNew?: boolean, isPartial?: boolean) {\r\n instanceType.call(this, model, doc, isNew, isPartial);\r\n };\r\n\r\n util.inherits(constructor, instanceType);\r\n\r\n _.each(Object.keys(model.schema),(property) => {\r\n if (model.transforms.hasOwnProperty(property)) {\r\n return Object.defineProperty(constructor.prototype, property, {\r\n get: function () {\r\n return model.transforms[property].fromDB(this._modified[property], property, model);\r\n },\r\n set: function (value) {\r\n this._modified[property] = model.transforms[property].toDB(value, property, model);\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n }\r\n\r\n Object.defineProperty(constructor.prototype, property, {\r\n get: function () {\r\n return this._modified[property];\r\n },\r\n set: function (value) {\r\n this._modified[property] = value;\r\n },\r\n enumerable: true\r\n });\r\n });\r\n\r\n return constructor;\r\n}\r\n"],"sourceRoot":"/source/"} \ No newline at end of file +{"version":3,"sources":["lib/ModelSpecificInstance.ts"],"names":[],"mappings":";;;;;;AAIA,IAAY,CAAC,WAAM,QAAQ,CAAC,CAAA;AAE5B;;;;;;;;;;;GAWG;AACH,+BAAkF,KAAkC,EAAE,YAA0D;IAC5K,IAAM,uBAAuB,GAA6B,YAAY,CAAC;IAEvE,IAAI,YAAY,GAAG;QAAc,2BAAuB;QACpD;YAAY,cAAO;iBAAP,WAAO,CAAP,sBAAO,CAAP,IAAO;gBAAP,6BAAO;;YACf,oBAAM,KAAK,SAAK,IAAI,EAAC,CAAC;QAC1B,CAAC;QACL,cAAC;IAAD,CAJmB,AAIlB,CAJgC,uBAAuB,EAIvD,CAAA;IAED,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,EAAC,UAAC,QAAQ;QACtC,EAAE,CAAC,CAAC,KAAK,CAAC,UAAU,CAAC,cAAc,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC;YAC5C,MAAM,CAAC,MAAM,CAAC,cAAc,CAAC,YAAY,CAAC,SAAS,EAAE,QAAQ,EAAE;gBAC3D,GAAG,EAAE;oBACD,MAAM,CAAC,KAAK,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,EAAE,QAAQ,EAAE,KAAK,CAAC,CAAC;gBACxF,CAAC;gBACD,GAAG,EAAE,UAAU,KAAK;oBAChB,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,GAAG,KAAK,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC,IAAI,CAAC,KAAK,EAAE,QAAQ,EAAE,KAAK,CAAC,CAAC;gBACvF,CAAC;gBACD,UAAU,EAAE,IAAI;gBAChB,YAAY,EAAE,IAAI;aACrB,CAAC,CAAC;QACP,CAAC;QAED,MAAM,CAAC,cAAc,CAAC,YAAY,CAAC,SAAS,EAAE,QAAQ,EAAE;YACpD,GAAG,EAAE;gBACD,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAC;YACpC,CAAC;YACD,GAAG,EAAE,UAAU,KAAK;gBAChB,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,GAAG,KAAK,CAAC;YACrC,CAAC;YACD,UAAU,EAAE,IAAI;SACnB,CAAC,CAAC;IACP,CAAC,CAAC,CAAC;IAEH,MAAM,CAAM,YAAY,CAAC;AAC7B,CAAC;AAnCe,6BAAqB,wBAmCpC,CAAA","file":"lib/ModelSpecificInstance.js","sourcesContent":["import {Model} from \"./Model\";\r\nimport {InstanceImplementation} from \"./InstanceInterface\";\r\nimport {ModelSpecificInstanceConstructor} from \"./ModelInterfaces\";\r\nimport * as util from \"util\";\r\nimport * as _ from \"lodash\";\r\n\r\n/**\r\n * Creates a new subclass of the given instanceType which correctly performs property transforms\r\n * and associates the instance with the correct model when instantiated.\r\n *\r\n * @param TDocument The interface representing the structure of the documents found in the database.\r\n * @param TInstance The interface or class representing the documents after they have been wrapped in an instance.\r\n *\r\n * @param model The model which instances should be associated with when the resulting constructor is used.\r\n * @param instanceType The constructor used to create new instances of type TInstance.\r\n *\r\n * @internal\r\n */\r\nexport function ModelSpecificInstance(model: Model, instanceType: InstanceImplementation): ModelSpecificInstanceConstructor {\r\n const instanceTypeConstructor = instanceType;\r\n \r\n let virtualClass = class extends instanceTypeConstructor {\r\n constructor(...args) {\r\n super(model, ...args);\r\n }\r\n }\r\n\r\n _.each(Object.keys(model.schema),(property) => {\r\n if (model.transforms.hasOwnProperty(property)) {\r\n return Object.defineProperty(virtualClass.prototype, property, {\r\n get: function () {\r\n return model.transforms[property].fromDB(this._modified[property], property, model);\r\n },\r\n set: function (value) {\r\n this._modified[property] = model.transforms[property].toDB(value, property, model);\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n }\r\n\r\n Object.defineProperty(virtualClass.prototype, property, {\r\n get: function () {\r\n return this._modified[property];\r\n },\r\n set: function (value) {\r\n this._modified[property] = value;\r\n },\r\n enumerable: true\r\n });\r\n });\r\n\r\n return virtualClass;\r\n}\r\n\r\ninterface InstanceConstructor {\r\n new(...args: any[]): this;\r\n prototype: any;\r\n}"],"sourceRoot":"/source/"} \ No newline at end of file diff --git a/dist/main.d.ts b/dist/main.d.ts index 752ec6e..a098df5 100644 --- a/dist/main.d.ts +++ b/dist/main.d.ts @@ -1,2672 +1,1851 @@ // Generated by typings -// Source: https://raw.githubusercontent.com/typed-typings/npm-bluebird/cfd8d3ac544649768a437b5f707fedbe4a60cd18/bluebird.d.ts -declare module '~iridium~bluebird/bluebird' { -// Type definitions for Bluebird v3.x.x -// Project: http://bluebirdjs.com - -class Bluebird implements Bluebird.Thenable, Bluebird.Inspection { - /** - * Create a new promise. The passed in function will receive functions `resolve` and `reject` as its arguments which can be called to seal the fate of the created promise. - */ - constructor(callback: (resolve: (thenableOrResult: R | Bluebird.Thenable) => void, reject: (error: any) => void) => void); +// Source: https://raw.githubusercontent.com/typed-typings/npm-es6-promise/fb04188767acfec1defd054fc8024fafa5cd4de7/dist/es6-promise.d.ts +declare module '~iridium~mongodb~es6-promise/dist/es6-promise' { +export interface Thenable { + then (onFulfilled?: (value: R) => U | Thenable, onRejected?: (error: any) => U | Thenable): Thenable; + then (onFulfilled?: (value: R) => U | Thenable, onRejected?: (error: any) => void): Thenable; +} +export class Promise implements Thenable { /** - * Promises/A+ `.then()`. Returns a new promise chained from this promise. The new promise will be rejected or resolved dedefer on the passed `fulfilledHandler`, `rejectedHandler` and the state of this promise. + * If you call resolve in the body of the callback passed to the constructor, + * your promise is fulfilled with result object passed to resolve. + * If you call reject your promise is rejected with the object passed to resolve. + * For consistency and debugging (eg stack traces), obj should be an instanceof Error. + * Any errors thrown in the constructor callback will be implicitly passed to reject(). */ - then(onFulfill: (value: R) => U | Bluebird.Thenable, onReject?: (error: any) => U | Bluebird.Thenable): Bluebird; - then(onFulfill: (value: R) => U | Bluebird.Thenable, onReject?: (error: any) => void | Bluebird.Thenable): Bluebird; + constructor (callback: (resolve : (value?: R | Thenable) => void, reject: (error?: any) => void) => void); /** - * This is a catch-all exception handler, shortcut for calling `.then(null, handler)` on this promise. Any exception happening in a `.then`-chain will propagate to nearest `.catch` handler. + * onFulfilled is called when/if "promise" resolves. onRejected is called when/if "promise" rejects. + * Both are optional, if either/both are omitted the next onFulfilled/onRejected in the chain is called. + * Both callbacks have a single parameter , the fulfillment value or rejection reason. + * "then" returns a new promise equivalent to the value you return from onFulfilled/onRejected after being passed through Promise.resolve. + * If an error is thrown in the callback, the returned promise rejects with that error. * - * Alias `.caught();` for compatibility with earlier ECMAScript version. + * @param onFulfilled called when/if "promise" resolves + * @param onRejected called when/if "promise" rejects */ - catch(onReject?: (error: any) => R | Bluebird.Thenable | void | Bluebird.Thenable): Bluebird; - catch(onReject?: (error: any) => U | Bluebird.Thenable): Bluebird; + then (onFulfilled?: (value: R) => U | Thenable, onRejected?: (error: any) => U | Thenable): Promise; + then (onFulfilled?: (value: R) => U | Thenable, onRejected?: (error: any) => void): Promise; /** - * This extends `.catch` to work more like catch-clauses in languages like Java or C#. Instead of manually checking `instanceof` or `.name === "SomeError"`, you may specify a number of error constructors which are eligible for this catch handler. The catch handler that is first met that has eligible constructors specified, is the one that will be called. - * - * This method also supports predicate-based filters. If you pass a predicate function instead of an error constructor, the predicate will receive the error as an argument. The return result of the predicate will be used determine whether the error handler should be called. + * Sugar for promise.then(undefined, onRejected) * - * Alias `.caught();` for compatibility with earlier ECMAScript version. + * @param onRejected called when/if "promise" rejects */ - catch(predicate: (error: any) => boolean, onReject: (error: any) => R | Bluebird.Thenable | void | Bluebird.Thenable): Bluebird; - catch(predicate: (error: any) => boolean, onReject: (error: any) => U | Bluebird.Thenable): Bluebird; - catch(ErrorClass: Function, onReject: (error: any) => R | Bluebird.Thenable | void | Bluebird.Thenable): Bluebird; - catch(ErrorClass: Function, onReject: (error: any) => U | Bluebird.Thenable): Bluebird; + catch (onRejected?: (error: any) => U | Thenable): Promise; /** - * Like `.catch` but instead of catching all types of exceptions, it only catches those that don't originate from thrown errors but rather from explicit rejections. + * Make a new promise from the thenable. + * A thenable is promise-like in as far as it has a "then" method. */ - error(onReject: (reason: any) => Bluebird.Thenable): Bluebird; - error(onReject: (reason: any) => U): Bluebird; + static resolve (): Promise; + static resolve (value: R | Thenable): Promise; /** - * Pass a handler that will be called regardless of this promise's fate. Returns a new promise chained from this promise. There are special semantics for `.finally()` in that the final value cannot be modified from the handler. - * - * Alias `.lastly();` for compatibility with earlier ECMAScript version. + * Make a promise that rejects to obj. For consistency and debugging (eg stack traces), obj should be an instanceof Error */ - finally(handler: () => Bluebird.Thenable): Bluebird; - finally(handler: () => U): Bluebird; - - lastly(handler: () => Bluebird.Thenable): Bluebird; - lastly(handler: () => U): Bluebird; + static reject (error: any): Promise; /** - * Create a promise that follows this promise, but is bound to the given `thisArg` value. A bound promise will call its handlers with the bound value set to `this`. Additionally promises derived from a bound promise will also be bound promises with the same `thisArg` binding as the original promise. + * Make a promise that fulfills when every item in the array fulfills, and rejects if (and when) any item rejects. + * the array passed to all can be a mixture of promise-like objects and other objects. + * The fulfillment value is an array (in order) of fulfillment values. The rejection value is the first rejection value. */ - bind(thisArg: any): Bluebird; + static all(values: [T1 | Thenable, T2 | Thenable, T3 | Thenable, T4 | Thenable , T5 | Thenable, T6 | Thenable, T7 | Thenable, T8 | Thenable, T9 | Thenable, T10 | Thenable]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10]>; + static all(values: [T1 | Thenable, T2 | Thenable, T3 | Thenable, T4 | Thenable , T5 | Thenable, T6 | Thenable, T7 | Thenable, T8 | Thenable, T9 | Thenable]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9]>; + static all(values: [T1 | Thenable, T2 | Thenable, T3 | Thenable, T4 | Thenable , T5 | Thenable, T6 | Thenable, T7 | Thenable, T8 | Thenable]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8]>; + static all(values: [T1 | Thenable, T2 | Thenable, T3 | Thenable, T4 | Thenable , T5 | Thenable, T6 | Thenable, T7 | Thenable]): Promise<[T1, T2, T3, T4, T5, T6, T7]>; + static all(values: [T1 | Thenable, T2 | Thenable, T3 | Thenable, T4 | Thenable , T5 | Thenable, T6 | Thenable]): Promise<[T1, T2, T3, T4, T5, T6]>; + static all(values: [T1 | Thenable, T2 | Thenable, T3 | Thenable, T4 | Thenable , T5 | Thenable]): Promise<[T1, T2, T3, T4, T5]>; + static all(values: [T1 | Thenable, T2 | Thenable, T3 | Thenable, T4 | Thenable ]): Promise<[T1, T2, T3, T4]>; + static all(values: [T1 | Thenable, T2 | Thenable, T3 | Thenable]): Promise<[T1, T2, T3]>; + static all(values: [T1 | Thenable, T2 | Thenable]): Promise<[T1, T2]>; + static all(values: [T1 | Thenable]): Promise<[T1]>; + static all(values: Array>): Promise; /** - * Like `.then()`, but any unhandled rejection that ends up here will be thrown as an error. + * Make a Promise that fulfills when any item fulfills, and rejects if any item rejects. */ - done(onFulfilled: (value: R) => Bluebird.Thenable, onRejected: (error: any) => Bluebird.Thenable): void; - done(onFulfilled: (value: R) => Bluebird.Thenable, onRejected?: (error: any) => U): void; - done(onFulfilled: (value: R) => U, onRejected: (error: any) => Bluebird.Thenable): void; - done(onFulfilled?: (value: R) => U, onRejected?: (error: any) => U): void; + static race (promises: (R | Thenable)[]): Promise; +} - /** - * Like `.finally()`, but not called for rejections. - */ - tap(onFulFill: (value: R) => Bluebird.Thenable): Bluebird; - tap(onFulfill: (value: R) => U): Bluebird; +/** + * The polyfill method will patch the global environment (in this case to the Promise name) when called. + */ +export function polyfill (): void; +} +declare module '~iridium~mongodb~es6-promise' { +export * from '~iridium~mongodb~es6-promise/dist/es6-promise'; +} - /** - * Same as calling `Promise.delay(ms, this)`. - */ - delay(ms: number): Bluebird; +// Generated by typings +// Source: https://raw.githubusercontent.com/Think7/typings-mongodb/d4269a9c672ab28a7865b38c8614673e8aecc8e5/mongodb.d.ts +declare module '~iridium~mongodb/mongodb' { +// Type definitions for MongoDB v2.1 +// Project: https://github.com/mongodb/node-mongodb-native/tree/2.1 +// Definitions by: Andrew +// Federico Caselli +// Definitions: https://github.com/Think7/typings-mongodb - /** - * Returns a promise that will be fulfilled with this promise's fulfillment value or rejection reason. - * However, if this promise is not fulfilled or rejected within ms milliseconds, the returned promise - * is rejected with a TimeoutError or the error as the reason. - * - * You may specify a custom error message with the `message` parameter. - */ - timeout(ms: number, message?: string | Error): Bluebird; +// Documentation : http://mongodb.github.io/node-mongodb-native/2.1/api/ - /** - * Register a node-style callback on this promise. When this promise is is either fulfilled or rejected, the node callback will be called back with the node.js convention where error reason is the first argument and success value is the second argument. The error argument will be `null` in case of success. - * If the `callback` argument is not a function, this method does not do anything. - */ - nodeify(callback: (err: any, value?: R) => void, options?: Bluebird.SpreadOption): this; - nodeify(...sink: any[]): this; - asCallback(callback: (err: any, value?: R) => void, options?: Bluebird.SpreadOption): this; - asCallback(...sink: any[]): this; +// Use typings to install this type definition https://github.com/typings/typings - /** - * See if this `promise` has been fulfilled. - */ - isFulfilled(): boolean; +import {EventEmitter} from 'events'; +import {Promise} from '~iridium~mongodb~es6-promise'; - /** - * See if this `promise` has been rejected. - */ - isRejected(): boolean; +// Class documentation : http://mongodb.github.io/node-mongodb-native/2.1/api/MongoClient.html +export class MongoClient { + constructor(); - /** - * See if this `promise` is still defer. - */ - isPending(): boolean; + static connect(uri: string, callback: MongoCallback): void; + static connect(uri: string, options?: MongoClientOptions): Promise; + static connect(uri: string, options: MongoClientOptions, callback: MongoCallback): void; - /** - * See if this `promise` is resolved -> either fulfilled or rejected. - */ - isResolved(): boolean; + connect(uri: string, callback: MongoCallback): void; + connect(uri: string, options?: MongoClientOptions): Promise; + connect(uri: string, options: MongoClientOptions, callback: MongoCallback): void; +} - /** - * Get the fulfillment value of the underlying promise. Throws if the promise isn't fulfilled yet. - * - * throws `TypeError` - */ - value(): R; +export interface MongoCallback { + (error: MongoError, result: T): void; +} - /** - * Get the rejection reason for the underlying promise. Throws if the promise isn't rejected yet. - * - * throws `TypeError` - */ - reason(): any; +// http://mongodb.github.io/node-mongodb-native/2.1/api/MongoError.html +export class MongoError extends Error { + constructor(message: string); + static create(options: Object): MongoError; +} - /** - * Synchronously inspect the state of this `promise`. The `PromiseInspection` will represent the state of the promise as snapshotted at the time of calling `.inspect()`. - */ - inspect(): Bluebird.Inspection; +//http://mongodb.github.io/node-mongodb-native/2.1/api/MongoClient.html#.connect +export interface MongoClientOptions { + uri_decode_auth?: boolean; + db?: DbCreateOptions; + server?: ServerOptions; + replSet?: ReplSetOptions; + mongos?: MongosOptions; + promiseLibrary?: Object; +} - /** - * This is a convenience method for doing: - * - * - * promise.then(function(obj){ - * return obj[propertyName].call(obj, arg...); - * }); - * - */ - call(propertyName: string, ...args: any[]): Bluebird; +// See : http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html +export interface DbCreateOptions { + authSource?: string; + // the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = ‘majority’ or tag acknowledges the write. + w?: number | string; + // set the timeout for waiting for write concern to finish (combines with w option). + wtimeout?: number; + j?: boolean; + // use c++ bson parser. default:false. + native_parser?: boolean; + // force server to create _id fields instead of client. default:false. + forceServerObjectId?: boolean; + serializeFunctions?: boolean; + ignoreUndefined?: boolean; + // peform operations using raw bson buffers. default:false. + raw?: boolean; + // when deserializing a Long will fit it into a Number if it’s smaller than 53 bits. default:true. + promoteLongs?: boolean; + bufferMaxEntries?: number; + // the prefered read preference. use 'ReadPreference' class. + readPreference?: ReadPreference | string; + // custom primary key factory to generate _id values (see Custom primary keys). + pkFactory?: Object; + promiseLibrary?: Object; + readConcern?: { level?: Object }; +} - /** - * This is a convenience method for doing: - * - * - * promise.then(function(obj){ - * return obj[propertyName]; - * }); - * - */ - // TODO: Use something like subtypes (TS roadmap ?) to get the type U automatically. - get(key: string | number): Bluebird; +// See http://mongodb.github.io/node-mongodb-native/2.1/api/ReadPreference.html +export class ReadPreference { + constructor(mode: string, tags: Object); + mode: string; + tags: any; + static PRIMARY: string; + static PRIMARY_PREFERRED: string; + static SECONDARY: string; + static SECONDARY_PREFERRED: string; + static NEAREST: string; + isValid(mode: string): boolean; + static isValid(mode: string): boolean; +} - /** - * Convenience method for: - * - * - * .then(function() { - * return value; - * }); - * - * - * in the case where `value` doesn't change its value. That means `value` is bound at the time of calling `.return()` - * - * Alias `.thenReturn();` for compatibility with earlier ECMAScript version. - */ - return(): Bluebird; - thenReturn(): Bluebird; - return(value: U): Bluebird; - thenReturn(value: U): Bluebird; - - /** - * Convenience method for: - * - * - * .then(function() { - * throw reason; - * }); - * - * Same limitations apply as with `.return()`. - * - * Alias `.thenThrow();` for compatibility with earlier ECMAScript version. - */ - throw(reason: Error): Bluebird; - thenThrow(reason: Error): Bluebird; +//http://mongodb.github.io/node-mongodb-native/2.1/api/Server.html +export interface SocketOptions { + // Reconnect on error. default:false + autoReconnect?: boolean; + // TCP Socket NoDelay option. default:true + noDelay?: boolean; + // TCP KeepAlive on the socket with a X ms delay before start. default:0 + keepAlive?: number; + // TCP Connection timeout setting. default 0 + connectTimeoutMS?: number; + // TCP Socket timeout setting. default 0 + socketTimeoutMS?: number; +} - /** - * Convert to String. - */ - toString(): string; +//http://mongodb.github.io/node-mongodb-native/2.1/api/Server.html +export interface ServerOptions { + // - specify the number of connections in the pool default:5 + poolSize?: number; + ssl?: boolean; + sslValidate?: Object; + checkServerIdentity?: boolean | Function; + sslCA?: Array; + sslCert?: Buffer | string; + sslKey?: Buffer | string; + sslPass?: Buffer | string; + socketOptions?: SocketOptions; + reconnectTries?: number; + reconnectInterval?: number; +} - /** - * This is implicitly called by `JSON.stringify` when serializing the object. Returns a serialized representation of the `Promise`. - */ - toJSON(): Object; +//http://mongodb.github.io/node-mongodb-native/2.1/api/ReplSet.html +export interface ReplSetOptions { + ha?: boolean; + haInterval?: number; + replicaSet?: string; + secondaryAcceptableLatencyMS?: number; + connectWithNoPrimary?: boolean; + // - specify the number of connections in the pool default:5 + poolSize?: number; + ssl?: boolean; + sslValidate?: Object; + checkServerIdentity?: boolean | Function; + sslCA?: Array; + sslCert?: Buffer | string; + sslKey?: Buffer | string; + sslPass?: Buffer | string; + socketOptions?: SocketOptions; +} - /** - * Like calling `.then`, but the fulfillment value or rejection reason is assumed to be an array, which is flattened to the formal parameters of the handlers. - */ - spread(fulfilledHandler: (...values: W[]) => U | Bluebird.Thenable): Bluebird; - spread(fulfilledHandler: Function): Bluebird; - spread(fulfilledHandler: Function): Bluebird; +//http://mongodb.github.io/node-mongodb-native/2.1/api/Mongos.html +export interface MongosOptions { + ha?: boolean; + haInterval?: number; + // - specify the number of connections in the pool default:5 + poolSize?: number; + ssl?: boolean; + sslValidate?: Object; + checkServerIdentity?: boolean | Function; + sslCA?: Array; + sslCert?: Buffer | string; + sslKey?: Buffer | string; + sslPass?: Buffer | string; + socketOptions?: SocketOptions; +} - /** - * Same as calling `Promise.all(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. - */ - // TODO type inference from array-resolving promise? - all(): Bluebird; +// Class documentation : http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html +export class Db extends EventEmitter { + constructor(databaseName: string, serverConfig: Server | ReplSet | Mongos, options?: DbCreateOptions); - /** - * Same as calling `Promise.props(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. - */ - // TODO how to model instance.props()? - props(): Bluebird; + serverConfig: Server | ReplSet | Mongos; + bufferMaxEntries: number; + databaseName: string; + options: any; + native_parser: boolean; + slaveOk: boolean; + writeConcern: any; - /** - * Same as calling `Promise.settle(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. - */ - // TODO type inference from array-resolving promise? - settle(): Bluebird[]>; + // http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html#addUser + addUser(username: string, password: string, callback: MongoCallback): void; + addUser(username: string, password: string, options?: DbAddUserOptions): Promise; + addUser(username: string, password: string, options: DbAddUserOptions, callback: MongoCallback): void; + //http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html#admin + admin(): Admin; + // http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html#authenticate + authenticate(userName: string, password: string, callback: MongoCallback): void; + authenticate(userName: string, password: string, options?: { authMechanism: string }): Promise; + authenticate(userName: string, password: string, options: { authMechanism: string }, callback: MongoCallback): void; + // http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html#close + close(callback: MongoCallback): void; + close(forceClose?: boolean): Promise; + close(forceClose: boolean, callback: MongoCallback): void; + // http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html#collection + collection(name: string): Collection; + collection(name: string, callback: MongoCallback): Collection; + collection(name: string, options: DbCollectionOptions, callback: MongoCallback): Collection; + //http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html#collections + collections(): Promise; + collections(callback: MongoCallback): void; + //http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html#command + command(command: Object, callback: MongoCallback): void; + command(command: Object, options?: { readPreference: ReadPreference | string }): Promise; + command(command: Object, options: { readPreference: ReadPreference | string }, callback: MongoCallback): void; + //http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html#createCollection + createCollection(name: string, callback: MongoCallback): void; + createCollection(name: string, options?: CollectionCreateOptions): Promise; + createCollection(name: string, options: CollectionCreateOptions, callback: MongoCallback): void; + //http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html#createIndex + createIndex(name: string, fieldOrSpec: string | Object, callback: MongoCallback): void; + createIndex(name: string, fieldOrSpec: string | Object, options?: IndexOptions): Promise; + createIndex(name: string, fieldOrSpec: string | Object, options: IndexOptions, callback: MongoCallback): void; + //http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html#db + db(dbName: string): Db; + db(dbName: string, options: { noListener?: boolean, returnNonCachedInstance?: boolean }): Db; + //http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html#dropCollection + dropCollection(name: string): Promise; + dropCollection(name: string, callback: MongoCallback): void; + // http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html#dropDatabase + dropDatabase(): Promise; + dropDatabase(callback: MongoCallback): void; - /** - * Same as calling `Promise.any(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. - */ - // TODO type inference from array-resolving promise? - any(): Bluebird; + //deprecated http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html#ensureIndex + // ensureIndex(collectionName: any, fieldOrSpec: any, options: IndexOptions, callback: Function): void; + //deprecated http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html#eval + // eval(code: any, parameters: any[], options?: any, callback?: MongoCallback): void; - /** - * Same as calling `Promise.some(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. - */ - // TODO type inference from array-resolving promise? - some(count: number): Bluebird; + //http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html#executeDbAdminCommand + executeDbAdminCommand(command: Object, callback: MongoCallback): void; + executeDbAdminCommand(command: Object, options?: { readPreference?: ReadPreference | string, maxTimeMS?: number }): Promise; + executeDbAdminCommand(command: Object, options: { readPreference?: ReadPreference | string, maxTimeMS?: number }, callback: MongoCallback): void; + // http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html#indexInformation + indexInformation(name: string, callback: MongoCallback): void; + indexInformation(name: string, options?: { full?: boolean, readPreference?: ReadPreference | string }): Promise; + indexInformation(name: string, options: { full?: boolean, readPreference?: ReadPreference | string }, callback: MongoCallback): void; + //http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html#listCollections + listCollections(filter: { name?: string }, options?: { batchSize?: number, readPreference?: ReadPreference | string }): CommandCursor; + //http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html#logout + logout(callback: MongoCallback): void; + logout(options?: { dbName?: string }): Promise; + logout(options: { dbName?: string }, callback: MongoCallback): void; + //http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html#open + open(): Promise; + open(callback: MongoCallback): void; + //http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html#removeUser + removeUser(username: string, callback: MongoCallback): void; + removeUser(username: string, options?: { w?: number | string, wtimeout?: number, j?: boolean }): Promise; + removeUser(username: string, options: { w?: number | string, wtimeout?: number, j?: boolean }, callback: MongoCallback): void; + // http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html#renameCollection + renameCollection(fromCollection: string, toCollection: string, callback: MongoCallback): void; + renameCollection(fromCollection: string, toCollection: string, options?: { dropTarget?: boolean }): Promise; + renameCollection(fromCollection: string, toCollection: string, options: { dropTarget?: boolean }, callback: MongoCallback): void; + // http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html#stats + stats(callback: MongoCallback): void; + stats(options?: { scale?: number }): Promise; + stats(options: { scale?: number }, callback: MongoCallback): void; +} - /** - * Same as calling `Promise.race(thisPromise, count)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. - */ - // TODO type inference from array-resolving promise? - race(): Bluebird; - /** - * Same as calling `Bluebird.map(thisPromise, mapper)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. - */ - // TODO type inference from array-resolving promise? - map(mapper: (item: Q, index: number, arrayLength: number) => Bluebird.Thenable, options?: Bluebird.ConcurrencyOption): Bluebird; - map(mapper: (item: Q, index: number, arrayLength: number) => U, options?: Bluebird.ConcurrencyOption): Bluebird; - /** - * Same as calling `Promise.reduce(thisPromise, Function reducer, initialValue)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. - */ - // TODO type inference from array-resolving promise? - reduce(reducer: (memo: U, item: Q, index: number, arrayLength: number) => Bluebird.Thenable, initialValue?: U): Bluebird; - reduce(reducer: (memo: U, item: Q, index: number, arrayLength: number) => U, initialValue?: U): Bluebird; +// Deprecated http://mongodb.github.io/node-mongodb-native/2.1/api/Server.html +export class Server extends EventEmitter { + constructor(host: string, port: number, options?: ServerOptions); - /** - * Same as calling ``Promise.filter(thisPromise, filterer)``. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. - */ - // TODO type inference from array-resolving promise? - filter(filterer: (item: U, index: number, arrayLength: number) => Bluebird.Thenable, options?: Bluebird.ConcurrencyOption): Bluebird; - filter(filterer: (item: U, index: number, arrayLength: number) => boolean, options?: Bluebird.ConcurrencyOption): Bluebird; + connections(): Array; +} - /** - * Same as calling ``Bluebird.each(thisPromise, iterator)``. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. - */ - each(iterator: (item: R, index: number, arrayLength: number) => U | Bluebird.Thenable): Bluebird; +// Deprecated http://mongodb.github.io/node-mongodb-native/2.1/api/ReplSet.html +export class ReplSet extends EventEmitter { + constructor(servers: Array, options?: ReplSetOptions); - /** - * Start the chain of promises with `Promise.try`. Any synchronous exceptions will be turned into rejections on the returned promise. - * - * Note about second argument: if it's specifically a true array, its values become respective arguments for the function call. Otherwise it is passed as is as the first argument for the function call. - * - * Alias for `attempt();` for compatibility with earlier ECMAScript version. - */ - static try(fn: () => Bluebird.Thenable): Bluebird; - static try(fn: () => R): Bluebird; + connections(): Array; +} - static attempt(fn: () => Bluebird.Thenable): Bluebird; - static attempt(fn: () => R): Bluebird; +// Deprecated http://mongodb.github.io/node-mongodb-native/2.1/api/ReplSet.html +export class Mongos extends EventEmitter { + constructor(servers: Array, options?: MongosOptions); - /** - * Returns a new function that wraps the given function `fn`. The new function will always return a promise that is fulfilled with the original functions return values or rejected with thrown exceptions from the original function. - * This method is convenient when a function can sometimes return synchronously or throw synchronously. - */ - static method(fn: Function): Function; + connections(): Array; +} +// http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html#addUser +export interface DbAddUserOptions { + w?: string | number; + wtimeout?: number; + j?: boolean; + customData?: Object; + roles?: Object[]; +} - /** - * Create a promise that is resolved with the given `value`. If `value` is a thenable or promise, the returned promise will assume its state. - */ - static resolve(): Bluebird; - static resolve(value: Bluebird.Thenable): Bluebird; - static resolve(value: R): Bluebird; +//http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html#createCollection +export interface CollectionCreateOptions { + w?: number | string; + wtimeout?: number; + j?: boolean; + raw?: boolean; + pkFactory?: Object; + readPreference?: ReadPreference | string; + serializeFunctions?: boolean; + strict?: boolean; + capped?: boolean; + size?: number; + max?: number; + autoIndexId?: boolean; +} - /** - * Create a promise that is rejected with the given `reason`. - */ - static reject(reason: any): Bluebird; - static reject(reason: any): Bluebird; +// http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html#collection +export interface DbCollectionOptions { + w?: number | string; + wtimeout?: number; + j?: boolean; + raw?: boolean; + pkFactory?: Object; + readPreference?: ReadPreference | string; + serializeFunctions?: boolean; + strict?: boolean; + readConcern?: { level: Object }; +} - /** - * Create a promise with undecided fate and return a `PromiseResolver` to control it. See resolution?: Promise(#promise-resolution). - */ - static defer(): Bluebird.Resolver; +//http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html#createIndex +export interface IndexOptions { + // The write concern. + w?: number | string; + // The write concern timeout. + wtimeout?: number; + // Specify a journal write concern. + j?: boolean; + // Creates an unique index. + unique?: boolean; + // Creates a sparse index. + sparse?: boolean; + // Creates the index in the background, yielding whenever possible. + background?: boolean; + // A unique index cannot be created on a key that has pre-existing duplicate values. + // If you would like to create the index anyway, keeping the first document the database indexes and + // deleting all subsequent documents that have duplicate value + dropDups?: boolean; + // For geo spatial indexes set the lower bound for the co-ordinates. + min?: number; + // For geo spatial indexes set the high bound for the co-ordinates. + max?: number; + // Specify the format version of the indexes. + v?: number; + // Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) + expireAfterSeconds?: number; + // Override the auto generated index name (useful if the resulting name is larger than 128 bytes) + name?: string; +} - /** - * Cast the given `value` to a trusted promise. If `value` is already a trusted `Promise`, it is returned as is. If `value` is not a thenable, a fulfilled is: Promise returned with `value` as its fulfillment value. If `value` is a thenable (Promise-like object, like those returned by jQuery's `$.ajax`), returns a trusted that: Promise assimilates the state of the thenable. - */ - static cast(value: Bluebird.Thenable): Bluebird; - static cast(value: R): Bluebird; +// http://mongodb.github.io/node-mongodb-native/2.1/api/Admin.html +export interface Admin { + // http://mongodb.github.io/node-mongodb-native/2.1/api/Admin.html#addUser + addUser(username: string, password: string, callback: MongoCallback): void; + addUser(username: string, password: string, options?: AddUserOptions): Promise; + addUser(username: string, password: string, options: AddUserOptions, callback: MongoCallback): void; + //http://mongodb.github.io/node-mongodb-native/2.1/api/Admin.html#authenticate + authenticate(username: string, callback: MongoCallback): void; + authenticate(username: string, password?: string): Promise; + authenticate(username: string, password: string, callback: MongoCallback): void; + //http://mongodb.github.io/node-mongodb-native/2.1/api/Admin.html#buildInfo + buildInfo(): Promise; + buildInfo(callback: MongoCallback): void; + //http://mongodb.github.io/node-mongodb-native/2.1/api/Admin.html#command + command(command: Object, callback: MongoCallback): void; + command(command: Object, options?: { readPreference?: ReadPreference | string, maxTimeMS?: number }): Promise; + command(command: Object, options: { readPreference?: ReadPreference | string, maxTimeMS?: number }, callback: MongoCallback): void; + //http://mongodb.github.io/node-mongodb-native/2.1/api/Admin.html#listDatabases + listDatabases(): Promise; + listDatabases(callback: MongoCallback): void; + //http://mongodb.github.io/node-mongodb-native/2.1/api/Admin.html#logout + logout(): Promise; + logout(callback: MongoCallback): void; + //http://mongodb.github.io/node-mongodb-native/2.1/api/Admin.html#ping + ping(): Promise; + ping(callback: MongoCallback): void; + //http://mongodb.github.io/node-mongodb-native/2.1/api/Admin.html#profilingInfo + profilingInfo(): Promise; + profilingInfo(callback: MongoCallback): void; + //http://mongodb.github.io/node-mongodb-native/2.1/api/Admin.html#profilingLevel + profilingLevel(): Promise; + profilingLevel(callback: MongoCallback): void; + //http://mongodb.github.io/node-mongodb-native/2.1/api/Admin.html#removeUser + removeUser(username: string, callback: MongoCallback): void; + removeUser(username: string, options?: FSyncOptions): Promise; + removeUser(username: string, options: FSyncOptions, callback: MongoCallback): void; + //http://mongodb.github.io/node-mongodb-native/2.1/api/Admin.html#replSetGetStatus + replSetGetStatus(): Promise; + replSetGetStatus(callback: MongoCallback): void; + //http://mongodb.github.io/node-mongodb-native/2.1/api/Admin.html#serverInfo + serverInfo(): Promise; + serverInfo(callback: MongoCallback): void; + //http://mongodb.github.io/node-mongodb-native/2.1/api/Admin.html#serverStatus + serverStatus(): Promise; + serverStatus(callback: MongoCallback): void; + //http://mongodb.github.io/node-mongodb-native/2.1/api/Admin.html#setProfilingLevel + setProfilingLevel(level: string): Promise; + setProfilingLevel(level: string, callback: MongoCallback): void; + // http://mongodb.github.io/node-mongodb-native/2.1/api/Admin.html#validateCollection + validateCollection(collectionNme: string, callback: MongoCallback): void; + validateCollection(collectionNme: string, options?: Object): Promise; + validateCollection(collectionNme: string, options: Object, callback: MongoCallback): void; +} - /** - * Sugar for `Promise.resolve(undefined).bind(thisArg);`. See `.bind()`. - */ - static bind(thisArg: any): Bluebird; +//http://mongodb.github.io/node-mongodb-native/2.1/api/Admin.html#addUser +export interface AddUserOptions { + w?: number | string; + wtimeout?: number; + j?: boolean; + fsync: boolean; + customData?: Object; + roles?: Object[] +} - /** - * See if `value` is a trusted Promise. - */ - static is(value: any): boolean; +//http://mongodb.github.io/node-mongodb-native/2.1/api/Admin.html#removeUser +export interface FSyncOptions { + w?: number | string; + wtimeout?: number; + j?: boolean; + fsync?: boolean +} - /** - * Call this right after the library is loaded to enabled long stack traces. Long stack traces cannot be disabled after being enabled, and cannot be enabled after promises have already been created. Long stack traces imply a substantial performance penalty, around 4-5x for throughput and 0.5x for latency. - */ - static longStackTraces(): void; +// Class documentation : http://mongodb.github.io/node-mongodb-native/2.1/api/ObjectID.html +export class ObjectID { + constructor(s?: string | number); - /** - * Returns a promise that will be resolved with value (or undefined) after given ms milliseconds. - * If value is a promise, the delay will start counting down when it is fulfilled and the returned - * promise will be fulfilled with the fulfillment value of the value promise. - */ - static delay(ms: number, value: R | Bluebird.Thenable): Bluebird; - static delay(ms: number): Bluebird; + generationTime: number; - /** - * Returns a function that will wrap the given `nodeFunction`. Instead of taking a callback, the returned function will return a promise whose fate is decided by the callback behavior of the given node function. The node function should conform to node.js convention of accepting a callback as last argument and calling that callback with error as the first argument and success value on the second argument. - * - * If the `nodeFunction` calls its callback with multiple success values, the fulfillment value will be an array of them. - * - * If you pass a `receiver`, the `nodeFunction` will be called as a method on the `receiver`. - */ - static promisify(func: (callback: (err: any, result: T) => void) => void, options?: Bluebird.PromisifyOptions): () => Bluebird; - static promisify(func: (arg1: A1, callback: (err: any, result: T) => void) => void, options?: Bluebird.PromisifyOptions): (arg1: A1) => Bluebird; - static promisify(func: (arg1: A1, arg2: A2, callback: (err: any, result: T) => void) => void, options?: Bluebird.PromisifyOptions): (arg1: A1, arg2: A2) => Bluebird; - static promisify(func: (arg1: A1, arg2: A2, arg3: A3, callback: (err: any, result: T) => void) => void, options?: Bluebird.PromisifyOptions): (arg1: A1, arg2: A2, arg3: A3) => Bluebird; - static promisify(func: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, callback: (err: any, result: T) => void) => void, options?: Bluebird.PromisifyOptions): (arg1: A1, arg2: A2, arg3: A3, arg4: A4) => Bluebird; - static promisify(func: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5, callback: (err: any, result: T) => void) => void, options?: Bluebird.PromisifyOptions): (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5) => Bluebird; - static promisify(nodeFunction: Function, options?: Bluebird.PromisifyOptions): Function; + // Creates an ObjectID from a hex string representation of an ObjectID. + // hexString – create a ObjectID from a passed in 24 byte hexstring. + static createFromHexString(hexString: string): ObjectID; + // Creates an ObjectID from a second based number, with the rest of the ObjectID zeroed out. Used for comparisons or sorting the ObjectID. + // time – an integer number representing a number of seconds. + static createFromTime(time: number): ObjectID; + // Checks if a value is a valid bson ObjectId + // id - Value to be checked + static isValid(id: string | number): boolean; + //Compares the equality of this ObjectID with otherID. + equals(otherID: ObjectID): boolean; + // Generate a 12 byte id string used in ObjectID's + // time - optional parameter allowing to pass in a second based timestamp + generate(time?: number): string; + // Returns the generation date (accurate up to the second) that this ID was generated. + getTimestamp(): Date; + // Returns the ObjectID id as a 24 byte hex string representation + toHexString(): string; +} - /** - * Promisifies the entire object by going through the object's properties and creating an async equivalent of each function on the object and its prototype chain. The promisified method name will be the original method name postfixed with `Async`. Returns the input object. - * - * Note that the original methods on the object are not overwritten but new methods are created with the `Async`-postfix. For example, if you `promisifyAll()` the node.js `fs` object use `fs.statAsync()` to call the promisified `stat` method. - */ - // TODO how to model promisifyAll? - static promisifyAll(target: Object, options?: Bluebird.PromisifyAllOptions): Object; +// Class documentation : http://mongodb.github.io/node-mongodb-native/2.1/api/Binary.html +export class Binary { + constructor(buffer: Buffer, subType?: number); - /** - * Returns a promise that is resolved by a node style callback function. - */ - static fromNode(resolver: (callback: (err: any, result?: any) => void) => void, options?: Bluebird.FromNodeOptions): Bluebird; - static fromNode(resolver: (callback: (err: any, result?: T) => void) => void, options?: Bluebird.FromNodeOptions): Bluebird; - static fromCallback(resolver: (callback: (err: any, result?: any) => void) => void, options?: Bluebird.FromNodeOptions): Bluebird; - static fromCallback(resolver: (callback: (err: any, result?: T) => void) => void, options?: Bluebird.FromNodeOptions): Bluebird; + static SUBTYPE_BYTE_ARRAY: number; + static SUBTYPE_DEFAULT: number; + static SUBTYPE_FUNCTION: number; + static SUBTYPE_MD5: number; + static SUBTYPE_USER_DEFINED: number; + static SUBTYPE_UUID: number; + static SUBTYPE_UUID_OLD: number; - /** - * Returns a function that can use `yield` to run asynchronous code synchronously. This feature requires the support of generators which are drafted in the next version of the language. Node version greater than `0.11.2` is required and needs to be executed with the `--harmony-generators` (or `--harmony`) command-line switch. - */ - // TODO fix coroutine GeneratorFunction - static coroutine(generatorFunction: Function): Function; + // The length of the binary. + length(): number; + // Updates this binary with byte_value + put(byte_value: number | string): void; + // Reads length bytes starting at position. + read(position: number, length: number): Buffer; + // Returns the value of this binary as a string. + value(): string; + // Writes a buffer or string to the binary + write(buffer: Buffer | string, offset: number): void; +} +//http://mongodb.github.io/node-mongodb-native/2.1/api/Double.html +export class Double { + constructor(value: number); - /** - * Add `handler` as the handler to call when there is a possibly unhandled rejection. The default handler logs the error stack to stderr or `console.error` in browsers. - * - * Passing no value or a non-function will have the effect of removing any kind of handling for possibly unhandled rejections. - */ - static onPossiblyUnhandledRejection(handler: (reason: any) => any): void; + valueOf(): number; +} - /** - * Given an array, or a promise of an array, which contains promises (or a mix of promises and values) return a promise that is fulfilled when all the items in the array are fulfilled. The promise's fulfillment value is an array with fulfillment values at respective positions to the original array. If any promise in the array rejects, the returned promise is rejected with the rejection reason. - */ - // TODO enable more overloads - // array with promises of different types - static all(values: [Bluebird.Thenable | T1]): Bluebird<[T1]>; - static all(values: [Bluebird.Thenable | T1, Bluebird.Thenable | T2]): Bluebird<[T1, T2]>; - static all(values: [Bluebird.Thenable | T1, Bluebird.Thenable | T2, Bluebird.Thenable | T3]): Bluebird<[T1, T2, T3]>; - static all(values: [Bluebird.Thenable | T1, Bluebird.Thenable | T2, Bluebird.Thenable | T3, Bluebird.Thenable | T4]): Bluebird<[T1, T2, T3, T4]>; - static all(values: [Bluebird.Thenable | T1, Bluebird.Thenable | T2, Bluebird.Thenable | T3, Bluebird.Thenable | T4, Bluebird.Thenable | T5]): Bluebird<[T1, T2, T3, T4, T5]>; - // array with values - static all(values: ((R | Bluebird.Thenable) | Bluebird.Thenable<(R | Bluebird.Thenable)>)[]): Bluebird; +//http://mongodb.github.io/node-mongodb-native/2.1/api/Long.html +export class Long { + constructor(low: number, high: number); - /** - * Like ``Promise.all`` but for object properties instead of array items. Returns a promise that is fulfilled when all the properties of the object are fulfilled. The promise's fulfillment value is an object with fulfillment values at respective keys to the original object. If any promise in the object rejects, the returned promise is rejected with the rejection reason. - * - * If `object` is a trusted `Promise`, then it will be treated as a promise for object rather than for its properties. All other objects are treated for their properties as is returned by `Object.keys` - the object's own enumerable properties. - * - * *The original object is not modified.* - */ - // TODO verify this is correct - // trusted promise for object - static props(object: Bluebird): Bluebird; - // object - static props(object: Object): Bluebird; - - /** - * Given an array, or a promise of an array, which contains promises (or a mix of promises and values) return a promise that is fulfilled when all the items in the array are either fulfilled or rejected. The fulfillment value is an array of ``PromiseInspection`` instances at respective positions in relation to the input array. - * - * *original: The array is not modified. The input array sparsity is retained in the resulting array.* - */ - // promise of array with promises of value - static settle(values: Bluebird.Thenable[]>): Bluebird[]>; - // promise of array with values - static settle(values: Bluebird.Thenable): Bluebird[]>; - // array with promises of value - static settle(values: Bluebird.Thenable[]): Bluebird[]>; - // array with values - static settle(values: R[]): Bluebird[]>; - - /** - * Like `Promise.some()`, with 1 as `count`. However, if the promise fulfills, the fulfillment value is not an array of 1 but the value directly. - */ - // promise of array with promises of value - static any(values: Bluebird.Thenable[]>): Bluebird; - // promise of array with values - static any(values: Bluebird.Thenable): Bluebird; - // array with promises of value - static any(values: Bluebird.Thenable[]): Bluebird; - // array with values - static any(values: R[]): Bluebird; - - /** - * Given an array, or a promise of an array, which contains promises (or a mix of promises and values) return a promise that is fulfilled or rejected as soon as a promise in the array is fulfilled or rejected with the respective rejection reason or fulfillment value. - * - * **Note** If you pass empty array or a sparse array with no values, or a promise/thenable for such, it will be forever pending. - */ - // promise of array with promises of value - static race(values: Bluebird.Thenable[]>): Bluebird; - // promise of array with values - static race(values: Bluebird.Thenable): Bluebird; - // array with promises of value - static race(values: Bluebird.Thenable[]): Bluebird; - // array with values - static race(values: R[]): Bluebird; - - /** - * Initiate a competetive race between multiple promises or values (values will become immediately fulfilled promises). When `count` amount of promises have been fulfilled, the returned promise is fulfilled with an array that contains the fulfillment values of the winners in order of resolution. - * - * If too many promises are rejected so that the promise can never become fulfilled, it will be immediately rejected with an array of rejection reasons in the order they were thrown in. - * - * *The original array is not modified.* - */ - // promise of array with promises of value - static some(values: Bluebird.Thenable[]>, count: number): Bluebird; - // promise of array with values - static some(values: Bluebird.Thenable, count: number): Bluebird; - // array with promises of value - static some(values: Bluebird.Thenable[], count: number): Bluebird; - // array with values - static some(values: R[], count: number): Bluebird; - - /** - * Promise.join( - * Promise|any values..., - * function handler - * ) -> Promise - * For coordinating multiple concurrent discrete promises. - * - * Note: In 1.x and 0.x Promise.join used to be a Promise.all that took the values in as arguments instead in an array. This behavior has been deprecated but is still supported partially - when the last argument is an immediate function value the new semantics will apply - */ - - // multiple values and handler - static join(arg1: A1 | Bluebird.Thenable, handler: (arg1?: A1) => R | Bluebird.Thenable): Bluebird; - static join(arg1: A1 | Bluebird.Thenable, arg2: A2 | Bluebird.Thenable, handler: (arg1?: A1, arg2?: A2) => R | Bluebird.Thenable): Bluebird; - static join(arg1: A1 | Bluebird.Thenable, arg2: A2 | Bluebird.Thenable, arg3: A3 | Bluebird.Thenable, handler: (arg1?: A1, arg2?: A2, arg3?: A3) => R | Bluebird.Thenable): Bluebird; - static join(arg1: A1 | Bluebird.Thenable, arg2: A2 | Bluebird.Thenable, arg3: A3 | Bluebird.Thenable, arg4: A4 | Bluebird.Thenable, handler: (arg1?: A1, arg2?: A2, arg3?: A3, arg4?: A4) => R | Bluebird.Thenable): Bluebird; - static join(arg1: A1 | Bluebird.Thenable, arg2: A2 | Bluebird.Thenable, arg3: A3 | Bluebird.Thenable, arg4: A4 | Bluebird.Thenable, arg5: A5 | Bluebird.Thenable, handler: (arg1?: A1, arg2?: A2, arg3?: A3, arg4?: A4, arg5?: A5) => R | Bluebird.Thenable): Bluebird; - - // variadic array with promises of value - static join(...values: Bluebird.Thenable[]): Bluebird; - // variadic array with values - static join(...values: R[]): Bluebird; - - /** - * Map an array, or a promise of an array, which contains a promises (or a mix of promises and values) with the given `mapper` function with the signature `(item, index, arrayLength)` where `item` is the resolved value of a respective promise in the input array. If any promise in the input array is rejected the returned promise is rejected as well. - * - * If the `mapper` function returns promises or thenables, the returned promise will wait for all the mapped results to be resolved as well. - * - * *The original array is not modified.* - */ - // promise of array with promises of value - static map(values: Bluebird.Thenable[]>, mapper: (item: R, index: number, arrayLength: number) => Bluebird.Thenable, options?: Bluebird.ConcurrencyOption): Bluebird; - static map(values: Bluebird.Thenable[]>, mapper: (item: R, index: number, arrayLength: number) => U, options?: Bluebird.ConcurrencyOption): Bluebird; - - // promise of array with values - static map(values: Bluebird.Thenable, mapper: (item: R, index: number, arrayLength: number) => Bluebird.Thenable, options?: Bluebird.ConcurrencyOption): Bluebird; - static map(values: Bluebird.Thenable, mapper: (item: R, index: number, arrayLength: number) => U, options?: Bluebird.ConcurrencyOption): Bluebird; - - // array with promises of value - static map(values: Bluebird.Thenable[], mapper: (item: R, index: number, arrayLength: number) => Bluebird.Thenable, options?: Bluebird.ConcurrencyOption): Bluebird; - static map(values: Bluebird.Thenable[], mapper: (item: R, index: number, arrayLength: number) => U, options?: Bluebird.ConcurrencyOption): Bluebird; - - // array with values - static map(values: R[], mapper: (item: R, index: number, arrayLength: number) => Bluebird.Thenable, options?: Bluebird.ConcurrencyOption): Bluebird; - static map(values: R[], mapper: (item: R, index: number, arrayLength: number) => U, options?: Bluebird.ConcurrencyOption): Bluebird; - - /** - * Reduce an array, or a promise of an array, which contains a promises (or a mix of promises and values) with the given `reducer` function with the signature `(total, current, index, arrayLength)` where `item` is the resolved value of a respective promise in the input array. If any promise in the input array is rejected the returned promise is rejected as well. - * - * If the reducer function returns a promise or a thenable, the result for the promise is awaited for before continuing with next iteration. - * - * *The original array is not modified. If no `intialValue` is given and the array doesn't contain at least 2 items, the callback will not be called and `undefined` is returned. If `initialValue` is given and the array doesn't have at least 1 item, `initialValue` is returned.* - */ - // promise of array with promises of value - static reduce(values: Bluebird.Thenable[]>, reducer: (total: U, current: R, index: number, arrayLength: number) => Bluebird.Thenable, initialValue?: U): Bluebird; - static reduce(values: Bluebird.Thenable[]>, reducer: (total: U, current: R, index: number, arrayLength: number) => U, initialValue?: U): Bluebird; - - // promise of array with values - static reduce(values: Bluebird.Thenable, reducer: (total: U, current: R, index: number, arrayLength: number) => Bluebird.Thenable, initialValue?: U): Bluebird; - static reduce(values: Bluebird.Thenable, reducer: (total: U, current: R, index: number, arrayLength: number) => U, initialValue?: U): Bluebird; - - // array with promises of value - static reduce(values: Bluebird.Thenable[], reducer: (total: U, current: R, index: number, arrayLength: number) => Bluebird.Thenable, initialValue?: U): Bluebird; - static reduce(values: Bluebird.Thenable[], reducer: (total: U, current: R, index: number, arrayLength: number) => U, initialValue?: U): Bluebird; - - // array with values - static reduce(values: R[], reducer: (total: U, current: R, index: number, arrayLength: number) => Bluebird.Thenable, initialValue?: U): Bluebird; - static reduce(values: R[], reducer: (total: U, current: R, index: number, arrayLength: number) => U, initialValue?: U): Bluebird; - - /** - * Filter an array, or a promise of an array, which contains a promises (or a mix of promises and values) with the given `filterer` function with the signature `(item, index, arrayLength)` where `item` is the resolved value of a respective promise in the input array. If any promise in the input array is rejected the returned promise is rejected as well. - * - * The return values from the filtered functions are coerced to booleans, with the exception of promises and thenables which are awaited for their eventual result. - * - * *The original array is not modified. - */ - // promise of array with promises of value - static filter(values: Bluebird.Thenable[]>, filterer: (item: R, index: number, arrayLength: number) => Bluebird.Thenable, option?: Bluebird.ConcurrencyOption): Bluebird; - static filter(values: Bluebird.Thenable[]>, filterer: (item: R, index: number, arrayLength: number) => boolean, option?: Bluebird.ConcurrencyOption): Bluebird; + static MAX_VALUE: Long; + static MIN_VALUE: Long; + static NEG_ONE: Long; + static ONE: Long; + static ZERO: Long; - // promise of array with values - static filter(values: Bluebird.Thenable, filterer: (item: R, index: number, arrayLength: number) => Bluebird.Thenable, option?: Bluebird.ConcurrencyOption): Bluebird; - static filter(values: Bluebird.Thenable, filterer: (item: R, index: number, arrayLength: number) => boolean, option?: Bluebird.ConcurrencyOption): Bluebird; + static fromBits(lowBits: number, highBits: number): Long; + static fromInt(value: number): Long; + static fromNumber(value: number): Long; + static fromString(str: string, radix?: number): Long; - // array with promises of value - static filter(values: Bluebird.Thenable[], filterer: (item: R, index: number, arrayLength: number) => Bluebird.Thenable, option?: Bluebird.ConcurrencyOption): Bluebird; - static filter(values: Bluebird.Thenable[], filterer: (item: R, index: number, arrayLength: number) => boolean, option?: Bluebird.ConcurrencyOption): Bluebird; + add(other: Long): Long; + and(other: Long): Long; + compare(other: Long): number; + div(other: Long): Long; + equals(other: Long): boolean; + getHighBits(): number; + getLowBits(): number; + getLowBitsUnsigned(): number; + getNumBitsAbs(): number; + greaterThan(other: Long): number; + greaterThanOrEqual(other: Long): number; + isNegative(): boolean; + isOdd(): boolean; + isZero(): boolean; + lessThan(other: Long): boolean; + lessThanOrEqual(other: Long): boolean; + modulo(other: Long): Long; + multiply(other: Long): Long; + negate(): Long; + not(): Long; + notEquals(other: Long): boolean; + or(other: Long): Long; + shiftLeft(other: number): Long; + shiftRight(other: number): Long; + shiftRightUnsigned(other: number): Long; + subtract(other: Long): Long; + toInt(): number; + toJSON(): string; + toNumber(): number; + toString(radix?: number): string; + xor(other: Long): Long; +} - // array with values - static filter(values: R[], filterer: (item: R, index: number, arrayLength: number) => Bluebird.Thenable, option?: Bluebird.ConcurrencyOption): Bluebird; - static filter(values: R[], filterer: (item: R, index: number, arrayLength: number) => boolean, option?: Bluebird.ConcurrencyOption): Bluebird; +//http://mongodb.github.io/node-mongodb-native/2.1/api/MaxKey.html +export class MaxKey { } - /** - * Iterate over an array, or a promise of an array, which contains promises (or a mix of promises and values) with the given iterator function with the signature (item, index, value) where item is the resolved value of a respective promise in the input array. Iteration happens serially. If any promise in the input array is rejected the returned promise is rejected as well. - * - * Resolves to the original array unmodified, this method is meant to be used for side effects. If the iterator function returns a promise or a thenable, the result for the promise is awaited for before continuing with next iteration. - */ - // promise of array with promises of value - static each(values: Bluebird.Thenable[]>, iterator: (item: R, index: number, arrayLength: number) => U | Bluebird.Thenable): Bluebird; - // array with promises of value - static each(values: Bluebird.Thenable[], iterator: (item: R, index: number, arrayLength: number) => U | Bluebird.Thenable): Bluebird; - // array with values OR promise of array with values - static each(values: R[] | Bluebird.Thenable, iterator: (item: R, index: number, arrayLength: number) => U | Bluebird.Thenable): Bluebird; +//http://mongodb.github.io/node-mongodb-native/2.1/api/MinKey.html +export class MinKey { } - /** - * A meta method used to specify the disposer method that cleans up a resource when using `Promise.using`. - * - * Returns a Disposer object which encapsulates both the resource as well as the method to clean it up. - * The user can pass this object to `Promise.using` to get access to the resource when it becomes available, - * as well as to ensure its automatically cleaned up. - * - * The second argument passed to a disposer is the result promise of the using block, which you can - * inspect synchronously. - */ - disposer(disposeFn: (arg: R, promise: Bluebird) => void | Bluebird.Thenable): Bluebird.Disposer; +//http://mongodb.github.io/node-mongodb-native/2.1/api/Timestamp.html +export class Timestamp { + constructor(low: number, high: number); - /** - * In conjunction with `.disposer`, using will make sure that no matter what, the specified disposer - * will be called when the promise returned by the callback passed to using has settled. The disposer is - * necessary because there is no standard interface in node for disposing resources. - */ - static using(disposer: Bluebird.Disposer, executor: (transaction: R) => Bluebird.Thenable): Bluebird; - static using(disposer: Bluebird.Disposer, disposer2: Bluebird.Disposer, executor: (transaction1: R1, transaction2: R2) => Bluebird.Thenable): Bluebird; - static using(disposer: Bluebird.Disposer, disposer2: Bluebird.Disposer, disposer3: Bluebird.Disposer, executor: (transaction1: R1, transaction2: R2, transaction3: R3) => Bluebird.Thenable): Bluebird; + static MAX_VALUE: Timestamp; + static MIN_VALUE: Timestamp; + static NEG_ONE: Timestamp; + static ONE: Timestamp; + static ZERO: Timestamp; - /** - * Add handler as the handler to call when there is a possibly unhandled rejection. - * The default handler logs the error stack to stderr or console.error in browsers. - * - * Passing no value or a non-function will have the effect of removing any kind of handling for possibly unhandled rejections. - * - * Note: this hook is specific to the bluebird instance its called on, application developers should use global rejection events. - */ - static onPossiblyUnhandledRejection(handler?: (error: Error, promise: Bluebird) => void): void; + static fromBits(lowBits: number, highBits: number): Timestamp; + static fromInt(value: number): Timestamp; + static fromNumber(value: number): Timestamp; + static fromString(str: string, radix?: number): Timestamp; - /** - * Configure long stack traces, warnings, monitoring and cancellation. - * Note that even though false is the default here, a development environment might be detected which automatically - * enables long stack traces and warnings. - */ - static config(options: { - /** Enable warnings */ - warnings?: boolean | { - /** Enables all warnings except forgotten return statements. */ - wForgottenReturn: boolean; - }; - /** Enable long stack traces */ - longStackTraces?: boolean; - /** Enable cancellation */ - cancellation?: boolean; - /** Enable monitoring */ - monitoring?: boolean; - }): void; + add(other: Timestamp): Timestamp; + and(other: Timestamp): Timestamp; + compare(other: Timestamp): number; + div(other: Timestamp): Timestamp; + equals(other: Timestamp): boolean; + getHighBits(): number; + getLowBits(): number; + getLowBitsUnsigned(): number; + getNumBitsAbs(): number; + greaterThan(other: Timestamp): number; + greaterThanOrEqual(other: Timestamp): number; + isNegative(): boolean; + isOdd(): boolean; + isZero(): boolean; + lessThan(other: Timestamp): boolean; + lessThanOrEqual(other: Timestamp): boolean; + modulo(other: Timestamp): Timestamp; + multiply(other: Timestamp): Timestamp; + negate(): Timestamp; + not(): Timestamp; + notEquals(other: Timestamp): boolean; + or(other: Timestamp): Timestamp; + shiftLeft(other: number): Timestamp; + shiftRight(other: number): Timestamp; + shiftRightUnsigned(other: number): Timestamp; + subtract(other: Timestamp): Timestamp; + toInt(): number; + toJSON(): string; + toNumber(): number; + toString(radix?: number): string; + xor(other: Timestamp): Timestamp; } -namespace Bluebird { - export interface ConcurrencyOption { - concurrency: number; - } - export interface SpreadOption { - spread: boolean; - } - export interface FromNodeOptions { - multiArgs?: boolean; - } - export interface PromisifyOptions { - context?: any; - multiArgs?: boolean; - } - export interface PromisifyAllOptions extends PromisifyOptions { - suffix?: string; - filter?: (name: string, func: Function, target?: any, passesDefaultFilter?: boolean) => boolean; - // The promisifier gets a reference to the original method and should return a function which returns a promise - promisifier?: (originalMethod: Function) => () => Thenable; - } - - /** - * Represents an error is an explicit promise rejection as opposed to a thrown error. - * For example, if an error is errbacked by a callback API promisified through undefined or undefined - * and is not a typed error, it will be converted to a `OperationalError` which has the original error in - * the `.cause` property. - * - * `OperationalError`s are caught in `.error` handlers. - */ - export class OperationalError extends Error { } +// Documentation : http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html +export interface Collection { + // Get the collection name. + collectionName: string; + // Get the full collection namespace. + namespace: string; + // The current write concern values. + writeConcern: any; + // The current read concern values. + readConcern: any; + // Get current index hint for collection. + hint: any; + //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#aggregate + aggregate(pipeline: Object[], callback: MongoCallback): AggregationCursor; + aggregate(pipeline: Object[], options?: CollectionAggregationOptions, callback?: MongoCallback): AggregationCursor; + //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#bulkWrite + bulkWrite(operations: Object[], callback: MongoCallback): void; + bulkWrite(operations: Object[], options?: CollectionBluckWriteOptions): Promise; + bulkWrite(operations: Object[], options: CollectionBluckWriteOptions, callback: MongoCallback): void; + //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#count + count(query: Object, callback: MongoCallback): void; + count(query: Object, options?: MongoCountPreferences): Promise; + count(query: Object, options: MongoCountPreferences, callback: MongoCallback): void; + //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#createIndex + createIndex(fieldOrSpec: string | any, callback: MongoCallback): void; + createIndex(fieldOrSpec: string | any, options?: IndexOptions): Promise; + createIndex(fieldOrSpec: string | any, options: IndexOptions, callback: MongoCallback): void; + //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#createIndexes and http://docs.mongodb.org/manual/reference/command/createIndexes/ + createIndexes(indexSpecs: Object[]): Promise; + createIndexes(indexSpecs: Object[], callback: MongoCallback): void; + //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#deleteMany + deleteMany(filter: Object, callback: MongoCallback): void; + deleteMany(filter: Object, options?: CollectionOptions): Promise; + deleteMany(filter: Object, options: CollectionOptions, callback: MongoCallback): void; + //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#deleteOne + deleteOne(filter: Object, callback: MongoCallback): void; + deleteOne(filter: Object, options?: { w?: number | string, wtimmeout?: number, j?: boolean, bypassDocumentValidation?: boolean }): Promise; + deleteOne(filter: Object, options: { w?: number | string, wtimmeout?: number, j?: boolean, bypassDocumentValidation?: boolean }, callback: MongoCallback): void; + //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#distinct + distinct(key: string, query: Object, callback: MongoCallback): void; + distinct(key: string, query: Object, options?: { readPreference?: ReadPreference | string }): Promise; + distinct(key: string, query: Object, options: { readPreference?: ReadPreference | string }, callback: MongoCallback): void; + //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#drop + drop(): Promise; + drop(callback: MongoCallback): void; + //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#dropIndex + dropIndex(indexName: string, callback: MongoCallback): void; + dropIndex(indexName: string, options?: CollectionOptions): Promise; + dropIndex(indexName: string, options: CollectionOptions, callback: MongoCallback): void; + // http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#dropIndexes + dropIndexes(): Promise; + dropIndexes(callback?: MongoCallback): void; + //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#find + find(query?: Object): Cursor; + /** @deprecated */ + find(query: Object, fields?: Object, skip?: number, limit?: number, timeout?: number): Cursor; + //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#findOne + /** @deprecated use find().limit(1).next(function(err, doc){}) */ + findOne(filter: Object, callback: MongoCallback): void; + /** @deprecated use find().limit(1).next(function(err, doc){}) */ + findOne(filter: Object, options?: FindOneOptions): Promise; + /** @deprecated use find().limit(1).next(function(err, doc){}) */ + findOne(filter: Object, options: FindOneOptions, callback: MongoCallback): void; + //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#findOneAndDelete + findOneAndDelete(filter: Object, callback: MongoCallback): void; + findOneAndDelete(filter: Object, options?: { projection?: Object, sort?: Object, maxTimeMS?: number }): Promise; + findOneAndDelete(filter: Object, options: { projection?: Object, sort?: Object, maxTimeMS?: number }, callback: MongoCallback): void; + //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#findOneAndReplace + findOneAndReplace(filter: Object, replacement: Object, callback: MongoCallback): void; + findOneAndReplace(filter: Object, replacement: Object, options?: FindOneAndReplaceOption): Promise; + findOneAndReplace(filter: Object, replacement: Object, options: FindOneAndReplaceOption, callback: MongoCallback): void; + //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#findOneAndUpdate + findOneAndUpdate(filter: Object, update: Object, callback: MongoCallback): void; + findOneAndUpdate(filter: Object, update: Object, options?: FindOneAndReplaceOption): Promise; + findOneAndUpdate(filter: Object, update: Object, options: FindOneAndReplaceOption, callback: MongoCallback): void; + //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#geoHaystackSearch + geoHaystackSearch(x: number, y: number, callback: MongoCallback): void; + geoHaystackSearch(x: number, y: number, options?: GeoHaystackSearchOptions): Promise; + geoHaystackSearch(x: number, y: number, options: GeoHaystackSearchOptions, callback: MongoCallback): void; + //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#geoNear + geoNear(x: number, y: number, callback: MongoCallback): void; + geoNear(x: number, y: number, options?: GeoNearOptions): Promise; + geoNear(x: number, y: number, options: GeoNearOptions, callback: MongoCallback): void; + //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#group + group(keys: Object | Array | Function | Code, condition: Object, initial: Object, reduce: Function | Code, finalize: Function | Code, command: boolean, callback: MongoCallback): void; + group(keys: Object | Array | Function | Code, condition: Object, initial: Object, reduce: Function | Code, finalize: Function | Code, command: boolean, options?: { readPreference?: ReadPreference | string }): Promise; + group(keys: Object | Array | Function | Code, condition: Object, initial: Object, reduce: Function | Code, finalize: Function | Code, command: boolean, options: { readPreference?: ReadPreference | string }, callback: MongoCallback): void; + //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#indexes + indexes(): Promise; + indexes(callback: MongoCallback): void; + //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#indexExists + indexExists(indexes: string | string[]): Promise; + indexExists(indexes: string | string[], callback: MongoCallback): void; + //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#indexInformation + indexInformation(callback: MongoCallback): void; + indexInformation(options?: { full: boolean }): Promise; + indexInformation(options: { full: boolean }, callback: MongoCallback): void; + //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#initializeOrderedBulkOp + initializeOrderedBulkOp(options?: CollectionOptions): OrderedBulkOperation; + //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#initializeUnorderedBulkOp + initializeUnorderedBulkOp(options?: CollectionOptions): UnorderedBulkOperation; + //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#insertOne + /** @deprecated Use insertOne, insertMany or bulkWrite */ + insert(docs: Object, callback: MongoCallback): void; + /** @deprecated Use insertOne, insertMany or bulkWrite */ + insert(docs: Object, options?: CollectionInsertOneOptions): Promise; + /** @deprecated Use insertOne, insertMany or bulkWrite */ + insert(docs: Object, options: CollectionInsertOneOptions, callback: MongoCallback): void; + //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#insertMany + insertMany(docs: Object[], callback: MongoCallback): void; + insertMany(docs: Object[], options?: CollectionInsertManyOptions): Promise; + insertMany(docs: Object[], options: CollectionInsertManyOptions, callback: MongoCallback): void; + //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#insertOne + insertOne(docs: Object, callback: MongoCallback): void; + insertOne(docs: Object, options?: CollectionInsertOneOptions): Promise; + insertOne(docs: Object, options: CollectionInsertOneOptions, callback: MongoCallback): void; + //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#isCapped + isCapped(): Promise; + isCapped(callback: MongoCallback): void; + //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#listIndexes + listIndexes(options?: { batchSize?: number, readPreference?: ReadPreference | string }): CommandCursor; + //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#mapReduce + mapReduce(map: Function | string, reduce: Function | string, callback: MongoCallback): void; + mapReduce(map: Function | string, reduce: Function | string, options?: MapReduceOptions): Promise; + mapReduce(map: Function | string, reduce: Function | string, options: MapReduceOptions, callback: MongoCallback): void; + //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#options + options(): Promise; + options(callback: MongoCallback): void; + //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#parallelCollectionScan + parallelCollectionScan(callback: MongoCallback): void; + parallelCollectionScan(options?: ParallelCollectionScanOptions): Promise; + parallelCollectionScan(options: ParallelCollectionScanOptions, callback: MongoCallback): void; + //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#reIndex + reIndex(): Promise; + reIndex(callback: MongoCallback): void; + //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#rename + rename(newName: string, callback: MongoCallback): void; + rename(newName: string, options?: { dropTarget?: boolean }): Promise; + rename(newName: string, options: { dropTarget?: boolean }, callback: MongoCallback): void; + //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#replaceOne + replaceOne(filter: Object, doc: Object, callback: MongoCallback): void; + replaceOne(filter: Object, doc: Object, options?: ReplaceOneOptions): Promise; + replaceOne(filter: Object, doc: Object, options: ReplaceOneOptions, callback: MongoCallback): void; + //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#save + /** @deprecated Use insertOne, insertMany, updateOne or updateMany */ + save(doc: Object, callback: MongoCallback): void; + save(doc: Object, options?: CollectionOptions): Promise; + save(doc: Object, options: CollectionOptions, callback: MongoCallback): void; + //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#stats + stats(callback: MongoCallback): void; + stats(options?: { scale: number }): Promise; + stats(options: { scale: number }, callback: MongoCallback): void; + // http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#update + /** @deprecated use updateOne, updateMany or bulkWrite */ + update(filter: Object, update: Object, callback: MongoCallback): void; + /** @deprecated use updateOne, updateMany or bulkWrite */ + update(filter: Object, update: Object, options?: ReplaceOneOptions & { multi?: boolean }): Promise; + /** @deprecated use updateOne, updateMany or bulkWrite */ + update(filter: Object, update: Object, options: ReplaceOneOptions & { multi?: boolean }, callback: MongoCallback): void; + //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#updateMany + updateMany(filter: Object, update: Object, callback: MongoCallback): void; + updateMany(filter: Object, update: Object, options?: { upsert?: boolean; w?: any; wtimeout?: number; j?: boolean; }): Promise; + updateMany(filter: Object, update: Object, options: { upsert?: boolean; w?: any; wtimeout?: number; j?: boolean; }, callback: MongoCallback): void; + //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#updateOne + updateOne(filter: Object, update: Object, callback: MongoCallback): void; + updateOne(filter: Object, update: Object, options?: ReplaceOneOptions): Promise; + updateOne(filter: Object, update: Object, options: ReplaceOneOptions, callback: MongoCallback): void; +} - /** - * Signals that an operation has timed out. Used as a custom cancellation reason in `.timeout`. - */ - export class TimeoutError extends Error { } +// Documentation: http://docs.mongodb.org/manual/reference/command/collStats/ +//TODO complete this +export interface CollStats { + // Namespace. + ns: string; + // Number of documents. + count: number; + // Collection size in bytes. + size: number; + // Average object size in bytes. + avgObjSize: number; + // (Pre)allocated space for the collection in bytes. + storageSize: number; + // Number of extents (contiguously allocated chunks of datafile space). + numExtents: number; + // Number of indexes. + nindexes: number; + // Size of the most recently created extent in bytes. + lastExtentSize: number; + // Padding can speed up updates if documents grow. + paddingFactor: number; + userFlags: number; + // Total index size in bytes. + totalIndexSize: number; + // Size of specific indexes in bytes. + indexSizes: { + _id_: number; + username: number; + }; + capped: boolean; + maxSize: boolean; + wiredTiger: any; + indexDetails: any; + ok: number +} - /** - * Signals that an operation has been aborted or cancelled. The default reason used by `.cancel`. - */ - export class CancellationError extends Error {} +//http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#aggregate +export interface CollectionAggregationOptions { + readPreference?: ReadPreference | string; + // Return the query as cursor, on 2.6 > it returns as a real cursor + // on pre 2.6 it returns as an emulated cursor. + cursor?: { batchSize: number }; + // Explain returns the aggregation execution plan (requires mongodb 2.6 >). + explain?: boolean; + // lets the server know if it can use disk to store + // temporary results for the aggregation (requires mongodb 2.6 >). + allowDiskUse?: boolean; + // specifies a cumulative time limit in milliseconds for processing operations + // on the cursor. MongoDB interrupts the operation at the earliest following interrupt point. + maxTimeMS?: boolean; + // Allow driver to bypass schema validation in MongoDB 3.2 or higher. + bypassDocumentValidation?: boolean; +} - /** - * A collection of errors. `AggregateError` is an array-like object, with numeric indices and a `.length` property. - * It supports all generic array methods such as `.forEach` directly. - * - * `AggregateError`s are caught in `.error` handlers, even if the contained errors are not operational. - * - * `Promise.some` and `Promise.any` use `AggregateError` as rejection reason when they fail. - */ - export class AggregateError extends Error {} +//http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#insertMany +export interface CollectionInsertManyOptions { + // The write concern. + w?: number | string; + // The write concern timeout. + wtimeout?: number; + // Specify a journal write concern. + j?: boolean; + // Serialize functions on any object. + serializeFunctions?: boolean; + //Force server to assign _id values instead of driver. + forceServerObjectId?: boolean; +} - /** - * returned by `Bluebird.disposer()`. - */ - export class Disposer { - } +//http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#bulkWrite +export interface CollectionBluckWriteOptions { + // The write concern. + w?: number | string; + // The write concern timeout. + wtimeout?: number; + // Specify a journal write concern. + j?: boolean; + // Serialize functions on any object. + serializeFunctions?: boolean; + // Execute write operation in ordered or unordered fashion. + ordered?: boolean; + // Allow driver to bypass schema validation in MongoDB 3.2 or higher. + bypassDocumentValidation?: boolean; +} - export interface Thenable { - then(onFulfilled: (value: R) => U | Thenable, onRejected?: (error: any) => U | Thenable): Thenable; - then(onFulfilled: (value: R) => U | Thenable, onRejected?: (error: any) => void | Thenable): Thenable; - } +//http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#~BulkWriteOpResult +export interface BulkWriteOpResultObject { + insertedCount?: number; + matchedCount?: number; + modifiedCount?: number; + deletedCount?: number; + upsertedCount?: number; + insertedIds?: any; + upsertedIds?: any; + result?: any; +} - export interface Resolver { - /** - * Returns a reference to the controlled promise that can be passed to clients. - */ - promise: Bluebird; +//http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#count +export interface MongoCountPreferences { + // The limit of documents to count. + limit?: number; + // The number of documents to skip for the count. + skip?: boolean; + // An index name hint for the query. + hint?: string; + // The preferred read preference + readPreference?: ReadPreference | string; +} - /** - * Resolve the underlying promise with `value` as the resolution value. If `value` is a thenable or a promise, the underlying promise will assume its state. - */ - resolve(value: R): void; - resolve(): void; +//http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#~deleteWriteOpResult +export interface DeleteWriteOpResultObject { + //The raw result returned from MongoDB, field will vary depending on server version. + result: { + //Is 1 if the command executed correctly. + ok?: number; + //The total count of documents deleted. + n?: number; + } + //The connection object used for the operation. + connection?: any; + //The number of documents deleted. + deletedCount?: number; +} - /** - * Reject the underlying promise with `reason` as the rejection reason. - */ - reject(reason: any): void; +//http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#~findAndModifyWriteOpResult +export interface FindAndModifyWriteOpResultObject { + //Document returned from findAndModify command. + value?: any; + //The raw lastErrorObject returned from the command. + lastErrorObject?: any; + //Is 1 if the command executed correctly. + ok?: number; +} - /** - * Gives you a callback representation of the `PromiseResolver`. Note that this is not a method but a property. The callback accepts error object in first argument and success values on the 2nd parameter and the rest, I.E. node js conventions. - * - * If the the callback is called with multiple success values, the resolver fullfills its promise with an array of the values. - */ - // TODO specify resolver callback - callback: (err: any, value: R, ...values: R[]) => void; - } +//http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#findOneAndReplace +export interface FindOneAndReplaceOption { + projection?: Object; + sort?: Object; + maxTimeMS?: number; + upsert?: boolean; + returnOriginal?: boolean; +} - export interface Inspection { - /** - * See if the underlying promise was fulfilled at the creation time of this inspection object. - */ - isFulfilled(): boolean; +//http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#geoHaystackSearch +export interface GeoHaystackSearchOptions { + readPreference?: ReadPreference | string; + maxDistance?: number; + search?: Object; + limit?: number; +} - /** - * See if the underlying promise was rejected at the creation time of this inspection object. - */ - isRejected(): boolean; +//http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#geoNear +export interface GeoNearOptions { + readPreference?: ReadPreference | string; + num?: number; + minDistance?: number; + maxDistance?: number; + distanceMultiplier?: number; + query?: Object; + spherical?: boolean; + uniqueDocs?: boolean; + includeLocs?: boolean; +} - /** - * See if the underlying promise was defer at the creation time of this inspection object. - */ - isPending(): boolean; +//http://mongodb.github.io/node-mongodb-native/2.1/api/Code.html +export class Code { + constructor(code: string | Function, scope?: Object) + code: string | Function; + scope: any; +} - /** - * Get the fulfillment value of the underlying promise. Throws if the promise wasn't fulfilled at the creation time of this inspection object. - * - * throws `TypeError` - */ - value(): R; +//http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#deleteMany +export interface CollectionOptions { + //The write concern. + w?: number | string; + //The write concern timeout. + wtimeout?: number; + //Specify a journal write concern. + j?: boolean; +} - /** - * Get the rejection reason for the underlying promise. Throws if the promise wasn't rejected at the creation time of this inspection object. - * - * throws `TypeError` - */ - reason(): any; - } +//http://mongodb.github.io/node-mongodb-native/2.1/api/OrderedBulkOperation.html +export interface OrderedBulkOperation { + length: number; + //http://mongodb.github.io/node-mongodb-native/2.1/api/OrderedBulkOperation.html#execute + execute(callback: MongoCallback): void; + execute(options?: FSyncOptions): Promise; + execute(options: FSyncOptions, callback: MongoCallback): void; + //http://mongodb.github.io/node-mongodb-native/2.1/api/OrderedBulkOperation.html#find + find(selector: Object): FindOperatorsOrdered; + //http://mongodb.github.io/node-mongodb-native/2.1/api/OrderedBulkOperation.html#insert + insert(doc: Object): OrderedBulkOperation; +} - /** - * Changes how bluebird schedules calls a-synchronously. - * - * @param scheduler Should be a function that asynchronously schedules - * the calling of the passed in function - */ - export function setScheduler(scheduler: (callback: (...args: any[]) => void) => void): void; +//http://mongodb.github.io/node-mongodb-native/2.1/api/BulkWriteResult.html +export interface BulkWriteResult { + ok: number; + nInserted: number; + nUpdated: number; + nUpserted: number; + nModified: number; + nRemoved: number; + + getInsertedIds(): Array; + getLastOp(): Object; + getRawResponse(): Object; + getUpsertedIdAt(index: number): Object; + getUpsertedIds(): Array; + getWriteConcernError(): WriteConcernError; + getWriteErrorAt(index: number): WriteError; + getWriteErrorCount(): number; + getWriteErrors(): Array; + hasWriteErrors(): boolean; } -export = Bluebird; +//http://mongodb.github.io/node-mongodb-native/2.1/api/WriteError.html +export interface WriteError { + //Write concern error code. + code: number; + //Write concern error original bulk operation index. + index: number; + //Write concern error message. + errmsg: string; } -declare module '~iridium~bluebird' { -import main = require('~iridium~bluebird/bluebird'); -export = main; + +//http://mongodb.github.io/node-mongodb-native/2.1/api/WriteConcernError.html +export interface WriteConcernError { + //Write concern error code. + code: number; + //Write concern error message. + errmsg: string; } -// Generated by typings -// Source: https://raw.githubusercontent.com/typed-typings/npm-es6-promise/fb04188767acfec1defd054fc8024fafa5cd4de7/dist/es6-promise.d.ts -declare module '~iridium~mongodb~es6-promise/dist/es6-promise' { -export interface Thenable { - then (onFulfilled?: (value: R) => U | Thenable, onRejected?: (error: any) => U | Thenable): Thenable; - then (onFulfilled?: (value: R) => U | Thenable, onRejected?: (error: any) => void): Thenable; +//http://mongodb.github.io/node-mongodb-native/2.1/api/FindOperatorsOrdered.html +export interface FindOperatorsOrdered { + delete(): OrderedBulkOperation; + deleteOne(): OrderedBulkOperation; + replaceOne(doc: Object): OrderedBulkOperation; + update(doc: Object): OrderedBulkOperation; + updateOne(doc: Object): OrderedBulkOperation; + upsert(): FindOperatorsOrdered; } -export class Promise implements Thenable { - /** - * If you call resolve in the body of the callback passed to the constructor, - * your promise is fulfilled with result object passed to resolve. - * If you call reject your promise is rejected with the object passed to resolve. - * For consistency and debugging (eg stack traces), obj should be an instanceof Error. - * Any errors thrown in the constructor callback will be implicitly passed to reject(). - */ - constructor (callback: (resolve : (value?: R | Thenable) => void, reject: (error?: any) => void) => void); +//http://mongodb.github.io/node-mongodb-native/2.1/api/UnorderedBulkOperation.html +export interface UnorderedBulkOperation { + //http://mongodb.github.io/node-mongodb-native/2.1/api/UnorderedBulkOperation.html#execute + execute(callback: MongoCallback): void; + execute(options?: FSyncOptions): Promise; + execute(options: FSyncOptions, callback: MongoCallback): void; + //http://mongodb.github.io/node-mongodb-native/2.1/api/UnorderedBulkOperation.html#find + find(selector: Object): FindOperatorsUnordered; + //http://mongodb.github.io/node-mongodb-native/2.1/api/UnorderedBulkOperation.html#insert + insert(doc: Object): UnorderedBulkOperation; +} - /** - * onFulfilled is called when/if "promise" resolves. onRejected is called when/if "promise" rejects. - * Both are optional, if either/both are omitted the next onFulfilled/onRejected in the chain is called. - * Both callbacks have a single parameter , the fulfillment value or rejection reason. - * "then" returns a new promise equivalent to the value you return from onFulfilled/onRejected after being passed through Promise.resolve. - * If an error is thrown in the callback, the returned promise rejects with that error. - * - * @param onFulfilled called when/if "promise" resolves - * @param onRejected called when/if "promise" rejects - */ - then (onFulfilled?: (value: R) => U | Thenable, onRejected?: (error: any) => U | Thenable): Promise; - then (onFulfilled?: (value: R) => U | Thenable, onRejected?: (error: any) => void): Promise; +//http://mongodb.github.io/node-mongodb-native/2.1/api/FindOperatorsUnordered.html +export interface FindOperatorsUnordered { + length: number; + remove(): UnorderedBulkOperation; + removeOne(): UnorderedBulkOperation; + replaceOne(doc: Object): UnorderedBulkOperation; + update(doc: Object): UnorderedBulkOperation; + updateOne(doc: Object): UnorderedBulkOperation; + upsert(): FindOperatorsUnordered; +} - /** - * Sugar for promise.then(undefined, onRejected) - * - * @param onRejected called when/if "promise" rejects - */ - catch (onRejected?: (error: any) => U | Thenable): Promise; +//http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#findOne +export interface FindOneOptions { + limit?: number, + sort?: Array | Object, + fields?: Object, + skip?: number, + hint?: Object, + explain?: boolean, + snapshot?: boolean, + timeout?: boolean, + tailable?: boolean, + batchSize?: number, + returnKey?: boolean, + maxScan?: number, + min?: number, + max?: number, + showDiskLoc?: boolean, + comment?: string, + raw?: boolean, + readPreference?: ReadPreference | string, + partial?: boolean, + maxTimeMs?: number +} - /** - * Make a new promise from the thenable. - * A thenable is promise-like in as far as it has a "then" method. - */ - static resolve (): Promise; - static resolve (value: R | Thenable): Promise; +//http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#~insertWriteOpResult +export interface InsertWriteOpResult { + insertedCount: number; + ops: Array; + insertedIds: Array; + connection: any; + result: { ok: number, n: number } +} - /** - * Make a promise that rejects to obj. For consistency and debugging (eg stack traces), obj should be an instanceof Error - */ - static reject (error: any): Promise; +//http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#insertOne +export interface CollectionInsertOneOptions { + // The write concern. + w?: number | string; + // The write concern timeout. + wtimeout?: number; + // Specify a journal write concern. + j?: boolean; + // Serialize functions on any object. + serializeFunctions?: boolean; + //Force server to assign _id values instead of driver. + forceServerObjectId?: boolean; + //Allow driver to bypass schema validation in MongoDB 3.2 or higher. + bypassDocumentValidation?: boolean +} - /** - * Make a promise that fulfills when every item in the array fulfills, and rejects if (and when) any item rejects. - * the array passed to all can be a mixture of promise-like objects and other objects. - * The fulfillment value is an array (in order) of fulfillment values. The rejection value is the first rejection value. - */ - static all(values: [T1 | Thenable, T2 | Thenable, T3 | Thenable, T4 | Thenable , T5 | Thenable, T6 | Thenable, T7 | Thenable, T8 | Thenable, T9 | Thenable, T10 | Thenable]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10]>; - static all(values: [T1 | Thenable, T2 | Thenable, T3 | Thenable, T4 | Thenable , T5 | Thenable, T6 | Thenable, T7 | Thenable, T8 | Thenable, T9 | Thenable]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9]>; - static all(values: [T1 | Thenable, T2 | Thenable, T3 | Thenable, T4 | Thenable , T5 | Thenable, T6 | Thenable, T7 | Thenable, T8 | Thenable]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8]>; - static all(values: [T1 | Thenable, T2 | Thenable, T3 | Thenable, T4 | Thenable , T5 | Thenable, T6 | Thenable, T7 | Thenable]): Promise<[T1, T2, T3, T4, T5, T6, T7]>; - static all(values: [T1 | Thenable, T2 | Thenable, T3 | Thenable, T4 | Thenable , T5 | Thenable, T6 | Thenable]): Promise<[T1, T2, T3, T4, T5, T6]>; - static all(values: [T1 | Thenable, T2 | Thenable, T3 | Thenable, T4 | Thenable , T5 | Thenable]): Promise<[T1, T2, T3, T4, T5]>; - static all(values: [T1 | Thenable, T2 | Thenable, T3 | Thenable, T4 | Thenable ]): Promise<[T1, T2, T3, T4]>; - static all(values: [T1 | Thenable, T2 | Thenable, T3 | Thenable]): Promise<[T1, T2, T3]>; - static all(values: [T1 | Thenable, T2 | Thenable]): Promise<[T1, T2]>; - static all(values: [T1 | Thenable]): Promise<[T1]>; - static all(values: Array>): Promise; +//http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#~insertOneWriteOpResult +export interface InsertOneWriteOpResult { + insertedCount: number; + ops: Array; + insertedId: ObjectID; + connection: any; + result: { ok: number, n: number } +} - /** - * Make a Promise that fulfills when any item fulfills, and rejects if any item rejects. - */ - static race (promises: (R | Thenable)[]): Promise; +//http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#parallelCollectionScan +export interface ParallelCollectionScanOptions { + readPreference?: ReadPreference | string; + batchSize?: number; + numCursors?: number; + raw?: boolean; } -/** - * The polyfill method will patch the global environment (in this case to the Promise name) when called. - */ -export function polyfill (): void; +//http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#replaceOne +export interface ReplaceOneOptions { + upsert?: boolean; + w?: number | string; + wtimeout?: number; + j?: boolean; + bypassDocumentValidation?: boolean; } -declare module '~iridium~mongodb~es6-promise' { -export * from '~iridium~mongodb~es6-promise/dist/es6-promise'; + +//http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#~updateWriteOpResult +export interface UpdateWriteOpResult { + result: { ok: number, n: number, nModified: number }; + connection: any; + matchedCount: number; + modifiedCount: number; + upsertedCount: number; + upsertedId: { _id: ObjectID }; } -// Generated by typings -// Source: https://raw.githubusercontent.com/Think7/typings-mongodb/3a50a13eeb9fbb63f8759200dcb2bf576ff33285/mongodb.d.ts -declare module '~iridium~mongodb/mongodb' { -// Type definitions for MongoDB v2.1 -// Project: https://github.com/mongodb/node-mongodb-native/tree/2.1 -// Definitions by: Andrew -// Federico Caselli -// Definitions: https://github.com/Think7/typings-mongodb +//http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#mapReduce +export interface MapReduceOptions { + readPreference?: ReadPreference | string; + out?: Object; + query?: Object; + sort?: Object; + limit?: number; + keeptemp?: boolean; + finalize?: Function | string; + scope?: Object; + jsMode?: boolean; + verbose?: boolean; + bypassDocumentValidation?: boolean +} -// Documentation : http://mongodb.github.io/node-mongodb-native/2.1/api/ +//http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#~WriteOpResult +export interface WriteOpResult { + ops: Array; + connection: any; + result: any; +} -// Use typings to install this type definition https://github.com/typings/typings +//http://mongodb.github.io/node-mongodb-native/2.1/api/external-Readable.html +export interface Readable { + pause(): void; + pipe(destination: Writable, options?: Object): void; + read(size: number): string | Buffer | void; + resume(): void; + setEncoding(encoding: string): void; + unpipe(destination?: Writable): void; + unshift(stream: Buffer | string): void; + wrap(stream: Stream): void; +} -import {EventEmitter} from 'events'; -import {Promise} from '~iridium~mongodb~es6-promise'; +export interface Writable { } +export interface Stream { } -// Class documentation : http://mongodb.github.io/node-mongodb-native/2.1/api/MongoClient.html -export class MongoClient { - constructor(); +//http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#~resultCallback +export type CursorResult = any | void | boolean; - static connect(uri: string, callback: MongoCallback): void; - static connect(uri: string, options?: MongoClientOptions): Promise; - static connect(uri: string, options: MongoClientOptions, callback: MongoCallback): void; +//http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html +export interface Cursor extends Readable, NodeJS.EventEmitter { - connect(uri: string, callback: MongoCallback): void; - connect(uri: string, options?: MongoClientOptions): Promise; - connect(uri: string, options: MongoClientOptions, callback: MongoCallback): void; + sortValue: string; + timeout: boolean; + readPreference: ReadPreference; + //http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html + addCursorFlag(flag: string, value: boolean): Cursor; + // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#addQueryModifier + addQueryModifier(name: string, value: boolean): Cursor; + // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#batchSize + batchSize(value: number): Cursor; + // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#clone + clone(): Cursor; + // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#close + close(): Promise; + close(callback: MongoCallback): void; + // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#comment + comment(value: string): Cursor; + // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#count + count(applySkipLimit: boolean, callback: MongoCallback): void; + count(applySkipLimit: boolean, options?: CursorCommentOptions): Promise; + count(applySkipLimit: boolean, options: CursorCommentOptions, callback: MongoCallback): void; + // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#explain + explain(): Promise; + explain(callback: MongoCallback): void; + //http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#filter + filter(filter: Object): Cursor; + // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#forEach + forEach(iterator: IteratorCallback, callback: EndCallback): void; + // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#hasNext + hasNext(): Promise; + hasNext(callback: MongoCallback): void; + // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#hint + hint(hint: Object): Cursor; + // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#isClosed + isClosed(): boolean; + // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#limit + limit(value: number): Cursor; + // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#map + map(transform: Function): void; + // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#max + max(max: number): Cursor; + //http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#maxAwaitTimeMS + maxAwaitTimeMS(value: number): Cursor; + // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#maxScan + maxScan(maxScan: Object): Cursor; + // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#maxTimeMS + maxTimeMS(value: number): Cursor; + // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#min + min(min: number): Cursor; + // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#next + next(): Promise; + next(callback: MongoCallback): void; + //http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#pause + pause(): void; + //http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#pipe + pipe(destination: Writable, options?: Object): void; + //http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#project + project(value: Object): Cursor; + //http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#read + read(size: number): string | Buffer | void; + //http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#resume + resume(): void; + // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#next + returnKey(returnKey: Object): Cursor; + //http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#rewind + rewind(): void; + // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#setCursorOption + setCursorOption(field: string, value: Object): Cursor; + //http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#setEncoding + setEncoding(encoding: string): void; + // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#setReadPreference + setReadPreference(readPreference: string | ReadPreference): Cursor; + // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#showRecordId + showRecordId(showRecordId: Object): Cursor; + // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#skip + skip(value: number): Cursor; + // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#snapshot + snapshot(snapshot: Object): Cursor; + // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#sort + sort(keyOrList: string | Object[] | Object | Object, direction?: number): Cursor; + // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#stream + stream(options?: { transform?: Function }): Cursor; + // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#toArray + toArray(): Promise; + toArray(callback: MongoCallback): void; + //http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#unpipe + unpipe(destination?: Writable): void; + //http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#unshift + unshift(stream: Buffer | string): void; + //http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#wrap + wrap(stream: Stream): void; } -export interface MongoCallback { - (error: MongoError, result: T): void; -} - -// http://mongodb.github.io/node-mongodb-native/2.1/api/MongoError.html -export class MongoError extends Error { - constructor(message: string); - static create(options: Object): MongoError; +//http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#count +export interface CursorCommentOptions { + skip?: number; + limit?: number; + maxTimeMS?: number; + hint?: string; + readPreference?: ReadPreference | string; } - -//http://mongodb.github.io/node-mongodb-native/2.1/api/MongoClient.html#.connect -export interface MongoClientOptions { - uri_decode_auth?: boolean; - db?: DbCreateOptions; - server?: ServerOptions; - replSet?: ReplSetOptions; - mongos?: MongosOptions; - promiseLibrary?: Object; -} - -// See : http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html -export interface DbCreateOptions { - authSource?: string; - // the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = ‘majority’ or tag acknowledges the write. - w?: number | string; - // set the timeout for waiting for write concern to finish (combines with w option). - wtimeout?: number; - j?: boolean; - // use c++ bson parser. default:false. - native_parser?: boolean; - // force server to create _id fields instead of client. default:false. - forceServerObjectId?: boolean; - serializeFunctions?: boolean; - ignoreUndefined?: boolean; - // peform operations using raw bson buffers. default:false. - raw?: boolean; - // when deserializing a Long will fit it into a Number if it’s smaller than 53 bits. default:true. - promoteLongs?: boolean; - bufferMaxEntries?: number; - // the prefered read preference. use 'ReadPreference' class. - readPreference?: ReadPreference | string; - // custom primary key factory to generate _id values (see Custom primary keys). - pkFactory?: Object; - promiseLibrary?: Object; - readConcern?: { level?: Object }; + +//http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#~iteratorCallback +export interface IteratorCallback { + (doc: any): void; } -// See http://mongodb.github.io/node-mongodb-native/2.1/api/ReadPreference.html -export class ReadPreference { - constructor(mode: string, tags: Object); - mode: string; - tags: any; - static PRIMARY: string; - static PRIMARY_PREFERRED: string; - static SECONDARY: string; - static SECONDARY_PREFERRED: string; - static NEAREST: string; - isValid(mode: string): boolean; - static isValid(mode: string): boolean; +//http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#~endCallback +export interface EndCallback { + (error: MongoError): void; } - -//http://mongodb.github.io/node-mongodb-native/2.1/api/Server.html -export interface SocketOptions { - // Reconnect on error. default:false - autoReconnect?: boolean; - // TCP Socket NoDelay option. default:true - noDelay?: boolean; - // TCP KeepAlive on the socket with a X ms delay before start. default:0 - keepAlive?: number; - // TCP Connection timeout setting. default 0 - connectTimeoutMS?: number; - // TCP Socket timeout setting. default 0 - socketTimeoutMS?: number; + +//http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#~resultCallback +export type AggregationCursorResult = any | void; + +//http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html +export interface AggregationCursor extends Readable, NodeJS.EventEmitter { + // http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#batchSize + batchSize(value: number): AggregationCursor; + // http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#clone + clone(): AggregationCursor; + // http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#close + close(): Promise; + close(callback: MongoCallback): void; + //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#each + each(callback: MongoCallback): void; + // http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#explain + explain(): Promise; + explain(callback: MongoCallback): void; + //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#geoNear + geoNear(document: Object): AggregationCursor; + //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#group + group(document: Object): AggregationCursor; + // http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#isClosed + isClosed(): boolean; + // http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#limit + limit(value: number): AggregationCursor; + //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#match + match(document: Object): AggregationCursor; + // http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#maxTimeMS + maxTimeMS(value: number): AggregationCursor; + // http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#next + next(): Promise; + next(callback: MongoCallback): void; + // http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#out + out(destination: string): AggregationCursor; + //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#pause + pause(): void; + //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#pipe + pipe(destination: Writable, options?: Object): void; + //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#project + project(document: Object): AggregationCursor; + //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#read + read(size: number): string | Buffer | void; + //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#redact + redact(document: Object): AggregationCursor; + //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#resume + resume(): void; + //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#rewind + rewind(): AggregationCursor; + //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#setEncoding + setEncoding(encoding: string): void; + // http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#skip + skip(value: number): AggregationCursor; + // http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#sort + sort(document: Object): AggregationCursor; + // http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#toArray + toArray(): Promise; + toArray(callback: MongoCallback): void; + //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#unpipe + unpipe(destination?: Writable): void; + //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#unshift + unshift(stream: Buffer | string): void; + //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#unwind + unwind(field: string): AggregationCursor; + //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#wrap + wrap(stream: Stream): void; } - -//http://mongodb.github.io/node-mongodb-native/2.1/api/Server.html -export interface ServerOptions { - // - specify the number of connections in the pool default:5 - poolSize?: number; - ssl?: boolean; - sslValidate?: Object; - checkServerIdentity?: boolean | Function; - sslCA?: Array; - sslCert?: Buffer | string; - sslKey?: Buffer | string; - sslPass?: Buffer | string; - socketOptions?: SocketOptions; - reconnectTries?: number; - reconnectInterval?: number; + +//http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html +export interface CommandCursor extends Readable, NodeJS.EventEmitter { + // http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#batchSize + batchSize(value: number): CommandCursor; + // http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#clone + clone(): CommandCursor; + // http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#close + close(): Promise; + close(callback: MongoCallback): void; + //http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#each + each(callback: MongoCallback): void; + // http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#isClosed + isClosed(): boolean; + // http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#maxTimeMS + maxTimeMS(value: number): CommandCursor; + // http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#next + next(): Promise; + next(callback: MongoCallback): void; + //http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#pause + pause(): void; + //http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#pipe + pipe(destination: Writable, options?: Object): void; + //http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#read + read(size: number): string | Buffer | void; + //http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#resume + resume(): void; + //http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#rewind + rewind(): CommandCursor; + //http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#setEncoding + setEncoding(encoding: string): void; + // http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#setReadPreference + setReadPreference(readPreference: string | ReadPreference): CommandCursor; + // http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#toArray + toArray(): Promise; + toArray(callback: MongoCallback): void; + //http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#unpipe + unpipe(destination?: Writable): void; + //http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#unshift + unshift(stream: Buffer | string): void; + //http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#wrap + wrap(stream: Stream): void; } - -//http://mongodb.github.io/node-mongodb-native/2.1/api/ReplSet.html -export interface ReplSetOptions { - ha?: boolean; - haInterval?: number; - replicaSet?: string; - secondaryAcceptableLatencyMS?: number; - connectWithNoPrimary?: boolean; - // - specify the number of connections in the pool default:5 - poolSize?: number; - ssl?: boolean; - sslValidate?: Object; - checkServerIdentity?: boolean | Function; - sslCA?: Array; - sslCert?: Buffer | string; - sslKey?: Buffer | string; - sslPass?: Buffer | string; - socketOptions?: SocketOptions; } - -//http://mongodb.github.io/node-mongodb-native/2.1/api/Mongos.html -export interface MongosOptions { - ha?: boolean; - haInterval?: number; - // - specify the number of connections in the pool default:5 - poolSize?: number; - ssl?: boolean; - sslValidate?: Object; - checkServerIdentity?: boolean | Function; - sslCA?: Array; - sslCert?: Buffer | string; - sslKey?: Buffer | string; - sslPass?: Buffer | string; - socketOptions?: SocketOptions; +declare module '~iridium~mongodb' { +export * from '~iridium~mongodb/mongodb'; } - -// Class documentation : http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html -export class Db extends EventEmitter { - constructor(databaseName: string, serverConfig: Server | ReplSet | Mongos, options?: DbCreateOptions); - serverConfig: Server | ReplSet | Mongos; - bufferMaxEntries: number; - databaseName: string; - options: any; - native_parser: boolean; - slaveOk: boolean; - writeConcern: any; +// Generated by typings +// Source: dist/lib/middleware/Express.d.ts +declare module '~iridium/dist/lib/middleware/Express' { +import * as http from 'http'; +import { Core } from '~iridium/dist/lib/Core'; +/** + * A factory method which creates Express/Connect compatible middleware functions to inject + * a "db" field on your request objects as well as ensuring that the Iridium Core is connected + * to a MongoDB database before handling any requests. + * + * @internal + */ +export function ExpressMiddlewareFactory(core: Core): ExpressMiddleware; +/** + * An Express/Connect compatible middleware function which injects req.db and ensures that the Iridium Core + * has an active database connection before continuing the request handling process. + */ +export interface ExpressMiddleware { + (req: http.ServerRequest, res: http.ServerResponse, next: (err?: Error, route?: String) => void): any; +} +} +declare module 'iridium/dist/lib/middleware/Express' { +export * from '~iridium/dist/lib/middleware/Express'; +} - // http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html#addUser - addUser(username: string, password: string, callback: MongoCallback): void; - addUser(username: string, password: string, options?: DbAddUserOptions): Promise; - addUser(username: string, password: string, options: DbAddUserOptions, callback: MongoCallback): void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html#admin - admin(): Admin; - // http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html#authenticate - authenticate(userName: string, password: string, callback: MongoCallback): void; - authenticate(userName: string, password: string, options?: { authMechanism: string }): Promise; - authenticate(userName: string, password: string, options: { authMechanism: string }, callback: MongoCallback): void; - // http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html#close - close(callback: MongoCallback): void; - close(forceClose?: boolean): Promise; - close(forceClose: boolean, callback: MongoCallback): void; - // http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html#collection - collection(name: string): Collection; - collection(name: string, callback: MongoCallback): Collection; - collection(name: string, options: DbCollectionOptions, callback: MongoCallback): Collection; - //http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html#collections - collections(): Promise; - collections(callback: MongoCallback): void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html#command - command(command: Object, callback?: MongoCallback): void; - command(command: Object, options?: { readPreference: ReadPreference | string }): Promise; - command(command: Object, options: { readPreference: ReadPreference | string }, callback: MongoCallback): void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html#createCollection - createCollection(name: string, callback: MongoCallback): void; - createCollection(name: string, options?: CollectionCreateOptions): Promise; - createCollection(name: string, options: CollectionCreateOptions, callback: MongoCallback): void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html#createIndex - createIndex(name: string, fieldOrSpec: string | Object, callback: MongoCallback): void; - createIndex(name: string, fieldOrSpec: string | Object, options?: IndexOptions): Promise; - createIndex(name: string, fieldOrSpec: string | Object, options: IndexOptions, callback: MongoCallback): void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html#db - db(dbName: string): Db; - db(dbName: string, options: { noListener?: boolean, returnNonCachedInstance?: boolean }): Db; - //http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html#dropCollection - dropCollection(name: string): Promise; - dropCollection(name: string, callback: MongoCallback): void; - // http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html#dropDatabase - dropDatabase(): Promise; - dropDatabase(callback: MongoCallback): void; - - //deprecated http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html#ensureIndex - // ensureIndex(collectionName: any, fieldOrSpec: any, options: IndexOptions, callback: Function): void; - //deprecated http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html#eval - // eval(code: any, parameters: any[], options?: any, callback?: MongoCallback): void; - - //http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html#executeDbAdminCommand - executeDbAdminCommand(command: Object, callback: MongoCallback): void; - executeDbAdminCommand(command: Object, options?: { readPreference?: ReadPreference | string, maxTimeMS?: number }): Promise; - executeDbAdminCommand(command: Object, options: { readPreference?: ReadPreference | string, maxTimeMS?: number }, callback: MongoCallback): void; - // http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html#indexInformation - indexInformation(name: string, callback: MongoCallback): void; - indexInformation(name: string, options?: { full?: boolean, readPreference?: ReadPreference | string }): Promise; - indexInformation(name: string, options: { full?: boolean, readPreference?: ReadPreference | string }, callback: MongoCallback): void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html#listCollections - listCollections(filter: { name?: string }, options?: { batchSize?: number, readPreference?: ReadPreference | string }): CommandCursor; - //http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html#logout - logout(callback: MongoCallback): void; - logout(options?: { dbName?: string }): Promise; - logout(options: { dbName?: string }, callback: MongoCallback): void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html#open - open(): Promise; - open(callback: MongoCallback): void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html#removeUser - removeUser(username: string, callback: MongoCallback): void; - removeUser(username: string, options?: { w?: number | string, wtimeout?: number, j?: boolean }): Promise; - removeUser(username: string, options: { w?: number | string, wtimeout?: number, j?: boolean }, callback: MongoCallback): void; - // http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html#renameCollection - renameCollection(fromCollection: string, toCollection: string, callback: MongoCallback): void; - renameCollection(fromCollection: string, toCollection: string, options?: { dropTarget?: boolean }): Promise; - renameCollection(fromCollection: string, toCollection: string, options: { dropTarget?: boolean }, callback: MongoCallback): void; - // http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html#stats - stats(callback: MongoCallback): void; - stats(options?: { scale?: number }): Promise; - stats(options: { scale?: number }, callback: MongoCallback): void; -} - - - -// Deprecated http://mongodb.github.io/node-mongodb-native/2.1/api/Server.html -export class Server extends EventEmitter { - constructor(host: string, port: number, options?: ServerOptions); - - connections(): Array; -} - -// Deprecated http://mongodb.github.io/node-mongodb-native/2.1/api/ReplSet.html -export class ReplSet extends EventEmitter { - constructor(servers: Array, options?: ReplSetOptions); - - connections(): Array; +// Generated by typings +// Source: dist/lib/Core.d.ts +declare module '~iridium/dist/lib/Core' { +import * as Bluebird from '~iridium~bluebird'; +import * as MongoDB from '~iridium~mongodb'; +import { Configuration } from '~iridium/dist/lib/Configuration'; +import { Plugin } from '~iridium/dist/lib/Plugins'; +import * as ExpressMiddleware from '~iridium/dist/lib/middleware/Express'; +import { Cache } from '~iridium/dist/lib/Cache'; +/** + * The Iridium Core, responsible for managing the connection to the database as well + * as any plugins you are making use of. + * + * Generally you will subclass this to provide your own custom core with the models you + * make use of within your application. + */ +export class Core { + /** + * Creates a new Iridium Core instance connected to the specified MongoDB instance + * @param {Iridium.IridiumConfiguration} config The config object defining the database to connect to + * @constructs Core + */ + constructor(config: Configuration); + /** + * Creates a new Iridium Core instance connected to the specified MongoDB instance + * @param {String} url The URL of the MongoDB instance to connect to + * @param {Iridium.IridiumConfiguration} config The config object made available as settings + * @constructs Core + */ + constructor(uri: string, config?: Configuration); + private mongoConnectAsyc; + private _plugins; + private _url; + private _config; + private _connection; + private _cache; + private _connectPromise; + /** + * Gets the plugins registered with this Iridium Core + * @returns {[Iridium.Plugin]} + */ + plugins: Plugin[]; + /** + * Gets the configuration specified in the construction of this + * Iridium Core. + * @returns {Iridium.Configuration} + */ + settings: Configuration; + /** + * Gets the currently active database connection for this Iridium + * Core. + * @returns {MongoDB.Db} + */ + connection: MongoDB.Db; + /** + * Gets the URL used to connect to MongoDB + * @returns {String} + */ + url: string; + /** + * Gets the cache used to store objects retrieved from the database for performance reasons + * @returns {cache} + */ + cache: Cache; + /** + * Registers a new plugin with this Iridium Core + * @param {Iridium.Plugin} plugin The plugin to register with this Iridium Core + * @returns {Iridium.Core} + */ + register(plugin: Plugin): Core; + /** + * Connects to the database server specified in the provided configuration + * @param {function(Error, Iridium.Core)} [callback] A callback to be triggered once the connection is established. + * @returns {Promise} + */ + connect(callback?: (err: Error, core: Core) => any): Bluebird; + /** + * Closes the active database connection + * @type {Promise} + */ + close(): Bluebird; + /** + * Provides an express middleware which can be used to set the req.db property + * to the current Iridium instance. + * @returns {Iridium.ExpressMiddleware} + */ + express(): ExpressMiddleware.ExpressMiddleware; + /** + * A method which is called whenever a new connection is made to the database. + * + * @param connection The underlying MongoDB connection which was created, you can modify or replace this if you wish. + * @returns A promise for the connection, allowing you to perform any asynchronous initialization required by your application. + * + * In subclassed Iridium Cores this method can be overridden to manipulate the properties + * of the underlying MongoDB connection object, such as authenticating. Until this method + * resolves a connection object, Iridium will be unable to execute any queries. If you wish + * to run Iridium queries then look at the onConnected method. + */ + protected onConnecting(connection: MongoDB.Db): Bluebird; + /** + * A method which is called once a database connection has been established and accepted by Iridium + * + * In subclassed Iridium cores this method can be overridden to perform tasks whenever a + * connection to the database has been established - such as setting up indexes for your + * collections or seeding the database. + */ + protected onConnected(): Bluebird; } - -// Deprecated http://mongodb.github.io/node-mongodb-native/2.1/api/ReplSet.html -export class Mongos extends EventEmitter { - constructor(servers: Array, options?: MongosOptions); - - connections(): Array; } -// http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html#addUser -export interface DbAddUserOptions { - w?: string | number; - wtimeout?: number; - j?: boolean; - customData?: Object; - roles?: Object[]; +declare module 'iridium/dist/lib/Core' { +export * from '~iridium/dist/lib/Core'; } -//http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html#createCollection -export interface CollectionCreateOptions { - w?: number | string; - wtimeout?: number; - j?: boolean; - raw?: boolean; - pkFactory?: Object; - readPreference?: ReadPreference | string; - serializeFunctions?: boolean; - strict?: boolean; - capped?: boolean; - size?: number; - max?: number; - autoIndexId?: boolean; -} - -// http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html#collection -export interface DbCollectionOptions { - w?: number | string; - wtimeout?: number; - j?: boolean; - raw?: boolean; - pkFactory?: Object; - readPreference?: ReadPreference | string; - serializeFunctions?: boolean; - strict?: boolean; - readConcern?: { level: Object }; -} - -//http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html#createIndex -export interface IndexOptions { - // The write concern. - w?: number | string; - // The write concern timeout. - wtimeout?: number; - // Specify a journal write concern. - j?: boolean; - // Creates an unique index. - unique?: boolean; - // Creates a sparse index. - sparse?: boolean; - // Creates the index in the background, yielding whenever possible. - background?: boolean; - // A unique index cannot be created on a key that has pre-existing duplicate values. - // If you would like to create the index anyway, keeping the first document the database indexes and - // deleting all subsequent documents that have duplicate value - dropDups?: boolean; - // For geo spatial indexes set the lower bound for the co-ordinates. - min?: number; - // For geo spatial indexes set the high bound for the co-ordinates. - max?: number; - // Specify the format version of the indexes. - v?: number; - // Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) - expireAfterSeconds?: number; - // Override the auto generated index name (useful if the resulting name is larger than 128 bytes) - name?: string; -} - -// http://mongodb.github.io/node-mongodb-native/2.1/api/Admin.html -export interface Admin { - // http://mongodb.github.io/node-mongodb-native/2.1/api/Admin.html#addUser - addUser(username: string, password: string, callback: MongoCallback): void; - addUser(username: string, password: string, options?: AddUserOptions): Promise; - addUser(username: string, password: string, options: AddUserOptions, callback: MongoCallback): void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/Admin.html#authenticate - authenticate(username: string, callback: MongoCallback): void; - authenticate(username: string, password?: string): Promise; - authenticate(username: string, password: string, callback: MongoCallback): void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/Admin.html#buildInfo - buildInfo(): Promise; - buildInfo(callback: MongoCallback): void - //http://mongodb.github.io/node-mongodb-native/2.1/api/Admin.html#command - command(command: Object, callback: MongoCallback): void; - command(command: Object, options?: { readPreference?: ReadPreference | string, maxTimeMS?: number }): Promise; - command(command: Object, options: { readPreference?: ReadPreference | string, maxTimeMS?: number }, callback: MongoCallback): void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/Admin.html#listDatabases - listDatabases(): Promise; - listDatabases(callback: MongoCallback): void - //http://mongodb.github.io/node-mongodb-native/2.1/api/Admin.html#logout - logout(): Promise; - logout(callback: MongoCallback): void - //http://mongodb.github.io/node-mongodb-native/2.1/api/Admin.html#ping - ping(): Promise; - ping(callback: MongoCallback): void - //http://mongodb.github.io/node-mongodb-native/2.1/api/Admin.html#profilingInfo - profilingInfo(): Promise; - profilingInfo(callback: MongoCallback): void - //http://mongodb.github.io/node-mongodb-native/2.1/api/Admin.html#profilingLevel - profilingLevel(): Promise; - profilingLevel(callback: MongoCallback): void - //http://mongodb.github.io/node-mongodb-native/2.1/api/Admin.html#removeUser - removeUser(username: string, callback: MongoCallback): void; - removeUser(username: string, options?: FSyncOptions): Promise; - removeUser(username: string, options: FSyncOptions, callback: MongoCallback): void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/Admin.html#replSetGetStatus - replSetGetStatus(): Promise; - replSetGetStatus(callback: MongoCallback): void - //http://mongodb.github.io/node-mongodb-native/2.1/api/Admin.html#serverInfo - serverInfo(): Promise; - serverInfo(callback: MongoCallback): void - //http://mongodb.github.io/node-mongodb-native/2.1/api/Admin.html#serverStatus - serverStatus(): Promise; - serverStatus(callback: MongoCallback): void - //http://mongodb.github.io/node-mongodb-native/2.1/api/Admin.html#setProfilingLevel - setProfilingLevel(level: string): Promise; - setProfilingLevel(level: string, callback: MongoCallback): void - // http://mongodb.github.io/node-mongodb-native/2.1/api/Admin.html#validateCollection - validateCollection(collectionNme: string, callback: MongoCallback): void; - validateCollection(collectionNme: string, options?: Object): Promise; - validateCollection(collectionNme: string, options: Object, callback: MongoCallback): void; +// Generated by typings +// Source: dist/lib/Cursor.d.ts +declare module '~iridium/dist/lib/Cursor' { +import { Model } from '~iridium/dist/lib/Model'; +import * as General from '~iridium/dist/lib/General'; +import * as MongoDB from '~iridium~mongodb'; +import * as Bluebird from '~iridium~bluebird'; +import * as Index from '~iridium/dist/lib/Index'; +/** + * An Iridium collection cursor which allows the itteration through documents + * in the collection, automatically wrapping them in the correct instance type. + * + * @param TDocument The interface representing the collection's documents + * @param TInstance The interface or class used to represent the wrapped documents. + */ +export class Cursor { + private model; + private conditions; + cursor: MongoDB.Cursor; + /** + * Creates a new Iridium cursor which wraps a MongoDB cursor object + * @param {Model} model The Iridium model that this cursor belongs to + * @param {Object} conditions The conditions that resulte in this cursor being created + * @param {MongoDB.Cursor} cursor The MongoDB native cursor object to be wrapped + * @constructor + */ + constructor(model: Model, conditions: any, cursor: MongoDB.Cursor); + /** + * Counts the number of documents which are matched by this cursor + * @param {function(Error, Number)} callback A callback which is triggered when the result is available + * @return {Promise} A promise which will resolve with the number of documents matched by this cursor + */ + count(callback?: General.Callback): Bluebird; + /** + * Runs the specified handler over each instance in the query results + * @param {function(Instance)} handler The handler which is triggered for each element in the query + * @param {function(Error)} callback A callback which is triggered when all operations have been dispatched + * @return {Promise} A promise which is resolved when all operations have been dispatched + */ + forEach(handler: (instance: TInstance) => void, callback?: General.Callback): Bluebird; + /** + * Runs the specified transform over each instance in the query results and returns the resulting transformed objects + * @param {function(Instance): TResult} transform A handler which is used to transform the result objects + * @param {function(Error, TResult[])} callback A callback which is triggered when the transformations are completed + * @return {Promise} A promise which is fulfilled with the results of the transformations + */ + map(transform: (instance: TInstance) => TResult | Bluebird, callback?: General.Callback): Bluebird; + /** + * Retrieves all matching instances and returns them in an array + * @param {function(Error, TInstance[])} callback A callback which is triggered with the resulting instances + * @return {Promise} A promise which resolves with the instances returned by the query + */ + toArray(callback?: General.Callback): Bluebird; + /** + * Retrieves the next item in the results list + * @param {function(Error, TInstance)} callback A callback which is triggered when the next item becomes available + * @return {Promise} A promise which is resolved with the next item + */ + next(callback?: General.Callback): Bluebird; + /** + * Retrieves the next item in the result list and then closes the cursor + * @param {function(Error, TInstance)} callback A callback which is triggered when the next item becomes available + * @return {Promise} A promise which is resolved once the item becomes available and the cursor has been closed. + */ + one(callback?: General.Callback): Bluebird; + /** + * Returns a new cursor which behaves the same as this one did before any results were retrieved + * @return {Cursor} The new cursor which starts at the beginning of the results + */ + rewind(): Cursor; + /** + * Returns a new cursor which sorts its results by the given index expression + * @param {model.IndexSpecification} sortExpression The index expression dictating the sort order and direction to use + * @return {Cursor} The new cursor which sorts its results by the sortExpression + */ + sort(sortExpression: Index.IndexSpecification): Cursor; + /** + * Returns a new cursor which limits the number of returned results + * @param {Number} limit The maximum number of results to return + * @return {Cursor} The new cursor which will return a maximum number of results + */ + limit(limit: number): Cursor; + /** + * Returns a new cursor which skips a number of results before it begins + * returning any. + * @param {Number} skip The number of results to skip before the cursor beings returning + * @return {Cursor} The new cursor which skips a number of results + */ + skip(skip: number): Cursor; + /** + * Returns a new cursor which will read from the specified node type. + * @param {String} type The type of node to read from - see https://docs.mongodb.org/manual/core/read-preference/ + * @return {Cursor} The new cursor which reads from the specified node type + */ + readFrom(type: string): Cursor; } - -//http://mongodb.github.io/node-mongodb-native/2.1/api/Admin.html#addUser -export interface AddUserOptions { - w?: number | string; - wtimeout?: number; - j?: boolean; - fsync: boolean; - customData?: Object; - roles?: Object[] } - -//http://mongodb.github.io/node-mongodb-native/2.1/api/Admin.html#removeUser -export interface FSyncOptions { - w?: number | string; - wtimeout?: number; - j?: boolean; - fsync?: boolean +declare module 'iridium/dist/lib/Cursor' { +export * from '~iridium/dist/lib/Cursor'; } -// Class documentation : http://mongodb.github.io/node-mongodb-native/2.1/api/ObjectID.html -export class ObjectID { - constructor(s?: string | number); - - generationTime: number; - - // Creates an ObjectID from a hex string representation of an ObjectID. - // hexString – create a ObjectID from a passed in 24 byte hexstring. - static createFromHexString(hexString: string): ObjectID; - // Creates an ObjectID from a second based number, with the rest of the ObjectID zeroed out. Used for comparisons or sorting the ObjectID. - // time – an integer number representing a number of seconds. - static createFromTime(time: number): ObjectID; - // Checks if a value is a valid bson ObjectId - // id - Value to be checked - static isValid(id: string | number): boolean; - //Compares the equality of this ObjectID with otherID. - equals(otherID: ObjectID): boolean; - // Generate a 12 byte id string used in ObjectID's - // time - optional parameter allowing to pass in a second based timestamp - generate(time?: number): string; - // Returns the generation date (accurate up to the second) that this ID was generated. - getTimestamp(): Date; - // Returns the ObjectID id as a 24 byte hex string representation - toHexString(): string; +// Generated by typings +// Source: dist/lib/ModelCache.d.ts +declare module '~iridium/dist/lib/ModelCache' { +import { Model } from '~iridium/dist/lib/Model'; +import * as Bluebird from '~iridium~bluebird'; +/** + * A centralized class which ties the cache and cache directors together in a cohesive way + * for use by Iridium. + * @internal + */ +export class ModelCache { + model: Model; + constructor(model: Model); + set(value: T): void; + get(conditions: any): Bluebird; + clear(conditions: any): void; } - -// Class documentation : http://mongodb.github.io/node-mongodb-native/2.1/api/Binary.html -export class Binary { - constructor(buffer: Buffer, subType?: number); - - static SUBTYPE_BYTE_ARRAY: number; - static SUBTYPE_DEFAULT: number; - static SUBTYPE_FUNCTION: number; - static SUBTYPE_MD5: number; - static SUBTYPE_USER_DEFINED: number; - static SUBTYPE_UUID: number; - static SUBTYPE_UUID_OLD: number; - - // The length of the binary. - length(): number; - // Updates this binary with byte_value - put(byte_value: number | string): void; - // Reads length bytes starting at position. - read(position: number, length: number): Buffer; - // Returns the value of this binary as a string. - value(): string; - // Writes a buffer or string to the binary - write(buffer: Buffer | string, offset: number): void; } -//http://mongodb.github.io/node-mongodb-native/2.1/api/Double.html -export class Double { - constructor(value: number); - - valueOf(): number; +declare module 'iridium/dist/lib/ModelCache' { +export * from '~iridium/dist/lib/ModelCache'; } - -//http://mongodb.github.io/node-mongodb-native/2.1/api/Long.html -export class Long { - constructor(low: number, high: number); - - static MAX_VALUE: Long; - static MIN_VALUE: Long; - static NEG_ONE: Long; - static ONE: Long; - static ZERO: Long; - - static fromBits(lowBits: number, highBits: number): Long; - static fromInt(value: number): Long; - static fromNumber(value: number): Long; - static fromString(str: string, radix?: number): Long; - add(other: Long): Long; - and(other: Long): Long; - compare(other: Long): number; - div(other: Long): Long; - equals(other: Long): boolean; - getHighBits(): number; - getLowBits(): number; - getLowBitsUnsigned(): number; - getNumBitsAbs(): number; - greaterThan(other: Long): number; - greaterThanOrEqual(other: Long): number; - isNegative(): boolean; - isOdd(): boolean; - isZero(): boolean; - lessThan(other: Long): boolean; - lessThanOrEqual(other: Long): boolean; - modulo(other: Long): Long; - multiply(other: Long): Long; - negate(): Long; - not(): Long; - notEquals(other: Long): boolean; - or(other: Long): Long; - shiftLeft(other: number): Long; - shiftRight(other: number): Long; - shiftRightUnsigned(other: number): Long; - subtract(other: Long): Long; - toInt(): number; - toJSON(): string; - toNumber(): number; - toString(radix?: number): string; - xor(other: Long): Long; +// Generated by typings +// Source: dist/lib/ModelHelpers.d.ts +declare module '~iridium/dist/lib/ModelHelpers' { +import { Model } from '~iridium/dist/lib/Model'; +import * as Skmatc from '~iridium~skmatc'; +/** + * A number of helper methods used commonly within Iridium, they provide a means to transform, + * validate, wrap and diff instances and documents. By keeping these methods in one place we + * help to improve testability and reduce code duplication (mouse abuse) throughout the codebase. + * @internal + */ +export class ModelHelpers { + model: Model; + constructor(model: Model); + private _validator; + /** + * Validates a document to ensure that it matches the model's ISchema requirements + * @param {any} document The document to validate against the ISchema + * @returns {SkmatcCore.IResult} The result of the validation + */ + validate(document: TDocument): Skmatc.Result; + /** + * Wraps the given document in an instance wrapper for use throughout the application + * @param {any} document The document to be wrapped as an instance + * @param {Boolean} isNew Whether the instance originated from the database or was created by the application + * @param {Boolean} isPartial Whether the document supplied contains all information present in the database + * @returns {any} An instance which wraps this document + */ + wrapDocument(document: TDocument, isNew?: boolean, isPartial?: boolean): TInstance; + /** + * Converts the given document to its database form into a form + * using the transforms defined on the model. + * @param {any} document The document to be converted + * @returns {any} The result of having transformed the document. + * @remarks This is only really called from insert/create - as + */ + transformToDB(document: T, options?: TransformOptions): T; + /** + * Converts the given document from its database form using the + * transforms defined on the model. + * @param document The document to be converted. + * @returns The result of having transformed the document. + * @remarks Unlike the transformToDB function - this method only applies + * document level transforms, as property level transforms are applied in + * their relevant instance setters. + */ + transformFromDB(document: TDocument, options?: TransformOptions): TDocument; + /** + * Converts the given document to its database form into a form + * using the transforms defined on the model. + * @param document The document to be converted + * @param processProperties Whether or not to process properties in addition + * document level transforms. + * @returns {any} A new document cloned from the original and transformed + */ + convertToDB(document: T, options?: TransformOptions): T; + /** + * Performs a diff operation between two documents and creates a MongoDB changes object to represent the differences + * @param {any} original The original document prior to changes being made + * @param {any} modified The document after changes were made + */ + diff(original: TDocument, modified: TDocument): any; + /** + * Clones the given document recursively, taking into account complex types like + * Buffers correctly. + * + * @param {any} The document you wish to clone deeply. + */ + cloneDocument(original: T): T; + /** + * Clones the given document recursively, taking into account complex types like + * Buffers correctly. Optimized for working with query documents instead of true + * documents. + * + * @param {any} The document you wish to clone deeply. + */ + cloneConditions(original: T): T; +} +export interface TransformOptions { + properties?: boolean; + document?: boolean; +} +} +declare module 'iridium/dist/lib/ModelHelpers' { +export * from '~iridium/dist/lib/ModelHelpers'; } - -//http://mongodb.github.io/node-mongodb-native/2.1/api/MaxKey.html -export class MaxKey { } - -//http://mongodb.github.io/node-mongodb-native/2.1/api/MinKey.html -export class MinKey { } - -//http://mongodb.github.io/node-mongodb-native/2.1/api/Timestamp.html -export class Timestamp { - constructor(low: number, high: number); - static MAX_VALUE: Timestamp; - static MIN_VALUE: Timestamp; - static NEG_ONE: Timestamp; - static ONE: Timestamp; - static ZERO: Timestamp; +// Generated by typings +// Source: dist/lib/ModelHandlers.d.ts +declare module '~iridium/dist/lib/ModelHandlers' { +import { Model } from '~iridium/dist/lib/Model'; +import * as ModelOptions from '~iridium/dist/lib/ModelOptions'; +import * as Bluebird from '~iridium~bluebird'; +/** + * Provides a number of methods which are used to handle events that occur within + * the Iridium workflow - such as what happens when a document is received from + * the database, or how to handle the creation of new documents and saving of instances. + * + * Mostly this is for cache support, wrapping and hook triggering. + * @internal + */ +export class ModelHandlers { + model: Model; + constructor(model: Model); + documentReceived(conditions: any, result: TDocument, wrapper: (document: TDocument, isNew?: boolean, isPartial?: boolean) => TResult, options?: ModelOptions.QueryOptions): Bluebird; + creatingDocuments(documents: TDocument[]): Bluebird; + savingDocument(instance: TInstance, changes: any): Bluebird; +} +} +declare module 'iridium/dist/lib/ModelHandlers' { +export * from '~iridium/dist/lib/ModelHandlers'; +} - static fromBits(lowBits: number, highBits: number): Timestamp; - static fromInt(value: number): Timestamp; - static fromNumber(value: number): Timestamp; - static fromString(str: string, radix?: number): Timestamp; +// Generated by typings +// Source: dist/lib/ModelInterfaces.d.ts +declare module '~iridium/dist/lib/ModelInterfaces' { +/** + * The interface to which a prepared instance constructor should conform. When called with a document + * object, it should instantiate a new instance of type TInstance which is associated with its parent + * model. + * + * This is primarily used internally for prepared model instance constructors. + * + * @param TDocument The interface used to describe the structure of the documents found in the database collection. + * @param TInstance The interface or class used to wrap the documents returned from the database. + * + * @internal + */ +export interface ModelSpecificInstanceConstructor { + new (doc: TDocument, isNew?: boolean, isPartial?: boolean): TInstance; +} +} +declare module 'iridium/dist/lib/ModelInterfaces' { +export * from '~iridium/dist/lib/ModelInterfaces'; +} - add(other: Timestamp): Timestamp; - and(other: Timestamp): Timestamp; - compare(other: Timestamp): number; - div(other: Timestamp): Timestamp; - equals(other: Timestamp): boolean; - getHighBits(): number; - getLowBits(): number; - getLowBitsUnsigned(): number; - getNumBitsAbs(): number; - greaterThan(other: Timestamp): number; - greaterThanOrEqual(other: Timestamp): number; - isNegative(): boolean; - isOdd(): boolean; - isZero(): boolean; - lessThan(other: Timestamp): boolean; - lessThanOrEqual(other: Timestamp): boolean; - modulo(other: Timestamp): Timestamp; - multiply(other: Timestamp): Timestamp; - negate(): Timestamp; - not(): Timestamp; - notEquals(other: Timestamp): boolean; - or(other: Timestamp): Timestamp; - shiftLeft(other: number): Timestamp; - shiftRight(other: number): Timestamp; - shiftRightUnsigned(other: number): Timestamp; - subtract(other: Timestamp): Timestamp; - toInt(): number; - toJSON(): string; - toNumber(): number; - toString(radix?: number): string; - xor(other: Timestamp): Timestamp; -} - -// Documentation : http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html -export interface Collection { - // Get the collection name. - collectionName: string; - // Get the full collection namespace. - namespace: string; - // The current write concern values. - writeConcern: any; - // The current read concern values. - readConcern: any; - // Get current index hint for collection. - hint: any; - //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#aggregate - aggregate(pipeline: Object[], callback: MongoCallback): void | AggregationCursor; - aggregate(pipeline: Object[], options: CollectionAggrigationOptions, callback: MongoCallback): void | AggregationCursor; - //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#bulkWrite - bulkWrite(operations: Object[], callback: MongoCallback): void - bulkWrite(operations: Object[], options?: CollectionBluckWriteOptions): Promise - bulkWrite(operations: Object[], options: CollectionBluckWriteOptions, callback: MongoCallback): void - //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#count - count(query: Object, callback: MongoCallback): void; - count(query: Object, options?: MongoCountPreferences): Promise; - count(query: Object, options: MongoCountPreferences, callback: MongoCallback): void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#createIndex - createIndex(fieldOrSpec: string | any, callback: MongoCallback): void; - createIndex(fieldOrSpec: string | any, options?: IndexOptions): Promise; - createIndex(fieldOrSpec: string | any, options: IndexOptions, callback: MongoCallback): void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#createIndexes and http://docs.mongodb.org/manual/reference/command/createIndexes/ - createIndexes(indexSpecs: Object[]): Promise; - createIndexes(indexSpecs: Object[], callback: MongoCallback): void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#deleteMany - deleteMany(filter: Object, callback: MongoCallback): void; - deleteMany(filter: Object, options?: CollectionOptions): Promise; - deleteMany(filter: Object, options: CollectionOptions, callback: MongoCallback): void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#deleteOne - deleteOne(filter: Object, callback: MongoCallback): void; - deleteOne(filter: Object, options?: { w?: number | string, wtimmeout?: number, j?: boolean, bypassDocumentValidation?: boolean }): Promise; - deleteOne(filter: Object, options: { w?: number | string, wtimmeout?: number, j?: boolean, bypassDocumentValidation?: boolean }, callback: MongoCallback): void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#distinct - distinct(key: string, query: Object, callback: MongoCallback): void - distinct(key: string, query: Object, options?: { readPreference?: ReadPreference | string }): Promise; - distinct(key: string, query: Object, options: { readPreference?: ReadPreference | string }, callback: MongoCallback): void - //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#drop - drop(): Promise; - drop(callback: MongoCallback): void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#dropIndex - dropIndex(indexName: string, callback: MongoCallback): void; - dropIndex(indexName: string, options?: CollectionOptions): Promise; - dropIndex(indexName: string, options: CollectionOptions, callback: MongoCallback): void; - // http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#dropIndexes - dropIndexes(): Promise; - dropIndexes(callback?: MongoCallback): void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#find - find(query: Object): Cursor; - //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#findOneAndDelete - findOneAndDelete(filter: Object, callback: MongoCallback): void; - findOneAndDelete(filter: Object, options?: { projection?: Object, sort?: Object, maxTimeMS?: number }): Promise; - findOneAndDelete(filter: Object, options: { projection?: Object, sort?: Object, maxTimeMS?: number }, callback: MongoCallback): void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#findOneAndReplace - findOneAndReplace(filter: Object, replacement: Object, callback: MongoCallback): void; - findOneAndReplace(filter: Object, replacement: Object, options?: FindOneAndReplaceOption): Promise; - findOneAndReplace(filter: Object, replacement: Object, options: FindOneAndReplaceOption, callback: MongoCallback): void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#findOneAndUpdate - findOneAndUpdate(filter: Object, update: Object, callback: MongoCallback): void; - findOneAndUpdate(filter: Object, update: Object, options?: FindOneAndReplaceOption): Promise; - findOneAndUpdate(filter: Object, update: Object, options: FindOneAndReplaceOption, callback: MongoCallback): void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#geoHaystackSearch - geoHaystackSearch(x: number, y: number, callback: MongoCallback): void; - geoHaystackSearch(x: number, y: number, options?: GeoHaystackSearchOptions): Promise; - geoHaystackSearch(x: number, y: number, options: GeoHaystackSearchOptions, callback: MongoCallback): void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#geoNear - geoNear(x: number, y: number, callback: MongoCallback): void; - geoNear(x: number, y: number, options?: GeoNearOptions): Promise; - geoNear(x: number, y: number, options: GeoNearOptions, callback: MongoCallback): void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#group - group(keys: Object | Array | Function | Code, condition: Object, initial: Object, reduce: Function | Code, finalize: Function | Code, command: boolean, callback: MongoCallback): void; - group(keys: Object | Array | Function | Code, condition: Object, initial: Object, reduce: Function | Code, finalize: Function | Code, command: boolean, options?: { readPreference?: ReadPreference | string }): Promise; - group(keys: Object | Array | Function | Code, condition: Object, initial: Object, reduce: Function | Code, finalize: Function | Code, command: boolean, options: { readPreference?: ReadPreference | string }, callback: MongoCallback): void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#indexes - indexes(): Promise; - indexes(callback: MongoCallback): void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#indexExists - indexExists(indexes: string | string[]): Promise; - indexExists(indexes: string | string[], callback: MongoCallback): void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#indexInformation - indexInformation(callback: MongoCallback): void; - indexInformation(options?: { full: boolean }): Promise; - indexInformation(options: { full: boolean }, callback: MongoCallback): void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#initializeOrderedBulkOp - initializeOrderedBulkOp(options: CollectionOptions): OrderedBulkOperation; - //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#initializeUnorderedBulkOp - initializeUnorderedBulkOp(options: CollectionOptions): UnorderedBulkOperation; - //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#insertMany - insertMany(docs: Object[], callback: MongoCallback): void - insertMany(docs: Object[], options?: CollectionInsertManyOptions): Promise; - insertMany(docs: Object[], options: CollectionInsertManyOptions, callback: MongoCallback): void - //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#insertOne - insertOne(docs: Object, callback: MongoCallback): void - insertOne(docs: Object, options?: CollectionInsertOneOptions): Promise; - insertOne(docs: Object, options: CollectionInsertOneOptions, callback: MongoCallback): void - //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#isCapped - isCapped(): Promise; - isCapped(callback: MongoCallback): void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#listIndexes - listIndexes(options?: { batchSize?: number, readPreference?: ReadPreference | string }): CommandCursor; - //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#mapReduce - mapReduce(map: Function | string, reduce: Function | string, callback: MongoCallback): void; - mapReduce(map: Function | string, reduce: Function | string, options?: MapReduceOptions): Promise; - mapReduce(map: Function | string, reduce: Function | string, options: MapReduceOptions, callback: MongoCallback): void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#options - options(): Promise; - options(callback: MongoCallback): void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#parallelCollectionScan - parallelCollectionScan(callback: MongoCallback): void; - parallelCollectionScan(options?: ParallelCollectionScanOptions): Promise; - parallelCollectionScan(options: ParallelCollectionScanOptions, callback: MongoCallback): void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#reIndex - reIndex(): Promise; - reIndex(callback: MongoCallback): void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#rename - rename(newName: string, callback: MongoCallback): void; - rename(newName: string, options?: { dropTarget?: boolean }): Promise; - rename(newName: string, options: { dropTarget?: boolean }, callback: MongoCallback): void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#replaceOne - replaceOne(filter: Object, doc: Object, callback: MongoCallback): void; - replaceOne(filter: Object, doc: Object, options?: ReplaceOneOptions): Promise; - replaceOne(filter: Object, doc: Object, options: ReplaceOneOptions, callback: MongoCallback): void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#stats - stats(callback: MongoCallback): void; - stats(options?: { scale: number }): Promise; - stats(options: { scale: number }, callback: MongoCallback): void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#updateMany - updateMany(filter: Object, update: Object, callback: MongoCallback): void; - updateMany(filter: Object, update: Object, options?: { upsert?: boolean; w?: any; wtimeout?: number; j?: boolean; }): Promise; - updateMany(filter: Object, update: Object, options: { upsert?: boolean; w?: any; wtimeout?: number; j?: boolean; }, callback: MongoCallback): void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#updateOne - updateOne(filter: Object, update: Object, callback: MongoCallback): void; - updateOne(filter: Object, update: Object, options?: ReplaceOneOptions): Promise; - updateOne(filter: Object, update: Object, options: ReplaceOneOptions, callback: MongoCallback): void; -} - -// Documentation: http://docs.mongodb.org/manual/reference/command/collStats/ -//TODO complete this -export interface CollStats { - // Namespace. - ns: string; - // Number of documents. - count: number; - // Collection size in bytes. - size: number; - // Average object size in bytes. - avgObjSize: number; - // (Pre)allocated space for the collection in bytes. - storageSize: number; - // Number of extents (contiguously allocated chunks of datafile space). - numExtents: number; - // Number of indexes. - nindexes: number; - // Size of the most recently created extent in bytes. - lastExtentSize: number; - // Padding can speed up updates if documents grow. - paddingFactor: number; - userFlags: number; - // Total index size in bytes. - totalIndexSize: number; - // Size of specific indexes in bytes. - indexSizes: { - _id_: number; - username: number; - }; - capped: boolean; - maxSize: boolean; - wiredTiger: any; - indexDetails: any; - ok: number -} - -//http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#aggregate -export interface CollectionAggrigationOptions { - readPreference?: ReadPreference | string; - // Return the query as cursor, on 2.6 > it returns as a real cursor - // on pre 2.6 it returns as an emulated cursor. - cursor?: { batchSize: number }; - // Explain returns the aggregation execution plan (requires mongodb 2.6 >). - explain?: boolean; - // lets the server know if it can use disk to store - // temporary results for the aggregation (requires mongodb 2.6 >). - allowDiskUse?: boolean; - // specifies a cumulative time limit in milliseconds for processing operations - // on the cursor. MongoDB interrupts the operation at the earliest following interrupt point. - maxTimeMS?: boolean; - // Allow driver to bypass schema validation in MongoDB 3.2 or higher. - bypassDocumentValidation?: boolean; -} - -//http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#insertMany -export interface CollectionInsertManyOptions { - // The write concern. - w?: number | string; - // The write concern timeout. - wtimeout?: number; - // Specify a journal write concern. - j?: boolean; - // Serialize functions on any object. - serializeFunctions?: boolean; - //Force server to assign _id values instead of driver. - forceServerObjectId?: boolean; -} - -//http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#bulkWrite -export interface CollectionBluckWriteOptions { - // The write concern. - w?: number | string; - // The write concern timeout. - wtimeout?: number; - // Specify a journal write concern. - j?: boolean; - // Serialize functions on any object. - serializeFunctions?: boolean; - // Execute write operation in ordered or unordered fashion. - ordered?: boolean; - // Allow driver to bypass schema validation in MongoDB 3.2 or higher. - bypassDocumentValidation?: boolean; -} - -//http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#~BulkWriteOpResult -export interface BulkWriteOpResultObject { - insertedCount?: number; - matchedCount?: number; - modifiedCount?: number; - deletedCount?: number; - upsertedCount?: number; - insertedIds?: any; - upsertedIds?: any; - result?: any; -} - -//http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#count -export interface MongoCountPreferences { - // The limit of documents to count. - limit?: number; - // The number of documents to skip for the count. - skip?: boolean; - // An index name hint for the query. - hint?: string; - // The preferred read preference - readPreference?: ReadPreference | string; -} - -//http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#~deleteWriteOpResult -export interface DeleteWriteOpResultObject { - //The raw result returned from MongoDB, field will vary depending on server version. - result: { - //Is 1 if the command executed correctly. - ok?: number; - //The total count of documents deleted. - n?: number; - } - //The connection object used for the operation. - connection?: any; - //The number of documents deleted. - deletedCount?: number; -} - -//http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#~findAndModifyWriteOpResult -export interface FindAndModifyWriteOpResultObject { - //Document returned from findAndModify command. - value?: any; - //The raw lastErrorObject returned from the command. - lastErrorObject?: any; - //Is 1 if the command executed correctly. - ok?: number; -} - -//http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#findOneAndReplace -export interface FindOneAndReplaceOption { - projection?: Object; - sort?: Object; - maxTimeMS?: number; - upsert?: boolean; - returnOriginal?: boolean; -} - -//http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#geoHaystackSearch -export interface GeoHaystackSearchOptions { - readPreference?: ReadPreference | string; - maxDistance?: number; - search?: Object; - limit?: number; -} - -//http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#geoNear -export interface GeoNearOptions { - readPreference?: ReadPreference | string; - num?: number; - minDistance?: number; - maxDistance?: number; - distanceMultiplier?: number; - query?: Object; - spherical?: boolean; - uniqueDocs?: boolean; - includeLocs?: boolean; -} - -//http://mongodb.github.io/node-mongodb-native/2.1/api/Code.html -export class Code { - constructor(code: string | Function, scope?: Object) - code: string | Function; - scope: any; -} - -//http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#deleteMany -export interface CollectionOptions { - //The write concern. - w?: number | string; - //The write concern timeout. - wtimeout?: number; - //Specify a journal write concern. - j?: boolean; -} - -//http://mongodb.github.io/node-mongodb-native/2.1/api/OrderedBulkOperation.html -export interface OrderedBulkOperation { - length: number; - //http://mongodb.github.io/node-mongodb-native/2.1/api/OrderedBulkOperation.html#execute - execute(callback: MongoCallback): void; - execute(options: FSyncOptions): Promise; - execute(options: FSyncOptions, callback: MongoCallback): void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/OrderedBulkOperation.html#find - find(selector: Object): FindOperatorsOrdered; - //http://mongodb.github.io/node-mongodb-native/2.1/api/OrderedBulkOperation.html#insert - insert(doc: Object): OrderedBulkOperation; -} - -//http://mongodb.github.io/node-mongodb-native/2.1/api/BulkWriteResult.html -export interface BulkWriteResult { - ok: number; - nInserted: number; - nUpdated: number; - nUpserted: number; - nModified: number; - nRemoved: number; - - getInsertedIds(): Array; - getLastOp(): Object; - getRawResponse(): Object; - getUpsertedIdAt(index: number): Object; - getUpsertedIds(): Array; - getWriteConcernError(): WriteConcernError; - getWriteErrorAt(index: number): WriteError; - getWriteErrorCount(): number; - getWriteErrors(): Array; - hasWriteErrors(): boolean; -} - -//http://mongodb.github.io/node-mongodb-native/2.1/api/WriteError.html -export interface WriteError { - //Write concern error code. - code: number; - //Write concern error original bulk operation index. - index: number; - //Write concern error message. - errmsg: string; -} - -//http://mongodb.github.io/node-mongodb-native/2.1/api/WriteConcernError.html -export interface WriteConcernError { - //Write concern error code. - code: number; - //Write concern error message. - errmsg: string; -} - -//http://mongodb.github.io/node-mongodb-native/2.1/api/FindOperatorsOrdered.html -export interface FindOperatorsOrdered { - delete(): OrderedBulkOperation; - deleteOne(): OrderedBulkOperation; - replaceOne(doc: Object): OrderedBulkOperation; - update(doc: Object): OrderedBulkOperation; - updateOne(doc: Object): OrderedBulkOperation; - upsert(): FindOperatorsOrdered; -} - -//http://mongodb.github.io/node-mongodb-native/2.1/api/UnorderedBulkOperation.html -export interface UnorderedBulkOperation { - //http://mongodb.github.io/node-mongodb-native/2.1/api/UnorderedBulkOperation.html#execute - execute(callback: MongoCallback): void; - execute(options: FSyncOptions): Promise; - execute(options: FSyncOptions, callback: MongoCallback): void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/UnorderedBulkOperation.html#find - find(selector: Object): FindOperatorsUnordered; - //http://mongodb.github.io/node-mongodb-native/2.1/api/UnorderedBulkOperation.html#insert - insert(doc: Object): UnorderedBulkOperation; -} - -//http://mongodb.github.io/node-mongodb-native/2.1/api/FindOperatorsUnordered.html -export interface FindOperatorsUnordered { - length: number; - remove(): UnorderedBulkOperation; - removeOne(): UnorderedBulkOperation; - replaceOne(doc: Object): UnorderedBulkOperation; - update(doc: Object): UnorderedBulkOperation; - updateOne(doc: Object): UnorderedBulkOperation; - upsert(): FindOperatorsUnordered; -} - -//http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#~insertWriteOpResult -export interface InsertWriteOpResult { - insertedCount: number; - ops: Array; - insertedIds: Array; - connection: any; - result: { ok: number, n: number } -} - -//http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#insertOne -export interface CollectionInsertOneOptions { - // The write concern. - w?: number | string; - // The write concern timeout. - wtimeout?: number; - // Specify a journal write concern. - j?: boolean; - // Serialize functions on any object. - serializeFunctions?: boolean; - //Force server to assign _id values instead of driver. - forceServerObjectId?: boolean; - //Allow driver to bypass schema validation in MongoDB 3.2 or higher. - bypassDocumentValidation?: boolean -} - -//http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#~insertOneWriteOpResult -export interface InsertOneWriteOpResult { - insertedCount: number; - ops: Array; - insertedId: ObjectID; - connection: any; - result: { ok: number, n: number } -} - -//http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#parallelCollectionScan -export interface ParallelCollectionScanOptions { - readPreference?: ReadPreference | string; - batchSize?: number; - numCursors?: number; - raw?: boolean; -} - -//http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#replaceOne -export interface ReplaceOneOptions { - upsert?: boolean; - w?: number | string; - wtimeout?: number; - j?: boolean; - bypassDocumentValidation?: boolean; -} - -//http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#~updateWriteOpResult -export interface UpdateWriteOpResult { - result: { ok: number, n: number, nModified: number }; - connection: any; - matchedCount: number; - modifiedCount: number; - upsertedCount: number; - upsertedId: { _id: ObjectID }; -} - -//http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#mapReduce -export interface MapReduceOptions { - readPreference?: ReadPreference | string; - out?: Object; - query?: Object; - sort?: Object; - limit?: number; - keeptemp?: boolean; - finalize?: Function | string; - scope?: Object; - jsMode?: boolean; - verbose?: boolean; - bypassDocumentValidation?: boolean -} - - -//http://mongodb.github.io/node-mongodb-native/2.1/api/external-Readable.html -export interface Readable { - pause(): void; - pipe(destination: Writable, options?: Object): void; - read(size: number): string | Buffer | void; - resume(): void; - setEncoding(encoding: string): void; - unpipe(destination?: Writable): void; - unshift(stream: Buffer | string): void; - wrap(stream: Stream): void; -} - -export interface Writable { } -export interface Stream { } - -//http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#~resultCallback -export type CursorResult = any | void | boolean; - -//http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html -export interface Cursor extends Readable, NodeJS.EventEmitter { - - sortValue: string; - timeout: boolean; - readPreference: ReadPreference; - //http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html - addCursorFlag(flag: string, value: boolean): Cursor; - // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#addQueryModifier - addQueryModifier(name: string, value: boolean): Cursor; - // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#batchSize - batchSize(value: number): Cursor; - // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#clone - clone(): Cursor; - // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#close - close(): Promise; - close(callback: MongoCallback): void; - // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#comment - comment(value: string): Cursor; - // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#count - count(applySkipLimit: boolean, callback: MongoCallback): void; - count(applySkipLimit: boolean, options?: CursorCommentOptions): Promise; - count(applySkipLimit: boolean, options: CursorCommentOptions, callback: MongoCallback): void; - // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#explain - explain(): Promise; - explain(callback: MongoCallback): void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#filter - filter(filter: Object): Cursor; - // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#forEach - forEach(iterator: IteratorCallback, callback: EndCallback): void; - // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#hasNext - hasNext(): Promise; - hasNext(callback: MongoCallback): void; - // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#hint - hint(hint: Object): Cursor; - // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#isClosed - isClosed(): boolean; - // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#limit - limit(value: number): Cursor; - // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#map - map(transform: Function): void; - // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#max - max(max: number): Cursor; - //http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#maxAwaitTimeMS - maxAwaitTimeMS(value: number): Cursor; - // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#maxScan - maxScan(maxScan: Object): Cursor; - // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#maxTimeMS - maxTimeMS(value: number): Cursor; - // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#min - min(min: number): Cursor; - // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#next - next(): Promise; - next(callback: MongoCallback): void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#pause - pause(): void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#pipe - pipe(destination: Writable, options?: Object): void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#project - project(value: Object): Cursor; - //http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#read - read(size: number): string | Buffer | void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#resume - resume(): void; - // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#next - returnKey(returnKey: Object): Cursor; - //http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#rewind - rewind(): void; - // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#setCursorOption - setCursorOption(field: string, value: Object): Cursor; - //http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#setEncoding - setEncoding(encoding: string): void; - // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#setReadPreference - setReadPreference(readPreference: string | ReadPreference): Cursor; - // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#showRecordId - showRecordId(showRecordId: Object): Cursor; - // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#skip - skip(value: number): Cursor; - // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#snapshot - snapshot(snapshot: Object): Cursor; - // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#sort - sort(keyOrList: string | Object[] | Object | Object, direction?: number): Cursor; - // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#stream - stream(options?: { transform?: Function }): Cursor; - // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#toArray - toArray(): Promise; - toArray(callback: MongoCallback): void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#unpipe - unpipe(destination?: Writable): void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#unshift - unshift(stream: Buffer | string): void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#wrap - wrap(stream: Stream): void; -} - -//http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#count -export interface CursorCommentOptions { - skip?: number; - limit?: number; - maxTimeMS?: number; - hint?: string; - readPreference?: ReadPreference | string; -} - -//http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#~iteratorCallback -export interface IteratorCallback { - (doc: any): void; -} - -//http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#~endCallback -export interface EndCallback { - (error: MongoError): void; -} - -//http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#~resultCallback -export type AggregationCursorResult = any | void; - -//http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html -export interface AggregationCursor extends Readable, NodeJS.EventEmitter { - // http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#batchSize - batchSize(value: number): AggregationCursor; - // http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#clone - clone(): AggregationCursor; - // http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#close - close(): Promise; - close(callback: MongoCallback): void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#each - each(callback: MongoCallback): void - // http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#explain - explain(): Promise; - explain(callback: MongoCallback): void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#geoNear - geoNear(document: Object): AggregationCursor; - //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#group - group(document: Object): AggregationCursor; - // http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#isClosed - isClosed(): boolean; - // http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#limit - limit(value: number): AggregationCursor; - //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#match - match(document: Object): AggregationCursor; - // http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#maxTimeMS - maxTimeMS(value: number): AggregationCursor; - // http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#next - next(): Promise; - next(callback: MongoCallback): void; - // http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#out - out(destination: string): AggregationCursor; - //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#pause - pause(): void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#pipe - pipe(destination: Writable, options?: Object): void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#project - project(document: Object): AggregationCursor; - //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#read - read(size: number): string | Buffer | void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#redact - redact(document: Object): AggregationCursor; - //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#resume - resume(): void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#rewind - rewind(): AggregationCursor; - //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#setEncoding - setEncoding(encoding: string): void; - // http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#skip - skip(value: number): AggregationCursor; - // http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#sort - sort(document: Object): AggregationCursor; - // http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#toArray - toArray(): Promise; - toArray(callback: MongoCallback): void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#unpipe - unpipe(destination?: Writable): void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#unshift - unshift(stream: Buffer | string): void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#unwind - unwind(field: string): AggregationCursor; - //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#wrap - wrap(stream: Stream): void; -} - -//http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html -export interface CommandCursor extends Readable, NodeJS.EventEmitter { - // http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#batchSize - batchSize(value: number): CommandCursor; - // http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#clone - clone(): CommandCursor; - // http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#close - close(): Promise; - close(callback: MongoCallback): void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#each - each(callback: MongoCallback): void - // http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#isClosed - isClosed(): boolean; - // http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#maxTimeMS - maxTimeMS(value: number): CommandCursor; - // http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#next - next(): Promise; - next(callback: MongoCallback): void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#pause - pause(): void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#pipe - pipe(destination: Writable, options?: Object): void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#read - read(size: number): string | Buffer | void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#resume - resume(): void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#rewind - rewind(): CommandCursor; - //http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#setEncoding - setEncoding(encoding: string): void; - // http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#setReadPreference - setReadPreference(readPreference: string | ReadPreference): CommandCursor; - // http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#toArray - toArray(): Promise; - toArray(callback: MongoCallback): void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#unpipe - unpipe(destination?: Writable): void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#unshift - unshift(stream: Buffer | string): void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#wrap - wrap(stream: Stream): void; -} -} -declare module '~iridium~mongodb' { -export * from '~iridium~mongodb/mongodb'; -} - -// Generated by typings -// Source: dist/lib/middleware/Express.d.ts -declare module '~iridium/dist/lib/middleware/Express' { -import * as http from 'http'; -import { Core } from '~iridium/dist/lib/Core'; -/** - * A factory method which creates Express/Connect compatible middleware functions to inject - * a "db" field on your request objects as well as ensuring that the Iridium Core is connected - * to a MongoDB database before handling any requests. - * - * @internal - */ -export function ExpressMiddlewareFactory(core: Core): ExpressMiddleware; -/** - * An Express/Connect compatible middleware function which injects req.db and ensures that the Iridium Core - * has an active database connection before continuing the request handling process. - */ -export interface ExpressMiddleware { - (req: http.ServerRequest, res: http.ServerResponse, next: (err?: Error, route?: String) => void): any; -} -} -declare module 'iridium/dist/lib/middleware/Express' { -export * from '~iridium/dist/lib/middleware/Express'; -} - -// Generated by typings -// Source: dist/lib/Core.d.ts -declare module '~iridium/dist/lib/Core' { -import * as Bluebird from '~iridium~bluebird'; -import * as MongoDB from '~iridium~mongodb'; -import { Configuration } from '~iridium/dist/lib/Configuration'; -import { Plugin } from '~iridium/dist/lib/Plugins'; -import * as ExpressMiddleware from '~iridium/dist/lib/middleware/Express'; -import { Cache } from '~iridium/dist/lib/Cache'; -/** - * The Iridium Core, responsible for managing the connection to the database as well - * as any plugins you are making use of. - * - * Generally you will subclass this to provide your own custom core with the models you - * make use of within your application. - */ -export class Core { - /** - * Creates a new Iridium Core instance connected to the specified MongoDB instance - * @param {Iridium.IridiumConfiguration} config The config object defining the database to connect to - * @constructs Core - */ - constructor(config: Configuration); - /** - * Creates a new Iridium Core instance connected to the specified MongoDB instance - * @param {String} url The URL of the MongoDB instance to connect to - * @param {Iridium.IridiumConfiguration} config The config object made available as settings - * @constructs Core - */ - constructor(uri: string, config?: Configuration); - private mongoConnectAsyc; - private _plugins; - private _url; - private _config; - private _connection; - private _cache; - private _connectPromise; - /** - * Gets the plugins registered with this Iridium Core - * @returns {[Iridium.Plugin]} - */ - plugins: Plugin[]; - /** - * Gets the configuration specified in the construction of this - * Iridium Core. - * @returns {Iridium.Configuration} - */ - settings: Configuration; - /** - * Gets the currently active database connection for this Iridium - * Core. - * @returns {MongoDB.Db} - */ - connection: MongoDB.Db; - /** - * Gets the URL used to connect to MongoDB - * @returns {String} - */ - url: string; - /** - * Gets the cache used to store objects retrieved from the database for performance reasons - * @returns {cache} - */ - cache: Cache; - /** - * Registers a new plugin with this Iridium Core - * @param {Iridium.Plugin} plugin The plugin to register with this Iridium Core - * @returns {Iridium.Core} - */ - register(plugin: Plugin): Core; - /** - * Connects to the database server specified in the provided configuration - * @param {function(Error, Iridium.Core)} [callback] A callback to be triggered once the connection is established. - * @returns {Promise} - */ - connect(callback?: (err: Error, core: Core) => any): Bluebird; - /** - * Closes the active database connection - * @type {Promise} - */ - close(): Bluebird; - /** - * Provides an express middleware which can be used to set the req.db property - * to the current Iridium instance. - * @returns {Iridium.ExpressMiddleware} - */ - express(): ExpressMiddleware.ExpressMiddleware; - /** - * A method which is called whenever a new connection is made to the database. - * - * @param connection The underlying MongoDB connection which was created, you can modify or replace this if you wish. - * @returns A promise for the connection, allowing you to perform any asynchronous initialization required by your application. - * - * In subclassed Iridium Cores this method can be overridden to manipulate the properties - * of the underlying MongoDB connection object, such as authenticating. Until this method - * resolves a connection object, Iridium will be unable to execute any queries. If you wish - * to run Iridium queries then look at the onConnected method. - */ - protected onConnecting(connection: MongoDB.Db): Bluebird; - /** - * A method which is called once a database connection has been established and accepted by Iridium - * - * In subclassed Iridium cores this method can be overridden to perform tasks whenever a - * connection to the database has been established - such as setting up indexes for your - * collections or seeding the database. - */ - protected onConnected(): Bluebird; -} -} -declare module 'iridium/dist/lib/Core' { -export * from '~iridium/dist/lib/Core'; -} - -// Generated by typings -// Source: dist/lib/Cursor.d.ts -declare module '~iridium/dist/lib/Cursor' { -import { Model } from '~iridium/dist/lib/Model'; -import * as General from '~iridium/dist/lib/General'; -import * as MongoDB from '~iridium~mongodb'; -import * as Bluebird from '~iridium~bluebird'; -import * as Index from '~iridium/dist/lib/Index'; -/** - * An Iridium collection cursor which allows the itteration through documents - * in the collection, automatically wrapping them in the correct instance type. - * - * @param TDocument The interface representing the collection's documents - * @param TInstance The interface or class used to represent the wrapped documents. - */ -export class Cursor { - private model; - private conditions; - cursor: MongoDB.Cursor; - /** - * Creates a new Iridium cursor which wraps a MongoDB cursor object - * @param {Model} model The Iridium model that this cursor belongs to - * @param {Object} conditions The conditions that resulte in this cursor being created - * @param {MongoDB.Cursor} cursor The MongoDB native cursor object to be wrapped - * @constructor - */ - constructor(model: Model, conditions: any, cursor: MongoDB.Cursor); - /** - * Counts the number of documents which are matched by this cursor - * @param {function(Error, Number)} callback A callback which is triggered when the result is available - * @return {Promise} A promise which will resolve with the number of documents matched by this cursor - */ - count(callback?: General.Callback): Bluebird; - /** - * Runs the specified handler over each instance in the query results - * @param {function(Instance)} handler The handler which is triggered for each element in the query - * @param {function(Error)} callback A callback which is triggered when all operations have been dispatched - * @return {Promise} A promise which is resolved when all operations have been dispatched - */ - forEach(handler: (instance: TInstance) => void, callback?: General.Callback): Bluebird; - /** - * Runs the specified transform over each instance in the query results and returns the resulting transformed objects - * @param {function(Instance): TResult} transform A handler which is used to transform the result objects - * @param {function(Error, TResult[])} callback A callback which is triggered when the transformations are completed - * @return {Promise} A promise which is fulfilled with the results of the transformations - */ - map(transform: (instance: TInstance) => TResult | Bluebird, callback?: General.Callback): Bluebird; - /** - * Retrieves all matching instances and returns them in an array - * @param {function(Error, TInstance[])} callback A callback which is triggered with the resulting instances - * @return {Promise} A promise which resolves with the instances returned by the query - */ - toArray(callback?: General.Callback): Bluebird; - /** - * Retrieves the next item in the results list - * @param {function(Error, TInstance)} callback A callback which is triggered when the next item becomes available - * @return {Promise} A promise which is resolved with the next item - */ - next(callback?: General.Callback): Bluebird; - /** - * Retrieves the next item in the result list and then closes the cursor - * @param {function(Error, TInstance)} callback A callback which is triggered when the next item becomes available - * @return {Promise} A promise which is resolved once the item becomes available and the cursor has been closed. - */ - one(callback?: General.Callback): Bluebird; - /** - * Returns a new cursor which behaves the same as this one did before any results were retrieved - * @return {Cursor} The new cursor which starts at the beginning of the results - */ - rewind(): Cursor; - /** - * Returns a new cursor which sorts its results by the given index expression - * @param {model.IndexSpecification} sortExpression The index expression dictating the sort order and direction to use - * @return {Cursor} The new cursor which sorts its results by the sortExpression - */ - sort(sortExpression: Index.IndexSpecification): Cursor; - /** - * Returns a new cursor which limits the number of returned results - * @param {Number} limit The maximum number of results to return - * @return {Cursor} The new cursor which will return a maximum number of results - */ - limit(limit: number): Cursor; - /** - * Returns a new cursor which skips a number of results before it begins - * returning any. - * @param {Number} skip The number of results to skip before the cursor beings returning - * @return {Cursor} The new cursor which skips a number of results - */ - skip(skip: number): Cursor; - /** - * Returns a new cursor which will read from the specified node type. - * @param {String} type The type of node to read from - see https://docs.mongodb.org/manual/core/read-preference/ - * @return {Cursor} The new cursor which reads from the specified node type - */ - readFrom(type: string): Cursor; -} -} -declare module 'iridium/dist/lib/Cursor' { -export * from '~iridium/dist/lib/Cursor'; -} - -// Generated by typings -// Source: dist/lib/ModelCache.d.ts -declare module '~iridium/dist/lib/ModelCache' { -import { Model } from '~iridium/dist/lib/Model'; -import * as Bluebird from '~iridium~bluebird'; -/** - * A centralized class which ties the cache and cache directors together in a cohesive way - * for use by Iridium. - * @internal - */ -export class ModelCache { - model: Model; - constructor(model: Model); - set(value: T): void; - get(conditions: any): Bluebird; - clear(conditions: any): void; -} -} -declare module 'iridium/dist/lib/ModelCache' { -export * from '~iridium/dist/lib/ModelCache'; -} - -// Generated by typings -// Source: dist/lib/ModelHelpers.d.ts -declare module '~iridium/dist/lib/ModelHelpers' { -import { Model } from '~iridium/dist/lib/Model'; -import * as Skmatc from '~iridium~skmatc'; -/** - * A number of helper methods used commonly within Iridium, they provide a means to transform, - * validate, wrap and diff instances and documents. By keeping these methods in one place we - * help to improve testability and reduce code duplication (mouse abuse) throughout the codebase. - * @internal - */ -export class ModelHelpers { - model: Model; - constructor(model: Model); - private _validator; - /** - * Validates a document to ensure that it matches the model's ISchema requirements - * @param {any} document The document to validate against the ISchema - * @returns {SkmatcCore.IResult} The result of the validation - */ - validate(document: TDocument): Skmatc.Result; - /** - * Wraps the given document in an instance wrapper for use throughout the application - * @param {any} document The document to be wrapped as an instance - * @param {Boolean} isNew Whether the instance originated from the database or was created by the application - * @param {Boolean} isPartial Whether the document supplied contains all information present in the database - * @returns {any} An instance which wraps this document - */ - wrapDocument(document: TDocument, isNew?: boolean, isPartial?: boolean): TInstance; - /** - * Converts the given document to its database form into a form - * using the transforms defined on the model. - * @param {any} document The document to be converted - * @returns {any} The result of having transformed the document. - * @remarks This is only really called from insert/create - as - */ - transformToDB(document: T, options?: TransformOptions): T; - /** - * Converts the given document from its database form using the - * transforms defined on the model. - * @param document The document to be converted. - * @returns The result of having transformed the document. - * @remarks Unlike the transformToDB function - this method only applies - * document level transforms, as property level transforms are applied in - * their relevant instance setters. - */ - transformFromDB(document: TDocument, options?: TransformOptions): TDocument; - /** - * Converts the given document to its database form into a form - * using the transforms defined on the model. - * @param document The document to be converted - * @param processProperties Whether or not to process properties in addition - * document level transforms. - * @returns {any} A new document cloned from the original and transformed - */ - convertToDB(document: T, options?: TransformOptions): T; - /** - * Performs a diff operation between two documents and creates a MongoDB changes object to represent the differences - * @param {any} original The original document prior to changes being made - * @param {any} modified The document after changes were made - */ - diff(original: TDocument, modified: TDocument): any; - /** - * Clones the given document recursively, taking into account complex types like - * Buffers correctly. - * - * @param {any} The document you wish to clone deeply. - */ - cloneDocument(original: T): T; - /** - * Clones the given document recursively, taking into account complex types like - * Buffers correctly. Optimized for working with query documents instead of true - * documents. - * - * @param {any} The document you wish to clone deeply. - */ - cloneConditions(original: T): T; -} -export interface TransformOptions { - properties?: boolean; - document?: boolean; -} -} -declare module 'iridium/dist/lib/ModelHelpers' { -export * from '~iridium/dist/lib/ModelHelpers'; -} - -// Generated by typings -// Source: dist/lib/ModelHandlers.d.ts -declare module '~iridium/dist/lib/ModelHandlers' { -import { Model } from '~iridium/dist/lib/Model'; -import * as ModelOptions from '~iridium/dist/lib/ModelOptions'; -import * as Bluebird from '~iridium~bluebird'; -/** - * Provides a number of methods which are used to handle events that occur within - * the Iridium workflow - such as what happens when a document is received from - * the database, or how to handle the creation of new documents and saving of instances. - * - * Mostly this is for cache support, wrapping and hook triggering. - * @internal - */ -export class ModelHandlers { - model: Model; - constructor(model: Model); - documentReceived(conditions: any, result: TDocument, wrapper: (document: TDocument, isNew?: boolean, isPartial?: boolean) => TResult, options?: ModelOptions.QueryOptions): Bluebird; - creatingDocuments(documents: TDocument[]): Bluebird; - savingDocument(instance: TInstance, changes: any): Bluebird; -} -} -declare module 'iridium/dist/lib/ModelHandlers' { -export * from '~iridium/dist/lib/ModelHandlers'; -} - -// Generated by typings -// Source: dist/lib/ModelInterfaces.d.ts -declare module '~iridium/dist/lib/ModelInterfaces' { -/** - * The interface to which a prepared instance constructor should conform. When called with a document - * object, it should instantiate a new instance of type TInstance which is associated with its parent - * model. - * - * This is primarily used internally for prepared model instance constructors. - * - * @param TDocument The interface used to describe the structure of the documents found in the database collection. - * @param TInstance The interface or class used to wrap the documents returned from the database. - * - * @internal - */ -export interface ModelSpecificInstanceConstructor { - new (doc: TDocument, isNew?: boolean, isPartial?: boolean): TInstance; -} -} -declare module 'iridium/dist/lib/ModelInterfaces' { -export * from '~iridium/dist/lib/ModelInterfaces'; -} - -// Generated by typings -// Source: dist/lib/InstanceInterface.d.ts -declare module '~iridium/dist/lib/InstanceInterface' { -import * as Skmatc from '~iridium~skmatc'; -import { Schema } from '~iridium/dist/lib/Schema'; -import { Model } from '~iridium/dist/lib/Model'; -import * as Index from '~iridium/dist/lib/Index'; -import { CacheDirector } from '~iridium/dist/lib/CacheDirector'; -import { Transforms } from '~iridium/dist/lib/Transforms'; -/** - * This interface dictates the format of an instance class which wraps documents received - * from the database for a specific Iridium model. - * - * @param TDocument The interface representing the documents stored in the database, after being passed through the transforms pipeline. - * @param TInstance The type of object which is instantiated when calling this implementation's constructor. - * - * It is important to note that, when implementing this interface, each of the properties and methods - * should be exposed statically. That is, you would expose the collection property as a static variable - * on the instance implementation, since prototype methods and variables become available to consumers of the - * instance itself. - */ -export interface InstanceImplementation { - /** - * A constructor which creates a new instance tied to the given model and representing the given document. - * @param model The Iridium Model which this instance should be tied to, gives the instance access to the database collection and any other context it requires. - * @param doc The document this instance should wrap from the database. This provides the data context for the instance. - * @param isNew Whether this document is known to exist in the database or not, for example, if the instance was generated from user input and hasn't been saved yet. - * @param isPartial Whether the document which has been given to this instance had any field restrictions imposed on it during the query, and may therefore only contain partial data. - */ - new (model: Model, doc: TDocument, isNew?: boolean, isPartial?: boolean): TInstance; - /** - * The name of the database collection from which documents are retrieved, and to which they are stored. - */ - collection: string; - /** - * The database schematic used for validation of instances prior to storing them in the database. - * This schematic should follow the guides set out in skmatc's documentation, and is used whenever - * you insert a new document into the collection or save an instance using the default instance type. - * Operations like update() (and by extension, save() when using the update operations) cannot be checked - * by skmatc for consistency and as a result will not have their data validated - be careful when making - * use of them as a result. - */ - schema: Schema; - /** - * Any additional indexes on the collection which should be managed by Iridium. - * This field is optional, but if provided allows you to make use of the model's ensureIndexes() method - * to automatically generate all specified indexes. - */ - indexes?: (Index.Index | Index.IndexSpecification)[]; - /** - * An optional method which will be called whenever a document is about to be inserted into the database, - * allowing you to set default values and do any preprocessing you wish prior to the document being inserted. - * - * @param document The document which will be inserted into the database. - * - * This method is executed synchronously, however you can perform asynchronous operations by returning a - * promise which resolves once your task has completed. Be aware that this method is executed for every - * document inserted into the database. As a result, long running tasks will have a significant impact - * on the performance of your inserts. - */ - onCreating?(document: TDocument): Promise | void; - /** - * An optional method which is called whenever a new document is received from the model's collection and - * prior to the document being wrapped, can be used to perform preprocessing if necessary - however we recommend - * you rather make use of transforms for that task. - * - * @param document The document that was retrieved from the database. - * - * This method is executed synchronously, however you can perform asynchronous operations by returning a - * promise which resolves once your task has completed. Be aware that this method is executed for every - * document retrieved from the database. As a result, long running tasks will have a significant impact - * on the performance of your queries. - */ - onRetrieved?(document: TDocument): Promise | void; - /** - * An optional method which is called whenever a new document for this model has been wrapped in an instance. - * - * @param instance The instance which has been created. - * - * This method is executed synchronously, however you can perform asynchronous operations by returning a - * promise which resolves once your task has completed. Be aware that this method is executed for every - * document retrieved from the database. As a result, long running tasks will have a significant impact - * on the performance of your queries. - */ - onReady?(instance: TInstance): Promise | void; - /** - * An optional method which is called prior to saving an instance, it is provided with the instance itself as - * well as the proposed changes to the instance. This allows you to make additional changes, such as updating - * a lastChanged property on the document, or abort changes by throwing an error. - * - * @param instance The instance to which the changes are being made - * @param changes The MongoDB change object describing the changes being made to the document. - * - * This method is executed synchronously, however you can perform asynchronous operations by returning a - * promise which resolves once your task has completed. Be aware that this method is executed for every - * call to save. As a result, long running tasks will have a significant impact on how quickly your save - * operations are dispatched. - */ - onSaving?(instance: TInstance, changes: any): Promise | void; - /** - * The cache controller used to determine whether a document may be cached, as well as deriving a unique cache - * key for the document and similarly, for a query. This works in concert with the cache implementation itself - * to ensure that documents are cached in an intelligent manner. By default this will simply make use of the - * document's _id field as the cache key - however that behaviour may be modified if you wish to query on other - * properties instead. - */ - cache?: CacheDirector; - /** - * Any additional validation types you wish to make available for use within this model's database schema. This - * allows you to validate using conditions otherwise not available within skmatc itself. For more information - * on implementing a validator, take a look at the skmatc documentation on GitHub. - */ - validators?: Skmatc.Validator[]; - /** - * Any transform operations you would like to perform on documents received from the database, or prior to being - * sent to the database. These may include things such as converting ObjectIDs to strings for the application, and - * then back to ObjectIDs once they return to the database. - */ - transforms?: Transforms; -} -} -declare module 'iridium/dist/lib/InstanceInterface' { -export * from '~iridium/dist/lib/InstanceInterface'; -} - -// Generated by typings -// Source: dist/lib/Aggregate.d.ts -declare module '~iridium/dist/lib/Aggregate' { -export interface Stage { -} -} -declare module 'iridium/dist/lib/Aggregate' { -export * from '~iridium/dist/lib/Aggregate'; +// Generated by typings +// Source: dist/lib/Aggregate.d.ts +declare module '~iridium/dist/lib/Aggregate' { +export interface Stage { +} +} +declare module 'iridium/dist/lib/Aggregate' { +export * from '~iridium/dist/lib/Aggregate'; } // Generated by typings @@ -3078,113 +2257,818 @@ export class Model): Bluebird; /** - * Drops the index with the specified name if it exists in the collection - * @param {String} name The name of the index to remove - * @param {function(Error, Boolean)} callback A callback which is triggered when the operation completes - * @returns {Promise} Whether the index was dropped + * Drops the index with the specified name if it exists in the collection + * @param {String} name The name of the index to remove + * @param {function(Error, Boolean)} callback A callback which is triggered when the operation completes + * @returns {Promise} Whether the index was dropped + */ + dropIndex(name: string, callback?: General.Callback): Bluebird; + /** + * Drops the index if it exists in the collection + * @param {IndexSpecification} index The index to remove + * @param {function(Error, Boolean)} callback A callback which is triggered when the operation completes + * @returns {Promise} Whether the index was dropped + */ + dropIndex(index: Index.IndexSpecification, callback?: General.Callback): Bluebird; + /** + * Removes all indexes (except for _id) from the collection + * @param {function(Error, Boolean)} callback A callback which is triggered when the operation completes + * @returns {Promise} Whether the indexes were dropped + */ + dropIndexes(callback?: General.Callback): Bluebird; +} +} +declare module 'iridium/dist/lib/Model' { +export * from '~iridium/dist/lib/Model'; +} + +// Generated by typings +// Source: dist/lib/General.d.ts +declare module '~iridium/dist/lib/General' { +/** + * A method which is called once an asynchronous operation has completed, an alternative + * to using Promises. + * @param T The type of object returned by the asynchronous operation. + */ +export interface Callback { + /** + * @param err The error object, if one occurred, otherwise null if the operation completed successfully. + * @param object The result of the asynchronous operation if it completed successfully. If err is defined, the presence of this value is unknown. + */ + (err: Error, object?: T): void; +} +/** + * A method which is used to determine whether a value within a collection meets a set of criteria. + * @param T The type of item in the collection. + */ +export interface Predicate { + /** + * @param object The value of the item in the collection + * @param key The key, if one is available, under which the item appeared within the collection + * @returns A true-y value if the item met the predicate conditions, false-y values if it did not. + */ + (object: T, key?: string): boolean; +} +/** + * A method which is called to retrieve a value of the given type. + * @param T The type of value to be retrieved. + */ +export interface PropertyGetter { + /** + * Gets the current value of the property + * @returns The current value + */ + (): T; +} +/** + * A method which is called to set a value of the given type. + * @param T The type of value to set + */ +export interface PropertySetter { + /** + * Sets the value to the provided one + * @param value The new value to set + */ + (value: T): void; +} +/** + * A compound property which provides either a getter, setter or both. + * @param T The type of objects stored in the property + */ +export interface Property { + /** + * An optional getter which can be used to retrieve the property's value + */ + get?: PropertyGetter; + /** + * An optional setter which can be used to set the property's value + */ + set?: PropertySetter; +} +} +declare module 'iridium/dist/lib/General' { +export * from '~iridium/dist/lib/General'; +} + +// Generated by typings +// Source: dist/lib/Index.d.ts +declare module '~iridium/dist/lib/Index' { +import * as MongoDB from '~iridium~mongodb'; +export interface Index { + spec: IndexSpecification; + options?: MongoDB.IndexOptions; +} +export interface IndexSpecification { + [key: string]: number | string; +} +} +declare module 'iridium/dist/lib/Index' { +export * from '~iridium/dist/lib/Index'; +} + +// Generated by typings +// Source: https://raw.githubusercontent.com/typed-typings/npm-bluebird/8bd917a7ac4fef6796cd7fe5fc1d3b0fb118ad1a/bluebird.d.ts +declare module '~iridium~bluebird/bluebird' { +// Type definitions for Bluebird v3.x.x +// Project: http://bluebirdjs.com + +class Bluebird implements Bluebird.Thenable, Bluebird.Inspection { + /** + * Create a new promise. The passed in function will receive functions `resolve` and `reject` as its arguments which can be called to seal the fate of the created promise. + */ + constructor(callback: (resolve: (thenableOrResult: R | Bluebird.Thenable) => void, reject: (error: any) => void) => void); + + /** + * Promises/A+ `.then()`. Returns a new promise chained from this promise. The new promise will be rejected or resolved dedefer on the passed `fulfilledHandler`, `rejectedHandler` and the state of this promise. + */ + then(onFulfill: (value: R) => U | Bluebird.Thenable, onReject?: (error: any) => U | Bluebird.Thenable): Bluebird; + then(onFulfill: (value: R) => U | Bluebird.Thenable, onReject?: (error: any) => void | Bluebird.Thenable): Bluebird; + + /** + * This is a catch-all exception handler, shortcut for calling `.then(null, handler)` on this promise. Any exception happening in a `.then`-chain will propagate to nearest `.catch` handler. + * + * Alias `.caught();` for compatibility with earlier ECMAScript version. + */ + catch(onReject?: (error: any) => R | Bluebird.Thenable | void | Bluebird.Thenable): Bluebird; + catch(onReject?: (error: any) => U | Bluebird.Thenable): Bluebird; + + /** + * This extends `.catch` to work more like catch-clauses in languages like Java or C#. Instead of manually checking `instanceof` or `.name === "SomeError"`, you may specify a number of error constructors which are eligible for this catch handler. The catch handler that is first met that has eligible constructors specified, is the one that will be called. + * + * This method also supports predicate-based filters. If you pass a predicate function instead of an error constructor, the predicate will receive the error as an argument. The return result of the predicate will be used determine whether the error handler should be called. + * + * Alias `.caught();` for compatibility with earlier ECMAScript version. + */ + catch(predicate: (error: any) => boolean, onReject: (error: any) => R | Bluebird.Thenable | void | Bluebird.Thenable): Bluebird; + catch(predicate: (error: any) => boolean, onReject: (error: any) => U | Bluebird.Thenable): Bluebird; + catch(ErrorClass: Function, onReject: (error: any) => R | Bluebird.Thenable | void | Bluebird.Thenable): Bluebird; + catch(ErrorClass: Function, onReject: (error: any) => U | Bluebird.Thenable): Bluebird; + + /** + * Like `.catch` but instead of catching all types of exceptions, it only catches those that don't originate from thrown errors but rather from explicit rejections. + */ + error(onReject: (reason: any) => U | Bluebird.Thenable): Bluebird; + + /** + * Pass a handler that will be called regardless of this promise's fate. Returns a new promise chained from this promise. There are special semantics for `.finally()` in that the final value cannot be modified from the handler. + * + * Alias `.lastly();` for compatibility with earlier ECMAScript version. + */ + finally(handler: () => U | Bluebird.Thenable): Bluebird; + + lastly(handler: () => U | Bluebird.Thenable): Bluebird; + + /** + * Create a promise that follows this promise, but is bound to the given `thisArg` value. A bound promise will call its handlers with the bound value set to `this`. Additionally promises derived from a bound promise will also be bound promises with the same `thisArg` binding as the original promise. + */ + bind(thisArg: any): Bluebird; + + /** + * Like `.then()`, but any unhandled rejection that ends up here will be thrown as an error. + */ + done(onFulfilled?: (value: R) => U | Bluebird.Thenable, onRejected?: (error: any) => U | Bluebird.Thenable): void; + + /** + * Like `.finally()`, but not called for rejections. + */ + tap(onFulFill: (value: R) => Bluebird.Thenable): Bluebird; + tap(onFulfill: (value: R) => U): Bluebird; + + /** + * Same as calling `Promise.delay(ms, this)`. + */ + delay(ms: number): Bluebird; + + /** + * Returns a promise that will be fulfilled with this promise's fulfillment value or rejection reason. + * However, if this promise is not fulfilled or rejected within ms milliseconds, the returned promise + * is rejected with a TimeoutError or the error as the reason. + * + * You may specify a custom error message with the `message` parameter. + */ + timeout(ms: number, message?: string | Error): Bluebird; + + /** + * Register a node-style callback on this promise. When this promise is is either fulfilled or rejected, the node callback will be called back with the node.js convention where error reason is the first argument and success value is the second argument. The error argument will be `null` in case of success. + * If the `callback` argument is not a function, this method does not do anything. + */ + nodeify(callback: (err: any, value?: R) => void, options?: Bluebird.SpreadOption): this; + nodeify(...sink: any[]): this; + asCallback(callback: (err: any, value?: R) => void, options?: Bluebird.SpreadOption): this; + asCallback(...sink: any[]): this; + + /** + * See if this `promise` has been fulfilled. + */ + isFulfilled(): boolean; + + /** + * See if this `promise` has been rejected. + */ + isRejected(): boolean; + + /** + * See if this `promise` is still defer. + */ + isPending(): boolean; + + /** + * See if this `promise` is resolved -> either fulfilled or rejected. + */ + isResolved(): boolean; + + /** + * Get the fulfillment value of the underlying promise. Throws if the promise isn't fulfilled yet. + * + * throws `TypeError` + */ + value(): R; + + /** + * Get the rejection reason for the underlying promise. Throws if the promise isn't rejected yet. + * + * throws `TypeError` + */ + reason(): any; + + /** + * Synchronously inspect the state of this `promise`. The `PromiseInspection` will represent the state of + * the promise as snapshotted at the time of calling `.reflect()`. + */ + reflect(): Bluebird.Inspection; + + /** + * This is a convenience method for doing: + * + * + * promise.then(function(obj){ + * return obj[propertyName].call(obj, arg...); + * }); + * + */ + call(propertyName: string, ...args: any[]): Bluebird; + + /** + * This is a convenience method for doing: + * + * + * promise.then(function(obj){ + * return obj[propertyName]; + * }); + * + */ + // TODO: Use "type property type" once it's there + // @see https://github.com/Microsoft/TypeScript/issues/1295 + get(key: string | number): Bluebird; + + /** + * Convenience method for: + * + * + * .then(function() { + * return value; + * }); + * + * + * in the case where `value` doesn't change its value. That means `value` is bound at the time of calling `.return()` + * + * Alias `.thenReturn();` for compatibility with earlier ECMAScript version. + */ + return(): Bluebird; + thenReturn(): Bluebird; + return(value: U): Bluebird; + thenReturn(value: U): Bluebird; + + /** + * Convenience method for: + * + * + * .then(function() { + * throw reason; + * }); + * + * Same limitations apply as with `.return()`. + * + * Alias `.thenThrow();` for compatibility with earlier ECMAScript version. + */ + throw(reason: Error): Bluebird; + thenThrow(reason: Error): Bluebird; + + /** + * Convert to String. + */ + toString(): string; + + /** + * This is implicitly called by `JSON.stringify` when serializing the object. Returns a serialized representation of the `Promise`. + */ + toJSON(): Object; + + /** + * Like calling `.then`, but the fulfillment value or rejection reason is assumed to be an array, which is flattened to the formal parameters of the handlers. + */ + spread(fulfilledHandler: (...values: W[]) => U | Bluebird.Thenable): Bluebird; + spread(fulfilledHandler: Function): Bluebird; + + /** + * Same as calling `Promise.all(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + */ + // TODO type inference from array-resolving promise? + all(): Bluebird; + + /** + * Same as calling `Promise.props(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + */ + // TODO how to model instance.props()? + props(): Bluebird; + + /** + * Same as calling `Promise.any(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + */ + // TODO type inference from array-resolving promise? + any(): Bluebird; + + /** + * Same as calling `Promise.some(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + */ + // TODO type inference from array-resolving promise? + some(count: number): Bluebird; + + /** + * Same as calling `Promise.race(thisPromise, count)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + */ + // TODO type inference from array-resolving promise? + race(): Bluebird; + + /** + * Same as calling `Bluebird.map(thisPromise, mapper)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + */ + // TODO type inference from array-resolving promise? + map(mapper: (item: Q, index: number, arrayLength: number) => U | Bluebird.Thenable, options?: Bluebird.ConcurrencyOption): Bluebird; + + /** + * Same as calling `Promise.reduce(thisPromise, Function reducer, initialValue)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + */ + // TODO type inference from array-resolving promise? + reduce(reducer: (memo: U, item: Q, index: number, arrayLength: number) => U | Bluebird.Thenable, initialValue?: U): Bluebird; + + /** + * Same as calling ``Promise.filter(thisPromise, filterer)``. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + */ + // TODO type inference from array-resolving promise? + filter(filterer: (item: U, index: number, arrayLength: number) => boolean | Bluebird.Thenable, options?: Bluebird.ConcurrencyOption): Bluebird; + + /** + * Same as calling ``Bluebird.each(thisPromise, iterator)``. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + */ + each(iterator: (item: R, index: number, arrayLength: number) => U | Bluebird.Thenable): Bluebird; + + /** + * Same as calling ``Bluebird.mapSeries(thisPromise, iterator)``. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + */ + mapSeries(iterator: (item: R, index: number, arrayLength: number) => U | Bluebird.Thenable): Bluebird; + + /** + * Start the chain of promises with `Promise.try`. Any synchronous exceptions will be turned into rejections on the returned promise. + * + * Note about second argument: if it's specifically a true array, its values become respective arguments for the function call. Otherwise it is passed as is as the first argument for the function call. + * + * Alias for `attempt();` for compatibility with earlier ECMAScript version. + */ + static try(fn: () => R | Bluebird.Thenable): Bluebird; + + static attempt(fn: () => R | Bluebird.Thenable): Bluebird; + + /** + * Returns a new function that wraps the given function `fn`. The new function will always return a promise that is fulfilled with the original functions return values or rejected with thrown exceptions from the original function. + * This method is convenient when a function can sometimes return synchronously or throw synchronously. + */ + static method(fn: Function): Function; + + /** + * Create a promise that is resolved with the given `value`. If `value` is a thenable or promise, the returned promise will assume its state. + */ + static resolve(): Bluebird; + static resolve(value: R | Bluebird.Thenable): Bluebird; + + /** + * Create a promise that is rejected with the given `reason`. + */ + static reject(reason: any): Bluebird; + static reject(reason: any): Bluebird; + + /** + * Create a promise with undecided fate and return a `PromiseResolver` to control it. See resolution?: Promise(#promise-resolution). + */ + static defer(): Bluebird.Resolver; + + /** + * Cast the given `value` to a trusted promise. If `value` is already a trusted `Promise`, it is returned as is. If `value` is not a thenable, a fulfilled is: Promise returned with `value` as its fulfillment value. If `value` is a thenable (Promise-like object, like those returned by jQuery's `$.ajax`), returns a trusted that: Promise assimilates the state of the thenable. + */ + static cast(value: R | Bluebird.Thenable): Bluebird; + + /** + * Sugar for `Promise.resolve(undefined).bind(thisArg);`. See `.bind()`. + */ + static bind(thisArg: any): Bluebird; + + /** + * See if `value` is a trusted Promise. + */ + static is(value: any): boolean; + + /** + * Call this right after the library is loaded to enabled long stack traces. Long stack traces cannot be disabled after being enabled, and cannot be enabled after promises have already been created. Long stack traces imply a substantial performance penalty, around 4-5x for throughput and 0.5x for latency. + */ + static longStackTraces(): void; + + /** + * Returns a promise that will be resolved with value (or undefined) after given ms milliseconds. + * If value is a promise, the delay will start counting down when it is fulfilled and the returned + * promise will be fulfilled with the fulfillment value of the value promise. + */ + static delay(ms: number, value: R | Bluebird.Thenable): Bluebird; + static delay(ms: number): Bluebird; + + /** + * Returns a function that will wrap the given `nodeFunction`. Instead of taking a callback, the returned function will return a promise whose fate is decided by the callback behavior of the given node function. The node function should conform to node.js convention of accepting a callback as last argument and calling that callback with error as the first argument and success value on the second argument. + * + * If the `nodeFunction` calls its callback with multiple success values, the fulfillment value will be an array of them. + * + * If you pass a `receiver`, the `nodeFunction` will be called as a method on the `receiver`. + */ + static promisify(func: (callback: (err: any, result: T) => void) => void, options?: Bluebird.PromisifyOptions): () => Bluebird; + static promisify(func: (arg1: A1, callback: (err: any, result: T) => void) => void, options?: Bluebird.PromisifyOptions): (arg1: A1) => Bluebird; + static promisify(func: (arg1: A1, arg2: A2, callback: (err: any, result: T) => void) => void, options?: Bluebird.PromisifyOptions): (arg1: A1, arg2: A2) => Bluebird; + static promisify(func: (arg1: A1, arg2: A2, arg3: A3, callback: (err: any, result: T) => void) => void, options?: Bluebird.PromisifyOptions): (arg1: A1, arg2: A2, arg3: A3) => Bluebird; + static promisify(func: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, callback: (err: any, result: T) => void) => void, options?: Bluebird.PromisifyOptions): (arg1: A1, arg2: A2, arg3: A3, arg4: A4) => Bluebird; + static promisify(func: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5, callback: (err: any, result: T) => void) => void, options?: Bluebird.PromisifyOptions): (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5) => Bluebird; + static promisify(nodeFunction: Function, options?: Bluebird.PromisifyOptions): Function; + + /** + * Promisifies the entire object by going through the object's properties and creating an async equivalent of each function on the object and its prototype chain. The promisified method name will be the original method name postfixed with `Async`. Returns the input object. + * + * Note that the original methods on the object are not overwritten but new methods are created with the `Async`-postfix. For example, if you `promisifyAll()` the node.js `fs` object use `fs.statAsync()` to call the promisified `stat` method. + */ + // TODO how to model promisifyAll? + static promisifyAll(target: Object, options?: Bluebird.PromisifyAllOptions): Object; + + /** + * Returns a promise that is resolved by a node style callback function. + */ + static fromNode(resolver: (callback: (err: any, result?: any) => void) => void, options?: Bluebird.FromNodeOptions): Bluebird; + static fromNode(resolver: (callback: (err: any, result?: T) => void) => void, options?: Bluebird.FromNodeOptions): Bluebird; + static fromCallback(resolver: (callback: (err: any, result?: any) => void) => void, options?: Bluebird.FromNodeOptions): Bluebird; + static fromCallback(resolver: (callback: (err: any, result?: T) => void) => void, options?: Bluebird.FromNodeOptions): Bluebird; + + /** + * Returns a function that can use `yield` to run asynchronous code synchronously. This feature requires the support of generators which are drafted in the next version of the language. Node version greater than `0.11.2` is required and needs to be executed with the `--harmony-generators` (or `--harmony`) command-line switch. + */ + // TODO fix coroutine GeneratorFunction + static coroutine(generatorFunction: Function): Function; + + /** + * Add `handler` as the handler to call when there is a possibly unhandled rejection. The default handler logs the error stack to stderr or `console.error` in browsers. + * + * Passing no value or a non-function will have the effect of removing any kind of handling for possibly unhandled rejections. + */ + static onPossiblyUnhandledRejection(handler: (reason: any) => any): void; + + /** + * Given an array, or a promise of an array, which contains promises (or a mix of promises and values) return a promise that is fulfilled when all the items in the array are fulfilled. The promise's fulfillment value is an array with fulfillment values at respective positions to the original array. If any promise in the array rejects, the returned promise is rejected with the rejection reason. + */ + // TODO enable more overloads + // array with promises of different types + static all(values: [Bluebird.Thenable | T1]): Bluebird<[T1]>; + static all(values: [Bluebird.Thenable | T1, Bluebird.Thenable | T2]): Bluebird<[T1, T2]>; + static all(values: [Bluebird.Thenable | T1, Bluebird.Thenable | T2, Bluebird.Thenable | T3]): Bluebird<[T1, T2, T3]>; + static all(values: [Bluebird.Thenable | T1, Bluebird.Thenable | T2, Bluebird.Thenable | T3, Bluebird.Thenable | T4]): Bluebird<[T1, T2, T3, T4]>; + static all(values: [Bluebird.Thenable | T1, Bluebird.Thenable | T2, Bluebird.Thenable | T3, Bluebird.Thenable | T4, Bluebird.Thenable | T5]): Bluebird<[T1, T2, T3, T4, T5]>; + // array with values + static all(values: ((R | Bluebird.Thenable) | Bluebird.Thenable<(R | Bluebird.Thenable)>)[]): Bluebird; + + /** + * Like ``Promise.all`` but for object properties instead of array items. Returns a promise that is fulfilled when all the properties of the object are fulfilled. The promise's fulfillment value is an object with fulfillment values at respective keys to the original object. If any promise in the object rejects, the returned promise is rejected with the rejection reason. + * + * If `object` is a trusted `Promise`, then it will be treated as a promise for object rather than for its properties. All other objects are treated for their properties as is returned by `Object.keys` - the object's own enumerable properties. + * + * *The original object is not modified.* + */ + // TODO verify this is correct + // trusted promise for object + static props(object: Bluebird): Bluebird; + // object + static props(object: Object): Bluebird; + + /** + * Like `Promise.some()`, with 1 as `count`. However, if the promise fulfills, the fulfillment value is not an array of 1 but the value directly. + */ + static any(values: Bluebird.Thenable<(Bluebird.Thenable | R)[]> | (Bluebird.Thenable | R)[]): Bluebird; + + /** + * Given an array, or a promise of an array, which contains promises (or a mix of promises and values) return a promise that is fulfilled or rejected as soon as a promise in the array is fulfilled or rejected with the respective rejection reason or fulfillment value. + * + * **Note** If you pass empty array or a sparse array with no values, or a promise/thenable for such, it will be forever pending. + */ + static race(values: Bluebird.Thenable<(Bluebird.Thenable | R)[]> | (Bluebird.Thenable | R)[]): Bluebird; + + /** + * Initiate a competetive race between multiple promises or values (values will become immediately fulfilled promises). When `count` amount of promises have been fulfilled, the returned promise is fulfilled with an array that contains the fulfillment values of the winners in order of resolution. + * + * If too many promises are rejected so that the promise can never become fulfilled, it will be immediately rejected with an array of rejection reasons in the order they were thrown in. + * + * *The original array is not modified.* + */ + // promise of array with promises of value + static some(values: Bluebird.Thenable[]>, count: number): Bluebird; + // promise of array with values + static some(values: Bluebird.Thenable, count: number): Bluebird; + // array with promises of value + static some(values: Bluebird.Thenable[], count: number): Bluebird; + // array with values + static some(values: R[], count: number): Bluebird; + + /** + * Promise.join( + * Promise|any values..., + * function handler + * ) -> Promise + * For coordinating multiple concurrent discrete promises. + * + * Note: In 1.x and 0.x Promise.join used to be a Promise.all that took the values in as arguments instead in an array. This behavior has been deprecated but is still supported partially - when the last argument is an immediate function value the new semantics will apply + */ + static join(arg1: A1 | Bluebird.Thenable, handler: (arg1?: A1) => R | Bluebird.Thenable): Bluebird; + static join(arg1: A1 | Bluebird.Thenable, arg2: A2 | Bluebird.Thenable, handler: (arg1?: A1, arg2?: A2) => R | Bluebird.Thenable): Bluebird; + static join(arg1: A1 | Bluebird.Thenable, arg2: A2 | Bluebird.Thenable, arg3: A3 | Bluebird.Thenable, handler: (arg1?: A1, arg2?: A2, arg3?: A3) => R | Bluebird.Thenable): Bluebird; + static join(arg1: A1 | Bluebird.Thenable, arg2: A2 | Bluebird.Thenable, arg3: A3 | Bluebird.Thenable, arg4: A4 | Bluebird.Thenable, handler: (arg1?: A1, arg2?: A2, arg3?: A3, arg4?: A4) => R | Bluebird.Thenable): Bluebird; + static join(arg1: A1 | Bluebird.Thenable, arg2: A2 | Bluebird.Thenable, arg3: A3 | Bluebird.Thenable, arg4: A4 | Bluebird.Thenable, arg5: A5 | Bluebird.Thenable, handler: (arg1?: A1, arg2?: A2, arg3?: A3, arg4?: A4, arg5?: A5) => R | Bluebird.Thenable): Bluebird; + + // variadic array + /** @deprecated use .all instead */ + static join(...values: (R | Bluebird.Thenable)[]): Bluebird; + + /** + * Map an array, or a promise of an array, which contains a promises (or a mix of promises and values) with the given `mapper` function with the signature `(item, index, arrayLength)` where `item` is the resolved value of a respective promise in the input array. If any promise in the input array is rejected the returned promise is rejected as well. + * + * If the `mapper` function returns promises or thenables, the returned promise will wait for all the mapped results to be resolved as well. + * + * *The original array is not modified.* + */ + // promise of array with promises of value + static map(values: Bluebird.Thenable[]>, mapper: (item: R, index: number, arrayLength: number) => U | Bluebird.Thenable, options?: Bluebird.ConcurrencyOption): Bluebird; + + // promise of array with values + static map(values: Bluebird.Thenable, mapper: (item: R, index: number, arrayLength: number) => U | Bluebird.Thenable, options?: Bluebird.ConcurrencyOption): Bluebird; + + // array with promises of value + static map(values: Bluebird.Thenable[], mapper: (item: R, index: number, arrayLength: number) => U | Bluebird.Thenable, options?: Bluebird.ConcurrencyOption): Bluebird; + + // array with values + static map(values: R[], mapper: (item: R, index: number, arrayLength: number) => U | Bluebird.Thenable, options?: Bluebird.ConcurrencyOption): Bluebird; + + /** + * Reduce an array, or a promise of an array, which contains a promises (or a mix of promises and values) with the given `reducer` function with the signature `(total, current, index, arrayLength)` where `item` is the resolved value of a respective promise in the input array. If any promise in the input array is rejected the returned promise is rejected as well. + * + * If the reducer function returns a promise or a thenable, the result for the promise is awaited for before continuing with next iteration. + * + * *The original array is not modified. If no `intialValue` is given and the array doesn't contain at least 2 items, the callback will not be called and `undefined` is returned. If `initialValue` is given and the array doesn't have at least 1 item, `initialValue` is returned.* + */ + // promise of array with promises of value + static reduce(values: Bluebird.Thenable[]>, reducer: (total: U, current: R, index: number, arrayLength: number) => U | Bluebird.Thenable, initialValue?: U): Bluebird; + + // promise of array with values + static reduce(values: Bluebird.Thenable, reducer: (total: U, current: R, index: number, arrayLength: number) => U | Bluebird.Thenable, initialValue?: U): Bluebird; + + // array with promises of value + static reduce(values: Bluebird.Thenable[], reducer: (total: U, current: R, index: number, arrayLength: number) => U | Bluebird.Thenable, initialValue?: U): Bluebird; + + // array with values + static reduce(values: R[], reducer: (total: U, current: R, index: number, arrayLength: number) => U | Bluebird.Thenable, initialValue?: U): Bluebird; + + /** + * Filter an array, or a promise of an array, which contains a promises (or a mix of promises and values) with the given `filterer` function with the signature `(item, index, arrayLength)` where `item` is the resolved value of a respective promise in the input array. If any promise in the input array is rejected the returned promise is rejected as well. + * + * The return values from the filtered functions are coerced to booleans, with the exception of promises and thenables which are awaited for their eventual result. + * + * *The original array is not modified. + */ + // promise of array with promises of value + static filter(values: Bluebird.Thenable[]>, filterer: (item: R, index: number, arrayLength: number) => boolean | Bluebird.Thenable, option?: Bluebird.ConcurrencyOption): Bluebird; + + // promise of array with values + static filter(values: Bluebird.Thenable, filterer: (item: R, index: number, arrayLength: number) => boolean | Bluebird.Thenable, option?: Bluebird.ConcurrencyOption): Bluebird; + + // array with promises of value + static filter(values: Bluebird.Thenable[], filterer: (item: R, index: number, arrayLength: number) => boolean | Bluebird.Thenable, option?: Bluebird.ConcurrencyOption): Bluebird; + + // array with values + static filter(values: R[], filterer: (item: R, index: number, arrayLength: number) => boolean | Bluebird.Thenable, option?: Bluebird.ConcurrencyOption): Bluebird; + + /** + * Iterate over an array, or a promise of an array, which contains promises (or a mix of promises and values) with the given iterator function with the signature (item, index, value) where item is the resolved value of a respective promise in the input array. Iteration happens serially. If any promise in the input array is rejected the returned promise is rejected as well. + * + * Resolves to the original array unmodified, this method is meant to be used for side effects. If the iterator function returns a promise or a thenable, the result for the promise is awaited for before continuing with next iteration. + */ + // promise of array with promises of value + static each(values: Bluebird.Thenable[]>, iterator: (item: R, index: number, arrayLength: number) => U | Bluebird.Thenable): Bluebird; + // array with promises of value + static each(values: Bluebird.Thenable[], iterator: (item: R, index: number, arrayLength: number) => U | Bluebird.Thenable): Bluebird; + // array with values OR promise of array with values + static each(values: R[] | Bluebird.Thenable, iterator: (item: R, index: number, arrayLength: number) => U | Bluebird.Thenable): Bluebird; + + /** + * Given an Iterable(arrays are Iterable), or a promise of an Iterable, which produces promises (or a mix of promises and values), iterate over all the values in the Iterable into an array and iterate over the array serially, in-order. + * + * Returns a promise for an array that contains the values returned by the iterator function in their respective positions. The iterator won't be called for an item until its previous item, and the promise returned by the iterator for that item are fulfilled. This results in a mapSeries kind of utility but it can also be used simply as a side effect iterator similar to Array#forEach. + * + * If any promise in the input array is rejected or any promise returned by the iterator function is rejected, the result will be rejected as well. + */ + static mapSeries(values: (R | Bluebird.Thenable)[] | Bluebird.Thenable<(R | Bluebird.Thenable)[]>, iterator: (item: R, index: number, arrayLength: number) => U | Bluebird.Thenable): Bluebird; + + /** + * A meta method used to specify the disposer method that cleans up a resource when using `Promise.using`. + * + * Returns a Disposer object which encapsulates both the resource as well as the method to clean it up. + * The user can pass this object to `Promise.using` to get access to the resource when it becomes available, + * as well as to ensure its automatically cleaned up. + * + * The second argument passed to a disposer is the result promise of the using block, which you can + * inspect synchronously. + */ + disposer(disposeFn: (arg: R, promise: Bluebird) => void | Bluebird.Thenable): Bluebird.Disposer; + + /** + * In conjunction with `.disposer`, using will make sure that no matter what, the specified disposer + * will be called when the promise returned by the callback passed to using has settled. The disposer is + * necessary because there is no standard interface in node for disposing resources. + */ + static using(disposer: Bluebird.Disposer, executor: (transaction: R) => Bluebird.Thenable): Bluebird; + static using(disposer: Bluebird.Disposer, disposer2: Bluebird.Disposer, executor: (transaction1: R1, transaction2: R2) => Bluebird.Thenable): Bluebird; + static using(disposer: Bluebird.Disposer, disposer2: Bluebird.Disposer, disposer3: Bluebird.Disposer, executor: (transaction1: R1, transaction2: R2, transaction3: R3) => Bluebird.Thenable): Bluebird; + + /** + * Add handler as the handler to call when there is a possibly unhandled rejection. + * The default handler logs the error stack to stderr or console.error in browsers. + * + * Passing no value or a non-function will have the effect of removing any kind of handling for possibly unhandled rejections. + * + * Note: this hook is specific to the bluebird instance its called on, application developers should use global rejection events. + */ + static onPossiblyUnhandledRejection(handler?: (error: Error, promise: Bluebird) => void): void; + + /** + * Configure long stack traces, warnings, monitoring and cancellation. + * Note that even though false is the default here, a development environment might be detected which automatically + * enables long stack traces and warnings. + */ + static config(options: { + /** Enable warnings */ + warnings?: boolean | { + /** Enables all warnings except forgotten return statements. */ + wForgottenReturn: boolean; + }; + /** Enable long stack traces */ + longStackTraces?: boolean; + /** Enable cancellation */ + cancellation?: boolean; + /** Enable monitoring */ + monitoring?: boolean; + }): void; +} + +namespace Bluebird { + export interface ConcurrencyOption { + concurrency: number; + } + export interface SpreadOption { + spread: boolean; + } + export interface FromNodeOptions { + multiArgs?: boolean; + } + export interface PromisifyOptions { + context?: any; + multiArgs?: boolean; + } + export interface PromisifyAllOptions extends PromisifyOptions { + suffix?: string; + filter?: (name: string, func: Function, target?: any, passesDefaultFilter?: boolean) => boolean; + // The promisifier gets a reference to the original method and should return a function which returns a promise + promisifier?: (originalMethod: Function) => () => Thenable; + } + + /** + * Represents an error is an explicit promise rejection as opposed to a thrown error. + * For example, if an error is errbacked by a callback API promisified through undefined or undefined + * and is not a typed error, it will be converted to a `OperationalError` which has the original error in + * the `.cause` property. + * + * `OperationalError`s are caught in `.error` handlers. + */ + export class OperationalError extends Error { } + + /** + * Signals that an operation has timed out. Used as a custom cancellation reason in `.timeout`. + */ + export class TimeoutError extends Error { } + + /** + * Signals that an operation has been aborted or cancelled. The default reason used by `.cancel`. + */ + export class CancellationError extends Error {} + + /** + * A collection of errors. `AggregateError` is an array-like object, with numeric indices and a `.length` property. + * It supports all generic array methods such as `.forEach` directly. + * + * `AggregateError`s are caught in `.error` handlers, even if the contained errors are not operational. + * + * `Promise.some` and `Promise.any` use `AggregateError` as rejection reason when they fail. + */ + export class AggregateError extends Error {} + + /** + * returned by `Bluebird.disposer()`. + */ + export class Disposer { + } + + export interface Thenable { + then(onFulfilled: (value: R) => U | Thenable, onRejected?: (error: any) => U | Thenable): Thenable; + then(onFulfilled: (value: R) => U | Thenable, onRejected?: (error: any) => void | Thenable): Thenable; + } + + export interface Resolver { + /** + * Returns a reference to the controlled promise that can be passed to clients. */ - dropIndex(name: string, callback?: General.Callback): Bluebird; + promise: Bluebird; + /** - * Drops the index if it exists in the collection - * @param {IndexSpecification} index The index to remove - * @param {function(Error, Boolean)} callback A callback which is triggered when the operation completes - * @returns {Promise} Whether the index was dropped + * Resolve the underlying promise with `value` as the resolution value. If `value` is a thenable or a promise, the underlying promise will assume its state. */ - dropIndex(index: Index.IndexSpecification, callback?: General.Callback): Bluebird; + resolve(value: R): void; + resolve(): void; + /** - * Removes all indexes (except for _id) from the collection - * @param {function(Error, Boolean)} callback A callback which is triggered when the operation completes - * @returns {Promise} Whether the indexes were dropped + * Reject the underlying promise with `reason` as the rejection reason. */ - dropIndexes(callback?: General.Callback): Bluebird; -} -} -declare module 'iridium/dist/lib/Model' { -export * from '~iridium/dist/lib/Model'; -} + reject(reason: any): void; -// Generated by typings -// Source: dist/lib/General.d.ts -declare module '~iridium/dist/lib/General' { -/** - * A method which is called once an asynchronous operation has completed, an alternative - * to using Promises. - * @param T The type of object returned by the asynchronous operation. - */ -export interface Callback { /** - * @param err The error object, if one occurred, otherwise null if the operation completed successfully. - * @param object The result of the asynchronous operation if it completed successfully. If err is defined, the presence of this value is unknown. + * Gives you a callback representation of the `PromiseResolver`. Note that this is not a method but a property. The callback accepts error object in first argument and success values on the 2nd parameter and the rest, I.E. node js conventions. + * + * If the the callback is called with multiple success values, the resolver fullfills its promise with an array of the values. */ - (err: Error, object?: T): void; -} -/** - * A method which is used to determine whether a value within a collection meets a set of criteria. - * @param T The type of item in the collection. - */ -export interface Predicate { + // TODO specify resolver callback + callback: (err: any, value: R, ...values: R[]) => void; + } + + export interface Inspection { /** - * @param object The value of the item in the collection - * @param key The key, if one is available, under which the item appeared within the collection - * @returns A true-y value if the item met the predicate conditions, false-y values if it did not. + * See if the underlying promise was fulfilled at the creation time of this inspection object. */ - (object: T, key?: string): boolean; -} -/** - * A method which is called to retrieve a value of the given type. - * @param T The type of value to be retrieved. - */ -export interface PropertyGetter { + isFulfilled(): boolean; + /** - * Gets the current value of the property - * @returns The current value + * See if the underlying promise was rejected at the creation time of this inspection object. */ - (): T; -} -/** - * A method which is called to set a value of the given type. - * @param T The type of value to set - */ -export interface PropertySetter { + isRejected(): boolean; + /** - * Sets the value to the provided one - * @param value The new value to set + * See if the underlying promise was defer at the creation time of this inspection object. */ - (value: T): void; -} -/** - * A compound property which provides either a getter, setter or both. - * @param T The type of objects stored in the property - */ -export interface Property { + isPending(): boolean; + /** - * An optional getter which can be used to retrieve the property's value + * Get the fulfillment value of the underlying promise. Throws if the promise wasn't fulfilled at the creation time of this inspection object. + * + * throws `TypeError` */ - get?: PropertyGetter; + value(): R; + /** - * An optional setter which can be used to set the property's value + * Get the rejection reason for the underlying promise. Throws if the promise wasn't rejected at the creation time of this inspection object. + * + * throws `TypeError` */ - set?: PropertySetter; -} -} -declare module 'iridium/dist/lib/General' { -export * from '~iridium/dist/lib/General'; -} + reason(): any; + } -// Generated by typings -// Source: dist/lib/Index.d.ts -declare module '~iridium/dist/lib/Index' { -import * as MongoDB from '~iridium~mongodb'; -export interface Index { - spec: IndexSpecification; - options?: MongoDB.IndexOptions; -} -export interface IndexSpecification { - [key: string]: number | string; + /** + * Changes how bluebird schedules calls a-synchronously. + * + * @param scheduler Should be a function that asynchronously schedules + * the calling of the passed in function + */ + export function setScheduler(scheduler: (callback: (...args: any[]) => void) => void): void; } + +export = Bluebird; } -declare module 'iridium/dist/lib/Index' { -export * from '~iridium/dist/lib/Index'; +declare module '~iridium~bluebird' { +import main = require('~iridium~bluebird/bluebird'); +export = main; } // Generated by typings @@ -3453,6 +3337,133 @@ declare module 'iridium/dist/lib/Instance' { export * from '~iridium/dist/lib/Instance'; } +// Generated by typings +// Source: dist/lib/InstanceInterface.d.ts +declare module '~iridium/dist/lib/InstanceInterface' { +import * as Skmatc from '~iridium~skmatc'; +import { Schema } from '~iridium/dist/lib/Schema'; +import { Model } from '~iridium/dist/lib/Model'; +import * as Index from '~iridium/dist/lib/Index'; +import { CacheDirector } from '~iridium/dist/lib/CacheDirector'; +import { Transforms } from '~iridium/dist/lib/Transforms'; +/** + * This interface dictates the format of an instance class which wraps documents received + * from the database for a specific Iridium model. + * + * @param TDocument The interface representing the documents stored in the database, after being passed through the transforms pipeline. + * @param TInstance The type of object which is instantiated when calling this implementation's constructor. + * + * It is important to note that, when implementing this interface, each of the properties and methods + * should be exposed statically. That is, you would expose the collection property as a static variable + * on the instance implementation, since prototype methods and variables become available to consumers of the + * instance itself. + */ +export interface InstanceImplementation { + /** + * A constructor which creates a new instance tied to the given model and representing the given document. + * @param model The Iridium Model which this instance should be tied to, gives the instance access to the database collection and any other context it requires. + * @param doc The document this instance should wrap from the database. This provides the data context for the instance. + * @param isNew Whether this document is known to exist in the database or not, for example, if the instance was generated from user input and hasn't been saved yet. + * @param isPartial Whether the document which has been given to this instance had any field restrictions imposed on it during the query, and may therefore only contain partial data. + */ + new (model: Model, doc: TDocument, isNew?: boolean, isPartial?: boolean): TInstance; + /** + * The name of the database collection from which documents are retrieved, and to which they are stored. + */ + collection: string; + /** + * The database schematic used for validation of instances prior to storing them in the database. + * This schematic should follow the guides set out in skmatc's documentation, and is used whenever + * you insert a new document into the collection or save an instance using the default instance type. + * Operations like update() (and by extension, save() when using the update operations) cannot be checked + * by skmatc for consistency and as a result will not have their data validated - be careful when making + * use of them as a result. + */ + schema: Schema; + /** + * Any additional indexes on the collection which should be managed by Iridium. + * This field is optional, but if provided allows you to make use of the model's ensureIndexes() method + * to automatically generate all specified indexes. + */ + indexes?: (Index.Index | Index.IndexSpecification)[]; + /** + * An optional method which will be called whenever a document is about to be inserted into the database, + * allowing you to set default values and do any preprocessing you wish prior to the document being inserted. + * + * @param document The document which will be inserted into the database. + * + * This method is executed synchronously, however you can perform asynchronous operations by returning a + * promise which resolves once your task has completed. Be aware that this method is executed for every + * document inserted into the database. As a result, long running tasks will have a significant impact + * on the performance of your inserts. + */ + onCreating?(document: TDocument): Promise | void; + /** + * An optional method which is called whenever a new document is received from the model's collection and + * prior to the document being wrapped, can be used to perform preprocessing if necessary - however we recommend + * you rather make use of transforms for that task. + * + * @param document The document that was retrieved from the database. + * + * This method is executed synchronously, however you can perform asynchronous operations by returning a + * promise which resolves once your task has completed. Be aware that this method is executed for every + * document retrieved from the database. As a result, long running tasks will have a significant impact + * on the performance of your queries. + */ + onRetrieved?(document: TDocument): Promise | void; + /** + * An optional method which is called whenever a new document for this model has been wrapped in an instance. + * + * @param instance The instance which has been created. + * + * This method is executed synchronously, however you can perform asynchronous operations by returning a + * promise which resolves once your task has completed. Be aware that this method is executed for every + * document retrieved from the database. As a result, long running tasks will have a significant impact + * on the performance of your queries. + */ + onReady?(instance: TInstance): Promise | void; + /** + * An optional method which is called prior to saving an instance, it is provided with the instance itself as + * well as the proposed changes to the instance. This allows you to make additional changes, such as updating + * a lastChanged property on the document, or abort changes by throwing an error. + * + * @param instance The instance to which the changes are being made + * @param changes The MongoDB change object describing the changes being made to the document. + * + * This method is executed synchronously, however you can perform asynchronous operations by returning a + * promise which resolves once your task has completed. Be aware that this method is executed for every + * call to save. As a result, long running tasks will have a significant impact on how quickly your save + * operations are dispatched. + */ + onSaving?(instance: TInstance, changes: any): Promise | void; + /** + * The cache controller used to determine whether a document may be cached, as well as deriving a unique cache + * key for the document and similarly, for a query. This works in concert with the cache implementation itself + * to ensure that documents are cached in an intelligent manner. By default this will simply make use of the + * document's _id field as the cache key - however that behaviour may be modified if you wish to query on other + * properties instead. + */ + cache?: CacheDirector; + /** + * Any additional validation types you wish to make available for use within this model's database schema. This + * allows you to validate using conditions otherwise not available within skmatc itself. For more information + * on implementing a validator, take a look at the skmatc documentation on GitHub. + */ + validators?: Skmatc.Validator[]; + /** + * Any transform operations you would like to perform on documents received from the database, or prior to being + * sent to the database. These may include things such as converting ObjectIDs to strings for the application, and + * then back to ObjectIDs once they return to the database. + */ + transforms?: Transforms; +} +} +declare module 'iridium/dist/lib/InstanceInterface' { +export * from '~iridium/dist/lib/InstanceInterface'; +} + // Generated by typings // Source: dist/lib/Decorators.d.ts declare module '~iridium/dist/lib/Decorators' {