diff --git a/dist/lib/Core.js b/dist/lib/Core.js index 62c71c4..22f024f 100644 --- a/dist/lib/Core.js +++ b/dist/lib/Core.js @@ -1,9 +1,9 @@ "use strict"; -var Bluebird = require("bluebird"); -var MongoDB = require("mongodb"); -var _ = require("lodash"); -var Express_1 = require("./middleware/Express"); -var NoOpCache_1 = require("./caches/NoOpCache"); +const Bluebird = require("bluebird"); +const MongoDB = require("mongodb"); +const _ = require("lodash"); +const Express_1 = require("./middleware/Express"); +const NoOpCache_1 = require("./caches/NoOpCache"); /** * The Iridium Core, responsible for managing the connection to the database as well * as any plugins you are making use of. @@ -11,14 +11,14 @@ var NoOpCache_1 = require("./caches/NoOpCache"); * Generally you will subclass this to provide your own custom core with the models you * make use of within your application. */ -var Core = (function () { - function Core(uri, config) { +class Core { + constructor(uri, config) { this.mongoConnectAsyc = Bluebird.promisify(MongoDB.MongoClient.connect); this._plugins = []; this._cache = new NoOpCache_1.NoOpCache(); - var args = Array.prototype.slice.call(arguments, 0); + let args = Array.prototype.slice.call(arguments, 0); uri = config = null; - for (var i = 0; i < args.length; i++) { + for (let i = 0; i < args.length; i++) { if (typeof args[i] == "string") uri = args[i]; else if (typeof args[i] == "object") @@ -29,159 +29,136 @@ var Core = (function () { this._url = uri; this._config = config; } - Object.defineProperty(Core.prototype, "plugins", { - /** - * Gets the plugins registered with this Iridium Core - * @returns {[Iridium.Plugin]} - */ - get: function () { - return this._plugins; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Core.prototype, "settings", { - /** - * Gets the configuration specified in the construction of this - * Iridium Core. - * @returns {Iridium.Configuration} - */ - get: function () { - return this._config; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Core.prototype, "connection", { - /** - * Gets the currently active database connection for this Iridium - * Core. - * @returns {MongoDB.Db} - */ - get: function () { - return this._connection; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Core.prototype, "url", { - /** - * Gets the URL used to connect to MongoDB - * @returns {String} - */ - get: function () { - var _this = this; - if (this._url) - return this._url; - var url = "mongodb://"; - if (this._config.username) { - url += this._config.username; - if (this._config.password) - url += ":" + this._config.password; - url += "@"; - } - var hosts = []; - if (this._config.host) { - if (this._config.port) - hosts.push(this._config.host + ":" + this._config.port); - else - hosts.push(this._config.host); - } - if (this._config.hosts) { - _.each(this._config.hosts, function (host) { - if (host.port) - hosts.push(host.address + ":" + host.port); - else if (_this._config.port) - hosts.push(host.address + ":" + _this._config.port); - else - hosts.push(host.address); - }); - } - if (hosts.length) - url += _.uniq(hosts).join(","); + /** + * Gets the plugins registered with this Iridium Core + * @returns {[Iridium.Plugin]} + */ + get plugins() { + return this._plugins; + } + /** + * Gets the configuration specified in the construction of this + * Iridium Core. + * @returns {Iridium.Configuration} + */ + get settings() { + return this._config; + } + /** + * Gets the currently active database connection for this Iridium + * Core. + * @returns {MongoDB.Db} + */ + get connection() { + return this._connection; + } + /** + * Gets the URL used to connect to MongoDB + * @returns {String} + */ + get url() { + if (this._url) + return this._url; + let url = "mongodb://"; + if (this._config.username) { + url += this._config.username; + if (this._config.password) + url += ":" + this._config.password; + url += "@"; + } + let hosts = []; + if (this._config.host) { + if (this._config.port) + hosts.push(this._config.host + ":" + this._config.port); else - url += "localhost"; - url += "/" + this._config.database; - return url; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Core.prototype, "cache", { - /** - * Gets the cache used to store objects retrieved from the database for performance reasons - * @returns {cache} - */ - get: function () { - return this._cache; - }, - set: function (value) { - this._cache = value; - }, - enumerable: true, - configurable: true - }); + hosts.push(this._config.host); + } + if (this._config.hosts) { + _.each(this._config.hosts, (host) => { + if (host.port) + hosts.push(host.address + ":" + host.port); + else if (this._config.port) + hosts.push(host.address + ":" + this._config.port); + else + hosts.push(host.address); + }); + } + if (hosts.length) + url += _.uniq(hosts).join(","); + else + url += "localhost"; + url += "/" + this._config.database; + return url; + } + /** + * Gets the cache used to store objects retrieved from the database for performance reasons + * @returns {cache} + */ + get cache() { + return this._cache; + } + set cache(value) { + this._cache = value; + } /** * Registers a new plugin with this Iridium Core * @param {Iridium.Plugin} plugin The plugin to register with this Iridium Core * @returns {Iridium.Core} */ - Core.prototype.register = function (plugin) { + register(plugin) { this.plugins.push(plugin); return this; - }; + } /** * 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} */ - Core.prototype.connect = function (callback) { - var _this = this; - return Bluebird.resolve().then(function () { - if (_this._connection) - return _this._connection; - if (_this._connectPromise) - return _this._connectPromise; - return _this._connectPromise = _this.mongoConnectAsyc(_this.url, _this._config && _this._config.options); - }).then(function (db) { - return _this.onConnecting(db); - }).then(function (db) { - _this._connection = db; - _this._connectPromise = null; - return _this.onConnected(); - }).then(function () { - return _this; - }, function (err) { - if (_this._connection) - _this._connection.close(); - _this._connection = null; - _this._connectPromise = null; + connect(callback) { + return Bluebird.resolve().then(() => { + if (this._connection) + return this._connection; + if (this._connectPromise) + return this._connectPromise; + return this._connectPromise = this.mongoConnectAsyc(this.url, this._config && this._config.options); + }).then((db) => { + return this.onConnecting(db); + }).then(db => { + this._connection = db; + this._connectPromise = null; + return this.onConnected(); + }).then(() => { + return this; + }, (err) => { + if (this._connection) + this._connection.close(); + this._connection = null; + this._connectPromise = null; return Bluebird.reject(err); }).nodeify(callback); - }; + } /** * Closes the active database connection * @type {Promise} */ - Core.prototype.close = function () { - var _this = this; - return Bluebird.resolve().then(function () { - if (!_this._connection) - return _this; - var conn = _this._connection; - _this._connection = null; + close() { + return Bluebird.resolve().then(() => { + if (!this._connection) + return this; + let conn = this._connection; + this._connection = null; conn.close(); - return _this; + return this; }); - }; + } /** * Provides an express middleware which can be used to set the req.db property * to the current Iridium instance. * @returns {Iridium.ExpressMiddleware} */ - Core.prototype.express = function () { + express() { return Express_1.ExpressMiddlewareFactory(this); - }; + } /** * A method which is called whenever a new connection is made to the database. * @@ -193,9 +170,9 @@ var Core = (function () { * 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. */ - Core.prototype.onConnecting = function (connection) { + onConnecting(connection) { return Bluebird.resolve(connection); - }; + } /** * A method which is called once a database connection has been established and accepted by Iridium * @@ -203,11 +180,10 @@ var Core = (function () { * connection to the database has been established - such as setting up indexes for your * collections or seeding the database. */ - Core.prototype.onConnected = function () { + onConnected() { return Bluebird.resolve(); - }; - return Core; -}()); + } +} exports.Core = Core; //# sourceMappingURL=Core.js.map diff --git a/dist/lib/Core.js.map b/dist/lib/Core.js.map index 2131bbf..fb9464c 100644 --- a/dist/lib/Core.js.map +++ b/dist/lib/Core.js.map @@ -1 +1 @@ -{"version":3,"sources":["lib/Core.ts"],"names":[],"mappings":";AAAA,IAAY,QAAQ,WAAM,UAAU,CAAC,CAAA;AACrC,IAAY,OAAO,WAAM,SAAS,CAAC,CAAA;AACnC,IAAY,CAAC,WAAM,QAAQ,CAAC,CAAA;AAW5B,wBAAuC,sBAAsB,CAAC,CAAA;AAG9D,0BAAwB,oBAAoB,CAAC,CAAA;AAG7C;;;;;;GAMG;AACH;IAcI,cAAY,GAA2B,EAAE,MAAsB;QAiBvD,qBAAgB,GAAG,QAAQ,CAAC,SAAS,CAA0B,OAAO,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC;QAE5F,aAAQ,GAAa,EAAE,CAAC;QAIxB,WAAM,GAAU,IAAI,qBAAS,EAAE,CAAC;QArBpC,IAAI,IAAI,GAAG,KAAK,CAAC,SAAS,CAAC,KAAK,CAAC,IAAI,CAAC,SAAS,EAAE,CAAC,CAAC,CAAC;QACpD,GAAG,GAAG,MAAM,GAAG,IAAI,CAAC;QACpB,GAAG,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;YACnC,EAAE,CAAC,CAAC,OAAO,IAAI,CAAC,CAAC,CAAC,IAAI,QAAQ,CAAC;gBAC3B,GAAG,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC;YAClB,IAAI,CA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KAAI,CAAC,WAAW,GAAG,IAAI,CAAC;YACxB,KAAI,CAAC,eAAe,GAAG,IAAI,CAAC;YAC5B,MAAM,CAAC,QAAQ,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;QAChC,CAAC,CAAC,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC;IACzB,CAAC;IAED;;;OAGG;IACH,oBAAK,GAAL;QAAA,iBAQC;QAPG,MAAM,CAAC,QAAQ,CAAC,OAAO,EAAE,CAAC,IAAI,CAAC;YAC3B,EAAE,CAAC,CAAC,CAAC,KAAI,CAAC,WAAW,CAAC;gBAAC,MAAM,CAAC,KAAI,CAAC;YACnC,IAAI,IAAI,GAAe,KAAI,CAAC,WAAW,CAAC;YACxC,KAAI,CAAC,WAAW,GAAG,IAAI,CAAC;YACxB,IAAI,CAAC,KAAK,EAAE,CAAC;YACb,MAAM,CAAC,KAAI,CAAC;QAChB,CAAC,CAAC,CAAC;IACP,CAAC;IAED;;;;OAIG;IACH,sBAAO,GAAP;QACI,MAAM,CAAC,kCAAwB,CAAC,IAAI,CAAC,CAAC;IAC1C,CAAC;IAED;;;;;;;;;;OAUG;IACO,2BAAY,GAAtB,UAAuB,UAAsB;QACzC,MAAM,CAAC,QAAQ,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC;IACxC,CAAC;IAED;;;;;;OAMG;IACO,0BAAW,GAArB;QACI,MAAM,CAAC,QAAQ,CAAC,OAAO,EAAE,CAAC;IAC9B,CAAC;IACL,WAAC;AAAD,CAhNA,AAgNC,IAAA;AAhNY,YAAI,OAgNhB,CAAA","file":"lib/Core.js","sourcesContent":["import * as Bluebird from \"bluebird\";\r\nimport * as MongoDB from \"mongodb\";\r\nimport * as _ from \"lodash\";\r\nimport * as http from \"http\";\r\nimport * as events from \"events\";\r\n\r\nimport {Configuration} from \"./Configuration\";\r\nimport {Plugin} from \"./Plugins\";\r\nimport {Model} from \"./Model\";\r\nimport {Instance} from \"./Instance\";\r\n\r\nimport {MiddlewareFactory} from \"./Middleware\";\r\nimport * as ExpressMiddleware from \"./middleware/Express\";\r\nimport {ExpressMiddlewareFactory} from \"./middleware/Express\";\r\n\r\nimport {Cache} from \"./Cache\";\r\nimport {NoOpCache} from \"./caches/NoOpCache\";\r\nimport {MemoryCache} from \"./caches/MemoryCache\";\r\n\r\n/**\r\n * The Iridium Core, responsible for managing the connection to the database as well\r\n * as any plugins you are making use of.\r\n *\r\n * Generally you will subclass this to provide your own custom core with the models you\r\n * make use of within your application.\r\n */\r\nexport class Core {\r\n /**\r\n * Creates a new Iridium Core instance connected to the specified MongoDB instance\r\n * @param {Iridium.IridiumConfiguration} config The config object defining the database to connect to\r\n * @constructs Core\r\n */\r\n constructor(config: Configuration);\r\n /**\r\n * Creates a new Iridium Core instance connected to the specified MongoDB instance\r\n * @param {String} url The URL of the MongoDB instance to connect to\r\n * @param {Iridium.IridiumConfiguration} config The config object made available as settings\r\n * @constructs Core\r\n */\r\n constructor(uri: string, config?: Configuration);\r\n constructor(uri: string | Configuration, config?: Configuration) {\r\n\r\n let args = Array.prototype.slice.call(arguments, 0);\r\n uri = config = null;\r\n for (let i = 0; i < args.length; i++) {\r\n if (typeof args[i] == \"string\")\r\n uri = args[i];\r\n else if (typeof args[i] == \"object\")\r\n config = args[i];\r\n }\r\n\r\n if (!uri && !config) throw new Error(\"Expected either a URI or config object to be supplied when initializing Iridium\");\r\n\r\n this._url = uri;\r\n this._config = config;\r\n }\r\n\r\n private mongoConnectAsyc = Bluebird.promisify(MongoDB.MongoClient.connect);\r\n\r\n private _plugins: Plugin[] = [];\r\n private _url: string;\r\n private _config: Configuration;\r\n private _connection: MongoDB.Db;\r\n private _cache: Cache = new NoOpCache();\r\n\r\n private _connectPromise: Bluebird;\r\n\r\n /**\r\n * Gets the plugins registered with this Iridium Core\r\n * @returns {[Iridium.Plugin]}\r\n */\r\n get plugins(): Plugin[] {\r\n return this._plugins;\r\n }\r\n\r\n /**\r\n * Gets the configuration specified in the construction of this\r\n * Iridium Core.\r\n * @returns {Iridium.Configuration}\r\n */\r\n get settings(): Configuration {\r\n return this._config;\r\n }\r\n\r\n /**\r\n * Gets the currently active database connection for this Iridium\r\n * Core.\r\n * @returns {MongoDB.Db}\r\n */\r\n get connection(): MongoDB.Db {\r\n return this._connection;\r\n }\r\n\r\n /**\r\n * Gets the URL used to connect to MongoDB\r\n * @returns {String}\r\n */\r\n get url(): string {\r\n if (this._url) return this._url;\r\n let url: string = \"mongodb://\";\r\n\r\n if (this._config.username) {\r\n url += this._config.username;\r\n if (this._config.password)\r\n url += \":\" + this._config.password;\r\n url += \"@\";\r\n }\r\n\r\n let hosts = [];\r\n\r\n if (this._config.host) {\r\n if (this._config.port)\r\n hosts.push(this._config.host + \":\" + this._config.port);\r\n else\r\n hosts.push(this._config.host);\r\n }\r\n\r\n if (this._config.hosts) {\r\n _.each(this._config.hosts, (host) => {\r\n if (host.port)\r\n hosts.push(host.address + \":\" + host.port);\r\n else if(this._config.port)\r\n hosts.push(host.address + \":\" + this._config.port);\r\n else\r\n hosts.push(host.address);\r\n });\r\n }\r\n\r\n if (hosts.length)\r\n url += _.uniq(hosts).join(\",\");\r\n else\r\n url += \"localhost\";\r\n\r\n url += \"/\" + this._config.database;\r\n\r\n return url;\r\n }\r\n\r\n /**\r\n * Gets the cache used to store objects retrieved from the database for performance reasons\r\n * @returns {cache}\r\n */\r\n get cache(): Cache {\r\n return this._cache;\r\n }\r\n\r\n set cache(value: Cache) {\r\n this._cache = value;\r\n }\r\n\r\n /**\r\n * Registers a new plugin with this Iridium Core\r\n * @param {Iridium.Plugin} plugin The plugin to register with this Iridium Core\r\n * @returns {Iridium.Core}\r\n */\r\n register(plugin: Plugin): Core {\r\n this.plugins.push(plugin);\r\n return this;\r\n }\r\n\r\n /**\r\n * Connects to the database server specified in the provided configuration\r\n * @param {function(Error, Iridium.Core)} [callback] A callback to be triggered once the connection is established.\r\n * @returns {Promise}\r\n */\r\n connect(callback?: (err: Error, core: Core) => any): Bluebird {\r\n return Bluebird.resolve().then(() => {\r\n if (this._connection) return this._connection;\r\n if (this._connectPromise) return this._connectPromise;\r\n return this._connectPromise = this.mongoConnectAsyc(this.url, this._config && this._config.options);\r\n }).then((db: MongoDB.Db) => {\r\n return this.onConnecting(db);\r\n }).then(db => {\r\n this._connection = db;\r\n this._connectPromise = null;\r\n return this.onConnected();\r\n }).then(() => {\r\n return this;\r\n }, (err) => {\r\n if (this._connection) this._connection.close();\r\n this._connection = null;\r\n this._connectPromise = null;\r\n return Bluebird.reject(err);\r\n }).nodeify(callback);\r\n }\r\n\r\n /**\r\n * Closes the active database connection\r\n * @type {Promise}\r\n */\r\n close(): Bluebird {\r\n return Bluebird.resolve().then(() => {\r\n if (!this._connection) return this;\r\n let conn: MongoDB.Db = this._connection;\r\n this._connection = null;\r\n conn.close();\r\n return this;\r\n });\r\n }\r\n\r\n /**\r\n * Provides an express middleware which can be used to set the req.db property\r\n * to the current Iridium instance.\r\n * @returns {Iridium.ExpressMiddleware}\r\n */\r\n express(): ExpressMiddleware.ExpressMiddleware {\r\n return ExpressMiddlewareFactory(this);\r\n }\r\n\r\n /**\r\n * A method which is called whenever a new connection is made to the database.\r\n *\r\n * @param connection The underlying MongoDB connection which was created, you can modify or replace this if you wish.\r\n * @returns A promise for the connection, allowing you to perform any asynchronous initialization required by your application.\r\n *\r\n * In subclassed Iridium Cores this method can be overridden to manipulate the properties\r\n * of the underlying MongoDB connection object, such as authenticating. Until this method\r\n * resolves a connection object, Iridium will be unable to execute any queries. If you wish\r\n * to run Iridium queries then look at the onConnected method.\r\n */\r\n protected onConnecting(connection: MongoDB.Db): Bluebird {\r\n return Bluebird.resolve(connection);\r\n }\r\n\r\n /**\r\n * A method which is called once a database connection has been established and accepted by Iridium\r\n *\r\n * In subclassed Iridium cores this method can be overridden to perform tasks whenever a\r\n * connection to the database has been established - such as setting up indexes for your\r\n * collections or seeding the database.\r\n */\r\n protected onConnected(): Bluebird {\r\n return Bluebird.resolve();\r\n }\r\n}\r\n"],"sourceRoot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EAAE,CAAC;YACb,MAAM,CAAC,IAAI,CAAC;QAChB,CAAC,CAAC,CAAC;IACP,CAAC;IAED;;;;OAIG;IACH,OAAO;QACH,MAAM,CAAC,kCAAwB,CAAC,IAAI,CAAC,CAAC;IAC1C,CAAC;IAED;;;;;;;;;;OAUG;IACO,YAAY,CAAC,UAAsB;QACzC,MAAM,CAAC,QAAQ,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC;IACxC,CAAC;IAED;;;;;;OAMG;IACO,WAAW;QACjB,MAAM,CAAC,QAAQ,CAAC,OAAO,EAAE,CAAC;IAC9B,CAAC;AACL,CAAC;AAhNY,YAAI,OAgNhB,CAAA","file":"lib/Core.js","sourcesContent":["import * as Bluebird from \"bluebird\";\r\nimport * as MongoDB from \"mongodb\";\r\nimport * as _ from \"lodash\";\r\nimport * as http from \"http\";\r\nimport * as events from \"events\";\r\n\r\nimport {Configuration} from \"./Configuration\";\r\nimport {Plugin} from \"./Plugins\";\r\nimport {Model} from \"./Model\";\r\nimport {Instance} from \"./Instance\";\r\n\r\nimport {MiddlewareFactory} from \"./Middleware\";\r\nimport * as ExpressMiddleware from \"./middleware/Express\";\r\nimport {ExpressMiddlewareFactory} from \"./middleware/Express\";\r\n\r\nimport {Cache} from \"./Cache\";\r\nimport {NoOpCache} from \"./caches/NoOpCache\";\r\nimport {MemoryCache} from \"./caches/MemoryCache\";\r\n\r\n/**\r\n * The Iridium Core, responsible for managing the connection to the database as well\r\n * as any plugins you are making use of.\r\n *\r\n * Generally you will subclass this to provide your own custom core with the models you\r\n * make use of within your application.\r\n */\r\nexport class Core {\r\n /**\r\n * Creates a new Iridium Core instance connected to the specified MongoDB instance\r\n * @param {Iridium.IridiumConfiguration} config The config object defining the database to connect to\r\n * @constructs Core\r\n */\r\n constructor(config: Configuration);\r\n /**\r\n * Creates a new Iridium Core instance connected to the specified MongoDB instance\r\n * @param {String} url The URL of the MongoDB instance to connect to\r\n * @param {Iridium.IridiumConfiguration} config The config object made available as settings\r\n * @constructs Core\r\n */\r\n constructor(uri: string, config?: Configuration);\r\n constructor(uri: string | Configuration, config?: Configuration) {\r\n\r\n let args = Array.prototype.slice.call(arguments, 0);\r\n uri = config = null;\r\n for (let i = 0; i < args.length; i++) {\r\n if (typeof args[i] == \"string\")\r\n uri = args[i];\r\n else if (typeof args[i] == \"object\")\r\n config = args[i];\r\n }\r\n\r\n if (!uri && !config) throw new Error(\"Expected either a URI or config object to be supplied when initializing Iridium\");\r\n\r\n this._url = uri;\r\n this._config = config;\r\n }\r\n\r\n private mongoConnectAsyc = Bluebird.promisify(MongoDB.MongoClient.connect);\r\n\r\n private _plugins: Plugin[] = [];\r\n private _url: string;\r\n private _config: Configuration;\r\n private _connection: MongoDB.Db;\r\n private _cache: Cache = new NoOpCache();\r\n\r\n private _connectPromise: Bluebird;\r\n\r\n /**\r\n * Gets the plugins registered with this Iridium Core\r\n * @returns {[Iridium.Plugin]}\r\n */\r\n get plugins(): Plugin[] {\r\n return this._plugins;\r\n }\r\n\r\n /**\r\n * Gets the configuration specified in the construction of this\r\n * Iridium Core.\r\n * @returns {Iridium.Configuration}\r\n */\r\n get settings(): Configuration {\r\n return this._config;\r\n }\r\n\r\n /**\r\n * Gets the currently active database connection for this Iridium\r\n * Core.\r\n * @returns {MongoDB.Db}\r\n */\r\n get connection(): MongoDB.Db {\r\n return this._connection;\r\n }\r\n\r\n /**\r\n * Gets the URL used to connect to MongoDB\r\n * @returns {String}\r\n */\r\n get url(): string {\r\n if (this._url) return this._url;\r\n let url: string = \"mongodb://\";\r\n\r\n if (this._config.username) {\r\n url += this._config.username;\r\n if (this._config.password)\r\n url += \":\" + this._config.password;\r\n url += \"@\";\r\n }\r\n\r\n let hosts = [];\r\n\r\n if (this._config.host) {\r\n if (this._config.port)\r\n hosts.push(this._config.host + \":\" + this._config.port);\r\n else\r\n hosts.push(this._config.host);\r\n }\r\n\r\n if (this._config.hosts) {\r\n _.each(this._config.hosts, (host) => {\r\n if (host.port)\r\n hosts.push(host.address + \":\" + host.port);\r\n else if(this._config.port)\r\n hosts.push(host.address + \":\" + this._config.port);\r\n else\r\n hosts.push(host.address);\r\n });\r\n }\r\n\r\n if (hosts.length)\r\n url += _.uniq(hosts).join(\",\");\r\n else\r\n url += \"localhost\";\r\n\r\n url += \"/\" + this._config.database;\r\n\r\n return url;\r\n }\r\n\r\n /**\r\n * Gets the cache used to store objects retrieved from the database for performance reasons\r\n * @returns {cache}\r\n */\r\n get cache(): Cache {\r\n return this._cache;\r\n }\r\n\r\n set cache(value: Cache) {\r\n this._cache = value;\r\n }\r\n\r\n /**\r\n * Registers a new plugin with this Iridium Core\r\n * @param {Iridium.Plugin} plugin The plugin to register with this Iridium Core\r\n * @returns {Iridium.Core}\r\n */\r\n register(plugin: Plugin): Core {\r\n this.plugins.push(plugin);\r\n return this;\r\n }\r\n\r\n /**\r\n * Connects to the database server specified in the provided configuration\r\n * @param {function(Error, Iridium.Core)} [callback] A callback to be triggered once the connection is established.\r\n * @returns {Promise}\r\n */\r\n connect(callback?: (err: Error, core: Core) => any): Bluebird {\r\n return Bluebird.resolve().then(() => {\r\n if (this._connection) return this._connection;\r\n if (this._connectPromise) return this._connectPromise;\r\n return this._connectPromise = this.mongoConnectAsyc(this.url, this._config && this._config.options);\r\n }).then((db: MongoDB.Db) => {\r\n return this.onConnecting(db);\r\n }).then(db => {\r\n this._connection = db;\r\n this._connectPromise = null;\r\n return this.onConnected();\r\n }).then(() => {\r\n return this;\r\n }, (err) => {\r\n if (this._connection) this._connection.close();\r\n this._connection = null;\r\n this._connectPromise = null;\r\n return Bluebird.reject(err);\r\n }).nodeify(callback);\r\n }\r\n\r\n /**\r\n * Closes the active database connection\r\n * @type {Promise}\r\n */\r\n close(): Bluebird {\r\n return Bluebird.resolve().then(() => {\r\n if (!this._connection) return this;\r\n let conn: MongoDB.Db = this._connection;\r\n this._connection = null;\r\n conn.close();\r\n return this;\r\n });\r\n }\r\n\r\n /**\r\n * Provides an express middleware which can be used to set the req.db property\r\n * to the current Iridium instance.\r\n * @returns {Iridium.ExpressMiddleware}\r\n */\r\n express(): ExpressMiddleware.ExpressMiddleware {\r\n return ExpressMiddlewareFactory(this);\r\n }\r\n\r\n /**\r\n * A method which is called whenever a new connection is made to the database.\r\n *\r\n * @param connection The underlying MongoDB connection which was created, you can modify or replace this if you wish.\r\n * @returns A promise for the connection, allowing you to perform any asynchronous initialization required by your application.\r\n *\r\n * In subclassed Iridium Cores this method can be overridden to manipulate the properties\r\n * of the underlying MongoDB connection object, such as authenticating. Until this method\r\n * resolves a connection object, Iridium will be unable to execute any queries. If you wish\r\n * to run Iridium queries then look at the onConnected method.\r\n */\r\n protected onConnecting(connection: MongoDB.Db): Bluebird {\r\n return Bluebird.resolve(connection);\r\n }\r\n\r\n /**\r\n * A method which is called once a database connection has been established and accepted by Iridium\r\n *\r\n * In subclassed Iridium cores this method can be overridden to perform tasks whenever a\r\n * connection to the database has been established - such as setting up indexes for your\r\n * collections or seeding the database.\r\n */\r\n protected onConnected(): Bluebird {\r\n return Bluebird.resolve();\r\n }\r\n}\r\n"],"sourceRoot":"/source/"} \ No newline at end of file diff --git a/dist/lib/Cursor.js b/dist/lib/Cursor.js index e740b77..b68f1c9 100644 --- a/dist/lib/Cursor.js +++ b/dist/lib/Cursor.js @@ -1,5 +1,5 @@ "use strict"; -var Bluebird = require("bluebird"); +const Bluebird = require("bluebird"); /** * An Iridium collection cursor which allows the itteration through documents * in the collection, automatically wrapping them in the correct instance type. @@ -7,7 +7,7 @@ var Bluebird = require("bluebird"); * @param TDocument The interface representing the collection's documents * @param TInstance The interface or class used to represent the wrapped documents. */ -var Cursor = (function () { +class Cursor { /** * Creates a new Iridium cursor which wraps a MongoDB cursor object * @param {Model} model The Iridium model that this cursor belongs to @@ -15,7 +15,7 @@ var Cursor = (function () { * @param {MongoDB.Cursor} cursor The MongoDB native cursor object to be wrapped * @constructor */ - function Cursor(model, conditions, cursor) { + constructor(model, conditions, cursor) { this.model = model; this.conditions = conditions; this.cursor = cursor; @@ -25,163 +25,156 @@ var Cursor = (function () { * @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 */ - Cursor.prototype.count = function (callback) { - var _this = this; - return new Bluebird(function (resolve, reject) { - _this.cursor.count(true, function (err, count) { + count(callback) { + return new Bluebird((resolve, reject) => { + this.cursor.count(true, (err, count) => { if (err) return reject(err); return resolve(count); }); }).nodeify(callback); - }; + } /** * 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 */ - Cursor.prototype.forEach = function (handler, callback) { - var _this = this; - var helpers = this.model.helpers; - return new Bluebird(function (resolve, reject) { - _this.cursor.forEach(function (item) { - _this.model.handlers.documentReceived(_this.conditions, item, function () { return helpers.wrapDocument.apply(helpers, arguments); }).then(handler); - }, function (err) { + forEach(handler, callback) { + let helpers = this.model.helpers; + return new Bluebird((resolve, reject) => { + this.cursor.forEach((item) => { + this.model.handlers.documentReceived(this.conditions, item, function () { return helpers.wrapDocument.apply(helpers, arguments); }).then(handler); + }, (err) => { if (err) return reject(err); return resolve(null); }); }).nodeify(callback); - }; + } /** * 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 */ - Cursor.prototype.map = function (transform, callback) { - var _this = this; - var helpers = this.model.helpers; - return new Bluebird(function (resolve, reject) { - var promises = []; - _this.cursor.forEach(function (item) { - promises.push(_this.model.handlers.documentReceived(_this.conditions, item, function () { return helpers.wrapDocument.apply(helpers, arguments); }) + map(transform, callback) { + let helpers = this.model.helpers; + return new Bluebird((resolve, reject) => { + let promises = []; + this.cursor.forEach((item) => { + promises.push(this.model.handlers.documentReceived(this.conditions, item, function () { return helpers.wrapDocument.apply(helpers, arguments); }) .then(transform)); - }, function (err) { + }, (err) => { if (err) return reject(err); return resolve(Bluebird.all(promises)); }); }).nodeify(callback); - }; + } /** * 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 */ - Cursor.prototype.toArray = function (callback) { - var _this = this; - var helpers = this.model.helpers; - return new Bluebird(function (resolve, reject) { - _this.cursor.toArray(function (err, results) { + toArray(callback) { + let helpers = this.model.helpers; + return new Bluebird((resolve, reject) => { + this.cursor.toArray((err, results) => { if (err) return reject(err); return resolve(results); }); - }).map(function (document) { - return _this.model.handlers.documentReceived(_this.conditions, document, function () { return helpers.wrapDocument.apply(helpers, arguments); }); + }).map((document) => { + return this.model.handlers.documentReceived(this.conditions, document, function () { return helpers.wrapDocument.apply(helpers, arguments); }); }).nodeify(callback); - }; + } /** * 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 */ - Cursor.prototype.next = function (callback) { - var _this = this; - return new Bluebird(function (resolve, reject) { - _this.cursor.next(function (err, result) { + next(callback) { + return new Bluebird((resolve, reject) => { + this.cursor.next((err, result) => { if (err) return reject(err); return resolve(result); }); - }).then(function (document) { + }).then((document) => { if (!document) return Bluebird.resolve(null); - return _this.model.handlers.documentReceived(_this.conditions, document, function (document, isNew, isPartial) { return _this.model.helpers.wrapDocument(document, isNew, isPartial); }); + return this.model.handlers.documentReceived(this.conditions, document, (document, isNew, isPartial) => this.model.helpers.wrapDocument(document, isNew, isPartial)); }).nodeify(callback); - }; + } /** * 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. */ - Cursor.prototype.one = function (callback) { - var _this = this; - return new Bluebird(function (resolve, reject) { - _this.cursor.next(function (err, result) { + one(callback) { + return new Bluebird((resolve, reject) => { + this.cursor.next((err, result) => { if (err) return reject(err); return resolve(result); }); - }).then(function (document) { - return new Bluebird(function (resolve, reject) { - _this.cursor.close(function (err) { + }).then((document) => { + return new Bluebird((resolve, reject) => { + this.cursor.close((err) => { if (err) return reject(err); return resolve(document); }); }); - }).then(function (document) { + }).then((document) => { if (!document) return Bluebird.resolve(null); - return _this.model.handlers.documentReceived(_this.conditions, document, function (document, isNew, isPartial) { return _this.model.helpers.wrapDocument(document, isNew, isPartial); }); + return this.model.handlers.documentReceived(this.conditions, document, (document, isNew, isPartial) => this.model.helpers.wrapDocument(document, isNew, isPartial)); }).nodeify(callback); - }; + } /** * 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 */ - Cursor.prototype.rewind = function () { + rewind() { this.cursor.rewind(); return this; - }; + } /** * 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 */ - Cursor.prototype.sort = function (sortExpression) { + sort(sortExpression) { return new Cursor(this.model, this.conditions, this.cursor.sort(sortExpression)); - }; + } /** * 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 */ - Cursor.prototype.limit = function (limit) { + limit(limit) { return new Cursor(this.model, this.conditions, this.cursor.limit(limit)); - }; + } /** * 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 */ - Cursor.prototype.skip = function (skip) { + skip(skip) { return new Cursor(this.model, this.conditions, this.cursor.skip(skip)); - }; + } /** * 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 */ - Cursor.prototype.readFrom = function (type) { + readFrom(type) { return new Cursor(this.model, this.conditions, this.cursor.setReadPreference(type)); - }; - return Cursor; -}()); + } +} exports.Cursor = Cursor; //# sourceMappingURL=Cursor.js.map diff --git a/dist/lib/Cursor.js.map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uKlB,CAAA","file":"lib/Cursor.js","sourcesContent":["import {Model} from \"./Model\";\r\nimport * as General from \"./General\";\r\nimport * as MongoDB from \"mongodb\";\r\nimport * as Bluebird from \"bluebird\";\r\nimport * as Index from \"./Index\";\r\n\r\n/**\r\n * An Iridium collection cursor which allows the itteration through documents\r\n * in the collection, automatically wrapping them in the correct instance type.\r\n *\r\n * @param TDocument The interface representing the collection's documents\r\n * @param TInstance The interface or class used to represent the wrapped documents.\r\n */\r\nexport class Cursor {\r\n /**\r\n * Creates a new Iridium cursor which wraps a MongoDB cursor object\r\n * @param {Model} model The Iridium model that this cursor belongs to\r\n * @param {Object} conditions The conditions that resulte in this cursor being created\r\n * @param {MongoDB.Cursor} cursor The MongoDB native cursor object to be wrapped\r\n * @constructor\r\n */\r\n constructor(private model: Model, private conditions: any, public cursor: MongoDB.Cursor) {\r\n\r\n }\r\n\r\n /**\r\n * Counts the number of documents which are matched by this cursor\r\n * @param {function(Error, Number)} callback A callback which is triggered when the result is available\r\n * @return {Promise} A promise which will resolve with the number of documents matched by this cursor\r\n */\r\n count(callback?: General.Callback): Bluebird {\r\n return new Bluebird((resolve, reject) => {\r\n this.cursor.count(true, (err, count) => {\r\n if (err) return reject(err);\r\n return resolve(count);\r\n });\r\n }).nodeify(callback);\r\n }\r\n\r\n /**\r\n * Runs the specified handler over each instance in the query results\r\n * @param {function(Instance)} handler The handler which is triggered for each element in the query\r\n * @param {function(Error)} callback A callback which is triggered when all operations have been dispatched\r\n * @return {Promise} A promise which is resolved when all operations have been dispatched\r\n */\r\n forEach(handler: (instance: TInstance) => void, callback?: General.Callback): Bluebird {\r\n let helpers = this.model.helpers;\r\n return new Bluebird((resolve, reject) => {\r\n this.cursor.forEach((item: TDocument) => {\r\n this.model.handlers.documentReceived(this.conditions, item, function () { return helpers.wrapDocument.apply(helpers, arguments); }).then(handler);\r\n }, (err) => {\r\n if (err) return reject(err);\r\n return resolve(null);\r\n });\r\n }).nodeify(callback);\r\n }\r\n\r\n /**\r\n * Runs the specified transform over each instance in the query results and returns the resulting transformed objects\r\n * @param {function(Instance): TResult} transform A handler which is used to transform the result objects\r\n * @param {function(Error, TResult[])} callback A callback which is triggered when the transformations are completed\r\n * @return {Promise} A promise which is fulfilled with the results of the transformations\r\n */\r\n map(transform: (instance: TInstance) => TResult | Bluebird, callback?: General.Callback): Bluebird {\r\n let helpers = this.model.helpers;\r\n return new Bluebird((resolve, reject) => {\r\n let promises: Bluebird[] = [];\r\n this.cursor.forEach((item: TDocument) => {\r\n promises.push(this.model.handlers.documentReceived(this.conditions, item, function () { return helpers.wrapDocument.apply(helpers, arguments); })\r\n .then(<(instance) => TResult>transform));\r\n }, (err) => {\r\n if (err) return reject(err);\r\n return resolve(Bluebird.all(promises));\r\n });\r\n }).nodeify(callback);\r\n }\r\n\r\n /**\r\n * Retrieves all matching instances and returns them in an array\r\n * @param {function(Error, TInstance[])} callback A callback which is triggered with the resulting instances\r\n * @return {Promise} A promise which resolves with the instances returned by the query\r\n */\r\n toArray(callback?: General.Callback): Bluebird {\r\n let helpers = this.model.helpers;\r\n return new Bluebird((resolve, reject) => {\r\n this.cursor.toArray((err, results: any[]) => {\r\n if (err) return reject(err);\r\n return resolve(results);\r\n });\r\n }).map((document) => {\r\n return this.model.handlers.documentReceived(this.conditions, document, function () { return helpers.wrapDocument.apply(helpers, arguments); });\r\n }).nodeify(callback);\r\n }\r\n\r\n /**\r\n * Retrieves the next item in the results list\r\n * @param {function(Error, TInstance)} callback A callback which is triggered when the next item becomes available\r\n * @return {Promise} A promise which is resolved with the next item\r\n */\r\n next(callback?: General.Callback): Bluebird {\r\n return new Bluebird((resolve, reject) => {\r\n this.cursor.next((err, result: any) => {\r\n if (err) return reject(err);\r\n return resolve(result);\r\n });\r\n }).then((document) => {\r\n if (!document) return Bluebird.resolve(null);\r\n return this.model.handlers.documentReceived(this.conditions, document, (document, isNew?, isPartial?) => this.model.helpers.wrapDocument(document, isNew, isPartial));\r\n }).nodeify(callback);\r\n }\r\n\r\n /**\r\n * Retrieves the next item in the result list and then closes the cursor\r\n * @param {function(Error, TInstance)} callback A callback which is triggered when the next item becomes available\r\n * @return {Promise} A promise which is resolved once the item becomes available and the cursor has been closed.\r\n */\r\n one(callback?: General.Callback): Bluebird {\r\n return new Bluebird((resolve, reject) => {\r\n this.cursor.next((err, result: any) => {\r\n if (err) return reject(err);\r\n return resolve(result);\r\n });\r\n }).then((document) => {\r\n return new Bluebird((resolve, reject) => {\r\n this.cursor.close((err) => {\r\n if (err) return reject(err);\r\n return resolve(document);\r\n });\r\n });\r\n }).then((document) => {\r\n if (!document) return Bluebird.resolve(null);\r\n return this.model.handlers.documentReceived(this.conditions, document, (document, isNew?, isPartial?) => this.model.helpers.wrapDocument(document, isNew, isPartial));\r\n }).nodeify(callback);\r\n }\r\n\r\n /**\r\n * Returns a new cursor which behaves the same as this one did before any results were retrieved\r\n * @return {Cursor} The new cursor which starts at the beginning of the results\r\n */\r\n rewind(): Cursor {\r\n this.cursor.rewind();\r\n return this;\r\n }\r\n\r\n /**\r\n * Returns a new cursor which sorts its results by the given index expression\r\n * @param {model.IndexSpecification} sortExpression The index expression dictating the sort order and direction to use\r\n * @return {Cursor} The new cursor which sorts its results by the sortExpression\r\n */\r\n sort(sortExpression: Index.IndexSpecification): Cursor {\r\n return new Cursor(this.model, this.conditions, this.cursor.sort(sortExpression));\r\n }\r\n\r\n /**\r\n * Returns a new cursor which limits the number of returned results\r\n * @param {Number} limit The maximum number of results to return\r\n * @return {Cursor} The new cursor which will return a maximum number of results\r\n */\r\n limit(limit: number): Cursor {\r\n return new Cursor(this.model, this.conditions, this.cursor.limit(limit));\r\n }\r\n\r\n /**\r\n * Returns a new cursor which skips a number of results before it begins\r\n * returning any.\r\n * @param {Number} skip The number of results to skip before the cursor beings returning\r\n * @return {Cursor} The new cursor which skips a number of results\r\n */\r\n skip(skip: number): Cursor {\r\n return new Cursor(this.model, this.conditions, this.cursor.skip(skip));\r\n }\r\n\r\n /**\r\n * Returns a new cursor which will read from the specified node type.\r\n * @param {String} type The type of node to read from - see https://docs.mongodb.org/manual/core/read-preference/\r\n * @return {Cursor} The new cursor which reads from the specified node type\r\n */\r\n readFrom(type: string): Cursor {\r\n return new Cursor(this.model, this.conditions, this.cursor.setReadPreference(type));\r\n }\r\n}"],"sourceRoot":"/source/"} \ No newline at end of file +{"version":3,"sources":["lib/Cursor.ts"],"names":[],"mappings":";AAGA,MAAY,QAAQ,WAAM,UAAU,CAAC,CAAA;AAGrC;;;;;;GAMG;AACH;IACI;;;;;;OAMG;IACH,YAAoB,KAAkC,EAAU,UAAe,EAAS,MAAsB;QAA1F,UAAK,GAAL,KAAK,CAA6B;QAAU,eAAU,GAAV,UAAU,CAAK;QAAS,WAAM,GAAN,MAAM,CAAgB;IAE9G,CAAC;IAED;;;;OAIG;IACH,KAAK,CAAC,QAAmC;QACrC,MAAM,CAAC,IAAI,QAAQ,CAAS,CAAC,OAAO,EAAE,MAAM;YACxC,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,IAAI,EAAE,CAAC,GAAG,EAAE,KAAK;gBAC/B,EAAE,CAAC,CAAC,GAAG,CAAC;oBAAC,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;gBAC5B,MAAM,CAAC,OAAO,CAAM,KAAK,CAAC,CAAC;YAC/B,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC;IACzB,CAAC;IAED;;;;;OAKG;IACH,OAAO,CAAC,OAAsC,EAAE,QAAiC;QAC7E,IAAI,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC;QACjC,MAAM,CAAC,IAAI,QAAQ,CAAO,CAAC,OAAO,EAAE,MAAM;YACtC,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,IAAe;gBAChC,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,gBAAgB,CAAC,IAAI,CAAC,UAAU,EAAE,IAAI,EAAE,cAAc,MAAM,CA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,EAAE,SAAU,KAAK,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,YAAY,CAAC,QAAQ,EAAE,KAAK,EAAE,SAAS,CAAC,CAAC,CAAC;QAC1K,CAAC,CAAC,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC;IACzB,CAAC;IAED;;;OAGG;IACH,MAAM;QACF,IAAI,CAAC,MAAM,CAAC,MAAM,EAAE,CAAC;QACrB,MAAM,CAAC,IAAI,CAAC;IAChB,CAAC;IAED;;;;OAIG;IACH,IAAI,CAAC,cAAwC;QACzC,MAAM,CAAC,IAAI,MAAM,CAAC,IAAI,CAAC,KAAK,EAAE,IAAI,CAAC,UAAU,EAAE,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC,CAAC;IACrF,CAAC;IAED;;;;OAIG;IACH,KAAK,CAAC,KAAa;QACf,MAAM,CAAC,IAAI,MAAM,CAAC,IAAI,CAAC,KAAK,EAAE,IAAI,CAAC,UAAU,EAAE,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC;IAC7E,CAAC;IAED;;;;;OAKG;IACH,IAAI,CAAC,IAAY;QACb,MAAM,CAAC,IAAI,MAAM,CAAC,IAAI,CAAC,KAAK,EAAE,IAAI,CAAC,UAAU,EAAE,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC;IAC3E,CAAC;IAED;;;;OAIG;IACH,QAAQ,CAAC,IAAY;QACjB,MAAM,CAAC,IAAI,MAAM,CAAC,IAAI,CAAC,KAAK,EAAE,IAAI,CAAC,UAAU,EAAE,IAAI,CAAC,MAAM,CAAC,iBAAiB,CAAC,IAAI,CAAC,CAAC,CAAC;IACxF,CAAC;AACL,CAAC;AAvKY,cAAM,SAuKlB,CAAA","file":"lib/Cursor.js","sourcesContent":["import {Model} from \"./Model\";\r\nimport * as General from \"./General\";\r\nimport * as MongoDB from \"mongodb\";\r\nimport * as Bluebird from \"bluebird\";\r\nimport * as Index from \"./Index\";\r\n\r\n/**\r\n * An Iridium collection cursor which allows the itteration through documents\r\n * in the collection, automatically wrapping them in the correct instance type.\r\n *\r\n * @param TDocument The interface representing the collection's documents\r\n * @param TInstance The interface or class used to represent the wrapped documents.\r\n */\r\nexport class Cursor {\r\n /**\r\n * Creates a new Iridium cursor which wraps a MongoDB cursor object\r\n * @param {Model} model The Iridium model that this cursor belongs to\r\n * @param {Object} conditions The conditions that resulte in this cursor being created\r\n * @param {MongoDB.Cursor} cursor The MongoDB native cursor object to be wrapped\r\n * @constructor\r\n */\r\n constructor(private model: Model, private conditions: any, public cursor: MongoDB.Cursor) {\r\n\r\n }\r\n\r\n /**\r\n * Counts the number of documents which are matched by this cursor\r\n * @param {function(Error, Number)} callback A callback which is triggered when the result is available\r\n * @return {Promise} A promise which will resolve with the number of documents matched by this cursor\r\n */\r\n count(callback?: General.Callback): Bluebird {\r\n return new Bluebird((resolve, reject) => {\r\n this.cursor.count(true, (err, count) => {\r\n if (err) return reject(err);\r\n return resolve(count);\r\n });\r\n }).nodeify(callback);\r\n }\r\n\r\n /**\r\n * Runs the specified handler over each instance in the query results\r\n * @param {function(Instance)} handler The handler which is triggered for each element in the query\r\n * @param {function(Error)} callback A callback which is triggered when all operations have been dispatched\r\n * @return {Promise} A promise which is resolved when all operations have been dispatched\r\n */\r\n forEach(handler: (instance: TInstance) => void, callback?: General.Callback): Bluebird {\r\n let helpers = this.model.helpers;\r\n return new Bluebird((resolve, reject) => {\r\n this.cursor.forEach((item: TDocument) => {\r\n this.model.handlers.documentReceived(this.conditions, item, function () { return helpers.wrapDocument.apply(helpers, arguments); }).then(handler);\r\n }, (err) => {\r\n if (err) return reject(err);\r\n return resolve(null);\r\n });\r\n }).nodeify(callback);\r\n }\r\n\r\n /**\r\n * Runs the specified transform over each instance in the query results and returns the resulting transformed objects\r\n * @param {function(Instance): TResult} transform A handler which is used to transform the result objects\r\n * @param {function(Error, TResult[])} callback A callback which is triggered when the transformations are completed\r\n * @return {Promise} A promise which is fulfilled with the results of the transformations\r\n */\r\n map(transform: (instance: TInstance) => TResult | Bluebird, callback?: General.Callback): Bluebird {\r\n let helpers = this.model.helpers;\r\n return new Bluebird((resolve, reject) => {\r\n let promises: Bluebird[] = [];\r\n this.cursor.forEach((item: TDocument) => {\r\n promises.push(this.model.handlers.documentReceived(this.conditions, item, function () { return helpers.wrapDocument.apply(helpers, arguments); })\r\n .then(<(instance) => TResult>transform));\r\n }, (err) => {\r\n if (err) return reject(err);\r\n return resolve(Bluebird.all(promises));\r\n });\r\n }).nodeify(callback);\r\n }\r\n\r\n /**\r\n * Retrieves all matching instances and returns them in an array\r\n * @param {function(Error, TInstance[])} callback A callback which is triggered with the resulting instances\r\n * @return {Promise} A promise which resolves with the instances returned by the query\r\n */\r\n toArray(callback?: General.Callback): Bluebird {\r\n let helpers = this.model.helpers;\r\n return new Bluebird((resolve, reject) => {\r\n this.cursor.toArray((err, results: any[]) => {\r\n if (err) return reject(err);\r\n return resolve(results);\r\n });\r\n }).map((document) => {\r\n return this.model.handlers.documentReceived(this.conditions, document, function () { return helpers.wrapDocument.apply(helpers, arguments); });\r\n }).nodeify(callback);\r\n }\r\n\r\n /**\r\n * Retrieves the next item in the results list\r\n * @param {function(Error, TInstance)} callback A callback which is triggered when the next item becomes available\r\n * @return {Promise} A promise which is resolved with the next item\r\n */\r\n next(callback?: General.Callback): Bluebird {\r\n return new Bluebird((resolve, reject) => {\r\n this.cursor.next((err, result: any) => {\r\n if (err) return reject(err);\r\n return resolve(result);\r\n });\r\n }).then((document) => {\r\n if (!document) return Bluebird.resolve(null);\r\n return this.model.handlers.documentReceived(this.conditions, document, (document, isNew?, isPartial?) => this.model.helpers.wrapDocument(document, isNew, isPartial));\r\n }).nodeify(callback);\r\n }\r\n\r\n /**\r\n * Retrieves the next item in the result list and then closes the cursor\r\n * @param {function(Error, TInstance)} callback A callback which is triggered when the next item becomes available\r\n * @return {Promise} A promise which is resolved once the item becomes available and the cursor has been closed.\r\n */\r\n one(callback?: General.Callback): Bluebird {\r\n return new Bluebird((resolve, reject) => {\r\n this.cursor.next((err, result: any) => {\r\n if (err) return reject(err);\r\n return resolve(result);\r\n });\r\n }).then((document) => {\r\n return new Bluebird((resolve, reject) => {\r\n this.cursor.close((err) => {\r\n if (err) return reject(err);\r\n return resolve(document);\r\n });\r\n });\r\n }).then((document) => {\r\n if (!document) return Bluebird.resolve(null);\r\n return this.model.handlers.documentReceived(this.conditions, document, (document, isNew?, isPartial?) => this.model.helpers.wrapDocument(document, isNew, isPartial));\r\n }).nodeify(callback);\r\n }\r\n\r\n /**\r\n * Returns a new cursor which behaves the same as this one did before any results were retrieved\r\n * @return {Cursor} The new cursor which starts at the beginning of the results\r\n */\r\n rewind(): Cursor {\r\n this.cursor.rewind();\r\n return this;\r\n }\r\n\r\n /**\r\n * Returns a new cursor which sorts its results by the given index expression\r\n * @param {model.IndexSpecification} sortExpression The index expression dictating the sort order and direction to use\r\n * @return {Cursor} The new cursor which sorts its results by the sortExpression\r\n */\r\n sort(sortExpression: Index.IndexSpecification): Cursor {\r\n return new Cursor(this.model, this.conditions, this.cursor.sort(sortExpression));\r\n }\r\n\r\n /**\r\n * Returns a new cursor which limits the number of returned results\r\n * @param {Number} limit The maximum number of results to return\r\n * @return {Cursor} The new cursor which will return a maximum number of results\r\n */\r\n limit(limit: number): Cursor {\r\n return new Cursor(this.model, this.conditions, this.cursor.limit(limit));\r\n }\r\n\r\n /**\r\n * Returns a new cursor which skips a number of results before it begins\r\n * returning any.\r\n * @param {Number} skip The number of results to skip before the cursor beings returning\r\n * @return {Cursor} The new cursor which skips a number of results\r\n */\r\n skip(skip: number): Cursor {\r\n return new Cursor(this.model, this.conditions, this.cursor.skip(skip));\r\n }\r\n\r\n /**\r\n * Returns a new cursor which will read from the specified node type.\r\n * @param {String} type The type of node to read from - see https://docs.mongodb.org/manual/core/read-preference/\r\n * @return {Cursor} The new cursor which reads from the specified node type\r\n */\r\n readFrom(type: string): Cursor {\r\n return new Cursor(this.model, this.conditions, this.cursor.setReadPreference(type));\r\n }\r\n}"],"sourceRoot":"/source/"} \ No newline at end of file diff --git a/dist/lib/Decorators.js b/dist/lib/Decorators.js index 54d16d2..9366524 100644 --- a/dist/lib/Decorators.js +++ b/dist/lib/Decorators.js @@ -1,8 +1,8 @@ "use strict"; -var MongoDB = require("mongodb"); -var _ = require("lodash"); -var Skmatc = require("skmatc"); -var Transforms_1 = require("./Transforms"); +const MongoDB = require("mongodb"); +const _ = require("lodash"); +const Skmatc = require("skmatc"); +const Transforms_1 = require("./Transforms"); /** * Specifies the name of the collection to which this instance's documents should be sent. * @param name The name of the MongoDB collection to store the documents in. @@ -45,20 +45,16 @@ exports.Index = Index; */ function Validate(forType, validate) { return function (target) { - target.validators = (target.validators || []).concat(Skmatc.create(function (schema) { return schema === forType; }, validate)); + target.validators = (target.validators || []).concat(Skmatc.create(schema => schema === forType, validate)); }; } exports.Validate = Validate; -function Property() { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i - 0] = arguments[_i]; - } - var name = null, asType = false, required = true; +function Property(...args) { + let name = null, asType = false, required = true; if (args.length > 1 && typeof args[args.length - 1] === "boolean") required = args.pop(); return function (target, property) { - var staticTarget = target; + let staticTarget = target; if (!property) name = args.shift(); else { @@ -91,9 +87,8 @@ exports.Property = Property; * fromDB or toDB is called. */ function Transform(fromDB, toDB) { - return function (target, property) { - if (property === void 0) { property = "$document"; } - var staticTarget = (target.constructor || target); + return function (target, property = "$document") { + let staticTarget = (target.constructor || target); staticTarget.transforms = _.clone(staticTarget.transforms || {}); staticTarget.transforms[property] = { fromDB: fromDB, diff --git a/dist/lib/Decorators.js.map b/dist/lib/Decorators.js.map index d764d7e..9da1c60 100644 --- a/dist/lib/Decorators.js.map +++ b/dist/lib/Decorators.js.map @@ -1 +1 @@ -{"version":3,"sources":["lib/Decorators.ts"],"names":[],"mappings":";AAAA,IAAY,OAAO,WAAM,SAAS,CAAC,CAAA;AACnC,IAAY,CAAC,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,CAAC,CAAC;AACH,CAAC;AAVe,iBAAS,YAUxB,CAAA;AAGD;;;;;;GAMG;AACH,kBAAyB,MAA0B,EAAE,IAAY;IAChE,QAAQ,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;IACzC,SAAS,CACR,8BAAiB,CAAC,QAAQ,CAAC,MAAM,EACjC,8BAAiB,CAAC,QAAQ,CAAC,IAAI,CAC/B,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;AACjB,CAAC;AANe,gBAAQ,WAMvB,CAAA;AAED;;;;;;;GAOG;AACH,gBAAuB,MAA0B,EAAE,IAAY;IAC9D,QAAQ,CAAC,MAAM,CAAC,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;IAC/B,SAAS,CACR,8BAAiB,CAAC,MAAM,CAAC,MAAM,EAC/B,8BAAiB,CAAC,MAAM,CAAC,IAAI,CAC7B,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;AACjB,CAAC;AANe,cAAM,SAMrB,CAAA","file":"lib/Decorators.js","sourcesContent":["import * as MongoDB from \"mongodb\";\r\nimport * as _ from \"lodash\";\r\nimport * as Skmatc from \"skmatc\";\r\nimport {Instance} from \"./Instance\";\r\nimport {Model} from \"./Model\";\r\nimport {Index, IndexSpecification} from \"./Index\";\r\nimport {Schema} from \"./Schema\";\r\nimport {InstanceImplementation} from \"./InstanceInterface\";\r\nimport {Transforms, DefaultTransforms} from \"./Transforms\";\r\n\r\n/**\r\n * Specifies the name of the collection to which this instance's documents should be sent.\r\n * @param name The name of the MongoDB collection to store the documents in.\r\n *\r\n * This decorator replaces the use of the static collection property on instance implementation\r\n * classes. If your transpiler does not support decorators then you are free to make use of the\r\n * property instead.\r\n */\r\nexport function Collection(name: string) {\r\n\treturn function(target: InstanceImplementation) {\r\n\t\ttarget.collection = name;\r\n\t};\r\n}\r\n\r\n/**\r\n * Specifies a MongoDB collection level index to be managed by Iridium for this instance type.\r\n * More than one instance of this decorator may be used if you wish to specify multiple indexes.\r\n * @param spec The formal index specification which defines the properties and ordering used in the index.\r\n * @param options The options dictating the way in which the index behaves.\r\n *\r\n * This decorator replaces the use of the static indexes property on instance implementation\r\n * classes. If your transpiler does not support decorators then you are free to make use of the\r\n * property instead.\r\n */\r\nexport function Index(spec: IndexSpecification, options?: MongoDB.IndexOptions) {\r\n\treturn function(target: InstanceImplementation) {\r\n\t\ttarget.indexes = (target.indexes || []).concat({ spec: spec, options: options || {} });\r\n\t}\r\n}\r\n\r\n/**\r\n * Specifies a custom validator to be made available for this collection's schema.\r\n * More than one instance of this decorator may be used if you wish to specify multiple validators.\r\n * @param forType The value in the schema which will be delegated to this function for validation.\r\n * @param validate A function which calls this.assert(condition) to determine whether a schema node is valid or not.\r\n *\r\n * This decorator replaces the use of the static validators property on instance implementation\r\n * classes. If your transpiler does not support decorators then you are free to make use of the\r\n * property instead.\r\n */\r\nexport function Validate(forType: any, validate: (schema: any, data: any, path: string) => Skmatc.Result) {\r\n\treturn function(target: InstanceImplementation) {\r\n\t\ttarget.validators = (target.validators || []).concat(Skmatc.create(schema => schema === forType, validate));\r\n\t}\r\n}\r\n\r\n/**\r\n * Specifies the schema type for the property this decorator is applied to. This can be used to replace the\r\n * static schema property on your instance. Multiple instances of this decorator can be applied, but no more\r\n * than one per property.\r\n *\r\n * @param asType The schema validation type to make use of for this property\r\n * @param required Whether this property is required to have a value or not, defaults to true.\r\n */\r\nexport function Property(asType: any, required?: boolean): (target: Instance, name: string) => void;\r\n/**\r\n * Specifies the schema type for a property with the given name on the class this decorator is applied to. This\r\n * can either compliment or replace the static schema property on your instance class.\r\n *\r\n * @param name The name of the property that is being targetted\r\n * @param asType The schema validation type to make use of for this property\r\n * @param required Whether this property is required to have a value or not, defaults to true.\r\n */\r\nexport function Property(name: string, asType: any, required?: boolean): (target: InstanceImplementation) => void;\r\nexport function Property(...args: any[]): (target: Instance | InstanceImplementation, name?: string) => void {\r\n\tlet name = null,\r\n\t\tasType = false,\r\n\t\trequired = true;\r\n\r\n\tif (args.length > 1 && typeof args[args.length - 1] === \"boolean\")\r\n\t\trequired = args.pop();\r\n\r\n\treturn function(target: InstanceImplementation, property?: string) {\r\n\t\tlet staticTarget: InstanceImplementation = target;\r\n\t\tif (!property) name = args.shift();\r\n\t\telse {\r\n\t\t\tname = property;\r\n\t\t\tstaticTarget = >target.constructor;\r\n\t\t}\r\n\t\tasType = args.pop() || false;\r\n\r\n\t\tstaticTarget.schema = _.clone(staticTarget.schema || { _id: false });\r\n\t\tif(!required && typeof asType !== \"boolean\") staticTarget.schema[name] = { $required: required, $type: asType };\r\n\t\telse staticTarget.schema[name] = asType;\r\n\t}\r\n}\r\n\r\n/**\r\n * Specifies a custom transform to be applied to the property this decorator is applied to.\r\n *\r\n * @param fromDB The function used to convert values from the database for the application.\r\n * @param toDB The function used to convert values from the application to the form used in the database.\r\n *\r\n * This decorator can either compliment or replace the static transforms property on your instance\r\n * class, however only one transform can be applied to any property at a time.\r\n * If your transpiler does not support decorators then you are free to make use of the\r\n * property instead.\r\n * \r\n * If this decorator is applied to the instance class itself, as opposed to a property, then\r\n * it will be treated as a $document transformer - and will receive the full document as opposed\r\n * to individual property values. Similarly, it is expected to return a full document when either\r\n * fromDB or toDB is called.\r\n */\r\nexport function Transform(fromDB: (value: any, property: string, model: Model) => any, toDB: (value: any, property: string, model: Model) => any) {\r\n\treturn function(target: Instance, property: string = \"$document\") {\r\n\t\tlet staticTarget: InstanceImplementation = >(target.constructor || target);\r\n\r\n\t\tstaticTarget.transforms = _.clone(staticTarget.transforms || {})\r\n\t\tstaticTarget.transforms[property] = {\r\n\t\t\tfromDB: fromDB,\r\n\t\t\ttoDB: toDB\r\n\t\t};\r\n\t};\r\n}\r\n\r\n\r\n/**\r\n * Specifies that this property should be treated as an ObjectID, with the requisite validator and transforms.\r\n *\r\n * This decorator applies an ObjectID validator to the property, which ensures that values sent to the database\r\n * are instances of the MongoDB ObjectID type, as well as applying a transform operation which converts ObjectIDs\r\n * to strings for your application, and then converts strings back to ObjectIDs for the database.\r\n */\r\nexport function ObjectID(target: Instance, name: string) {\r\n\tProperty(MongoDB.ObjectID)(target, name);\r\n\tTransform(\r\n\t\tDefaultTransforms.ObjectID.fromDB,\r\n\t\tDefaultTransforms.ObjectID.toDB\r\n\t)(target, name);\r\n}\r\n\r\n/**\r\n * Specifies that this property should be stored using the MongoDB binary type and represented as a Buffer.\r\n * \r\n * This decorator applies a Buffer validator to the property, which ensures that values you send to the database\r\n * are well formatted Buffer objects represented using the BSON Binary datatype. In addition to this, it will\r\n * apply a transform which ensures you only work with Buffer objects and that data is always stored in Binary\r\n * format.\r\n */\r\nexport function Binary(target: Instance, name: string) {\r\n\tProperty(Buffer)(target, name);\r\n\tTransform(\r\n\t\tDefaultTransforms.Binary.fromDB,\r\n\t\tDefaultTransforms.Binary.toDB\r\n\t)(target, name);\r\n}"],"sourceRoot":"/source/"} \ No newline at end of file +{"version":3,"sources":["lib/Decorators.ts"],"names":[],"mappings":";AAAA,MAAY,OAAO,WAAM,SAAS,CAAC,CAAA;AACnC,MAAY,CAAC,WAAM,QAAQ,CAAC,CAAA;AAC5B,MAAY,MAAM,WAAM,QAAQ,CAAC,CAAA;AAMjC,6BAA4C,cAAc,CAAC,CAAA;AAE3D;;;;;;;GAOG;AACH,oBAA2B,IAAY;IACtC,MAAM,CAAC,UAAS,MAAwC;QACvD,MAAM,CAAC,UAAU,GAAG,IAAI,CAAC;IAC1B,CAAC,CAAC;AACH,CAAC;AAJe,kBAAU,aAIzB,CAAA;AAED;;;;;;;;;GASG;AACH,eAAsB,IAAwB,EAAE,OAA8B;IAC7E,MAAM,CAAC,UAAS,MAAuC;QACtD,MAAM,CAAC,OAAO,GAAG,CAAC,MAAM,CAAC,OAAO,IAAI,EAAE,CAAC,CAAC,MAAM,CAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,OAAO,EAAE,OAAO,IAAI,EAAE,EAAE,CAAC,CAAC;IAC/F,CAAC,CAAA;AACF,CAAC;AAJe,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ators.js","sourcesContent":["import * as MongoDB from \"mongodb\";\r\nimport * as _ from \"lodash\";\r\nimport * as Skmatc from \"skmatc\";\r\nimport {Instance} from \"./Instance\";\r\nimport {Model} from \"./Model\";\r\nimport {Index, IndexSpecification} from \"./Index\";\r\nimport {Schema} from \"./Schema\";\r\nimport {InstanceImplementation} from \"./InstanceInterface\";\r\nimport {Transforms, DefaultTransforms} from \"./Transforms\";\r\n\r\n/**\r\n * Specifies the name of the collection to which this instance's documents should be sent.\r\n * @param name The name of the MongoDB collection to store the documents in.\r\n *\r\n * This decorator replaces the use of the static collection property on instance implementation\r\n * classes. If your transpiler does not support decorators then you are free to make use of the\r\n * property instead.\r\n */\r\nexport function Collection(name: string) {\r\n\treturn function(target: InstanceImplementation) {\r\n\t\ttarget.collection = name;\r\n\t};\r\n}\r\n\r\n/**\r\n * Specifies a MongoDB collection level index to be managed by Iridium for this instance type.\r\n * More than one instance of this decorator may be used if you wish to specify multiple indexes.\r\n * @param spec The formal index specification which defines the properties and ordering used in the index.\r\n * @param options The options dictating the way in which the index behaves.\r\n *\r\n * This decorator replaces the use of the static indexes property on instance implementation\r\n * classes. If your transpiler does not support decorators then you are free to make use of the\r\n * property instead.\r\n */\r\nexport function Index(spec: IndexSpecification, options?: MongoDB.IndexOptions) {\r\n\treturn function(target: InstanceImplementation) {\r\n\t\ttarget.indexes = (target.indexes || []).concat({ spec: spec, options: options || {} });\r\n\t}\r\n}\r\n\r\n/**\r\n * Specifies a custom validator to be made available for this collection's schema.\r\n * More than one instance of this decorator may be used if you wish to specify multiple validators.\r\n * @param forType The value in the schema which will be delegated to this function for validation.\r\n * @param validate A function which calls this.assert(condition) to determine whether a schema node is valid or not.\r\n *\r\n * This decorator replaces the use of the static validators property on instance implementation\r\n * classes. If your transpiler does not support decorators then you are free to make use of the\r\n * property instead.\r\n */\r\nexport function Validate(forType: any, validate: (schema: any, data: any, path: string) => Skmatc.Result) {\r\n\treturn function(target: InstanceImplementation) {\r\n\t\ttarget.validators = (target.validators || []).concat(Skmatc.create(schema => schema === forType, validate));\r\n\t}\r\n}\r\n\r\n/**\r\n * Specifies the schema type for the property this decorator is applied to. This can be used to replace the\r\n * static schema property on your instance. Multiple instances of this decorator can be applied, but no more\r\n * than one per property.\r\n *\r\n * @param asType The schema validation type to make use of for this property\r\n * @param required Whether this property is required to have a value or not, defaults to true.\r\n */\r\nexport function Property(asType: any, required?: boolean): (target: Instance, name: string) => void;\r\n/**\r\n * Specifies the schema type for a property with the given name on the class this decorator is applied to. This\r\n * can either compliment or replace the static schema property on your instance class.\r\n *\r\n * @param name The name of the property that is being targetted\r\n * @param asType The schema validation type to make use of for this property\r\n * @param required Whether this property is required to have a value or not, defaults to true.\r\n */\r\nexport function Property(name: string, asType: any, required?: boolean): (target: InstanceImplementation) => void;\r\nexport function Property(...args: any[]): (target: Instance | InstanceImplementation, name?: string) => void {\r\n\tlet name = null,\r\n\t\tasType = false,\r\n\t\trequired = true;\r\n\r\n\tif (args.length > 1 && typeof args[args.length - 1] === \"boolean\")\r\n\t\trequired = args.pop();\r\n\r\n\treturn function(target: InstanceImplementation, property?: string) {\r\n\t\tlet staticTarget: InstanceImplementation = target;\r\n\t\tif (!property) name = args.shift();\r\n\t\telse {\r\n\t\t\tname = property;\r\n\t\t\tstaticTarget = >target.constructor;\r\n\t\t}\r\n\t\tasType = args.pop() || false;\r\n\r\n\t\tstaticTarget.schema = _.clone(staticTarget.schema || { _id: false });\r\n\t\tif(!required && typeof asType !== \"boolean\") staticTarget.schema[name] = { $required: required, $type: asType };\r\n\t\telse staticTarget.schema[name] = asType;\r\n\t}\r\n}\r\n\r\n/**\r\n * Specifies a custom transform to be applied to the property this decorator is applied to.\r\n *\r\n * @param fromDB The function used to convert values from the database for the application.\r\n * @param toDB The function used to convert values from the application to the form used in the database.\r\n *\r\n * This decorator can either compliment or replace the static transforms property on your instance\r\n * class, however only one transform can be applied to any property at a time.\r\n * If your transpiler does not support decorators then you are free to make use of the\r\n * property instead.\r\n * \r\n * If this decorator is applied to the instance class itself, as opposed to a property, then\r\n * it will be treated as a $document transformer - and will receive the full document as opposed\r\n * to individual property values. Similarly, it is expected to return a full document when either\r\n * fromDB or toDB is called.\r\n */\r\nexport function Transform(fromDB: (value: any, property: string, model: Model) => any, toDB: (value: any, property: string, model: Model) => any) {\r\n\treturn function(target: Instance, property: string = \"$document\") {\r\n\t\tlet staticTarget: InstanceImplementation = >(target.constructor || target);\r\n\r\n\t\tstaticTarget.transforms = _.clone(staticTarget.transforms || {})\r\n\t\tstaticTarget.transforms[property] = {\r\n\t\t\tfromDB: fromDB,\r\n\t\t\ttoDB: toDB\r\n\t\t};\r\n\t};\r\n}\r\n\r\n\r\n/**\r\n * Specifies that this property should be treated as an ObjectID, with the requisite validator and transforms.\r\n *\r\n * This decorator applies an ObjectID validator to the property, which ensures that values sent to the database\r\n * are instances of the MongoDB ObjectID type, as well as applying a transform operation which converts ObjectIDs\r\n * to strings for your application, and then converts strings back to ObjectIDs for the database.\r\n */\r\nexport function ObjectID(target: Instance, name: string) {\r\n\tProperty(MongoDB.ObjectID)(target, name);\r\n\tTransform(\r\n\t\tDefaultTransforms.ObjectID.fromDB,\r\n\t\tDefaultTransforms.ObjectID.toDB\r\n\t)(target, name);\r\n}\r\n\r\n/**\r\n * Specifies that this property should be stored using the MongoDB binary type and represented as a Buffer.\r\n * \r\n * This decorator applies a Buffer validator to the property, which ensures that values you send to the database\r\n * are well formatted Buffer objects represented using the BSON Binary datatype. In addition to this, it will\r\n * apply a transform which ensures you only work with Buffer objects and that data is always stored in Binary\r\n * format.\r\n */\r\nexport function Binary(target: Instance, name: string) {\r\n\tProperty(Buffer)(target, name);\r\n\tTransform(\r\n\t\tDefaultTransforms.Binary.fromDB,\r\n\t\tDefaultTransforms.Binary.toDB\r\n\t)(target, name);\r\n}"],"sourceRoot":"/source/"} \ No newline at end of file diff --git a/dist/lib/Instance.js b/dist/lib/Instance.js index 75a324a..22f5c15 100644 --- a/dist/lib/Instance.js +++ b/dist/lib/Instance.js @@ -1,7 +1,7 @@ "use strict"; -var Validators_1 = require("./Validators"); -var _ = require("lodash"); -var Bluebird = require("bluebird"); +const Validators_1 = require("./Validators"); +const _ = require("lodash"); +const Bluebird = require("bluebird"); /** * The default Iridium Instance implementation which provides methods for saving, refreshing and * removing the wrapped document from the collection, as well as integrating with Omnom, our @@ -16,7 +16,7 @@ var Bluebird = require("bluebird"); * The instance returned by the model, and all of this instance's methods, will be of type * TInstance - which should represent the merger of TSchema and IInstance for best results. */ -var Instance = (function () { +class Instance { /** * Creates a new instance which represents the given document as a type of model * @param model The model that dictates the collection the document originated from as well as how validations are performed. @@ -25,40 +25,28 @@ var Instance = (function () { * @param isPartial Whether the document has only a subset of its fields populated * */ - function Instance(model, document, isNew, isPartial) { - var _this = this; - if (isNew === void 0) { isNew = true; } - if (isPartial === void 0) { isPartial = false; } + constructor(model, document, isNew = true, isPartial = false) { this._model = model; this._isNew = !!isNew; this._isPartial = isPartial; this._original = document; this._modified = model.helpers.cloneDocument(document); - _.each(model.core.plugins, function (plugin) { + _.each(model.core.plugins, (plugin) => { if (plugin.newInstance) - plugin.newInstance(_this, model); + plugin.newInstance(this, model); }); } - Object.defineProperty(Instance.prototype, "document", { - /** - * Gets the underlying document representation of this instance - */ - get: function () { - return this._modified; - }, - enumerable: true, - configurable: true - }); - Instance.prototype.save = function () { - var _this = this; - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i - 0] = arguments[_i]; - } - var callback = null; - var changes = null; - var conditions = {}; - Array.prototype.slice.call(args, 0).reverse().forEach(function (arg) { + /** + * Gets the underlying document representation of this instance + */ + get document() { + return this._modified; + } + save(...args) { + let callback = null; + let changes = null; + let conditions = {}; + Array.prototype.slice.call(args, 0).reverse().forEach((arg) => { if (typeof arg == "function") callback = arg; else if (typeof arg == "object") { @@ -68,31 +56,31 @@ var Instance = (function () { conditions = arg; } }); - return Bluebird.resolve().then(function () { - conditions = _this._model.helpers.cloneConditions(conditions); - _.merge(conditions, { _id: _this._modified._id }); + return Bluebird.resolve().then(() => { + conditions = this._model.helpers.cloneConditions(conditions); + _.merge(conditions, { _id: this._modified._id }); if (!changes) { - var validation = _this._model.helpers.validate(_this._modified); + let validation = this._model.helpers.validate(this._modified); if (validation.failed) - return Bluebird.reject(validation.error).bind(_this).nodeify(callback); - var original = _this._model.helpers.cloneDocument(_this._original); - var modified = _this._model.helpers.cloneDocument(_this._modified); - modified = _this._model.helpers.transformToDB(modified, { document: true }); - changes = _this._model.helpers.diff(original, modified); + return Bluebird.reject(validation.error).bind(this).nodeify(callback); + let original = this._model.helpers.cloneDocument(this._original); + let modified = this._model.helpers.cloneDocument(this._modified); + modified = this._model.helpers.transformToDB(modified, { document: true }); + changes = this._model.helpers.diff(original, modified); } if (!_.keys(changes).length) return null; return changes; - }).then(function (changes) { - if (!changes && !_this._isNew) + }).then((changes) => { + if (!changes && !this._isNew) return changes; - return _this._model.handlers.savingDocument(_this, changes).then(function () { return changes; }); - }).then(function (changes) { - if (!changes && !_this._isNew) + return this._model.handlers.savingDocument(this, changes).then(() => changes); + }).then((changes) => { + if (!changes && !this._isNew) return false; - if (_this._isNew) { - return new Bluebird(function (resolve, reject) { - _this._model.collection.insertOne(_this._modified, { w: "majority" }, function (err, doc) { + if (this._isNew) { + return new Bluebird((resolve, reject) => { + this._model.collection.insertOne(this._modified, { w: "majority" }, (err, doc) => { if (err) return reject(err); return resolve(!!doc); @@ -100,8 +88,8 @@ var Instance = (function () { }); } else { - return new Bluebird(function (resolve, reject) { - _this._model.collection.updateOne(conditions, changes, { w: "majority" }, function (err, changed) { + return new Bluebird((resolve, reject) => { + this._model.collection.updateOne(conditions, changes, { w: "majority" }, (err, changed) => { if (err) { err["conditions"] = conditions; err["changes"] = changes; @@ -111,128 +99,124 @@ var Instance = (function () { }); }); } - }).catch(function (err) { - err["original"] = _this._original; - err["modified"] = _this._modified; + }).catch(err => { + err["original"] = this._original; + err["modified"] = this._modified; return Bluebird.reject(err); - }).then(function (changed) { - conditions = { _id: _this._modified._id }; + }).then((changed) => { + conditions = { _id: this._modified._id }; if (!changed) - return _this._modified; - return new Bluebird(function (resolve, reject) { - _this._model.collection.find(conditions).limit(1).next(function (err, latest) { + return this._modified; + return new Bluebird((resolve, reject) => { + this._model.collection.find(conditions).limit(1).next((err, latest) => { if (err) return reject(err); return resolve(latest); }); }); - }).then(function (latest) { + }).then((latest) => { if (!latest) { - _this._isNew = true; - _this._original = _this._model.helpers.cloneDocument(_this._modified); - return Bluebird.resolve(_this); + this._isNew = true; + this._original = this._model.helpers.cloneDocument(this._modified); + return Bluebird.resolve(this); } - return _this._model.handlers.documentReceived(conditions, latest, function (value) { - _this._isPartial = false; - _this._isNew = false; - _this._modified = value; - _this._original = _this._model.helpers.cloneDocument(value); - return _this; + return this._model.handlers.documentReceived(conditions, latest, (value) => { + this._isPartial = false; + this._isNew = false; + this._modified = value; + this._original = this._model.helpers.cloneDocument(value); + return this; }); }).nodeify(callback); - }; + } /** * Updates this instance to match the latest document available in the backing collection * @param {function(Error, IInstance)} callback A callback which is triggered when the update completes * @returns {Promise} */ - Instance.prototype.update = function (callback) { + update(callback) { return this.refresh(callback); - }; + } /** * Updates this instance to match the latest document available in the backing collection * @param {function(Error, IInstance)} callback A callback which is triggered when the update completes * @returns {Promise} */ - Instance.prototype.refresh = function (callback) { - var _this = this; - var conditions = { _id: this._original._id }; - return Bluebird.resolve().then(function () { - return new Bluebird(function (resolve, reject) { - _this._model.collection.find(conditions).limit(1).next(function (err, doc) { + refresh(callback) { + let conditions = { _id: this._original._id }; + return Bluebird.resolve().then(() => { + return new Bluebird((resolve, reject) => { + this._model.collection.find(conditions).limit(1).next((err, doc) => { if (err) return reject(err); return resolve(doc); }); }); - }).then(function (newDocument) { + }).then((newDocument) => { if (!newDocument) { - _this._isPartial = true; - _this._isNew = true; - _this._original = _this._model.helpers.cloneDocument(_this._modified); - return _this; + this._isPartial = true; + this._isNew = true; + this._original = this._model.helpers.cloneDocument(this._modified); + return this; } - return _this._model.handlers.documentReceived(conditions, newDocument, function (doc) { - _this._isNew = false; - _this._isPartial = false; - _this._original = doc; - _this._modified = _this._model.helpers.cloneDocument(doc); - return _this; + return this._model.handlers.documentReceived(conditions, newDocument, (doc) => { + this._isNew = false; + this._isPartial = false; + this._original = doc; + this._modified = this._model.helpers.cloneDocument(doc); + return this; }); }).nodeify(callback); - }; + } /** * Removes this instance's document from the backing collection * @param {function(Error, IInstance)} callback A callback which is triggered when the operation completes * @returns {Promise} */ - Instance.prototype.delete = function (callback) { + delete(callback) { return this.remove(callback); - }; + } /** * Removes this instance's document from the backing collection * @param {function(Error, IInstance)} callback A callback which is triggered when the operation completes * @returns {Promise} */ - Instance.prototype.remove = function (callback) { - var _this = this; - var conditions = { _id: this._original._id }; - return Bluebird.resolve().then(function () { - if (_this._isNew) + remove(callback) { + let conditions = { _id: this._original._id }; + return Bluebird.resolve().then(() => { + if (this._isNew) return 0; - return new Bluebird(function (resolve, reject) { - _this._model.collection.deleteOne(conditions, { w: "majority" }, function (err, removed) { + return new Bluebird((resolve, reject) => { + this._model.collection.deleteOne(conditions, { w: "majority" }, (err, removed) => { if (err) return reject(err); return resolve(removed); }); }); - }).then(function (removed) { + }).then((removed) => { if (removed) - return _this._model.cache.clear(conditions); + return this._model.cache.clear(conditions); return false; - }).then(function () { - _this._isNew = true; - return _this; + }).then(() => { + this._isNew = true; + return this; }).nodeify(callback); - }; - Instance.prototype.first = function (collection, predicate) { - var _this = this; - var result = null; - _.each(collection, function (value, key) { - if (predicate.call(_this, value, key)) { + } + first(collection, predicate) { + let result = null; + _.each(collection, (value, key) => { + if (predicate.call(this, value, key)) { result = value; return false; } }); return result; - }; - Instance.prototype.select = function (collection, predicate) { - var _this = this; - var isArray = Array.isArray(collection); - var results = isArray ? [] : {}; - _.each(collection, function (value, key) { - if (predicate.call(_this, value, key)) { + } + select(collection, predicate) { + let isArray = Array.isArray(collection); + let results = isArray ? [] : {}; + _.each(collection, (value, key) => { + if (predicate.call(this, value, key)) { if (isArray) results.push(value); else @@ -240,41 +224,40 @@ var Instance = (function () { } }); return results; - }; + } /** * Gets the JSON representation of this instance * @returns {TDocument} */ - Instance.prototype.toJSON = function () { + toJSON() { return this.document; - }; + } /** * Gets a string representation of this instance * @returns {String} */ - Instance.prototype.toString = function () { + toString() { return JSON.stringify(this.document, null, 2); - }; - /** - * The schema used to validate documents of this type before being stored in the database. - */ - Instance.schema = { - _id: false - }; - /** - * Additional which should be made available for use in the schema definition for this instance. - */ - Instance.validators = Validators_1.DefaultValidators(); - /** - * The transformations which should be applied to properties of documents of this type. - */ - Instance.transforms = {}; - /** - * The indexes which should be managed by Iridium for the collection used by this type. - */ - Instance.indexes = []; - return Instance; -}()); + } +} +/** + * The schema used to validate documents of this type before being stored in the database. + */ +Instance.schema = { + _id: false +}; +/** + * Additional which should be made available for use in the schema definition for this instance. + */ +Instance.validators = Validators_1.DefaultValidators(); +/** + * The transformations which should be applied to properties of documents of this type. + */ +Instance.transforms = {}; +/** + * The indexes which should be managed by Iridium for the collection used by this type. + */ +Instance.indexes = []; exports.Instance = Instance; //# sourceMappingURL=Instance.js.map diff --git a/dist/lib/Instance.js.map b/dist/lib/Instance.js.map index f60860b..4a42854 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,K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;QAAhF,iBAYC;QAXG,IAAI,OAAO,GAAG,KAAK,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC;QACxC,IAAI,OAAO,GAAQ,OAAO,GAAG,EAAE,GAAG,EAAE,CAAC;QAErC,CAAC,CAAC,IAAI,CAAC,UAAU,EAAE,UAAC,KAAQ,EAAE,GAAG;YAC7B,EAAE,CAAC,CAAC,SAAS,CAAC,IAAI,CAAC,KAAI,EAAE,KAAK,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC;gBACnC,EAAE,CAAC,CAAC,OAAO,CAAC;oBAAC,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;gBACjC,IAAI;oBAAC,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 | 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 +{"version":3,"sources":["lib/Instance.ts"],"names":[],"mappings":";AASA,6BAAgC,cAAc,CAAC,CAAA;AAE/C,MAAY,CAAC,WAAM,QAAQ,CAAC,CAAA;AAE5B,MAAY,QAAQ,WAAM,UAAU,CAAC,CAAA;AAGrC;;;;;;;;;;;;;GAaG;AACH;IACI;;;;;;;OAOG;IACH,YAAY,KAAkC,EAAE,QAAmB,EAAE,KAAK,GAAY,IAAI,EAAE,SAAS,GAAY,KAAK;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,S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,CAAC,CAAC,CAAC,CAAC;gBACnC,EAAE,CAAC,CAAC,OAAO,CAAC;oBAAC,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;gBACjC,IAAI;oBAAC,OAAO,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC;YAC9B,CAAC;QACL,CAAC,CAAC,CAAC;QAEH,MAAM,CAAC,OAAO,CAAC;IACnB,CAAC;IAED;;;OAGG;IACH,MAAM;QACF,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC;IACzB,CAAC;IAED;;;OAGG;IACH,QAAQ;QACJ,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,QAAQ,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC;IAClD,CAAC;AACL,CAAC;AA9RG;;GAEG;AACI,eAAM,GAAW;IACpB,GAAG,EAAE,KAAK;CACb,CAAC;AAEF;;GAEG;AACI,mBAAU,GAAuB,8BAAiB,EAAE,CAAC;AAE5D;;GAEG;AACI,mBAAU,GAAe,EAE/B,CAAC;AAOF;;GAEG;AACI,gBAAO,GAA+C,EAAE,CAAC;AAjGvD,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/Model.js b/dist/lib/Model.js index c3c4865..30148bc 100644 --- a/dist/lib/Model.js +++ b/dist/lib/Model.js @@ -1,15 +1,15 @@ "use strict"; -var MongoDB = require("mongodb"); -var Bluebird = require("bluebird"); -var _ = require("lodash"); -var Core_1 = require("./Core"); -var Instance_1 = require("./Instance"); -var Cursor_1 = require("./Cursor"); -var ModelCache_1 = require("./ModelCache"); -var ModelHelpers_1 = require("./ModelHelpers"); -var ModelHandlers_1 = require("./ModelHandlers"); -var ModelSpecificInstance_1 = require("./ModelSpecificInstance"); -var Transforms_1 = require("./Transforms"); +const MongoDB = require("mongodb"); +const Bluebird = require("bluebird"); +const _ = require("lodash"); +const Core_1 = require("./Core"); +const Instance_1 = require("./Instance"); +const Cursor_1 = require("./Cursor"); +const ModelCache_1 = require("./ModelCache"); +const ModelHelpers_1 = require("./ModelHelpers"); +const ModelHandlers_1 = require("./ModelHandlers"); +const ModelSpecificInstance_1 = require("./ModelSpecificInstance"); +const Transforms_1 = require("./Transforms"); /** * An Iridium Model which represents a structured MongoDB collection. * Models expose the methods you will generally use to query those collections, and ensure that @@ -20,14 +20,14 @@ var Transforms_1 = require("./Transforms"); * * @class */ -var Model = (function () { +class Model { /** * Creates a new Iridium model representing a given ISchema and backed by a collection whose name is specified * @param core The Iridium core that this model should use for database access * @param instanceType The class which will be instantiated for each document retrieved from the database * @constructor */ - function Model(core, instanceType) { + constructor(core, instanceType) { this._hooks = {}; if (!(core instanceof Core_1.Core)) throw new Error("You failed to provide a valid Iridium core for this model"); @@ -45,7 +45,7 @@ var Model = (function () { /** * Loads any externally available properties (generally accessed using public getters/setters). */ - Model.prototype.loadExternal = function (instanceType) { + loadExternal(instanceType) { this._collection = instanceType.collection; this._schema = instanceType.schema; this._hooks = instanceType; @@ -61,218 +61,156 @@ var Model = (function () { this._Instance = ModelSpecificInstance_1.ModelSpecificInstance(this, instanceType); else this._Instance = instanceType.bind(undefined, this); - }; + } /** * Loads any internally (protected/private) properties and helpers only used within Iridium itself. */ - Model.prototype.loadInternal = function () { + loadInternal() { this._cache = new ModelCache_1.ModelCache(this); this._helpers = new ModelHelpers_1.ModelHelpers(this); this._handlers = new ModelHandlers_1.ModelHandlers(this); - }; + } /** * Process any callbacks and plugin delegation for the creation of this model. * It will generally be called whenever a new Iridium Core is created, however is * more specifically tied to the lifespan of the models themselves. */ - Model.prototype.onNewModel = function () { - var _this = this; - this._core.plugins.forEach(function (plugin) { return plugin.newModel && plugin.newModel(_this); }); - }; - Object.defineProperty(Model.prototype, "helpers", { - /** - * Provides helper methods used by Iridium for common tasks - * @returns A set of helper methods which are used within Iridium for common tasks - */ - get: function () { - return this._helpers; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Model.prototype, "handlers", { - /** - * Provides helper methods used by Iridium for hook delegation and common processes - * @returns A set of helper methods which perform common event and response handling tasks within Iridium. - */ - get: function () { - return this._handlers; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Model.prototype, "hooks", { - /** - * Gets the even hooks subscribed on this model for a number of different state changes. - * These hooks are primarily intended to allow lifecycle manipulation logic to be added - * in the user's model definition, allowing tasks such as the setting of default values - * or automatic client-side joins to take place. - */ - get: function () { - return this._hooks; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Model.prototype, "schema", { - /** - * Gets the schema dictating the data structure represented by this model. - * The schema is used by skmatc to validate documents before saving to the database, however - * until MongoDB 3.1 becomes widely available (with server side validation support) we are - * limited in our ability to validate certain types of updates. As such, these validations - * act more as a data-integrity check than anything else, unless you purely make use of Omnom - * updates within instances. - * @public - * @returns The defined validation schema for this model - */ - get: function () { - return this._schema; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Model.prototype, "core", { - /** - * Gets the Iridium core that this model is associated with. - * @public - * @returns The Iridium core that this model is bound to - */ - get: function () { - return this._core; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Model.prototype, "collection", { - /** - * Gets the underlying MongoDB collection from which this model's documents are retrieved. - * You can make use of this object if you require any low level access to the MongoDB collection, - * however we recommend you make use of the Iridium methods whereever possible, as we cannot - * guarantee the accuracy of the type definitions for the underlying MongoDB driver. - * @public - * @returns {Collection} - */ - get: function () { - if (!this.core.connection) - throw new Error("Iridium Core not connected to a database."); - return this.core.connection.collection(this._collection); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Model.prototype, "collectionName", { - /** - * Gets the name of the underlying MongoDB collection from which this model's documents are retrieved - * @public - */ - get: function () { - return this._collection; - }, - /** - * Sets the name of the underlying MongoDB collection from which this model's documents are retrieved - * @public - */ - set: function (value) { - this._collection = value; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Model.prototype, "cacheDirector", { - /** - * Gets the cache controller which dictates which queries will be cached, and under which key - * @public - * @returns {CacheDirector} - */ - get: function () { - return this._cacheDirector; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Model.prototype, "cache", { - /** - * Gets the cache responsible for storing objects for quick retrieval under certain conditions - * @public - * @returns {ModelCache} - */ - get: function () { - return this._cache; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Model.prototype, "Instance", { - /** - * Gets the constructor responsible for creating instances for this model - */ - get: function () { - return this._Instance; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Model.prototype, "transforms", { - /** - * Gets the transforms which are applied whenever a document is received from the database, or - * prior to storing a document in the database. Tasks such as converting an ObjectID to a string - * and vice versa are all listed in this object. - */ - get: function () { - return this._transforms; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Model.prototype, "validators", { - /** - * Gets the custom validation types available for this model. These validators are added to the - * default skmatc validators, as well as those available through plugins, for use when checking - * your instances. - */ - get: function () { - return this._validators; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Model.prototype, "indexes", { - /** - * Gets the indexes which Iridium will manage on this model's database collection. - */ - get: function () { - return this._indexes; - }, - enumerable: true, - configurable: true - }); - Model.prototype.find = function (conditions, fields) { + onNewModel() { + this._core.plugins.forEach(plugin => plugin.newModel && plugin.newModel(this)); + } + /** + * Provides helper methods used by Iridium for common tasks + * @returns A set of helper methods which are used within Iridium for common tasks + */ + get helpers() { + return this._helpers; + } + /** + * Provides helper methods used by Iridium for hook delegation and common processes + * @returns A set of helper methods which perform common event and response handling tasks within Iridium. + */ + get handlers() { + return this._handlers; + } + /** + * Gets the even hooks subscribed on this model for a number of different state changes. + * These hooks are primarily intended to allow lifecycle manipulation logic to be added + * in the user's model definition, allowing tasks such as the setting of default values + * or automatic client-side joins to take place. + */ + get hooks() { + return this._hooks; + } + /** + * Gets the schema dictating the data structure represented by this model. + * The schema is used by skmatc to validate documents before saving to the database, however + * until MongoDB 3.1 becomes widely available (with server side validation support) we are + * limited in our ability to validate certain types of updates. As such, these validations + * act more as a data-integrity check than anything else, unless you purely make use of Omnom + * updates within instances. + * @public + * @returns The defined validation schema for this model + */ + get schema() { + return this._schema; + } + /** + * Gets the Iridium core that this model is associated with. + * @public + * @returns The Iridium core that this model is bound to + */ + get core() { + return this._core; + } + /** + * Gets the underlying MongoDB collection from which this model's documents are retrieved. + * You can make use of this object if you require any low level access to the MongoDB collection, + * however we recommend you make use of the Iridium methods whereever possible, as we cannot + * guarantee the accuracy of the type definitions for the underlying MongoDB driver. + * @public + * @returns {Collection} + */ + get collection() { + if (!this.core.connection) + throw new Error("Iridium Core not connected to a database."); + return this.core.connection.collection(this._collection); + } + /** + * Gets the name of the underlying MongoDB collection from which this model's documents are retrieved + * @public + */ + get collectionName() { + return this._collection; + } + /** + * Sets the name of the underlying MongoDB collection from which this model's documents are retrieved + * @public + */ + set collectionName(value) { + this._collection = value; + } + /** + * Gets the cache controller which dictates which queries will be cached, and under which key + * @public + * @returns {CacheDirector} + */ + get cacheDirector() { + return this._cacheDirector; + } + /** + * Gets the cache responsible for storing objects for quick retrieval under certain conditions + * @public + * @returns {ModelCache} + */ + get cache() { + return this._cache; + } + /** + * Gets the constructor responsible for creating instances for this model + */ + get Instance() { + return this._Instance; + } + /** + * Gets the transforms which are applied whenever a document is received from the database, or + * prior to storing a document in the database. Tasks such as converting an ObjectID to a string + * and vice versa are all listed in this object. + */ + get transforms() { + return this._transforms; + } + /** + * Gets the custom validation types available for this model. These validators are added to the + * default skmatc validators, as well as those available through plugins, for use when checking + * your instances. + */ + get validators() { + return this._validators; + } + /** + * Gets the indexes which Iridium will manage on this model's database collection. + */ + get indexes() { + return this._indexes; + } + find(conditions, fields) { conditions = conditions || {}; if (!_.isPlainObject(conditions)) conditions = { _id: conditions }; conditions = this._helpers.convertToDB(conditions); - var cursor = this.collection.find(conditions); + let cursor = this.collection.find(conditions); if (fields) cursor = cursor.project(fields); return new Cursor_1.Cursor(this, conditions, cursor); - }; - Model.prototype.get = function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i - 0] = arguments[_i]; - } + } + get(...args) { return this.findOne.apply(this, args); - }; - Model.prototype.findOne = function () { - var _this = this; - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i - 0] = arguments[_i]; - } - var conditions = null; - var options = null; - var callback = null; - for (var argI = 0; argI < args.length; argI++) { + } + findOne(...args) { + let conditions = null; + let options = null; + let callback = null; + for (let argI = 0; argI < args.length; argI++) { if (typeof args[argI] === "function") callback = callback || args[argI]; else if (_.isPlainObject(args[argI])) { @@ -289,14 +227,14 @@ var Model = (function () { _.defaults(options, { cache: true }); - return Bluebird.resolve().bind(this).then(function () { - conditions = _this._helpers.convertToDB(conditions); - return _this._cache.get(conditions); - }).then(function (cachedDocument) { + return Bluebird.resolve().bind(this).then(() => { + conditions = this._helpers.convertToDB(conditions); + return this._cache.get(conditions); + }).then((cachedDocument) => { if (cachedDocument) return cachedDocument; - return new Bluebird(function (resolve, reject) { - var cursor = _this.collection.find(conditions); + return new Bluebird((resolve, reject) => { + let cursor = this.collection.find(conditions); if (options.sort) cursor = cursor.sort(options.sort); if (typeof options.skip === "number") @@ -304,34 +242,25 @@ var Model = (function () { cursor = cursor.limit(1); if (options.fields) cursor = cursor.project(options.fields); - return cursor.next(function (err, result) { + return cursor.next((err, result) => { if (err) return reject(err); return resolve(result); }); }); - }).then(function (document) { + }).then((document) => { if (!document) return null; - return _this._handlers.documentReceived(conditions, document, function (document, isNew, isPartial) { return _this._helpers.wrapDocument(document, isNew, isPartial); }, options); + return this._handlers.documentReceived(conditions, document, (document, isNew, isPartial) => this._helpers.wrapDocument(document, isNew, isPartial), options); }).nodeify(callback); - }; - Model.prototype.create = function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i - 0] = arguments[_i]; - } + } + create(...args) { return this.insert.apply(this, args); - }; - Model.prototype.insert = function (objs) { - var _this = this; - var args = []; - for (var _i = 1; _i < arguments.length; _i++) { - args[_i - 1] = arguments[_i]; - } - var objects; - var options = {}; - var callback = null; + } + insert(objs, ...args) { + let objects; + let options = {}; + let callback = null; if (typeof args[0] === "function") callback = args[0]; else { @@ -347,16 +276,16 @@ var Model = (function () { w: "majority", forceServerObjectId: true }); - return Bluebird.resolve().then(function () { - var queryOptions = { w: options.w, upsert: options.upsert, new: true }; + return Bluebird.resolve().then(() => { + let queryOptions = { w: options.w, upsert: options.upsert, new: true }; if (options.upsert) { - var docs = _this._handlers.creatingDocuments(objects); - return docs.map(function (object) { - return new Bluebird(function (resolve, reject) { - _this.collection.findOneAndUpdate({ _id: object._id }, object, { + let docs = this._handlers.creatingDocuments(objects); + return docs.map((object) => { + return new Bluebird((resolve, reject) => { + this.collection.findOneAndUpdate({ _id: object._id }, object, { upsert: options.upsert, returnOriginal: false - }, function (err, result) { + }, (err, result) => { if (err) return reject(err); return resolve(result.value); @@ -365,25 +294,24 @@ var Model = (function () { }); } else - return _this._handlers.creatingDocuments(objects).then(function (objects) { return _.chunk(objects, 1000); }).map(function (objects) { - return new Bluebird(function (resolve, reject) { - _this.collection.insertMany(objects, queryOptions, function (err, result) { + return this._handlers.creatingDocuments(objects).then(objects => _.chunk(objects, 1000)).map((objects) => { + return new Bluebird((resolve, reject) => { + this.collection.insertMany(objects, queryOptions, (err, result) => { if (err) return reject(err); return resolve(result.ops); }); }); - }).then(function (results) { return _.flatten(results); }); - }).map(function (inserted) { - return _this._handlers.documentReceived(null, inserted, function (document, isNew, isPartial) { return _this._helpers.wrapDocument(document, isNew, isPartial); }, { cache: options.cache }); - }).then(function (results) { + }).then(results => _.flatten(results)); + }).map((inserted) => { + return this._handlers.documentReceived(null, inserted, (document, isNew, isPartial) => this._helpers.wrapDocument(document, isNew, isPartial), { cache: options.cache }); + }).then((results) => { if (Array.isArray(objs)) return results; return results[0]; }).nodeify(callback); - }; - Model.prototype.update = function (conditions, changes, options, callback) { - var _this = this; + } + update(conditions, changes, options, callback) { if (typeof options === "function") { callback = options; options = {}; @@ -397,10 +325,10 @@ var Model = (function () { w: "majority", multi: true }); - return Bluebird.resolve().then(function () { - conditions = _this._helpers.convertToDB(conditions); - return new Bluebird(function (resolve, reject) { - _this.collection.updateMany(conditions, changes, options, function (err, response) { + return Bluebird.resolve().then(() => { + conditions = this._helpers.convertToDB(conditions); + return new Bluebird((resolve, reject) => { + this.collection.updateMany(conditions, changes, options, (err, response) => { if (err) return reject(err); // New MongoDB 2.6+ response type @@ -411,10 +339,9 @@ var Model = (function () { }); }); }).nodeify(callback); - }; - Model.prototype.count = function (conds, callback) { - var _this = this; - var conditions = conds; + } + count(conds, callback) { + let conditions = conds; if (typeof conds === "function") { callback = conds; conditions = {}; @@ -424,20 +351,19 @@ var Model = (function () { conditions = { _id: conditions }; - return Bluebird.resolve().then(function () { - conditions = _this._helpers.convertToDB(conditions); - return new Bluebird(function (resolve, reject) { - _this.collection.count(conditions, function (err, results) { + return Bluebird.resolve().then(() => { + conditions = this._helpers.convertToDB(conditions); + return new Bluebird((resolve, reject) => { + this.collection.count(conditions, (err, results) => { if (err) return reject(err); return resolve(results); }); }); }).nodeify(callback); - }; - Model.prototype.remove = function (conds, options, callback) { - var _this = this; - var conditions = conds; + } + remove(conds, options, callback) { + let conditions = conds; if (typeof options === "function") { callback = options; options = {}; @@ -456,95 +382,89 @@ var Model = (function () { conditions = { _id: conditions }; - return Bluebird.resolve().then(function () { - conditions = _this._helpers.convertToDB(conditions); - return new Bluebird(function (resolve, reject) { + return Bluebird.resolve().then(() => { + conditions = this._helpers.convertToDB(conditions); + return new Bluebird((resolve, reject) => { if (options.single) - return _this.collection.deleteOne(conditions, options, function (err, response) { + return this.collection.deleteOne(conditions, options, (err, response) => { if (err) return reject(err); return resolve(response.result.n); }); - _this.collection.deleteMany(conditions, options, function (err, response) { + this.collection.deleteMany(conditions, options, (err, response) => { if (err) return reject(err); return resolve(response.result.n); }); }); - }).then(function (count) { + }).then((count) => { if (count === 1) - _this._cache.clear(conditions); + this._cache.clear(conditions); return Bluebird.resolve(count); }).nodeify(callback); - }; - Model.prototype.aggregate = function (pipeline) { - var _this = this; - return new Bluebird(function (resolve, reject) { - _this.collection.aggregate(pipeline, function (err, results) { + } + aggregate(pipeline) { + return new Bluebird((resolve, reject) => { + this.collection.aggregate(pipeline, (err, results) => { if (err) return reject(err); return resolve(results); }); }); - }; - Model.prototype.ensureIndex = function (specification, options, callback) { - var _this = this; + } + ensureIndex(specification, options, callback) { if (typeof options === "function") { callback = options; options = {}; } - return new Bluebird(function (resolve, reject) { - _this.collection.createIndex(specification, options, function (err, name) { + return new Bluebird((resolve, reject) => { + this.collection.createIndex(specification, options, (err, name) => { if (err) return reject(err); return resolve(name); }); }).nodeify(callback); - }; + } /** * Ensures that all indexes defined in the model's options are created * @param {function(Error, String[])} callback A callback which is triggered when the operation completes * @returns {Promise} The names of the indexes */ - Model.prototype.ensureIndexes = function (callback) { - var _this = this; - return Bluebird.resolve(this._indexes).map(function (index) { - return _this.ensureIndex(index.spec || index, index.options || {}); + ensureIndexes(callback) { + return Bluebird.resolve(this._indexes).map((index) => { + return this.ensureIndex(index.spec || index, index.options || {}); }).nodeify(callback); - }; - Model.prototype.dropIndex = function (specification, callback) { - var _this = this; - var index; + } + dropIndex(specification, callback) { + let index; if (typeof (specification) === "string") index = specification; else { - index = _(specification).map(function (direction, key) { return (key + "_" + direction); }).reduce(function (x, y) { return (x + "_" + y); }); + index = _(specification).map((direction, key) => `${key}_${direction}`).reduce((x, y) => `${x}_${y}`); } - return new Bluebird(function (resolve, reject) { - _this.collection.dropIndex(index, function (err, result) { + return new Bluebird((resolve, reject) => { + this.collection.dropIndex(index, (err, result) => { if (err) return reject(err); return resolve(!!result.ok); }); }).nodeify(callback); - }; + } /** * 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 */ - Model.prototype.dropIndexes = function (callback) { - var _this = this; - return new Bluebird(function (resolve, reject) { - _this.collection.dropIndexes(function (err, count) { + dropIndexes(callback) { + return new Bluebird((resolve, reject) => { + this.collection.dropIndexes((err, count) => { if (err) return reject(err); return resolve(count); }); }).nodeify(callback); - }; - return Model; -}()); + } +} exports.Model = Model; //# sourceMappingURL=Model.js.map diff --git a/dist/lib/Model.js.map b/dist/lib/Model.js.map index 357b9ea..3ce0038 100644 --- a/dist/lib/Model.js.map +++ b/dist/lib/Model.js.map @@ -1 +1 @@ -{"version":3,"sources":["lib/Model.ts"],"names":[],"mappings":";AAAA,IAAa,OAAO,WAAM,SAAS,CAAC,CAAA;AACpC,IAAY,QAAQ,WAAM,UAAU,CAAC,CA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C,UAAC,GAAG,EAAE,KAAK;gBACnC,EAAE,CAAC,CAAC,GAAG,CAAC;oBAAC,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;gBAC5B,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;YAC1B,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC;IACzB,CAAC;IACL,YAAC;AAAD,CA3tBA,AA2tBC,IAAA;AA3tBY,aAAK,QA2tBjB,CAAA","file":"lib/Model.js","sourcesContent":["import * as MongoDB from \"mongodb\";\r\nimport * as Bluebird from \"bluebird\";\r\nimport * as util from \"util\";\r\nimport * as _ from \"lodash\";\r\nimport * as Skmatc from \"skmatc\";\r\n\r\nimport {Core} from \"./Core\";\r\nimport {Instance} from \"./Instance\";\r\nimport {Schema} from \"./Schema\";\r\nimport {Hooks} from \"./Hooks\";\r\nimport {Plugin} from \"./Plugins\";\r\nimport {Cache} from \"./Cache\";\r\nimport {CacheDirector} from \"./CacheDirector\";\r\nimport * as General from \"./General\";\r\nimport {Cursor} from \"./Cursor\";\r\nimport * as Index from \"./Index\";\r\nimport * as ModelOptions from \"./ModelOptions\";\r\n\r\nimport {Omnom} from \"./utils/Omnom\";\r\nimport {ModelCache} from \"./ModelCache\";\r\nimport {ModelHelpers} from \"./ModelHelpers\";\r\nimport {ModelHandlers} from \"./ModelHandlers\";\r\nimport * as ModelInterfaces from \"./ModelInterfaces\";\r\nimport {ModelSpecificInstance} from \"./ModelSpecificInstance\";\r\nimport {InstanceImplementation} from \"./InstanceInterface\";\r\nimport {Transforms, DefaultTransforms} from \"./Transforms\";\r\nimport * as AggregationPipeline from \"./Aggregate\";\r\n\r\n/**\r\n * An Iridium Model which represents a structured MongoDB collection.\r\n * Models expose the methods you will generally use to query those collections, and ensure that\r\n * the results of those queries are returned as {TInstance} instances.\r\n *\r\n * @param TDocument The interface used to determine the schema of documents in the collection.\r\n * @param TInstance The interface or class used to represent collection documents in the JS world.\r\n *\r\n * @class\r\n */\r\nexport class Model {\r\n /**\r\n * Creates a new Iridium model representing a given ISchema and backed by a collection whose name is specified\r\n * @param core The Iridium core that this model should use for database access\r\n * @param instanceType The class which will be instantiated for each document retrieved from the database\r\n * @constructor\r\n */\r\n constructor(core: Core, instanceType: InstanceImplementation) {\r\n if (!(core instanceof Core)) throw new Error(\"You failed to provide a valid Iridium core for this model\");\r\n if (typeof instanceType !== \"function\") throw new Error(\"You failed to provide a valid instance constructor for this model\");\r\n if (typeof instanceType.collection !== \"string\" || !instanceType.collection) throw new Error(\"You failed to provide a valid collection name for this model\");\r\n if (!_.isPlainObject(instanceType.schema) || instanceType.schema._id === undefined) throw new Error(\"You failed to provide a valid schema for this model\");\r\n\r\n this._core = core;\r\n\r\n this.loadExternal(instanceType);\r\n this.onNewModel();\r\n this.loadInternal();\r\n }\r\n\r\n /**\r\n * Loads any externally available properties (generally accessed using public getters/setters).\r\n */\r\n private loadExternal(instanceType: InstanceImplementation) {\r\n this._collection = instanceType.collection;\r\n this._schema = instanceType.schema;\r\n this._hooks = instanceType;\r\n this._cacheDirector = instanceType.cache;\r\n this._transforms = instanceType.transforms || {};\r\n this._validators = instanceType.validators || [];\r\n this._indexes = instanceType.indexes || [];\r\n\r\n if(!this._schema._id) this._schema._id = MongoDB.ObjectID;\r\n\r\n if(this._schema._id === MongoDB.ObjectID && !this._transforms._id)\r\n this._transforms._id = DefaultTransforms.ObjectID;\r\n\r\n if ((instanceType).prototype instanceof Instance)\r\n this._Instance = ModelSpecificInstance(this, instanceType);\r\n else\r\n this._Instance = instanceType.bind(undefined, this);\r\n }\r\n\r\n /**\r\n * Loads any internally (protected/private) properties and helpers only used within Iridium itself.\r\n */\r\n private loadInternal() {\r\n this._cache = new ModelCache(this);\r\n this._helpers = new ModelHelpers(this);\r\n this._handlers = new ModelHandlers(this);\r\n }\r\n\r\n /**\r\n * Process any callbacks and plugin delegation for the creation of this model.\r\n * It will generally be called whenever a new Iridium Core is created, however is\r\n * more specifically tied to the lifespan of the models themselves.\r\n */\r\n private onNewModel() {\r\n this._core.plugins.forEach(plugin => plugin.newModel && plugin.newModel(this));\r\n }\r\n\r\n private _helpers: ModelHelpers;\r\n /**\r\n * Provides helper methods used by Iridium for common tasks\r\n * @returns A set of helper methods which are used within Iridium for common tasks\r\n */\r\n get helpers(): ModelHelpers {\r\n return this._helpers;\r\n }\r\n\r\n private _handlers: ModelHandlers;\r\n /**\r\n * Provides helper methods used by Iridium for hook delegation and common processes\r\n * @returns A set of helper methods which perform common event and response handling tasks within Iridium.\r\n */\r\n get handlers(): ModelHandlers {\r\n return this._handlers;\r\n }\r\n\r\n private _hooks: Hooks = {};\r\n\r\n /**\r\n * Gets the even hooks subscribed on this model for a number of different state changes.\r\n * These hooks are primarily intended to allow lifecycle manipulation logic to be added\r\n * in the user's model definition, allowing tasks such as the setting of default values\r\n * or automatic client-side joins to take place.\r\n */\r\n get hooks(): Hooks {\r\n return this._hooks;\r\n }\r\n\r\n private _schema: Schema;\r\n /**\r\n * Gets the schema dictating the data structure represented by this model.\r\n * The schema is used by skmatc to validate documents before saving to the database, however\r\n * until MongoDB 3.1 becomes widely available (with server side validation support) we are\r\n * limited in our ability to validate certain types of updates. As such, these validations\r\n * act more as a data-integrity check than anything else, unless you purely make use of Omnom\r\n * updates within instances.\r\n * @public\r\n * @returns The defined validation schema for this model\r\n */\r\n get schema(): Schema {\r\n return this._schema;\r\n }\r\n\r\n private _core: Core;\r\n /**\r\n * Gets the Iridium core that this model is associated with.\r\n * @public\r\n * @returns The Iridium core that this model is bound to\r\n */\r\n get core(): Core {\r\n return this._core;\r\n }\r\n\r\n private _collection: string;\r\n /**\r\n * Gets the underlying MongoDB collection from which this model's documents are retrieved.\r\n * You can make use of this object if you require any low level access to the MongoDB collection,\r\n * however we recommend you make use of the Iridium methods whereever possible, as we cannot\r\n * guarantee the accuracy of the type definitions for the underlying MongoDB driver.\r\n * @public\r\n * @returns {Collection}\r\n */\r\n get collection(): MongoDB.Collection {\r\n if (!this.core.connection) throw new Error(\"Iridium Core not connected to a database.\");\r\n return this.core.connection.collection(this._collection);\r\n }\r\n\r\n /**\r\n * Gets the name of the underlying MongoDB collection from which this model's documents are retrieved\r\n * @public\r\n */\r\n get collectionName(): string {\r\n return this._collection;\r\n }\r\n\r\n /**\r\n * Sets the name of the underlying MongoDB collection from which this model's documents are retrieved\r\n * @public\r\n */\r\n set collectionName(value: string) {\r\n this._collection = value;\r\n }\r\n\r\n private _cacheDirector: CacheDirector;\r\n /**\r\n * Gets the cache controller which dictates which queries will be cached, and under which key\r\n * @public\r\n * @returns {CacheDirector}\r\n */\r\n get cacheDirector(): CacheDirector {\r\n return this._cacheDirector;\r\n }\r\n\r\n private _cache: ModelCache;\r\n /**\r\n * Gets the cache responsible for storing objects for quick retrieval under certain conditions\r\n * @public\r\n * @returns {ModelCache}\r\n */\r\n get cache(): ModelCache {\r\n return this._cache;\r\n }\r\n\r\n private _Instance: ModelInterfaces.ModelSpecificInstanceConstructor;\r\n\r\n /**\r\n * Gets the constructor responsible for creating instances for this model\r\n */\r\n get Instance(): ModelInterfaces.ModelSpecificInstanceConstructor {\r\n return this._Instance;\r\n }\r\n\r\n private _transforms: Transforms;\r\n\r\n /**\r\n * Gets the transforms which are applied whenever a document is received from the database, or\r\n * prior to storing a document in the database. Tasks such as converting an ObjectID to a string\r\n * and vice versa are all listed in this object.\r\n */\r\n get transforms() {\r\n return this._transforms;\r\n }\r\n\r\n private _validators: Skmatc.Validator[];\r\n\r\n /**\r\n * Gets the custom validation types available for this model. These validators are added to the\r\n * default skmatc validators, as well as those available through plugins, for use when checking\r\n * your instances.\r\n */\r\n get validators() {\r\n return this._validators;\r\n }\r\n\r\n private _indexes: (Index.Index | Index.IndexSpecification)[];\r\n\r\n /**\r\n * Gets the indexes which Iridium will manage on this model's database collection.\r\n */\r\n get indexes() {\r\n return this._indexes;\r\n }\r\n\r\n /**\r\n * Retrieves all documents in the collection and wraps them as instances\r\n * @param {function(Error, TInstance[])} callback An optional callback which will be triggered when results are available\r\n * @returns {Promise}\r\n */\r\n find(): Cursor;\r\n /**\r\n * Returns all documents in the collection which match the conditions and wraps them as instances\r\n * @param {Object} conditions The MongoDB query dictating which documents to return\r\n * @returns {Promise}\r\n */\r\n find(conditions: { _id?: any, [key: string]: any } | any): Cursor;\r\n /**\r\n * Returns all documents in the collection which match the conditions\r\n * @param {Object} conditions The MongoDB query dictating which documents to return\r\n * @param {Object} fields The fields to include or exclude from the document\r\n * @returns {Promise}\r\n */\r\n find(conditions: { _id?: any, [key: string]: any } | any, fields: { [name: string]: number }): Cursor;\r\n find(conditions?: { _id?: any, [key: string]: any } | any, fields?: any): Cursor {\r\n conditions = conditions || {};\r\n\r\n if (!_.isPlainObject(conditions)) conditions = { _id: conditions };\r\n conditions = this._helpers.convertToDB(conditions);\r\n\r\n let cursor = this.collection.find(conditions);\r\n \r\n if(fields)\r\n cursor = cursor.project(fields);\r\n\r\n return new Cursor(this, conditions, cursor);\r\n }\r\n\r\n /**\r\n * Retrieves a single document from the collection and wraps it as an instance\r\n * @param {function(Error, TInstance)} callback An optional callback which will be triggered when a result is available\r\n * @returns {Promise}\r\n */\r\n get(callback?: General.Callback): Bluebird;\r\n /**\r\n * Retrieves a single document from the collection with the given ID and wraps it as an instance\r\n * @param {any} id The document's unique _id field value in downstream format\r\n * @param {function(Error, TInstance)} callback An optional callback which will be triggered when a result is available\r\n * @returns {Promise}\r\n */\r\n get(id: any, callback?: General.Callback): Bluebird;\r\n /**\r\n * Retrieves a single document from the collection which matches the conditions\r\n * @param {Object} conditions The MongoDB query dictating which document to return\r\n * @param {function(Error, TInstance)} callback An optional callback which will be triggered when a result is available\r\n * @returns {Promise}\r\n */\r\n get(conditions: { _id?: any, [key: string]: any }, callback?: General.Callback): Bluebird;\r\n /**\r\n * Retrieves a single document from the collection with the given ID and wraps it as an instance\r\n * @param {any} id The document's unique _id field value in downstream format\r\n * @param {QueryOptions} options The options dictating how this function behaves\r\n * @param {function(Error, TInstance)} callback An optional callback which will be triggered when a result is available\r\n * @returns {Promise}\r\n */\r\n get(id: any, options: ModelOptions.QueryOptions, callback?: General.Callback): Bluebird;\r\n /**\r\n * Retrieves a single document from the collection which matches the conditions\r\n * @param {Object} conditions The MongoDB query dictating which document to return\r\n * @param {QueryOptions} options The options dictating how this function behaves\r\n * @param {function(Error, TInstance)} callback An optional callback which will be triggered when a result is available\r\n * @returns {Promise}\r\n */\r\n get(conditions: { _id?: any, [key: string]: any }, options: ModelOptions.QueryOptions, callback?: General.Callback): Bluebird;\r\n get(...args: any[]): Bluebird {\r\n return this.findOne.apply(this, args);\r\n }\r\n\r\n /**\r\n * Retrieves a single document from the collection and wraps it as an instance\r\n * @param {function(Error, TInstance)} callback An optional callback which will be triggered when a result is available\r\n * @returns {Promise}\r\n */\r\n findOne(callback?: General.Callback): Bluebird;\r\n /**\r\n * Retrieves a single document from the collection with the given ID and wraps it as an instance\r\n * @param {any} id The document's unique _id field value in downstream format\r\n * @param {function(Error, TInstance)} callback An optional callback which will be triggered when a result is available\r\n * @returns {Promise}\r\n */\r\n findOne(id: any, callback?: General.Callback): Bluebird;\r\n /**\r\n * Retrieves a single document from the collection which matches the conditions\r\n * @param {Object} conditions The MongoDB query dictating which document to return\r\n * @param {function(Error, TInstance)} callback An optional callback which will be triggered when a result is available\r\n * @returns {Promise}\r\n */\r\n findOne(conditions: { _id?: any, [key: string]: any }, callback?: General.Callback): Bluebird;\r\n /**\r\n * Retrieves a single document from the collection with the given ID and wraps it as an instance\r\n * @param {any} id The document's unique _id field value in downstream format\r\n * @param {QueryOptions} options The options dictating how this function behaves\r\n * @param {function(Error, TInstance)} callback An optional callback which will be triggered when a result is available\r\n * @returns {Promise}\r\n */\r\n findOne(id: any, options: ModelOptions.QueryOptions, callback?: General.Callback): Bluebird;\r\n /**\r\n * Retrieves a single document from the collection which matches the conditions\r\n * @param {Object} conditions The MongoDB query dictating which document to return\r\n * @param {QueryOptions} options The options dictating how this function behaves\r\n * @param {function(Error, TInstance)} callback An optional callback which will be triggered when a result is available\r\n * @returns {Promise}\r\n */\r\n findOne(conditions: { _id?: any, [key: string]: any }, options: ModelOptions.QueryOptions, callback?: General.Callback): Bluebird;\r\n findOne(...args: any[]): Bluebird {\r\n let conditions: { _id?: any, [key: string]: any } = null;\r\n let options: ModelOptions.QueryOptions = null;\r\n let callback: General.Callback = null;\r\n\r\n for (let argI = 0; argI < args.length; argI++) {\r\n if (typeof args[argI] === \"function\") callback = callback || args[argI];\r\n else if (_.isPlainObject(args[argI])) {\r\n if (conditions) options = args[argI];\r\n else conditions = args[argI];\r\n }\r\n else conditions = { _id: args[argI] };\r\n }\r\n\r\n conditions = conditions || {};\r\n options = options || {};\r\n\r\n _.defaults(options, {\r\n cache: true\r\n });\r\n\r\n return Bluebird.resolve().bind(this).then(() => {\r\n conditions = this._helpers.convertToDB(conditions);\r\n\r\n return this._cache.get(conditions);\r\n }).then((cachedDocument: TDocument) => {\r\n if (cachedDocument) return cachedDocument;\r\n return new Bluebird((resolve, reject) => {\r\n let cursor = this.collection.find(conditions);\r\n \r\n if(options.sort)\r\n cursor = cursor.sort(options.sort);\r\n \r\n if(typeof options.skip === \"number\")\r\n cursor = cursor.skip(options.skip);\r\n \r\n cursor = cursor.limit(1);\r\n \r\n if(options.fields)\r\n cursor = cursor.project(options.fields);\r\n \r\n return cursor.next((err, result) => {\r\n if (err) return reject(err);\r\n return resolve(result);\r\n });\r\n });\r\n }).then((document: TDocument) => {\r\n if (!document) return null;\r\n return this._handlers.documentReceived(conditions, document, (document, isNew?, isPartial?) => this._helpers.wrapDocument(document, isNew, isPartial), options);\r\n }).nodeify(callback);\r\n }\r\n\r\n /**\r\n * Inserts an object into the collection after validating it against this model's schema\r\n * @param {Object} object The object to insert into the collection\r\n * @param {function(Error, TInstance)} callback A callback which is triggered when the operation completes\r\n * @returns {Promise}\r\n */\r\n create(objects: TDocument, callback?: General.Callback): Bluebird;\r\n /**\r\n * Inserts an object into the collection after validating it against this model's schema\r\n * @param {Object} object The object to insert into the collection\r\n * @param {CreateOptions} options The options dictating how this function behaves\r\n * @param {function(Error, TInstance)} callback A callback which is triggered when the operation completes\r\n * @returns {Promise}\r\n */\r\n create(objects: TDocument, options: ModelOptions.CreateOptions, callback?: General.Callback): Bluebird;\r\n /**\r\n * Inserts the objects into the collection after validating them against this model's schema\r\n * @param {Object[]} objects The objects to insert into the collection\r\n * @param {function(Error, TInstance)} callback A callback which is triggered when the operation completes\r\n * @returns {Promise}\r\n */\r\n create(objects: TDocument[], callback?: General.Callback): Bluebird;\r\n /**\r\n * Inserts the objects into the collection after validating them against this model's schema\r\n * @param {Object[]} objects The objects to insert into the collection\r\n * @param {CreateOptions} options The options dictating how this function behaves\r\n * @param {function(Error, TInstance)} callback A callback which is triggered when the operation completes\r\n * @returns {Promise}\r\n */\r\n create(objects: TDocument[], options: ModelOptions.CreateOptions, callback?: General.Callback): Bluebird;\r\n create(...args: any[]): Bluebird {\r\n return this.insert.apply(this, args);\r\n }\r\n\r\n /**\r\n * Inserts an object into the collection after validating it against this model's schema\r\n * @param {Object} object The object to insert into the collection\r\n * @param {function(Error, TInstance)} callback A callback which is triggered when the operation completes\r\n * @returns {Promise}\r\n */\r\n insert(objects: TDocument, callback?: General.Callback): Bluebird;\r\n /**\r\n * Inserts an object into the collection after validating it against this model's schema\r\n * @param {Object} object The object to insert into the collection\r\n * @param {CreateOptions} options The options dictating how this function behaves\r\n * @param {function(Error, TInstance)} callback A callback which is triggered when the operation completes\r\n * @returns {Promise}\r\n */\r\n insert(objects: TDocument, options: ModelOptions.CreateOptions, callback?: General.Callback): Bluebird;\r\n /**\r\n * Inserts the objects into the collection after validating them against this model's schema\r\n * @param {Object[]} objects The objects to insert into the collection\r\n * @param {function(Error, TInstance[])} callback A callback which is triggered when the operation completes\r\n * @returns {Promise}\r\n */\r\n insert(objects: TDocument[], callback?: General.Callback): Bluebird;\r\n /**\r\n * Inserts the objects into the collection after validating them against this model's schema\r\n * @param {Object[]} objects The objects to insert into the collection\r\n * @param {CreateOptions} options The options dictating how this function behaves\r\n * @param {function(Error, TInstance[])} callback A callback which is triggered when the operation completes\r\n * @returns {Promise}\r\n */\r\n insert(objects: TDocument[], options: ModelOptions.CreateOptions, callback?: General.Callback): Bluebird;\r\n insert(objs: TDocument | TDocument[], ...args: any[]): Bluebird {\r\n let objects: TDocument[];\r\n let options: ModelOptions.CreateOptions = {};\r\n let callback: General.Callback = null;\r\n if (typeof args[0] === \"function\") callback = args[0];\r\n else {\r\n options = args[0];\r\n callback = args[1];\r\n }\r\n\r\n if (Array.isArray(objs))\r\n objects = objs;\r\n else\r\n objects = [objs];\r\n\r\n options = options || {};\r\n _.defaults(options, {\r\n w: \"majority\",\r\n forceServerObjectId: true\r\n });\r\n\r\n return Bluebird.resolve().then(() => {\r\n let queryOptions = { w: options.w, upsert: options.upsert, new: true };\r\n\r\n if (options.upsert) {\r\n let docs = this._handlers.creatingDocuments(objects);\r\n return docs.map((object: { _id: any; }) => {\r\n return new Bluebird((resolve, reject) => {\r\n this.collection.findOneAndUpdate({ _id: object._id }, object, {\r\n upsert: options.upsert,\r\n returnOriginal: false\r\n }, (err, result) => {\r\n if (err) return reject(err);\r\n return resolve(result.value);\r\n });\r\n });\r\n });\r\n }\r\n else\r\n return this._handlers.creatingDocuments(objects).then(objects => _.chunk(objects, 1000)).map((objects: any[]) => {\r\n return new Bluebird((resolve, reject) => {\r\n this.collection.insertMany(objects, queryOptions, (err, result) => {\r\n if (err) return reject(err);\r\n return resolve(result.ops);\r\n });\r\n });\r\n }).then(results => _.flatten(results));\r\n }).map((inserted: any) => {\r\n return this._handlers.documentReceived(null, inserted, (document, isNew?, isPartial?) => this._helpers.wrapDocument(document, isNew, isPartial), { cache: options.cache });\r\n }).then((results: TInstance[]) => {\r\n if (Array.isArray(objs)) return results;\r\n return results[0];\r\n }).nodeify(callback);\r\n }\r\n\r\n /**\r\n * Updates the documents in the backing collection which match the conditions using the given update instructions\r\n * @param {Object} conditions The conditions which determine which documents will be updated\r\n * @param {Object} changes The changes to make to the documents\r\n * @param {function(Error, Number)} callback A callback which is triggered when the operation completes\r\n */\r\n update(conditions: { _id?: any, [key: string]: any } | any, changes: any, callback?: General.Callback): Bluebird;\r\n /**\r\n * Updates the documents in the backing collection which match the conditions using the given update instructions\r\n * @param {Object} conditions The conditions which determine which documents will be updated\r\n * @param {Object} changes The changes to make to the documents\r\n * @param {UpdateOptions} options The options which dictate how this function behaves\r\n * @param {function(Error, Number)} callback A callback which is triggered when the operation completes\r\n */\r\n update(conditions: { _id?: any, [key: string]: any } | any, changes: any, options: ModelOptions.UpdateOptions, callback?: General.Callback): Bluebird;\r\n update(conditions: { _id?: any, [key: string]: any } | any, changes: any, options?: ModelOptions.UpdateOptions, callback?: General.Callback): Bluebird {\r\n if (typeof options === \"function\") {\r\n callback = >options;\r\n options = {};\r\n }\r\n\r\n options = options || {};\r\n\r\n if (!_.isPlainObject(conditions)) conditions = {\r\n _id: conditions\r\n };\r\n\r\n _.defaults(options, {\r\n w: \"majority\",\r\n multi: true\r\n });\r\n\r\n return Bluebird.resolve().then(() => {\r\n conditions = this._helpers.convertToDB(conditions);\r\n\r\n return new Bluebird((resolve, reject) => {\r\n this.collection.updateMany(conditions, changes, options, (err, response) => {\r\n if (err) return reject(err);\r\n\r\n // New MongoDB 2.6+ response type\r\n if (response.result && response.result.nModified !== undefined) return resolve(response.result.nModified);\r\n\r\n // Legacy response type\r\n return resolve(response.result.n);\r\n });\r\n })\r\n }).nodeify(callback);\r\n }\r\n\r\n /**\r\n * Counts the number of documents in the collection\r\n * @param {function(Error, Number)} callback A callback which is triggered when the operation completes\r\n * @returns {Promise}\r\n */\r\n count(callback?: General.Callback): Bluebird;\r\n /**\r\n * Counts the number of documents in the collection which match the conditions provided\r\n * @param {Object} conditions The conditions which determine whether an object is counted or not\r\n * @param {function(Error, Number)} callback A callback which is triggered when the operation completes\r\n * @returns {Promise}\r\n */\r\n count(conditions: { _id?: any, [key: string]: any } | any, callback?: General.Callback): Bluebird;\r\n count(conds?: any, callback?: General.Callback): Bluebird {\r\n let conditions: { _id?: any, [key: string]: any } = <{ _id?: any, [key: string]: any }>conds;\r\n if (typeof conds === \"function\") {\r\n callback = >conds;\r\n conditions = {};\r\n }\r\n\r\n conditions = conditions || {};\r\n\r\n if (!_.isPlainObject(conditions)) conditions = {\r\n _id: conditions\r\n };\r\n\r\n return Bluebird.resolve().then(() => {\r\n conditions = this._helpers.convertToDB(conditions);\r\n\r\n return new Bluebird((resolve, reject) => {\r\n this.collection.count(conditions, (err, results) => {\r\n if (err) return reject(err);\r\n return resolve(results);\r\n });\r\n });\r\n }).nodeify(callback);\r\n }\r\n\r\n /**\r\n * Removes all documents from the collection\r\n * @param {function(Error, Number)} 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 /**\r\n * Removes all documents from the collection which match the conditions\r\n * @param {Object} conditions The conditions determining whether an object is removed or not\r\n * @param {function(Error, Number)} callback A callback which is triggered when the operation completes\r\n * @returns {Promise}\r\n */\r\n remove(conditions: { _id?: any, [key: string]: any } | any, callback?: General.Callback): Bluebird;\r\n /**\r\n * Removes all documents from the collection which match the conditions\r\n * @param {Object} conditions The conditions determining whether an object is removed or not\r\n * @param {Object} options The options controlling the way in which the function behaves\r\n * @param {function(Error, Number)} callback A callback which is triggered when the operation completes\r\n * @returns {Promise}\r\n */\r\n remove(conditions: { _id?: any, [key: string]: any }, options: ModelOptions.RemoveOptions, callback?: General.Callback): Bluebird;\r\n remove(conds?: any, options?: ModelOptions.RemoveOptions, callback?: General.Callback): Bluebird {\r\n let conditions: { _id?: any, [key: string]: any } = <{ _id?: any, [key: string]: any }>conds;\r\n\r\n if (typeof options === \"function\") {\r\n callback = >options;\r\n options = {};\r\n }\r\n\r\n if (typeof conds === \"function\") {\r\n callback = >conds;\r\n options = {};\r\n conditions = {};\r\n }\r\n\r\n conditions = conditions || {};\r\n options = options || {};\r\n\r\n _.defaults(options, {\r\n w: \"majority\"\r\n });\r\n\r\n if (!_.isPlainObject(conditions)) conditions = {\r\n _id: conditions\r\n };\r\n\r\n return Bluebird.resolve().then(() => {\r\n conditions = this._helpers.convertToDB(conditions);\r\n\r\n return new Bluebird((resolve, reject) => {\r\n if(options.single) return this.collection.deleteOne(conditions, options, (err, response) => {\r\n if (err) return reject(err);\r\n return resolve(response.result.n);\r\n });\r\n \r\n this.collection.deleteMany(conditions, options, (err, response) => {\r\n if (err) return reject(err);\r\n return resolve(response.result.n);\r\n });\r\n });\r\n }).then((count) => {\r\n if (count === 1) this._cache.clear(conditions);\r\n return Bluebird.resolve(count);\r\n }).nodeify(callback);\r\n }\r\n\r\n aggregate(pipeline: AggregationPipeline.Stage[]): Bluebird {\r\n return new Bluebird((resolve, reject) => {\r\n this.collection.aggregate(pipeline, (err, results) => {\r\n if(err) return reject(err);\r\n return resolve(results);\r\n });\r\n });\r\n }\r\n\r\n /**\r\n * Ensures that the given index is created for the collection\r\n * @param {Object} specification The index specification object used by MongoDB\r\n * @param {function(Error, String)} callback A callback which is triggered when the operation completes\r\n * @returns {Promise} The name of the index\r\n */\r\n ensureIndex(specification: Index.IndexSpecification, callback?: General.Callback): Bluebird;\r\n /**\r\n * Ensures that the given index is created for the collection\r\n * @param {Object} specification The index specification object used by MongoDB\r\n * @param {MongoDB.IndexOptions} options The options dictating how the index is created and behaves\r\n * @param {function(Error, String)} callback A callback which is triggered when the operation completes\r\n * @returns {Promise} The name of the index\r\n */\r\n ensureIndex(specification: Index.IndexSpecification, options: MongoDB.IndexOptions, callback?: General.Callback): Bluebird;\r\n ensureIndex(specification: Index.IndexSpecification, options?: MongoDB.IndexOptions, callback?: General.Callback): Bluebird {\r\n if (typeof options === \"function\") {\r\n callback = >options;\r\n options = {};\r\n }\r\n\r\n return new Bluebird((resolve, reject) => {\r\n this.collection.createIndex(specification, options, (err, name: any) => {\r\n if (err) return reject(err);\r\n return resolve(name);\r\n });\r\n }).nodeify(callback);\r\n }\r\n\r\n /**\r\n * Ensures that all indexes defined in the model's options are created\r\n * @param {function(Error, String[])} callback A callback which is triggered when the operation completes\r\n * @returns {Promise} The names of the indexes\r\n */\r\n ensureIndexes(callback?: General.Callback): Bluebird {\r\n return Bluebird.resolve(this._indexes).map((index: Index.Index | Index.IndexSpecification) => {\r\n return this.ensureIndex((index).spec || index, (index).options || {});\r\n }).nodeify(callback);\r\n }\r\n\r\n /**\r\n * Drops the index with the specified name if it exists in the collection\r\n * @param {String} name The name of the index to remove\r\n * @param {function(Error, Boolean)} callback A callback which is triggered when the operation completes\r\n * @returns {Promise} Whether the index was dropped\r\n */\r\n dropIndex(name: string, callback?: General.Callback): Bluebird;\r\n /**\r\n * Drops the index if it exists in the collection\r\n * @param {IndexSpecification} index The index to remove\r\n * @param {function(Error, Boolean)} callback A callback which is triggered when the operation completes\r\n * @returns {Promise} Whether the index was dropped\r\n */\r\n dropIndex(index: Index.IndexSpecification, callback?: General.Callback): Bluebird;\r\n dropIndex(specification: string | Index.IndexSpecification, callback?: General.Callback): Bluebird {\r\n let index: string;\r\n\r\n if (typeof (specification) === \"string\") index = specification;\r\n else {\r\n index = _(specification).map((direction, key) => `${key}_${direction}`).reduce((x, y) => `${x}_${y}`);\r\n }\r\n\r\n return new Bluebird((resolve, reject) => {\r\n this.collection.dropIndex(index, (err, result: { ok: number }) => {\r\n if (err) return reject(err);\r\n return resolve(!!result.ok);\r\n });\r\n }).nodeify(callback);\r\n }\r\n\r\n /**\r\n * Removes all indexes (except for _id) from the collection\r\n * @param {function(Error, Boolean)} callback A callback which is triggered when the operation completes\r\n * @returns {Promise} Whether the indexes were dropped\r\n */\r\n dropIndexes(callback?: General.Callback): Bluebird {\r\n return new Bluebird((resolve, reject) => {\r\n this.collection.dropIndexes((err, count) => {\r\n if (err) return reject(err);\r\n return resolve(count);\r\n });\r\n }).nodeify(callback);\r\n }\r\n}\r\n"],"sourceRoot":"/source/"} \ No newline at end of file +{"version":3,"sources":["lib/Model.ts"],"names":[],"mappings":";AA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EAAE,MAAM;YACzC,IAAI,CAAC,UAAU,CAAC,SAAS,CAAC,KAAK,EAAE,CAAC,GAAG,EAAE,MAAsB;gBACzD,EAAE,CAAC,CAAC,GAAG,CAAC;oBAAC,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;gBAC5B,MAAM,CAAC,OAAO,CAAM,CAAC,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;YACrC,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC;IACzB,CAAC;IAED;;;;OAIG;IACH,WAAW,CAAC,QAAoC;QAC5C,MAAM,CAAC,IAAI,QAAQ,CAAM,CAAC,OAAO,EAAE,MAAM;YACrC,IAAI,CAAC,UAAU,CAAC,WAAW,CAAC,CAAC,GAAG,EAAE,KAAK;gBACnC,EAAE,CAAC,CAAC,GAAG,CAAC;oBAAC,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;gBAC5B,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;YAC1B,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC;IACzB,CAAC;AACL,CAAC;AA3tBY,aAAK,QA2tBjB,CAAA","file":"lib/Model.js","sourcesContent":["import * as MongoDB from \"mongodb\";\r\nimport * as Bluebird from \"bluebird\";\r\nimport * as util from \"util\";\r\nimport * as _ from \"lodash\";\r\nimport * as Skmatc from \"skmatc\";\r\n\r\nimport {Core} from \"./Core\";\r\nimport {Instance} from \"./Instance\";\r\nimport {Schema} from \"./Schema\";\r\nimport {Hooks} from \"./Hooks\";\r\nimport {Plugin} from \"./Plugins\";\r\nimport {Cache} from \"./Cache\";\r\nimport {CacheDirector} from \"./CacheDirector\";\r\nimport * as General from \"./General\";\r\nimport {Cursor} from \"./Cursor\";\r\nimport * as Index from \"./Index\";\r\nimport * as ModelOptions from \"./ModelOptions\";\r\n\r\nimport {Omnom} from \"./utils/Omnom\";\r\nimport {ModelCache} from \"./ModelCache\";\r\nimport {ModelHelpers} from \"./ModelHelpers\";\r\nimport {ModelHandlers} from \"./ModelHandlers\";\r\nimport * as ModelInterfaces from \"./ModelInterfaces\";\r\nimport {ModelSpecificInstance} from \"./ModelSpecificInstance\";\r\nimport {InstanceImplementation} from \"./InstanceInterface\";\r\nimport {Transforms, DefaultTransforms} from \"./Transforms\";\r\nimport * as AggregationPipeline from \"./Aggregate\";\r\n\r\n/**\r\n * An Iridium Model which represents a structured MongoDB collection.\r\n * Models expose the methods you will generally use to query those collections, and ensure that\r\n * the results of those queries are returned as {TInstance} instances.\r\n *\r\n * @param TDocument The interface used to determine the schema of documents in the collection.\r\n * @param TInstance The interface or class used to represent collection documents in the JS world.\r\n *\r\n * @class\r\n */\r\nexport class Model {\r\n /**\r\n * Creates a new Iridium model representing a given ISchema and backed by a collection whose name is specified\r\n * @param core The Iridium core that this model should use for database access\r\n * @param instanceType The class which will be instantiated for each document retrieved from the database\r\n * @constructor\r\n */\r\n constructor(core: Core, instanceType: InstanceImplementation) {\r\n if (!(core instanceof Core)) throw new Error(\"You failed to provide a valid Iridium core for this model\");\r\n if (typeof instanceType !== \"function\") throw new Error(\"You failed to provide a valid instance constructor for this model\");\r\n if (typeof instanceType.collection !== \"string\" || !instanceType.collection) throw new Error(\"You failed to provide a valid collection name for this model\");\r\n if (!_.isPlainObject(instanceType.schema) || instanceType.schema._id === undefined) throw new Error(\"You failed to provide a valid schema for this model\");\r\n\r\n this._core = core;\r\n\r\n this.loadExternal(instanceType);\r\n this.onNewModel();\r\n this.loadInternal();\r\n }\r\n\r\n /**\r\n * Loads any externally available properties (generally accessed using public getters/setters).\r\n */\r\n private loadExternal(instanceType: InstanceImplementation) {\r\n this._collection = instanceType.collection;\r\n this._schema = instanceType.schema;\r\n this._hooks = instanceType;\r\n this._cacheDirector = instanceType.cache;\r\n this._transforms = instanceType.transforms || {};\r\n this._validators = instanceType.validators || [];\r\n this._indexes = instanceType.indexes || [];\r\n\r\n if(!this._schema._id) this._schema._id = MongoDB.ObjectID;\r\n\r\n if(this._schema._id === MongoDB.ObjectID && !this._transforms._id)\r\n this._transforms._id = DefaultTransforms.ObjectID;\r\n\r\n if ((instanceType).prototype instanceof Instance)\r\n this._Instance = ModelSpecificInstance(this, instanceType);\r\n else\r\n this._Instance = instanceType.bind(undefined, this);\r\n }\r\n\r\n /**\r\n * Loads any internally (protected/private) properties and helpers only used within Iridium itself.\r\n */\r\n private loadInternal() {\r\n this._cache = new ModelCache(this);\r\n this._helpers = new ModelHelpers(this);\r\n this._handlers = new ModelHandlers(this);\r\n }\r\n\r\n /**\r\n * Process any callbacks and plugin delegation for the creation of this model.\r\n * It will generally be called whenever a new Iridium Core is created, however is\r\n * more specifically tied to the lifespan of the models themselves.\r\n */\r\n private onNewModel() {\r\n this._core.plugins.forEach(plugin => plugin.newModel && plugin.newModel(this));\r\n }\r\n\r\n private _helpers: ModelHelpers;\r\n /**\r\n * Provides helper methods used by Iridium for common tasks\r\n * @returns A set of helper methods which are used within Iridium for common tasks\r\n */\r\n get helpers(): ModelHelpers {\r\n return this._helpers;\r\n }\r\n\r\n private _handlers: ModelHandlers;\r\n /**\r\n * Provides helper methods used by Iridium for hook delegation and common processes\r\n * @returns A set of helper methods which perform common event and response handling tasks within Iridium.\r\n */\r\n get handlers(): ModelHandlers {\r\n return this._handlers;\r\n }\r\n\r\n private _hooks: Hooks = {};\r\n\r\n /**\r\n * Gets the even hooks subscribed on this model for a number of different state changes.\r\n * These hooks are primarily intended to allow lifecycle manipulation logic to be added\r\n * in the user's model definition, allowing tasks such as the setting of default values\r\n * or automatic client-side joins to take place.\r\n */\r\n get hooks(): Hooks {\r\n return this._hooks;\r\n }\r\n\r\n private _schema: Schema;\r\n /**\r\n * Gets the schema dictating the data structure represented by this model.\r\n * The schema is used by skmatc to validate documents before saving to the database, however\r\n * until MongoDB 3.1 becomes widely available (with server side validation support) we are\r\n * limited in our ability to validate certain types of updates. As such, these validations\r\n * act more as a data-integrity check than anything else, unless you purely make use of Omnom\r\n * updates within instances.\r\n * @public\r\n * @returns The defined validation schema for this model\r\n */\r\n get schema(): Schema {\r\n return this._schema;\r\n }\r\n\r\n private _core: Core;\r\n /**\r\n * Gets the Iridium core that this model is associated with.\r\n * @public\r\n * @returns The Iridium core that this model is bound to\r\n */\r\n get core(): Core {\r\n return this._core;\r\n }\r\n\r\n private _collection: string;\r\n /**\r\n * Gets the underlying MongoDB collection from which this model's documents are retrieved.\r\n * You can make use of this object if you require any low level access to the MongoDB collection,\r\n * however we recommend you make use of the Iridium methods whereever possible, as we cannot\r\n * guarantee the accuracy of the type definitions for the underlying MongoDB driver.\r\n * @public\r\n * @returns {Collection}\r\n */\r\n get collection(): MongoDB.Collection {\r\n if (!this.core.connection) throw new Error(\"Iridium Core not connected to a database.\");\r\n return this.core.connection.collection(this._collection);\r\n }\r\n\r\n /**\r\n * Gets the name of the underlying MongoDB collection from which this model's documents are retrieved\r\n * @public\r\n */\r\n get collectionName(): string {\r\n return this._collection;\r\n }\r\n\r\n /**\r\n * Sets the name of the underlying MongoDB collection from which this model's documents are retrieved\r\n * @public\r\n */\r\n set collectionName(value: string) {\r\n this._collection = value;\r\n }\r\n\r\n private _cacheDirector: CacheDirector;\r\n /**\r\n * Gets the cache controller which dictates which queries will be cached, and under which key\r\n * @public\r\n * @returns {CacheDirector}\r\n */\r\n get cacheDirector(): CacheDirector {\r\n return this._cacheDirector;\r\n }\r\n\r\n private _cache: ModelCache;\r\n /**\r\n * Gets the cache responsible for storing objects for quick retrieval under certain conditions\r\n * @public\r\n * @returns {ModelCache}\r\n */\r\n get cache(): ModelCache {\r\n return this._cache;\r\n }\r\n\r\n private _Instance: ModelInterfaces.ModelSpecificInstanceConstructor;\r\n\r\n /**\r\n * Gets the constructor responsible for creating instances for this model\r\n */\r\n get Instance(): ModelInterfaces.ModelSpecificInstanceConstructor {\r\n return this._Instance;\r\n }\r\n\r\n private _transforms: Transforms;\r\n\r\n /**\r\n * Gets the transforms which are applied whenever a document is received from the database, or\r\n * prior to storing a document in the database. Tasks such as converting an ObjectID to a string\r\n * and vice versa are all listed in this object.\r\n */\r\n get transforms() {\r\n return this._transforms;\r\n }\r\n\r\n private _validators: Skmatc.Validator[];\r\n\r\n /**\r\n * Gets the custom validation types available for this model. These validators are added to the\r\n * default skmatc validators, as well as those available through plugins, for use when checking\r\n * your instances.\r\n */\r\n get validators() {\r\n return this._validators;\r\n }\r\n\r\n private _indexes: (Index.Index | Index.IndexSpecification)[];\r\n\r\n /**\r\n * Gets the indexes which Iridium will manage on this model's database collection.\r\n */\r\n get indexes() {\r\n return this._indexes;\r\n }\r\n\r\n /**\r\n * Retrieves all documents in the collection and wraps them as instances\r\n * @param {function(Error, TInstance[])} callback An optional callback which will be triggered when results are available\r\n * @returns {Promise}\r\n */\r\n find(): Cursor;\r\n /**\r\n * Returns all documents in the collection which match the conditions and wraps them as instances\r\n * @param {Object} conditions The MongoDB query dictating which documents to return\r\n * @returns {Promise}\r\n */\r\n find(conditions: { _id?: any, [key: string]: any } | any): Cursor;\r\n /**\r\n * Returns all documents in the collection which match the conditions\r\n * @param {Object} conditions The MongoDB query dictating which documents to return\r\n * @param {Object} fields The fields to include or exclude from the document\r\n * @returns {Promise}\r\n */\r\n find(conditions: { _id?: any, [key: string]: any } | any, fields: { [name: string]: number }): Cursor;\r\n find(conditions?: { _id?: any, [key: string]: any } | any, fields?: any): Cursor {\r\n conditions = conditions || {};\r\n\r\n if (!_.isPlainObject(conditions)) conditions = { _id: conditions };\r\n conditions = this._helpers.convertToDB(conditions);\r\n\r\n let cursor = this.collection.find(conditions);\r\n \r\n if(fields)\r\n cursor = cursor.project(fields);\r\n\r\n return new Cursor(this, conditions, cursor);\r\n }\r\n\r\n /**\r\n * Retrieves a single document from the collection and wraps it as an instance\r\n * @param {function(Error, TInstance)} callback An optional callback which will be triggered when a result is available\r\n * @returns {Promise}\r\n */\r\n get(callback?: General.Callback): Bluebird;\r\n /**\r\n * Retrieves a single document from the collection with the given ID and wraps it as an instance\r\n * @param {any} id The document's unique _id field value in downstream format\r\n * @param {function(Error, TInstance)} callback An optional callback which will be triggered when a result is available\r\n * @returns {Promise}\r\n */\r\n get(id: any, callback?: General.Callback): Bluebird;\r\n /**\r\n * Retrieves a single document from the collection which matches the conditions\r\n * @param {Object} conditions The MongoDB query dictating which document to return\r\n * @param {function(Error, TInstance)} callback An optional callback which will be triggered when a result is available\r\n * @returns {Promise}\r\n */\r\n get(conditions: { _id?: any, [key: string]: any }, callback?: General.Callback): Bluebird;\r\n /**\r\n * Retrieves a single document from the collection with the given ID and wraps it as an instance\r\n * @param {any} id The document's unique _id field value in downstream format\r\n * @param {QueryOptions} options The options dictating how this function behaves\r\n * @param {function(Error, TInstance)} callback An optional callback which will be triggered when a result is available\r\n * @returns {Promise}\r\n */\r\n get(id: any, options: ModelOptions.QueryOptions, callback?: General.Callback): Bluebird;\r\n /**\r\n * Retrieves a single document from the collection which matches the conditions\r\n * @param {Object} conditions The MongoDB query dictating which document to return\r\n * @param {QueryOptions} options The options dictating how this function behaves\r\n * @param {function(Error, TInstance)} callback An optional callback which will be triggered when a result is available\r\n * @returns {Promise}\r\n */\r\n get(conditions: { _id?: any, [key: string]: any }, options: ModelOptions.QueryOptions, callback?: General.Callback): Bluebird;\r\n get(...args: any[]): Bluebird {\r\n return this.findOne.apply(this, args);\r\n }\r\n\r\n /**\r\n * Retrieves a single document from the collection and wraps it as an instance\r\n * @param {function(Error, TInstance)} callback An optional callback which will be triggered when a result is available\r\n * @returns {Promise}\r\n */\r\n findOne(callback?: General.Callback): Bluebird;\r\n /**\r\n * Retrieves a single document from the collection with the given ID and wraps it as an instance\r\n * @param {any} id The document's unique _id field value in downstream format\r\n * @param {function(Error, TInstance)} callback An optional callback which will be triggered when a result is available\r\n * @returns {Promise}\r\n */\r\n findOne(id: any, callback?: General.Callback): Bluebird;\r\n /**\r\n * Retrieves a single document from the collection which matches the conditions\r\n * @param {Object} conditions The MongoDB query dictating which document to return\r\n * @param {function(Error, TInstance)} callback An optional callback which will be triggered when a result is available\r\n * @returns {Promise}\r\n */\r\n findOne(conditions: { _id?: any, [key: string]: any }, callback?: General.Callback): Bluebird;\r\n /**\r\n * Retrieves a single document from the collection with the given ID and wraps it as an instance\r\n * @param {any} id The document's unique _id field value in downstream format\r\n * @param {QueryOptions} options The options dictating how this function behaves\r\n * @param {function(Error, TInstance)} callback An optional callback which will be triggered when a result is available\r\n * @returns {Promise}\r\n */\r\n findOne(id: any, options: ModelOptions.QueryOptions, callback?: General.Callback): Bluebird;\r\n /**\r\n * Retrieves a single document from the collection which matches the conditions\r\n * @param {Object} conditions The MongoDB query dictating which document to return\r\n * @param {QueryOptions} options The options dictating how this function behaves\r\n * @param {function(Error, TInstance)} callback An optional callback which will be triggered when a result is available\r\n * @returns {Promise}\r\n */\r\n findOne(conditions: { _id?: any, [key: string]: any }, options: ModelOptions.QueryOptions, callback?: General.Callback): Bluebird;\r\n findOne(...args: any[]): Bluebird {\r\n let conditions: { _id?: any, [key: string]: any } = null;\r\n let options: ModelOptions.QueryOptions = null;\r\n let callback: General.Callback = null;\r\n\r\n for (let argI = 0; argI < args.length; argI++) {\r\n if (typeof args[argI] === \"function\") callback = callback || args[argI];\r\n else if (_.isPlainObject(args[argI])) {\r\n if (conditions) options = args[argI];\r\n else conditions = args[argI];\r\n }\r\n else conditions = { _id: args[argI] };\r\n }\r\n\r\n conditions = conditions || {};\r\n options = options || {};\r\n\r\n _.defaults(options, {\r\n cache: true\r\n });\r\n\r\n return Bluebird.resolve().bind(this).then(() => {\r\n conditions = this._helpers.convertToDB(conditions);\r\n\r\n return this._cache.get(conditions);\r\n }).then((cachedDocument: TDocument) => {\r\n if (cachedDocument) return cachedDocument;\r\n return new Bluebird((resolve, reject) => {\r\n let cursor = this.collection.find(conditions);\r\n \r\n if(options.sort)\r\n cursor = cursor.sort(options.sort);\r\n \r\n if(typeof options.skip === \"number\")\r\n cursor = cursor.skip(options.skip);\r\n \r\n cursor = cursor.limit(1);\r\n \r\n if(options.fields)\r\n cursor = cursor.project(options.fields);\r\n \r\n return cursor.next((err, result) => {\r\n if (err) return reject(err);\r\n return resolve(result);\r\n });\r\n });\r\n }).then((document: TDocument) => {\r\n if (!document) return null;\r\n return this._handlers.documentReceived(conditions, document, (document, isNew?, isPartial?) => this._helpers.wrapDocument(document, isNew, isPartial), options);\r\n }).nodeify(callback);\r\n }\r\n\r\n /**\r\n * Inserts an object into the collection after validating it against this model's schema\r\n * @param {Object} object The object to insert into the collection\r\n * @param {function(Error, TInstance)} callback A callback which is triggered when the operation completes\r\n * @returns {Promise}\r\n */\r\n create(objects: TDocument, callback?: General.Callback): Bluebird;\r\n /**\r\n * Inserts an object into the collection after validating it against this model's schema\r\n * @param {Object} object The object to insert into the collection\r\n * @param {CreateOptions} options The options dictating how this function behaves\r\n * @param {function(Error, TInstance)} callback A callback which is triggered when the operation completes\r\n * @returns {Promise}\r\n */\r\n create(objects: TDocument, options: ModelOptions.CreateOptions, callback?: General.Callback): Bluebird;\r\n /**\r\n * Inserts the objects into the collection after validating them against this model's schema\r\n * @param {Object[]} objects The objects to insert into the collection\r\n * @param {function(Error, TInstance)} callback A callback which is triggered when the operation completes\r\n * @returns {Promise}\r\n */\r\n create(objects: TDocument[], callback?: General.Callback): Bluebird;\r\n /**\r\n * Inserts the objects into the collection after validating them against this model's schema\r\n * @param {Object[]} objects The objects to insert into the collection\r\n * @param {CreateOptions} options The options dictating how this function behaves\r\n * @param {function(Error, TInstance)} callback A callback which is triggered when the operation completes\r\n * @returns {Promise}\r\n */\r\n create(objects: TDocument[], options: ModelOptions.CreateOptions, callback?: General.Callback): Bluebird;\r\n create(...args: any[]): Bluebird {\r\n return this.insert.apply(this, args);\r\n }\r\n\r\n /**\r\n * Inserts an object into the collection after validating it against this model's schema\r\n * @param {Object} object The object to insert into the collection\r\n * @param {function(Error, TInstance)} callback A callback which is triggered when the operation completes\r\n * @returns {Promise}\r\n */\r\n insert(objects: TDocument, callback?: General.Callback): Bluebird;\r\n /**\r\n * Inserts an object into the collection after validating it against this model's schema\r\n * @param {Object} object The object to insert into the collection\r\n * @param {CreateOptions} options The options dictating how this function behaves\r\n * @param {function(Error, TInstance)} callback A callback which is triggered when the operation completes\r\n * @returns {Promise}\r\n */\r\n insert(objects: TDocument, options: ModelOptions.CreateOptions, callback?: General.Callback): Bluebird;\r\n /**\r\n * Inserts the objects into the collection after validating them against this model's schema\r\n * @param {Object[]} objects The objects to insert into the collection\r\n * @param {function(Error, TInstance[])} callback A callback which is triggered when the operation completes\r\n * @returns {Promise}\r\n */\r\n insert(objects: TDocument[], callback?: General.Callback): Bluebird;\r\n /**\r\n * Inserts the objects into the collection after validating them against this model's schema\r\n * @param {Object[]} objects The objects to insert into the collection\r\n * @param {CreateOptions} options The options dictating how this function behaves\r\n * @param {function(Error, TInstance[])} callback A callback which is triggered when the operation completes\r\n * @returns {Promise}\r\n */\r\n insert(objects: TDocument[], options: ModelOptions.CreateOptions, callback?: General.Callback): Bluebird;\r\n insert(objs: TDocument | TDocument[], ...args: any[]): Bluebird {\r\n let objects: TDocument[];\r\n let options: ModelOptions.CreateOptions = {};\r\n let callback: General.Callback = null;\r\n if (typeof args[0] === \"function\") callback = args[0];\r\n else {\r\n options = args[0];\r\n callback = args[1];\r\n }\r\n\r\n if (Array.isArray(objs))\r\n objects = objs;\r\n else\r\n objects = [objs];\r\n\r\n options = options || {};\r\n _.defaults(options, {\r\n w: \"majority\",\r\n forceServerObjectId: true\r\n });\r\n\r\n return Bluebird.resolve().then(() => {\r\n let queryOptions = { w: options.w, upsert: options.upsert, new: true };\r\n\r\n if (options.upsert) {\r\n let docs = this._handlers.creatingDocuments(objects);\r\n return docs.map((object: { _id: any; }) => {\r\n return new Bluebird((resolve, reject) => {\r\n this.collection.findOneAndUpdate({ _id: object._id }, object, {\r\n upsert: options.upsert,\r\n returnOriginal: false\r\n }, (err, result) => {\r\n if (err) return reject(err);\r\n return resolve(result.value);\r\n });\r\n });\r\n });\r\n }\r\n else\r\n return this._handlers.creatingDocuments(objects).then(objects => _.chunk(objects, 1000)).map((objects: any[]) => {\r\n return new Bluebird((resolve, reject) => {\r\n this.collection.insertMany(objects, queryOptions, (err, result) => {\r\n if (err) return reject(err);\r\n return resolve(result.ops);\r\n });\r\n });\r\n }).then(results => _.flatten(results));\r\n }).map((inserted: any) => {\r\n return this._handlers.documentReceived(null, inserted, (document, isNew?, isPartial?) => this._helpers.wrapDocument(document, isNew, isPartial), { cache: options.cache });\r\n }).then((results: TInstance[]) => {\r\n if (Array.isArray(objs)) return results;\r\n return results[0];\r\n }).nodeify(callback);\r\n }\r\n\r\n /**\r\n * Updates the documents in the backing collection which match the conditions using the given update instructions\r\n * @param {Object} conditions The conditions which determine which documents will be updated\r\n * @param {Object} changes The changes to make to the documents\r\n * @param {function(Error, Number)} callback A callback which is triggered when the operation completes\r\n */\r\n update(conditions: { _id?: any, [key: string]: any } | any, changes: any, callback?: General.Callback): Bluebird;\r\n /**\r\n * Updates the documents in the backing collection which match the conditions using the given update instructions\r\n * @param {Object} conditions The conditions which determine which documents will be updated\r\n * @param {Object} changes The changes to make to the documents\r\n * @param {UpdateOptions} options The options which dictate how this function behaves\r\n * @param {function(Error, Number)} callback A callback which is triggered when the operation completes\r\n */\r\n update(conditions: { _id?: any, [key: string]: any } | any, changes: any, options: ModelOptions.UpdateOptions, callback?: General.Callback): Bluebird;\r\n update(conditions: { _id?: any, [key: string]: any } | any, changes: any, options?: ModelOptions.UpdateOptions, callback?: General.Callback): Bluebird {\r\n if (typeof options === \"function\") {\r\n callback = >options;\r\n options = {};\r\n }\r\n\r\n options = options || {};\r\n\r\n if (!_.isPlainObject(conditions)) conditions = {\r\n _id: conditions\r\n };\r\n\r\n _.defaults(options, {\r\n w: \"majority\",\r\n multi: true\r\n });\r\n\r\n return Bluebird.resolve().then(() => {\r\n conditions = this._helpers.convertToDB(conditions);\r\n\r\n return new Bluebird((resolve, reject) => {\r\n this.collection.updateMany(conditions, changes, options, (err, response) => {\r\n if (err) return reject(err);\r\n\r\n // New MongoDB 2.6+ response type\r\n if (response.result && response.result.nModified !== undefined) return resolve(response.result.nModified);\r\n\r\n // Legacy response type\r\n return resolve(response.result.n);\r\n });\r\n })\r\n }).nodeify(callback);\r\n }\r\n\r\n /**\r\n * Counts the number of documents in the collection\r\n * @param {function(Error, Number)} callback A callback which is triggered when the operation completes\r\n * @returns {Promise}\r\n */\r\n count(callback?: General.Callback): Bluebird;\r\n /**\r\n * Counts the number of documents in the collection which match the conditions provided\r\n * @param {Object} conditions The conditions which determine whether an object is counted or not\r\n * @param {function(Error, Number)} callback A callback which is triggered when the operation completes\r\n * @returns {Promise}\r\n */\r\n count(conditions: { _id?: any, [key: string]: any } | any, callback?: General.Callback): Bluebird;\r\n count(conds?: any, callback?: General.Callback): Bluebird {\r\n let conditions: { _id?: any, [key: string]: any } = <{ _id?: any, [key: string]: any }>conds;\r\n if (typeof conds === \"function\") {\r\n callback = >conds;\r\n conditions = {};\r\n }\r\n\r\n conditions = conditions || {};\r\n\r\n if (!_.isPlainObject(conditions)) conditions = {\r\n _id: conditions\r\n };\r\n\r\n return Bluebird.resolve().then(() => {\r\n conditions = this._helpers.convertToDB(conditions);\r\n\r\n return new Bluebird((resolve, reject) => {\r\n this.collection.count(conditions, (err, results) => {\r\n if (err) return reject(err);\r\n return resolve(results);\r\n });\r\n });\r\n }).nodeify(callback);\r\n }\r\n\r\n /**\r\n * Removes all documents from the collection\r\n * @param {function(Error, Number)} 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 /**\r\n * Removes all documents from the collection which match the conditions\r\n * @param {Object} conditions The conditions determining whether an object is removed or not\r\n * @param {function(Error, Number)} callback A callback which is triggered when the operation completes\r\n * @returns {Promise}\r\n */\r\n remove(conditions: { _id?: any, [key: string]: any } | any, callback?: General.Callback): Bluebird;\r\n /**\r\n * Removes all documents from the collection which match the conditions\r\n * @param {Object} conditions The conditions determining whether an object is removed or not\r\n * @param {Object} options The options controlling the way in which the function behaves\r\n * @param {function(Error, Number)} callback A callback which is triggered when the operation completes\r\n * @returns {Promise}\r\n */\r\n remove(conditions: { _id?: any, [key: string]: any }, options: ModelOptions.RemoveOptions, callback?: General.Callback): Bluebird;\r\n remove(conds?: any, options?: ModelOptions.RemoveOptions, callback?: General.Callback): Bluebird {\r\n let conditions: { _id?: any, [key: string]: any } = <{ _id?: any, [key: string]: any }>conds;\r\n\r\n if (typeof options === \"function\") {\r\n callback = >options;\r\n options = {};\r\n }\r\n\r\n if (typeof conds === \"function\") {\r\n callback = >conds;\r\n options = {};\r\n conditions = {};\r\n }\r\n\r\n conditions = conditions || {};\r\n options = options || {};\r\n\r\n _.defaults(options, {\r\n w: \"majority\"\r\n });\r\n\r\n if (!_.isPlainObject(conditions)) conditions = {\r\n _id: conditions\r\n };\r\n\r\n return Bluebird.resolve().then(() => {\r\n conditions = this._helpers.convertToDB(conditions);\r\n\r\n return new Bluebird((resolve, reject) => {\r\n if(options.single) return this.collection.deleteOne(conditions, options, (err, response) => {\r\n if (err) return reject(err);\r\n return resolve(response.result.n);\r\n });\r\n \r\n this.collection.deleteMany(conditions, options, (err, response) => {\r\n if (err) return reject(err);\r\n return resolve(response.result.n);\r\n });\r\n });\r\n }).then((count) => {\r\n if (count === 1) this._cache.clear(conditions);\r\n return Bluebird.resolve(count);\r\n }).nodeify(callback);\r\n }\r\n\r\n aggregate(pipeline: AggregationPipeline.Stage[]): Bluebird {\r\n return new Bluebird((resolve, reject) => {\r\n this.collection.aggregate(pipeline, (err, results) => {\r\n if(err) return reject(err);\r\n return resolve(results);\r\n });\r\n });\r\n }\r\n\r\n /**\r\n * Ensures that the given index is created for the collection\r\n * @param {Object} specification The index specification object used by MongoDB\r\n * @param {function(Error, String)} callback A callback which is triggered when the operation completes\r\n * @returns {Promise} The name of the index\r\n */\r\n ensureIndex(specification: Index.IndexSpecification, callback?: General.Callback): Bluebird;\r\n /**\r\n * Ensures that the given index is created for the collection\r\n * @param {Object} specification The index specification object used by MongoDB\r\n * @param {MongoDB.IndexOptions} options The options dictating how the index is created and behaves\r\n * @param {function(Error, String)} callback A callback which is triggered when the operation completes\r\n * @returns {Promise} The name of the index\r\n */\r\n ensureIndex(specification: Index.IndexSpecification, options: MongoDB.IndexOptions, callback?: General.Callback): Bluebird;\r\n ensureIndex(specification: Index.IndexSpecification, options?: MongoDB.IndexOptions, callback?: General.Callback): Bluebird {\r\n if (typeof options === \"function\") {\r\n callback = >options;\r\n options = {};\r\n }\r\n\r\n return new Bluebird((resolve, reject) => {\r\n this.collection.createIndex(specification, options, (err, name: any) => {\r\n if (err) return reject(err);\r\n return resolve(name);\r\n });\r\n }).nodeify(callback);\r\n }\r\n\r\n /**\r\n * Ensures that all indexes defined in the model's options are created\r\n * @param {function(Error, String[])} callback A callback which is triggered when the operation completes\r\n * @returns {Promise} The names of the indexes\r\n */\r\n ensureIndexes(callback?: General.Callback): Bluebird {\r\n return Bluebird.resolve(this._indexes).map((index: Index.Index | Index.IndexSpecification) => {\r\n return this.ensureIndex((index).spec || index, (index).options || {});\r\n }).nodeify(callback);\r\n }\r\n\r\n /**\r\n * Drops the index with the specified name if it exists in the collection\r\n * @param {String} name The name of the index to remove\r\n * @param {function(Error, Boolean)} callback A callback which is triggered when the operation completes\r\n * @returns {Promise} Whether the index was dropped\r\n */\r\n dropIndex(name: string, callback?: General.Callback): Bluebird;\r\n /**\r\n * Drops the index if it exists in the collection\r\n * @param {IndexSpecification} index The index to remove\r\n * @param {function(Error, Boolean)} callback A callback which is triggered when the operation completes\r\n * @returns {Promise} Whether the index was dropped\r\n */\r\n dropIndex(index: Index.IndexSpecification, callback?: General.Callback): Bluebird;\r\n dropIndex(specification: string | Index.IndexSpecification, callback?: General.Callback): Bluebird {\r\n let index: string;\r\n\r\n if (typeof (specification) === \"string\") index = specification;\r\n else {\r\n index = _(specification).map((direction, key) => `${key}_${direction}`).reduce((x, y) => `${x}_${y}`);\r\n }\r\n\r\n return new Bluebird((resolve, reject) => {\r\n this.collection.dropIndex(index, (err, result: { ok: number }) => {\r\n if (err) return reject(err);\r\n return resolve(!!result.ok);\r\n });\r\n }).nodeify(callback);\r\n }\r\n\r\n /**\r\n * Removes all indexes (except for _id) from the collection\r\n * @param {function(Error, Boolean)} callback A callback which is triggered when the operation completes\r\n * @returns {Promise} Whether the indexes were dropped\r\n */\r\n dropIndexes(callback?: General.Callback): Bluebird {\r\n return new Bluebird((resolve, reject) => {\r\n this.collection.dropIndexes((err, count) => {\r\n if (err) return reject(err);\r\n return resolve(count);\r\n });\r\n }).nodeify(callback);\r\n }\r\n}\r\n"],"sourceRoot":"/source/"} \ No newline at end of file diff --git a/dist/lib/ModelCache.js b/dist/lib/ModelCache.js index ce90d1d..aef065b 100644 --- a/dist/lib/ModelCache.js +++ b/dist/lib/ModelCache.js @@ -1,31 +1,30 @@ "use strict"; -var Bluebird = require("bluebird"); +const Bluebird = require("bluebird"); /** * A centralized class which ties the cache and cache directors together in a cohesive way * for use by Iridium. * @internal */ -var ModelCache = (function () { - function ModelCache(model) { +class ModelCache { + constructor(model) { this.model = model; } - ModelCache.prototype.set = function (value) { + set(value) { if (!this.model.cacheDirector || !this.model.cacheDirector.valid(value)) return; this.model.core.cache.set(this.model.cacheDirector.buildKey(value), value); - }; - ModelCache.prototype.get = function (conditions) { + } + get(conditions) { if (!this.model.cacheDirector || !this.model.cacheDirector.validQuery(conditions)) return Bluebird.resolve(null); return Bluebird.resolve(this.model.core.cache.get(this.model.cacheDirector.buildQueryKey(conditions))); - }; - ModelCache.prototype.clear = function (conditions) { + } + clear(conditions) { if (!this.model.cacheDirector || !this.model.cacheDirector.validQuery(conditions)) return; this.model.core.cache.clear(this.model.cacheDirector.buildQueryKey(conditions)); - }; - return ModelCache; -}()); + } +} exports.ModelCache = ModelCache; //# sourceMappingURL=ModelCache.js.map diff --git a/dist/lib/ModelCache.js.map b/dist/lib/ModelCache.js.map index 995a478..67536e5 100644 --- a/dist/lib/ModelCache.js.map +++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C,IAAI,CAAC,KAAK,CAAC,aAAa,CAAC,aAAa,CAAC,UAAU,CAAC,CAAC,CAAC;IACpF,CAAC;IACL,iBAAC;AAAD,CAnBA,AAmBC,IAAA;AAnBY,kBAAU,aAmBtB,CAAA","file":"lib/ModelCache.js","sourcesContent":["import {Model} from \"./Model\";\r\nimport * as Bluebird from \"bluebird\";\r\n\r\n/**\r\n * A centralized class which ties the cache and cache directors together in a cohesive way\r\n * for use by Iridium.\r\n * @internal\r\n */\r\nexport class ModelCache {\r\n constructor(public model: Model) {\r\n\r\n }\r\n\r\n set(value: T): void {\r\n if (!this.model.cacheDirector || !this.model.cacheDirector.valid(value)) return;\r\n this.model.core.cache.set(this.model.cacheDirector.buildKey(value), value);\r\n }\r\n\r\n get(conditions: any): Bluebird {\r\n if (!this.model.cacheDirector || !this.model.cacheDirector.validQuery(conditions)) return Bluebird.resolve(null);\r\n return Bluebird.resolve(this.model.core.cache.get(this.model.cacheDirector.buildQueryKey(conditions)));\r\n }\r\n\r\n clear(conditions: any): void {\r\n if (!this.model.cacheDirector || !this.model.cacheDirector.validQuery(conditions)) return;\r\n this.model.core.cache.clear(this.model.cacheDirector.buildQueryKey(conditions));\r\n }\r\n}\r\n"],"sourceRoot":"/source/"} \ No newline at end of file +{"version":3,"sources":["lib/ModelCache.ts"],"names":[],"mappings":";AACA,MAAY,QAAQ,WAAM,UAAU,CAAC,CAAA;AAErC;;;;GAIG;AACH;IACI,YAAmB,KAAqB;QAArB,UAAK,GAAL,KAAK,CAAgB;IAExC,CAAC;IAED,GAAG,CAAI,KAAQ;QACX,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,aAAa,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,aAAa,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;YAAC,MAAM,CAAC;QAChF,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,aAAa,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE,KAAK,CAAC,CAAC;IAC/E,CAAC;IAED,GAAG,CAAI,UAAe;QAClB,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,aAAa,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,aAAa,CAAC,UAAU,CAAC,UAAU,CAAC,CAAC;YAAC,MAAM,CAAC,QAAQ,CAAC,OAAO,CAAI,IAAI,CAAC,CAAC;QACpH,MAAM,CAAC,QAAQ,CAAC,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,GAAG,CAAI,IAAI,CAAC,KAAK,CAAC,aAAa,CAAC,aAAa,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;IAC9G,CAAC;IAED,KAAK,CAAC,UAAe;QACjB,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,aAAa,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,aAAa,CAAC,UAAU,CAAC,UAAU,CAAC,CAAC;YAAC,MAAM,CAAC;QAC1F,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,aAAa,CAAC,aAAa,CAAC,UAAU,CAAC,CAAC,CAAC;IACpF,CAAC;AACL,CAAC;AAnBY,kBAAU,aAmBtB,CAAA","file":"lib/ModelCache.js","sourcesContent":["import {Model} from \"./Model\";\r\nimport * as Bluebird from \"bluebird\";\r\n\r\n/**\r\n * A centralized class which ties the cache and cache directors together in a cohesive way\r\n * for use by Iridium.\r\n * @internal\r\n */\r\nexport class ModelCache {\r\n constructor(public model: Model) {\r\n\r\n }\r\n\r\n set(value: T): void {\r\n if (!this.model.cacheDirector || !this.model.cacheDirector.valid(value)) return;\r\n this.model.core.cache.set(this.model.cacheDirector.buildKey(value), value);\r\n }\r\n\r\n get(conditions: any): Bluebird {\r\n if (!this.model.cacheDirector || !this.model.cacheDirector.validQuery(conditions)) return Bluebird.resolve(null);\r\n return Bluebird.resolve(this.model.core.cache.get(this.model.cacheDirector.buildQueryKey(conditions)));\r\n }\r\n\r\n clear(conditions: any): void {\r\n if (!this.model.cacheDirector || !this.model.cacheDirector.validQuery(conditions)) return;\r\n this.model.core.cache.clear(this.model.cacheDirector.buildQueryKey(conditions));\r\n }\r\n}\r\n"],"sourceRoot":"/source/"} \ No newline at end of file diff --git a/dist/lib/ModelHandlers.js b/dist/lib/ModelHandlers.js index 73d0060..0585539 100644 --- a/dist/lib/ModelHandlers.js +++ b/dist/lib/ModelHandlers.js @@ -1,6 +1,6 @@ "use strict"; -var _ = require("lodash"); -var Bluebird = require("bluebird"); +const _ = require("lodash"); +const Bluebird = require("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 @@ -9,60 +9,56 @@ var Bluebird = require("bluebird"); * Mostly this is for cache support, wrapping and hook triggering. * @internal */ -var ModelHandlers = (function () { - function ModelHandlers(model) { +class ModelHandlers { + constructor(model) { this.model = model; } - ModelHandlers.prototype.documentReceived = function (conditions, result, wrapper, options) { - var _this = this; - if (options === void 0) { options = {}; } + documentReceived(conditions, result, wrapper, options = {}) { _.defaults(options, { cache: true, partial: false }); - var wrapped; - return Bluebird.resolve(this.model.helpers.transformFromDB(result, { document: true })).then(function (target) { + let wrapped; + return Bluebird.resolve(this.model.helpers.transformFromDB(result, { document: true })).then((target) => { return Bluebird - .resolve(_this.model.hooks.onRetrieved && _this.model.hooks.onRetrieved(target)) - .then(function () { + .resolve(this.model.hooks.onRetrieved && this.model.hooks.onRetrieved(target)) + .then(() => { // Cache the document if caching is enabled - if (_this.model.core.cache && options.cache && !options.fields) { - _this.model.cache.set(target); // Does not block execution pipeline - fire and forget + if (this.model.core.cache && options.cache && !options.fields) { + this.model.cache.set(target); // Does not block execution pipeline - fire and forget } // Wrap the document and trigger the ready hook - var wrapped = wrapper(target, false, !!options.fields); + let wrapped = wrapper(target, false, !!options.fields); // Only incur the additional promise's performance penalty if this hook is being used - if (_this.model.hooks.onReady) + if (this.model.hooks.onReady) return Bluebird - .resolve(_this.model.hooks.onReady(wrapped)) - .then(function () { return wrapped; }); + .resolve(this.model.hooks.onReady(wrapped)) + .then(() => wrapped); return wrapped; }); }); - }; - ModelHandlers.prototype.creatingDocuments = function (documents) { - var _this = this; - return Bluebird.all(documents.map(function (document) { + } + creatingDocuments(documents) { + return Bluebird.all(documents.map((document) => { return Bluebird - .resolve(_this.model.hooks.onCreating && _this.model.hooks.onCreating(document)) - .then(function () { - document = _this.model.helpers.convertToDB(document, { document: true, properties: true }); - var validation = _this.model.helpers.validate(document); + .resolve(this.model.hooks.onCreating && this.model.hooks.onCreating(document)) + .then(() => { + document = this.model.helpers.convertToDB(document, { document: true, properties: true }); + let validation = this.model.helpers.validate(document); if (validation.failed) return Bluebird.reject(validation.error); return document; }); })); - }; - ModelHandlers.prototype.savingDocument = function (instance, changes) { + } + savingDocument(instance, changes) { return Bluebird .resolve(this.model.hooks.onSaving && this.model.hooks.onSaving(instance, changes)) - .then(function () { + .then(() => { return instance; }); - }; - return ModelHandlers; -}()); + } +} exports.ModelHandlers = ModelHandlers; //# sourceMappingURL=ModelHandlers.js.map diff --git a/dist/lib/ModelHandlers.js.map b/dist/lib/ModelHandlers.js.map index 2a6f2ca..fe5c63d 100644 --- a/dist/lib/ModelHandlers.js.map +++ b/dist/lib/ModelHandlers.js.map @@ -1 +1 @@ -{"version":3,"sources":["lib/ModelHandlers.ts"],"names":[],"mappings":";AAOA,IAAY,CAAC,WAAM,QAAQ,CAAC,CAAA;AAE5B,IAAY,QAAQ,WAAM,UAAU,CAAC,CAAA;AAErC;;;;;;;GAOG;AACH;IACI,uBAAmB,KAAkC;QAAlC,UAAK,GAAL,KAAK,CAA6B;IAErD,CAAC;IAED,wCAAgB,GAAhB,UAA0B,UAAe,EACrC,MAAiB,EACjB,OAA+E,EAC/E,OAAuC;QAH3C,iBA+BC;QA5BG,uBAAuC,GAAvC,YAAuC;QACvC,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elCache} from \"./ModelCache\";\r\nimport * as ModelOptions from \"./ModelOptions\";\r\n\r\nimport * as Skmatc from \"skmatc\";\r\nimport * as _ from \"lodash\";\r\nimport * as MongoDB from \"mongodb\";\r\nimport * as Bluebird from \"bluebird\";\r\n\r\n/**\r\n * Provides a number of methods which are used to handle events that occur within\r\n * the Iridium workflow - such as what happens when a document is received from\r\n * the database, or how to handle the creation of new documents and saving of instances.\r\n *\r\n * Mostly this is for cache support, wrapping and hook triggering.\r\n * @internal\r\n */\r\nexport class ModelHandlers {\r\n constructor(public model: Model) {\r\n\r\n }\r\n\r\n documentReceived(conditions: any,\r\n result: TDocument,\r\n wrapper: (document: TDocument, isNew?: boolean, isPartial?: boolean) => TResult,\r\n options: ModelOptions.QueryOptions = {}): Bluebird {\r\n _.defaults(options, {\r\n cache: true,\r\n partial: false\r\n });\r\n\r\n let wrapped: TResult;\r\n return Bluebird.resolve(this.model.helpers.transformFromDB(result, { document: true })).then((target: any) => {\r\n return >Bluebird\r\n // If onRetrieved returns a Bluebird promise then there is no significant performance overhead here\r\n .resolve(this.model.hooks.onRetrieved && this.model.hooks.onRetrieved(target))\r\n .then(() => {\r\n // Cache the document if caching is enabled\r\n if (this.model.core.cache && options.cache && !options.fields) {\r\n this.model.cache.set(target); // Does not block execution pipeline - fire and forget\r\n }\r\n\r\n // Wrap the document and trigger the ready hook\r\n let wrapped: TResult = wrapper(target, false, !!options.fields);\r\n\r\n // Only incur the additional promise's performance penalty if this hook is being used\r\n if (this.model.hooks.onReady)\r\n return Bluebird\r\n .resolve(this.model.hooks.onReady(wrapped))\r\n .then(() => wrapped);\r\n return wrapped;\r\n });\r\n });\r\n }\r\n\r\n creatingDocuments(documents: TDocument[]): Bluebird {\r\n return Bluebird.all(documents.map((document: any) => {\r\n return Bluebird\r\n // If onCreating returns a Bluebird promise then there is no significant performance overhead here\r\n .resolve(this.model.hooks.onCreating && this.model.hooks.onCreating(document))\r\n .then(() => {\r\n document = this.model.helpers.convertToDB(document, { document: true, properties: true });\r\n let validation: Skmatc.Result = this.model.helpers.validate(document);\r\n if (validation.failed) return Bluebird.reject(validation.error);\r\n\r\n return document;\r\n });\r\n }));\r\n }\r\n\r\n savingDocument(instance: TInstance, changes: any): Bluebird {\r\n return Bluebird\r\n // If onSaving returns a Bluebird promise then there is no significant performance overhead here\r\n .resolve(this.model.hooks.onSaving && this.model.hooks.onSaving(instance, changes))\r\n .then(() => {\r\n return instance;\r\n });\r\n }\r\n}\r\n"],"sourceRoot":"/source/"} \ No newline at end of file +{"version":3,"sources":["lib/ModelHandlers.ts"],"names":[],"mappings":";AAOA,MAAY,CAAC,WAAM,QAAQ,CAAC,CAAA;AAE5B,MAAY,QAAQ,WAAM,UAAU,CAAC,CAAA;AAErC;;;;;;;GAOG;AACH;IACI,YAAmB,KAAkC;QAAlC,UAAK,GAAL,KAAK,CAA6B;IAErD,CAAC;IAED,gBAAgB,CAAU,UAAe,EACrC,MAAiB,EACjB,OAA+E,EAC/E,OAAO,GAA8B,EAAE;QACvC,CAAC,CAAC,QAAQ,CAAC,OAAO,EAAE;YAChB,KAAK,EAAE,IAAI;YACX,OAAO,EAAE,KAAK;SACjB,CAAC,CAAC;QAEH,IAAI,OAAgB,CAAC;QACrB,MAAM,CAAC,QAAQ,CAAC,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,eAAe,CAAC,MAAM,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,MAAW;YACrG,MAAM,CAAoB,QAAQ;iBAE7B,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,WAAW,IAAI,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,WAAW,CAAC,MAAM,CAAC,CAAC;iBAC7E,IAAI,CAAC;gBACF,2CAA2C;gBAC3C,EAAE,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,IAAI,OAAO,CAAC,KAAK,IAAI,CAA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C,KAAK,CAAC,CAAC;gBAEhE,MAAM,CAAC,QAAQ,CAAC;YACpB,CAAC,CAAC,CAAC;QACX,CAAC,CAAC,CAAC,CAAC;IACR,CAAC;IAED,cAAc,CAAC,QAAmB,EAAE,OAAY;QAC5C,MAAM,CAAC,QAAQ;aAEV,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,QAAQ,IAAI,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,QAAQ,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAC;aAClF,IAAI,CAAC;YACF,MAAM,CAAC,QAAQ,CAAC;QACpB,CAAC,CAAC,CAAC;IACX,CAAC;AACL,CAAC;AA7DY,qBAAa,gBA6DzB,CAAA","file":"lib/ModelHandlers.js","sourcesContent":["import {Core} from \"./Core\";\r\nimport {Schema} from \"./Schema\";\r\nimport {Model} from \"./Model\";\r\nimport {ModelCache} from \"./ModelCache\";\r\nimport * as ModelOptions from \"./ModelOptions\";\r\n\r\nimport * as Skmatc from \"skmatc\";\r\nimport * as _ from \"lodash\";\r\nimport * as MongoDB from \"mongodb\";\r\nimport * as Bluebird from \"bluebird\";\r\n\r\n/**\r\n * Provides a number of methods which are used to handle events that occur within\r\n * the Iridium workflow - such as what happens when a document is received from\r\n * the database, or how to handle the creation of new documents and saving of instances.\r\n *\r\n * Mostly this is for cache support, wrapping and hook triggering.\r\n * @internal\r\n */\r\nexport class ModelHandlers {\r\n constructor(public model: Model) {\r\n\r\n }\r\n\r\n documentReceived(conditions: any,\r\n result: TDocument,\r\n wrapper: (document: TDocument, isNew?: boolean, isPartial?: boolean) => TResult,\r\n options: ModelOptions.QueryOptions = {}): Bluebird {\r\n _.defaults(options, {\r\n cache: true,\r\n partial: false\r\n });\r\n\r\n let wrapped: TResult;\r\n return Bluebird.resolve(this.model.helpers.transformFromDB(result, { document: true })).then((target: any) => {\r\n return >Bluebird\r\n // If onRetrieved returns a Bluebird promise then there is no significant performance overhead here\r\n .resolve(this.model.hooks.onRetrieved && this.model.hooks.onRetrieved(target))\r\n .then(() => {\r\n // Cache the document if caching is enabled\r\n if (this.model.core.cache && options.cache && !options.fields) {\r\n this.model.cache.set(target); // Does not block execution pipeline - fire and forget\r\n }\r\n\r\n // Wrap the document and trigger the ready hook\r\n let wrapped: TResult = wrapper(target, false, !!options.fields);\r\n\r\n // Only incur the additional promise's performance penalty if this hook is being used\r\n if (this.model.hooks.onReady)\r\n return Bluebird\r\n .resolve(this.model.hooks.onReady(wrapped))\r\n .then(() => wrapped);\r\n return wrapped;\r\n });\r\n });\r\n }\r\n\r\n creatingDocuments(documents: TDocument[]): Bluebird {\r\n return Bluebird.all(documents.map((document: any) => {\r\n return Bluebird\r\n // If onCreating returns a Bluebird promise then there is no significant performance overhead here\r\n .resolve(this.model.hooks.onCreating && this.model.hooks.onCreating(document))\r\n .then(() => {\r\n document = this.model.helpers.convertToDB(document, { document: true, properties: true });\r\n let validation: Skmatc.Result = this.model.helpers.validate(document);\r\n if (validation.failed) return Bluebird.reject(validation.error);\r\n\r\n return document;\r\n });\r\n }));\r\n }\r\n\r\n savingDocument(instance: TInstance, changes: any): Bluebird {\r\n return Bluebird\r\n // If onSaving returns a Bluebird promise then there is no significant performance overhead here\r\n .resolve(this.model.hooks.onSaving && this.model.hooks.onSaving(instance, changes))\r\n .then(() => {\r\n return instance;\r\n });\r\n }\r\n}\r\n"],"sourceRoot":"/source/"} \ No newline at end of file diff --git a/dist/lib/ModelHelpers.js b/dist/lib/ModelHelpers.js index 9a49d34..436421c 100644 --- a/dist/lib/ModelHelpers.js +++ b/dist/lib/ModelHelpers.js @@ -1,29 +1,28 @@ "use strict"; -var MongoDB = require("mongodb"); -var Skmatc = require("skmatc"); -var Omnom_1 = require("./utils/Omnom"); -var _ = require("lodash"); +const MongoDB = require("mongodb"); +const Skmatc = require("skmatc"); +const Omnom_1 = require("./utils/Omnom"); +const _ = require("lodash"); /** * 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 */ -var ModelHelpers = (function () { - function ModelHelpers(model) { - var _this = this; +class ModelHelpers { + constructor(model) { this.model = model; this._validator = Skmatc.scope(model.schema); - model.validators.forEach(function (validator) { return _this._validator.register(validator); }); + model.validators.forEach(validator => this._validator.register(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 */ - ModelHelpers.prototype.validate = function (document) { + validate(document) { return this._validator.validate(document); - }; + } /** * Wraps the given document in an instance wrapper for use throughout the application * @param {any} document The document to be wrapped as an instance @@ -31,9 +30,9 @@ var ModelHelpers = (function () { * @param {Boolean} isPartial Whether the document supplied contains all information present in the database * @returns {any} An instance which wraps this document */ - ModelHelpers.prototype.wrapDocument = function (document, isNew, isPartial) { + wrapDocument(document, isNew, isPartial) { return new this.model.Instance(document, isNew, isPartial); - }; + } /** * Converts the given document to its database form into a form * using the transforms defined on the model. @@ -41,20 +40,19 @@ var ModelHelpers = (function () { * @returns {any} The result of having transformed the document. * @remarks This is only really called from insert/create - as */ - ModelHelpers.prototype.transformToDB = function (document, options) { - if (options === void 0) { options = { properties: true }; } + transformToDB(document, options = { properties: true }) { if (options.document && this.model.transforms.$document) document = this.model.transforms.$document.toDB(document, "$document", this.model); if (!options.properties) return document; - for (var property in this.model.transforms) + for (let property in this.model.transforms) if (property === "$document") continue; else if (document.hasOwnProperty(property)) { document[property] = this.model.transforms[property].toDB(document[property], property, this.model); } return document; - }; + } /** * Converts the given document from its database form using the * transforms defined on the model. @@ -64,20 +62,19 @@ var ModelHelpers = (function () { * document level transforms, as property level transforms are applied in * their relevant instance setters. */ - ModelHelpers.prototype.transformFromDB = function (document, options) { - if (options === void 0) { options = { properties: true }; } + transformFromDB(document, options = { properties: true }) { if (options.document && this.model.transforms.$document) document = this.model.transforms.$document.fromDB(document, "$document", this.model); if (!options.properties) return document; - for (var property in this.model.transforms) + for (let property in this.model.transforms) if (property === "$document") continue; else if (document.hasOwnProperty(property)) { document[property] = this.model.transforms[property].fromDB(document[property], property, this.model); } return document; - }; + } /** * Converts the given document to its database form into a form * using the transforms defined on the model. @@ -86,29 +83,28 @@ var ModelHelpers = (function () { * document level transforms. * @returns {any} A new document cloned from the original and transformed */ - ModelHelpers.prototype.convertToDB = function (document, options) { - if (options === void 0) { options = { properties: true }; } - var doc = this.cloneDocument(document); + convertToDB(document, options = { properties: true }) { + let doc = this.cloneDocument(document); return this.transformToDB(doc, options); - }; + } /** * 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 */ - ModelHelpers.prototype.diff = function (original, modified) { - var omnom = new Omnom_1.Omnom(); + diff(original, modified) { + let omnom = new Omnom_1.Omnom(); omnom.diff(original, modified); return omnom.changes; - }; + } /** * Clones the given document recursively, taking into account complex types like * Buffers correctly. * * @param {any} The document you wish to clone deeply. */ - ModelHelpers.prototype.cloneDocument = function (original) { - return _.cloneDeepWith(original, function (value) { + cloneDocument(original) { + return _.cloneDeepWith(original, (value) => { if (Buffer.isBuffer(value)) { return value; } @@ -119,7 +115,7 @@ var ModelHelpers = (function () { return value; } }); - }; + } /** * Clones the given document recursively, taking into account complex types like * Buffers correctly. Optimized for working with query documents instead of true @@ -127,11 +123,10 @@ var ModelHelpers = (function () { * * @param {any} The document you wish to clone deeply. */ - ModelHelpers.prototype.cloneConditions = function (original) { + cloneConditions(original) { return this.cloneDocument(original); - }; - return ModelHelpers; -}()); + } +} exports.ModelHelpers = ModelHelpers; //# sourceMappingURL=ModelHelpers.js.map diff --git a/dist/lib/ModelHelpers.js.map b/dist/lib/ModelHelpers.js.map index cc7dd50..2740be4 100644 --- a/dist/lib/ModelHelpers.js.map +++ b/dist/lib/ModelHelpers.js.map @@ -1 +1 @@ -{"version":3,"sources":["lib/ModelHelpers.ts"],"names":[],"mappings":";AAAA,IAAY,OAAO,WAAM,SAAS,CAAC,CAAA;AAE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AAC,QAAQ,CAAC,CAAC;IACxC,CAAC;IACL,mBAAC;AAAD,CAlIA,AAkIC,IAAA;AAlIY,oBAAY,eAkIxB,CAAA","file":"lib/ModelHelpers.js","sourcesContent":["import * as MongoDB from \"mongodb\";\r\nimport {Model} from \"./Model\";\r\nimport * as Skmatc from \"skmatc\";\r\nimport {Omnom} from \"./utils/Omnom\";\r\nimport * as _ from \"lodash\";\r\nimport * as Bluebird from \"bluebird\";\r\n\r\n/**\r\n * A number of helper methods used commonly within Iridium, they provide a means to transform,\r\n * validate, wrap and diff instances and documents. By keeping these methods in one place we\r\n * help to improve testability and reduce code duplication (mouse abuse) throughout the codebase.\r\n * @internal\r\n */\r\nexport class ModelHelpers {\r\n constructor(public model: Model) {\r\n this._validator = Skmatc.scope(model.schema);\r\n model.validators.forEach(validator => this._validator.register(validator));\r\n }\r\n\r\n private _validator: Skmatc.Skmatc;\r\n\r\n /**\r\n * Validates a document to ensure that it matches the model's ISchema requirements\r\n * @param {any} document The document to validate against the ISchema\r\n * @returns {SkmatcCore.IResult} The result of the validation\r\n */\r\n validate(document: TDocument): Skmatc.Result {\r\n return this._validator.validate(document);\r\n }\r\n\r\n /**\r\n * Wraps the given document in an instance wrapper for use throughout the application\r\n * @param {any} document The document to be wrapped as an instance\r\n * @param {Boolean} isNew Whether the instance originated from the database or was created by the application\r\n * @param {Boolean} isPartial Whether the document supplied contains all information present in the database\r\n * @returns {any} An instance which wraps this document\r\n */\r\n wrapDocument(document: TDocument, isNew?: boolean, isPartial?: boolean): TInstance {\r\n return new this.model.Instance(document, isNew, isPartial);\r\n }\r\n\r\n /**\r\n * Converts the given document to its database form into a form\r\n * using the transforms defined on the model.\r\n * @param {any} document The document to be converted\r\n * @returns {any} The result of having transformed the document.\r\n * @remarks This is only really called from insert/create - as \r\n */\r\n transformToDB(document: T, options: TransformOptions = { properties: true }): T {\r\n if(options.document && this.model.transforms.$document)\r\n document = this.model.transforms.$document.toDB(document, \"$document\", this.model);\r\n \r\n if(!options.properties) return document;\r\n \r\n for (let property in this.model.transforms)\r\n if(property === \"$document\") continue;\r\n else if(document.hasOwnProperty(property)) {\r\n document[property] = this.model.transforms[property].toDB(document[property], property, this.model);\r\n }\r\n \r\n return document;\r\n }\r\n \r\n /**\r\n * Converts the given document from its database form using the\r\n * transforms defined on the model.\r\n * @param document The document to be converted.\r\n * @returns The result of having transformed the document.\r\n * @remarks Unlike the transformToDB function - this method only applies\r\n * document level transforms, as property level transforms are applied in\r\n * their relevant instance setters.\r\n */\r\n transformFromDB(document: TDocument, options: TransformOptions = { properties: true }): TDocument {\r\n if(options.document && this.model.transforms.$document)\r\n document = this.model.transforms.$document.fromDB(document, \"$document\", this.model);\r\n \r\n if(!options.properties) return document;\r\n \r\n for (let property in this.model.transforms)\r\n if(property === \"$document\") continue;\r\n else if(document.hasOwnProperty(property)) {\r\n document[property] = this.model.transforms[property].fromDB(document[property], property, this.model);\r\n }\r\n \r\n return document;\r\n }\r\n\r\n /**\r\n * Converts the given document to its database form into a form\r\n * using the transforms defined on the model.\r\n * @param document The document to be converted\r\n * @param processProperties Whether or not to process properties in addition\r\n * document level transforms.\r\n * @returns {any} A new document cloned from the original and transformed\r\n */\r\n convertToDB(document: T, options: TransformOptions = { properties: true }): T {\r\n let doc: T = this.cloneDocument(document);\r\n return this.transformToDB(doc, options);\r\n }\r\n\r\n /**\r\n * Performs a diff operation between two documents and creates a MongoDB changes object to represent the differences\r\n * @param {any} original The original document prior to changes being made\r\n * @param {any} modified The document after changes were made\r\n */\r\n diff(original: TDocument, modified: TDocument): any {\r\n let omnom = new Omnom();\r\n omnom.diff(original, modified);\r\n return omnom.changes;\r\n }\r\n \r\n /**\r\n * Clones the given document recursively, taking into account complex types like\r\n * Buffers correctly.\r\n * \r\n * @param {any} The document you wish to clone deeply.\r\n */\r\n cloneDocument(original: T): T {\r\n return _.cloneDeepWith(original, (value) => {\r\n if(Buffer.isBuffer(value)) {\r\n return value;\r\n }\r\n \r\n if(value instanceof MongoDB.Binary) {\r\n return value;\r\n }\r\n \r\n if(value instanceof MongoDB.ObjectID) {\r\n return value;\r\n }\r\n });\r\n }\r\n \r\n /**\r\n * Clones the given document recursively, taking into account complex types like\r\n * Buffers correctly. Optimized for working with query documents instead of true\r\n * documents.\r\n * \r\n * @param {any} The document you wish to clone deeply.\r\n */\r\n cloneConditions(original: T): T {\r\n return this.cloneDocument(original);\r\n }\r\n}\r\n\r\nexport interface TransformOptions {\r\n properties?: boolean;\r\n document?: boolean;\r\n}"],"sourceRoot":"/source/"} \ No newline at end of file +{"version":3,"sources":["lib/ModelHelpers.ts"],"names":[],"mappings":";AAAA,MAAY,OAAO,WAAM,SAAS,CAAC,CAAA;AAEnC,MAAY,MAAM,WAAM,QAAQ,CAAC,CAAA;AACjC,wBAAoB,eAAe,CAAC,CAAA;AACpC,MAAY,CAAC,WAAM,QAAQ,CAAC,CAAA;AAG5B;;;;;GAKG;AACH;IACI,YAAmB,KAAkC;QAAlC,UAAK,GAAL,KAAK,CAA6B;QACjD,IAAI,CAAC,UAAU,GAAG,MAAM,CAAC,KAAK,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;QAC7C,KAAK,CAAC,UAAU,CAAC,OAAO,CAAC,SAAS,IAAI,IAAI,CAAC,UAAU,CAAC,QAAQ,CAAC,SAAS,CAAC,CAAC,CAAC;IAC/E,CAAC;IAID;;;;OAIG;IACH,QAAQ,CAAC,QAAmB;QACxB,MAAM,CAAC,IAAI,CAAC,UAAU,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC;IAC9C,CAAC;IAED;;;;;;OAMG;IACH,YAAY,CAAC,QAAmB,EAAE,KAAe,EAAE,SAAmB;QAClE,MAAM,CAAC,IAAI,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,QAAQ,EAAE,KAAK,EAAE,SAAS,CAAC,CAAC;IAC/D,CAAC;IAED;;;;;;OAMG;IACH,aAAa,CAAI,QAAW,EAAE,OAAO,GAAqB,EAAE,UAAU,EAAE,IAAI,EAAE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MAAM,CAAC,KAAK,CAAC;YACjB,CAAC;YAED,EAAE,CAAA,CAAC,KAAK,YAAY,OAAO,CAAC,QAAQ,CAAC,CAAC,CAAC;gBACnC,MAAM,CAAC,KAAK,CAAC;YACjB,CAAC;QACJ,CAAC,CAAC,CAAC;IACP,CAAC;IAED;;;;;;OAMG;IACH,eAAe,CAAI,QAAW;QAC1B,MAAM,CAAC,IAAI,CAAC,aAAa,CAAC,QAAQ,CAAC,CAAC;IACxC,CAAC;AACL,CAAC;AAlIY,oBAAY,eAkIxB,CAAA","file":"lib/ModelHelpers.js","sourcesContent":["import * as MongoDB from \"mongodb\";\r\nimport {Model} from \"./Model\";\r\nimport * as Skmatc from \"skmatc\";\r\nimport {Omnom} from \"./utils/Omnom\";\r\nimport * as _ from \"lodash\";\r\nimport * as Bluebird from \"bluebird\";\r\n\r\n/**\r\n * A number of helper methods used commonly within Iridium, they provide a means to transform,\r\n * validate, wrap and diff instances and documents. By keeping these methods in one place we\r\n * help to improve testability and reduce code duplication (mouse abuse) throughout the codebase.\r\n * @internal\r\n */\r\nexport class ModelHelpers {\r\n constructor(public model: Model) {\r\n this._validator = Skmatc.scope(model.schema);\r\n model.validators.forEach(validator => this._validator.register(validator));\r\n }\r\n\r\n private _validator: Skmatc.Skmatc;\r\n\r\n /**\r\n * Validates a document to ensure that it matches the model's ISchema requirements\r\n * @param {any} document The document to validate against the ISchema\r\n * @returns {SkmatcCore.IResult} The result of the validation\r\n */\r\n validate(document: TDocument): Skmatc.Result {\r\n return this._validator.validate(document);\r\n }\r\n\r\n /**\r\n * Wraps the given document in an instance wrapper for use throughout the application\r\n * @param {any} document The document to be wrapped as an instance\r\n * @param {Boolean} isNew Whether the instance originated from the database or was created by the application\r\n * @param {Boolean} isPartial Whether the document supplied contains all information present in the database\r\n * @returns {any} An instance which wraps this document\r\n */\r\n wrapDocument(document: TDocument, isNew?: boolean, isPartial?: boolean): TInstance {\r\n return new this.model.Instance(document, isNew, isPartial);\r\n }\r\n\r\n /**\r\n * Converts the given document to its database form into a form\r\n * using the transforms defined on the model.\r\n * @param {any} document The document to be converted\r\n * @returns {any} The result of having transformed the document.\r\n * @remarks This is only really called from insert/create - as \r\n */\r\n transformToDB(document: T, options: TransformOptions = { properties: true }): T {\r\n if(options.document && this.model.transforms.$document)\r\n document = this.model.transforms.$document.toDB(document, \"$document\", this.model);\r\n \r\n if(!options.properties) return document;\r\n \r\n for (let property in this.model.transforms)\r\n if(property === \"$document\") continue;\r\n else if(document.hasOwnProperty(property)) {\r\n document[property] = this.model.transforms[property].toDB(document[property], property, this.model);\r\n }\r\n \r\n return document;\r\n }\r\n \r\n /**\r\n * Converts the given document from its database form using the\r\n * transforms defined on the model.\r\n * @param document The document to be converted.\r\n * @returns The result of having transformed the document.\r\n * @remarks Unlike the transformToDB function - this method only applies\r\n * document level transforms, as property level transforms are applied in\r\n * their relevant instance setters.\r\n */\r\n transformFromDB(document: TDocument, options: TransformOptions = { properties: true }): TDocument {\r\n if(options.document && this.model.transforms.$document)\r\n document = this.model.transforms.$document.fromDB(document, \"$document\", this.model);\r\n \r\n if(!options.properties) return document;\r\n \r\n for (let property in this.model.transforms)\r\n if(property === \"$document\") continue;\r\n else if(document.hasOwnProperty(property)) {\r\n document[property] = this.model.transforms[property].fromDB(document[property], property, this.model);\r\n }\r\n \r\n return document;\r\n }\r\n\r\n /**\r\n * Converts the given document to its database form into a form\r\n * using the transforms defined on the model.\r\n * @param document The document to be converted\r\n * @param processProperties Whether or not to process properties in addition\r\n * document level transforms.\r\n * @returns {any} A new document cloned from the original and transformed\r\n */\r\n convertToDB(document: T, options: TransformOptions = { properties: true }): T {\r\n let doc: T = this.cloneDocument(document);\r\n return this.transformToDB(doc, options);\r\n }\r\n\r\n /**\r\n * Performs a diff operation between two documents and creates a MongoDB changes object to represent the differences\r\n * @param {any} original The original document prior to changes being made\r\n * @param {any} modified The document after changes were made\r\n */\r\n diff(original: TDocument, modified: TDocument): any {\r\n let omnom = new Omnom();\r\n omnom.diff(original, modified);\r\n return omnom.changes;\r\n }\r\n \r\n /**\r\n * Clones the given document recursively, taking into account complex types like\r\n * Buffers correctly.\r\n * \r\n * @param {any} The document you wish to clone deeply.\r\n */\r\n cloneDocument(original: T): T {\r\n return _.cloneDeepWith(original, (value) => {\r\n if(Buffer.isBuffer(value)) {\r\n return value;\r\n }\r\n \r\n if(value instanceof MongoDB.Binary) {\r\n return value;\r\n }\r\n \r\n if(value instanceof MongoDB.ObjectID) {\r\n return value;\r\n }\r\n });\r\n }\r\n \r\n /**\r\n * Clones the given document recursively, taking into account complex types like\r\n * Buffers correctly. Optimized for working with query documents instead of true\r\n * documents.\r\n * \r\n * @param {any} The document you wish to clone deeply.\r\n */\r\n cloneConditions(original: T): T {\r\n return this.cloneDocument(original);\r\n }\r\n}\r\n\r\nexport interface TransformOptions {\r\n properties?: boolean;\r\n document?: boolean;\r\n}"],"sourceRoot":"/source/"} \ No newline at end of file diff --git a/dist/lib/ModelSpecificInstance.js b/dist/lib/ModelSpecificInstance.js index 65ecf02..5d7816b 100644 --- a/dist/lib/ModelSpecificInstance.js +++ b/dist/lib/ModelSpecificInstance.js @@ -1,10 +1,5 @@ "use strict"; -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"); +const _ = require("lodash"); /** * Creates a new subclass of the given instanceType which correctly performs property transforms * and associates the instance with the correct model when instantiated. @@ -18,19 +13,14 @@ var _ = require("lodash"); * @internal */ function ModelSpecificInstance(model, 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)); + const instanceTypeConstructor = instanceType; + let virtualClass = class extends instanceTypeConstructor { + constructor(...args) { + super(model, ...args); } - return class_1; - }(instanceTypeConstructor)); - _.each(Object.keys(model.schema), function (property) { + } + ; + _.each(Object.keys(model.schema), (property) => { if (model.transforms.hasOwnProperty(property)) { return Object.defineProperty(virtualClass.prototype, property, { get: function () { diff --git a/dist/lib/ModelSpecificInstance.js.map b/dist/lib/ModelSpecificInstance.js.map index d975ddb..d63334b 100644 --- a/dist/lib/ModelSpecificInstance.js.map +++ b/dist/lib/ModelSpecificInstance.js.map @@ -1 +1 @@ -{"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 +{"version":3,"sources":["lib/ModelSpecificInstance.ts"],"names":[],"mappings":";AAIA,MAAY,CAAC,WAAM,QAAQ,CAAC,CAAA;AAE5B;;;;;;;;;;;GAWG;AACH,+BAAkF,KAAkC,EAAE,YAA0D;IAC5K,MAAM,uBAAuB,GAA6B,YAAY,CAAC;IAEvE,IAAI,YAAY,GAAG,cAAc,uBAAuB;QACpD,YAAY,GAAG,IAAI;YACf,MAAM,KAAK,EAAE,GAAG,IAAI,CAAC,CAAC;QAC1B,CAAC;IACL,CAAC;IAAA,CAAA;IAED,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,EAAC,CAAC,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/lib/Transforms.js b/dist/lib/Transforms.js index 415ed49..e7e5965 100644 --- a/dist/lib/Transforms.js +++ b/dist/lib/Transforms.js @@ -1,19 +1,19 @@ "use strict"; -var BSON_1 = require("./BSON"); +const BSON_1 = require("./BSON"); exports.DefaultTransforms = { ObjectID: { - fromDB: function (value) { return value instanceof BSON_1.ObjectID ? value.toHexString() : value; }, - toDB: function (value) { return typeof value === "string" ? new BSON_1.ObjectID(value) : value; } + fromDB: value => value instanceof BSON_1.ObjectID ? value.toHexString() : value, + toDB: value => typeof value === "string" ? new BSON_1.ObjectID(value) : value }, Binary: { - fromDB: function (value) { + fromDB: value => { if (!value) return null; if (value instanceof BSON_1.Binary) return value.buffer; return value; }, - toDB: function (value) { + toDB: value => { if (Buffer.isBuffer(value)) return new BSON_1.Binary(value); if (Array.isArray(value)) diff --git a/dist/lib/Transforms.js.map b/dist/lib/Transforms.js.map index 33863a7..c1f2251 100644 --- a/dist/lib/Transforms.js.map +++ b/dist/lib/Transforms.js.map @@ -1 +1 @@ -{"version":3,"sources":["lib/Transforms.ts"],"names":[],"mappings":";AAAA,qBAA+B,QAAQ,CAAC,CAAA;AAqC3B,yBAAiB,GAAG;IAC/B,QAAQ,EAA+B;QACvC,MAAM,EAAE,UAAA,KAAK,IAAI,OAAA,KAAK,YAAY,eAAQ,GAAG,KAAK,CAAC,WAAW,EAAE,GAAG,KAAK,EAAvD,CAAuD;QACxE,IAAI,EAAE,UAAA,KAAK,IAAI,OAAA,OAAO,KAAK,KAAK,QAAQ,GAAG,IAAI,eAAQ,CAAC,KAAK,CAAC,GAAG,KAAK,EAAvD,CAAuD;KACtE;IACD,MAAM,EAA6B;QAClC,MAAM,EAAE,UAAA,KAAK;YACZ,EAAE,CAAA,CAAC,CAAC,KAAK,CAAC;gBAAC,MAAM,CAAC,IAAI,CAAC;YACvB,EAAE,CAAA,CAAC,KAAK,YAAY,aAAM,CAAC;gBAAC,MAAM,CAAO,KAAM,CAAC,MAAM,CAAC;YAEvD,MAAM,CAAC,KAAK,CAAC;QACd,CAAC;QACD,IAAI,EAAE,UAAA,KAAK;YACV,EAAE,CAAA,CAAC,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;gBAAC,MAAM,CAAC,IAAI,aAAM,CAAC,KAAK,CAAC,CAAC;YACpD,EAAE,CAAA,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;gBAAC,MAAM,CAAC,IAAI,aAAM,CAAC,IAAI,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;YAC9D,MAAM,CAAC,IAAI,CAAC;QACb,CAAC;KACD;CACD,CAAA","file":"lib/Transforms.js","sourcesContent":["import {ObjectID, Binary} from \"./BSON\";\r\nimport {Model} from \"./Model\";\r\n\r\nexport interface Transforms {\r\n\t/**\r\n\t * A transform which is applied to the entire document.\r\n\t */\r\n\t$document?: PropertyTransform;\r\n\t_id?: PropertyTransform;\r\n\t[property:string]: PropertyTransform;\r\n}\r\n\r\n/**\r\n * Converts the value of a property to and from its database representation.\r\n */\r\nexport interface PropertyTransform {\r\n\t/**\r\n\t * Converts a property's value from its database representation into one\r\n\t * suitable for the application.\r\n\t * @param value The value stored in the MongoDB database document.\r\n\t * @param property The name of the document property to which this transform is being applied.\r\n\t * @param model The Iridium Model on which this transform is being applied\r\n\t * @returns A derived value which is more useful to the application.\r\n\t */\r\n\tfromDB(value: T, property: string, model: Model): any;\r\n\r\n\t/**\r\n\t * Converts a property's value into a representation more suitable for\r\n\t * the database.\r\n\t * @param value The value used by the application.\r\n\t * @param property The name of the document property to which this transform is being applied.\r\n\t * @param model The Iridium Model on which this transform is being applied\r\n\t * @returns The database optimized representation of the value.\r\n\t */\r\n\ttoDB(value: any, property: string, model: Model): T;\r\n}\r\n\r\nexport const DefaultTransforms = {\r\n \tObjectID: >{\r\n\t\tfromDB: value => value instanceof ObjectID ? value.toHexString() : value,\r\n\t\ttoDB: value => typeof value === \"string\" ? new ObjectID(value) : value\r\n\t},\r\n\tBinary: >{\r\n\t\tfromDB: value => {\r\n\t\t\tif(!value) return null;\r\n\t\t\tif(value instanceof Binary) return (value).buffer;\r\n\t\t\t\r\n\t\t\treturn value;\r\n\t\t},\r\n\t\ttoDB: value => {\r\n\t\t\tif(Buffer.isBuffer(value)) return new Binary(value);\r\n\t\t\tif(Array.isArray(value)) return new Binary(new Buffer(value));\r\n\t\t\treturn null;\r\n\t\t}\r\n\t}\r\n}"],"sourceRoot":"/source/"} \ No newline at end of file +{"version":3,"sources":["lib/Transforms.ts"],"names":[],"mappings":";AAAA,uBAA+B,QAAQ,CAAC,CAAA;AAqC3B,yBAAiB,GAAG;IAC/B,QAAQ,EAA+B;QACvC,MAAM,EAAE,KAAK,IAAI,KAAK,YAAY,eAAQ,GAAG,KAAK,CAAC,WAAW,EAAE,GAAG,KAAK;QACxE,IAAI,EAAE,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ,GAAG,IAAI,eAAQ,CAAC,KAAK,CAAC,GAAG,KAAK;KACtE;IACD,MAAM,EAA6B;QAClC,MAAM,EAAE,KAAK;YACZ,EAAE,CAAA,CAAC,CAAC,KAAK,CAAC;gBAAC,MAAM,CAAC,IAAI,CAAC;YACvB,EAAE,CAAA,CAAC,KAAK,YAAY,aAAM,CAAC;gBAAC,MAAM,CAAO,KAAM,CAAC,MAAM,CAAC;YAEvD,MAAM,CAAC,KAAK,CAAC;QACd,CAAC;QACD,IAAI,EAAE,KAAK;YACV,EAAE,CAAA,CAAC,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;gBAAC,MAAM,CAAC,IAAI,aAAM,CAAC,KAAK,CAAC,CAAC;YACpD,EAAE,CAAA,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;gBAAC,MAAM,CAAC,IAAI,aAAM,CAAC,IAAI,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;YAC9D,MAAM,CAAC,IAAI,CAAC;QACb,CAAC;KACD;CACD,CAAA","file":"lib/Transforms.js","sourcesContent":["import {ObjectID, Binary} from \"./BSON\";\r\nimport {Model} from \"./Model\";\r\n\r\nexport interface Transforms {\r\n\t/**\r\n\t * A transform which is applied to the entire document.\r\n\t */\r\n\t$document?: PropertyTransform;\r\n\t_id?: PropertyTransform;\r\n\t[property:string]: PropertyTransform;\r\n}\r\n\r\n/**\r\n * Converts the value of a property to and from its database representation.\r\n */\r\nexport interface PropertyTransform {\r\n\t/**\r\n\t * Converts a property's value from its database representation into one\r\n\t * suitable for the application.\r\n\t * @param value The value stored in the MongoDB database document.\r\n\t * @param property The name of the document property to which this transform is being applied.\r\n\t * @param model The Iridium Model on which this transform is being applied\r\n\t * @returns A derived value which is more useful to the application.\r\n\t */\r\n\tfromDB(value: T, property: string, model: Model): any;\r\n\r\n\t/**\r\n\t * Converts a property's value into a representation more suitable for\r\n\t * the database.\r\n\t * @param value The value used by the application.\r\n\t * @param property The name of the document property to which this transform is being applied.\r\n\t * @param model The Iridium Model on which this transform is being applied\r\n\t * @returns The database optimized representation of the value.\r\n\t */\r\n\ttoDB(value: any, property: string, model: Model): T;\r\n}\r\n\r\nexport const DefaultTransforms = {\r\n \tObjectID: >{\r\n\t\tfromDB: value => value instanceof ObjectID ? value.toHexString() : value,\r\n\t\ttoDB: value => typeof value === \"string\" ? new ObjectID(value) : value\r\n\t},\r\n\tBinary: >{\r\n\t\tfromDB: value => {\r\n\t\t\tif(!value) return null;\r\n\t\t\tif(value instanceof Binary) return (value).buffer;\r\n\t\t\t\r\n\t\t\treturn value;\r\n\t\t},\r\n\t\ttoDB: value => {\r\n\t\t\tif(Buffer.isBuffer(value)) return new Binary(value);\r\n\t\t\tif(Array.isArray(value)) return new Binary(new Buffer(value));\r\n\t\t\treturn null;\r\n\t\t}\r\n\t}\r\n}"],"sourceRoot":"/source/"} \ No newline at end of file diff --git a/dist/lib/Validators.js b/dist/lib/Validators.js index 8e3f71e..3c9cc8a 100644 --- a/dist/lib/Validators.js +++ b/dist/lib/Validators.js @@ -1,12 +1,12 @@ "use strict"; -var MongoDB = require("mongodb"); -var Skmatc = require("skmatc"); +const MongoDB = require("mongodb"); +const Skmatc = require("skmatc"); function DefaultValidators() { return [ - Skmatc.create(function (schema) { return schema === MongoDB.ObjectID; }, function (schema, data) { + Skmatc.create(schema => schema === MongoDB.ObjectID, function (schema, data) { return this.assert(!data || data instanceof MongoDB.ObjectID || (data._bsontype === "ObjectID" && data.id), "Expected " + JSON.stringify(data) + " to be a valid MongoDB.ObjectID object"); }, { name: "ObjectID validation" }), - Skmatc.create(function (schema) { return schema === Buffer; }, function (schema, data) { + Skmatc.create(schema => schema === Buffer, function (schema, data) { return this.assert(data && (data instanceof MongoDB.Binary || (data._bsontype === "Binary" && data.buffer)), "Expected " + JSON.stringify(data) + " to be a valid MongoDB.Binary object"); }, { name: "Buffer validation" }) ]; diff --git a/dist/lib/Validators.js.map b/dist/lib/Validators.js.map index 39d1303..b12b6ff 100644 --- a/dist/lib/Validators.js.map +++ b/dist/lib/Validators.js.map @@ -1 +1 @@ -{"version":3,"sources":["lib/Validators.ts"],"names":[],"mappings":";AAAA,IAAY,OAAO,WAAM,SAAS,CAAC,CAAA;AACnC,IAAY,MAAM,WAAM,QAAQ,CAAC,CAAA;AAEjC;IACC,MAAM,CAAC;QACN,MAAM,CAAC,MAAM,CAAC,UAAA,MAAM,IAAI,OAAA,MAAM,KAAK,OAAO,CAAC,QAAQ,EAA3B,CAA2B,EAAE,UAAS,MAAM,EAAE,IAAI;YACzE,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,IAAI,IAAI,IAAI,YAAY,OAAO,CAAC,QAAQ,IAAI,CAAC,IAAI,CAAC,SAAS,KAAK,UAAU,IAAI,IAAI,CAAC,EAAE,CAAC,EAAE,WAAW,GAAG,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,GAAG,wCAAwC,CAAC,CAAC;QAC5L,CAAC,EAAE,EAAE,IAAI,EAAE,qBAAqB,EAAE,CAAC;QACnC,MAAM,CAAC,MAAM,CAAC,UAAA,MAAM,IAAI,OAAA,MAAM,KAAK,MAAM,EAAjB,CAAiB,EAAE,UAAS,MAAM,EAAE,IAAI;YAC/D,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,IAAI,IAAI,CAAC,IAAI,YAAY,OAAO,CAAC,MAAM,IAAI,CAAC,IAAI,CAAC,SAAS,KAAK,QAAQ,IAAI,IAAI,CAAC,MAAM,CAAC,CAAC,EAAE,WAAW,GAAG,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,GAAG,sCAAsC,CAAC,CAAC;QAC3L,CAAC,EAAE,EAAE,IAAI,EAAE,mBAAmB,EAAE,CAAC;KACjC,CAAC;AACH,CAAC;AATe,yBAAiB,oBAShC,CAAA","file":"lib/Validators.js","sourcesContent":["import * as MongoDB from \"mongodb\";\r\nimport * as Skmatc from \"skmatc\";\r\n\r\nexport function DefaultValidators() {\r\n\treturn [\r\n\t\tSkmatc.create(schema => schema === MongoDB.ObjectID, function(schema, data) {\r\n\t\t\treturn this.assert(!data || data instanceof MongoDB.ObjectID || (data._bsontype === \"ObjectID\" && data.id), \"Expected \" + JSON.stringify(data) + \" to be a valid MongoDB.ObjectID object\");\r\n\t\t}, { name: \"ObjectID validation\" }),\r\n\t\tSkmatc.create(schema => schema === Buffer, function(schema, data) {\r\n\t\t\treturn this.assert(data && (data instanceof MongoDB.Binary || (data._bsontype === \"Binary\" && data.buffer)), \"Expected \" + JSON.stringify(data) + \" to be a valid MongoDB.Binary object\");\r\n\t\t}, { name: \"Buffer validation\" })\r\n\t];\r\n}"],"sourceRoot":"/source/"} \ No newline at end of file +{"version":3,"sources":["lib/Validators.ts"],"names":[],"mappings":";AAAA,MAAY,OAAO,WAAM,SAAS,CAAC,CAAA;AACnC,MAAY,MAAM,WAAM,QAAQ,CAAC,CAAA;AAEjC;IACC,MAAM,CAAC;QACN,MAAM,CAAC,MAAM,CAAC,MAAM,IAAI,MAAM,KAAK,OAAO,CAAC,QAAQ,EAAE,UAAS,MAAM,EAAE,IAAI;YACzE,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,IAAI,IAAI,IAAI,YAAY,OAAO,CAAC,QAAQ,IAAI,CAAC,IAAI,CAAC,SAAS,KAAK,UAAU,IAAI,IAAI,CAAC,EAAE,CAAC,EAAE,WAAW,GAAG,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,GAAG,wCAAwC,CAAC,CAAC;QAC5L,CAAC,EAAE,EAAE,IAAI,EAAE,qBAAqB,EAAE,CAAC;QACnC,MAAM,CAAC,MAAM,CAAC,MAAM,IAAI,MAAM,KAAK,MAAM,EAAE,UAAS,MAAM,EAAE,IAAI;YAC/D,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,IAAI,IAAI,CAAC,IAAI,YAAY,OAAO,CAAC,MAAM,IAAI,CAAC,IAAI,CAAC,SAAS,KAAK,QAAQ,IAAI,IAAI,CAAC,MAAM,CAAC,CAAC,EAAE,WAAW,GAAG,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,GAAG,sCAAsC,CAAC,CAAC;QAC3L,CAAC,EAAE,EAAE,IAAI,EAAE,mBAAmB,EAAE,CAAC;KACjC,CAAC;AACH,CAAC;AATe,yBAAiB,oBAShC,CAAA","file":"lib/Validators.js","sourcesContent":["import * as MongoDB from \"mongodb\";\r\nimport * as Skmatc from \"skmatc\";\r\n\r\nexport function DefaultValidators() {\r\n\treturn [\r\n\t\tSkmatc.create(schema => schema === MongoDB.ObjectID, function(schema, data) {\r\n\t\t\treturn this.assert(!data || data instanceof MongoDB.ObjectID || (data._bsontype === \"ObjectID\" && data.id), \"Expected \" + JSON.stringify(data) + \" to be a valid MongoDB.ObjectID object\");\r\n\t\t}, { name: \"ObjectID validation\" }),\r\n\t\tSkmatc.create(schema => schema === Buffer, function(schema, data) {\r\n\t\t\treturn this.assert(data && (data instanceof MongoDB.Binary || (data._bsontype === \"Binary\" && data.buffer)), \"Expected \" + JSON.stringify(data) + \" to be a valid MongoDB.Binary object\");\r\n\t\t}, { name: \"Buffer validation\" })\r\n\t];\r\n}"],"sourceRoot":"/source/"} \ No newline at end of file diff --git a/dist/lib/cacheControllers/IDDirector.js b/dist/lib/cacheControllers/IDDirector.js index ede7112..88263ee 100644 --- a/dist/lib/cacheControllers/IDDirector.js +++ b/dist/lib/cacheControllers/IDDirector.js @@ -1,32 +1,29 @@ "use strict"; -var MongoDB = require("mongodb"); +const MongoDB = require("mongodb"); /** * Caches documents using their _id field as the unique cache key. This * is useful if you primarily query your documents using their _id field, * however can be suboptimal (or even a complete waste) if you use different * types of queries. */ -var CacheOnID = (function () { - function CacheOnID() { - } - CacheOnID.prototype.valid = function (object) { +class CacheOnID { + valid(object) { return !!object._id; - }; - CacheOnID.prototype.buildKey = function (object) { + } + buildKey(object) { if (object._id._bsontype === "ObjectID") return new MongoDB.ObjectID(object._id.id).toHexString(); return object._id; - }; - CacheOnID.prototype.validQuery = function (conditions) { + } + validQuery(conditions) { return !!conditions._id; - }; - CacheOnID.prototype.buildQueryKey = function (conditions) { + } + buildQueryKey(conditions) { if (conditions._id._bsontype === "ObjectID") return new MongoDB.ObjectID(conditions._id.id).toHexString(); return conditions._id; - }; - return CacheOnID; -}()); + } +} exports.CacheOnID = CacheOnID; //# sourceMappingURL=IDDirector.js.map diff --git a/dist/lib/cacheControllers/IDDirector.js.map b/dist/lib/cacheControllers/IDDirector.js.map index e1d6600..1b1c9ea 100644 --- a/dist/lib/cacheControllers/IDDirector.js.map +++ b/dist/lib/cacheControllers/IDDirector.js.map @@ -1 +1 @@ -{"version":3,"sources":["lib/cacheControllers/IDDirector.ts"],"names":[],"mappings":";AACA,IAAY,OAAO,WAAM,SAAS,CAAC,CAAA;AAEnC;;;;;GAKG;AACH;IAAA;IAoBA,CAAC;IAnBG,yBAAK,GAAL,UAAM,MAAoB;QACtB,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC;IACxB,CAAC;IAED,4BAAQ,GAAR,UAAS,MAAoB;QACzB,EAAE,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,SAAS,KAAK,UAAU,CAAC;YACpC,MAAM,CAAC,IAAI,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,WAAW,EAAE,CAAC;QAC7D,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC;IACtB,CAAC;IAED,8BAAU,GAAV,UAAW,UAAU;QACjB,MAAM,CAAC,CAAC,CAAC,UAAU,CAAC,GAAG,CAAC;IAC5B,CAAC;IAED,iCAAa,GAAb,UAAc,UAAU;QACpB,EAAE,CAAC,CAAC,UAAU,CAAC,GAAG,CAAC,SAAS,KAAK,UAAU,CAAC;YACxC,MAAM,CAAC,IAAI,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,WAAW,EAAE,CAAC;QACjE,MAAM,CAAC,UAAU,CAAC,GAAG,CAAC;IAC1B,CAAC;IACL,gBAAC;AAAD,CApBA,AAoBC,IAAA;AApBY,iBAAS,YAoBrB,CAAA","file":"lib/cacheControllers/IDDirector.js","sourcesContent":["import {CacheDirector} from \"../CacheDirector\";\r\nimport * as MongoDB from \"mongodb\";\r\n\r\n/**\r\n * Caches documents using their _id field as the unique cache key. This\r\n * is useful if you primarily query your documents using their _id field,\r\n * however can be suboptimal (or even a complete waste) if you use different\r\n * types of queries.\r\n */\r\nexport class CacheOnID implements CacheDirector{\r\n valid(object: { _id: any }) {\r\n return !!object._id;\r\n }\r\n\r\n buildKey(object: { _id: any }) {\r\n if (object._id._bsontype === \"ObjectID\")\r\n return new MongoDB.ObjectID(object._id.id).toHexString();\r\n return object._id;\r\n }\r\n\r\n validQuery(conditions) {\r\n return !!conditions._id;\r\n }\r\n\r\n buildQueryKey(conditions) {\r\n if (conditions._id._bsontype === \"ObjectID\")\r\n return new MongoDB.ObjectID(conditions._id.id).toHexString();\r\n return conditions._id;\r\n }\r\n}"],"sourceRoot":"/source/"} \ No newline at end of file +{"version":3,"sources":["lib/cacheControllers/IDDirector.ts"],"names":[],"mappings":";AACA,MAAY,OAAO,WAAM,SAAS,CAAC,CAAA;AAEnC;;;;;GAKG;AACH;IACI,KAAK,CAAC,MAAoB;QACtB,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC;IACxB,CAAC;IAED,QAAQ,CAAC,MAAoB;QACzB,EAAE,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,SAAS,KAAK,UAAU,CAAC;YACpC,MAAM,CAAC,IAAI,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,WAAW,EAAE,CAAC;QAC7D,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC;IACtB,CAAC;IAED,UAAU,CAAC,UAAU;QACjB,MAAM,CAAC,CAAC,CAAC,UAAU,CAAC,GAAG,CAAC;IAC5B,CAAC;IAED,aAAa,CAAC,UAAU;QACpB,EAAE,CAAC,CAAC,UAAU,CAAC,GAAG,CAAC,SAAS,KAAK,UAAU,CAAC;YACxC,MAAM,CAAC,IAAI,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,WAAW,EAAE,CAAC;QACjE,MAAM,CAAC,UAAU,CAAC,GAAG,CAAC;IAC1B,CAAC;AACL,CAAC;AApBY,iBAAS,YAoBrB,CAAA","file":"lib/cacheControllers/IDDirector.js","sourcesContent":["import {CacheDirector} from \"../CacheDirector\";\r\nimport * as MongoDB from \"mongodb\";\r\n\r\n/**\r\n * Caches documents using their _id field as the unique cache key. This\r\n * is useful if you primarily query your documents using their _id field,\r\n * however can be suboptimal (or even a complete waste) if you use different\r\n * types of queries.\r\n */\r\nexport class CacheOnID implements CacheDirector{\r\n valid(object: { _id: any }) {\r\n return !!object._id;\r\n }\r\n\r\n buildKey(object: { _id: any }) {\r\n if (object._id._bsontype === \"ObjectID\")\r\n return new MongoDB.ObjectID(object._id.id).toHexString();\r\n return object._id;\r\n }\r\n\r\n validQuery(conditions) {\r\n return !!conditions._id;\r\n }\r\n\r\n buildQueryKey(conditions) {\r\n if (conditions._id._bsontype === \"ObjectID\")\r\n return new MongoDB.ObjectID(conditions._id.id).toHexString();\r\n return conditions._id;\r\n }\r\n}"],"sourceRoot":"/source/"} \ No newline at end of file diff --git a/dist/lib/caches/MemoryCache.js b/dist/lib/caches/MemoryCache.js index eb979d6..b4e7e55 100644 --- a/dist/lib/caches/MemoryCache.js +++ b/dist/lib/caches/MemoryCache.js @@ -1,30 +1,29 @@ "use strict"; -var Bluebird = require("bluebird"); +const Bluebird = require("bluebird"); /** * A cache implementation which stores documents in an in-memory cache. * * Be aware that this is an incredibly simplistic implementation which doesn't manage * memory usage at all and is very likely NOT suitable for production use. */ -var MemoryCache = (function () { - function MemoryCache() { +class MemoryCache { + constructor() { this.cache = {}; } - MemoryCache.prototype.set = function (key, value) { + set(key, value) { this.cache[key] = value; return Bluebird.resolve(value); - }; - MemoryCache.prototype.get = function (key) { + } + get(key) { return Bluebird.resolve(this.cache[key]); - }; - MemoryCache.prototype.clear = function (key) { - var has = this.cache.hasOwnProperty(key); + } + clear(key) { + let has = this.cache.hasOwnProperty(key); if (has) delete this.cache[key]; return Bluebird.resolve(has); - }; - return MemoryCache; -}()); + } +} exports.MemoryCache = MemoryCache; //# sourceMappingURL=MemoryCache.js.map diff --git a/dist/lib/caches/MemoryCache.js.map b/dist/lib/caches/MemoryCache.js.map index baef17c..dba4e2b 100644 --- a/dist/lib/caches/MemoryCache.js.map +++ b/dist/lib/caches/MemoryCache.js.map @@ -1 +1 @@ -{"version":3,"sources":["lib/caches/MemoryCache.ts"],"names":[],"mappings":";AAAA,IAAY,QAAQ,WAAM,UAAU,CAAC,CAAA;AAGrC;;;;;GAKG;AACH;IAAA;QACY,UAAK,GAAQ,EAAE,CAAC;IAgB5B,CAAC;IAdG,yBAAG,GAAH,UAAO,GAAW,EAAE,KAAQ;QACxB,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC;QACxB,MAAM,CAAC,QAAQ,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;IACnC,CAAC;IAED,yBAAG,GAAH,UAAO,GAAW;QACd,MAAM,CAAC,QAAQ,CAAC,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC;IAC7C,CAAC;IAED,2BAAK,GAAL,UAAM,GAAW;QACb,IAAI,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC,cAAc,CAAC,GAAG,CAAC,CAAC;QACzC,EAAE,CAAA,CAAC,GAAG,CAAC;YAAC,OAAO,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;QAC/B,MAAM,CAAC,QAAQ,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;IACjC,CAAC;IACL,kBAAC;AAAD,CAjBA,AAiBC,IAAA;AAjBY,mBAAW,cAiBvB,CAAA","file":"lib/caches/MemoryCache.js","sourcesContent":["import * as Bluebird from \"bluebird\";\r\nimport {Cache} from \"../Cache\";\r\n\r\n/**\r\n * A cache implementation which stores documents in an in-memory cache.\r\n *\r\n * Be aware that this is an incredibly simplistic implementation which doesn't manage\r\n * memory usage at all and is very likely NOT suitable for production use.\r\n */\r\nexport class MemoryCache implements Cache {\r\n private cache: any = {};\r\n\r\n set(key: string, value: T): Bluebird {\r\n this.cache[key] = value;\r\n return Bluebird.resolve(value);\r\n }\r\n\r\n get(key: string): Bluebird {\r\n return Bluebird.resolve(this.cache[key]);\r\n }\r\n\r\n clear(key: string) : Bluebird {\r\n let has = this.cache.hasOwnProperty(key);\r\n if(has) delete this.cache[key];\r\n return Bluebird.resolve(has);\r\n }\r\n}"],"sourceRoot":"/source/"} \ No newline at end of file +{"version":3,"sources":["lib/caches/MemoryCache.ts"],"names":[],"mappings":";AAAA,MAAY,QAAQ,WAAM,UAAU,CAAC,CAAA;AAGrC;;;;;GAKG;AACH;IAAA;QACY,UAAK,GAAQ,EAAE,CAAC;IAgB5B,CAAC;IAdG,GAAG,CAAI,GAAW,EAAE,KAAQ;QACxB,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC;QACxB,MAAM,CAAC,QAAQ,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;IACnC,CAAC;IAED,GAAG,CAAI,GAAW;QACd,MAAM,CAAC,QAAQ,CAAC,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC;IAC7C,CAAC;IAED,KAAK,CAAC,GAAW;QACb,IAAI,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC,cAAc,CAAC,GAAG,CAAC,CAAC;QACzC,EAAE,CAAA,CAAC,GAAG,CAAC;YAAC,OAAO,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;QAC/B,MAAM,CAAC,QAAQ,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;IACjC,CAAC;AACL,CAAC;AAjBY,mBAAW,cAiBvB,CAAA","file":"lib/caches/MemoryCache.js","sourcesContent":["import * as Bluebird from \"bluebird\";\r\nimport {Cache} from \"../Cache\";\r\n\r\n/**\r\n * A cache implementation which stores documents in an in-memory cache.\r\n *\r\n * Be aware that this is an incredibly simplistic implementation which doesn't manage\r\n * memory usage at all and is very likely NOT suitable for production use.\r\n */\r\nexport class MemoryCache implements Cache {\r\n private cache: any = {};\r\n\r\n set(key: string, value: T): Bluebird {\r\n this.cache[key] = value;\r\n return Bluebird.resolve(value);\r\n }\r\n\r\n get(key: string): Bluebird {\r\n return Bluebird.resolve(this.cache[key]);\r\n }\r\n\r\n clear(key: string) : Bluebird {\r\n let has = this.cache.hasOwnProperty(key);\r\n if(has) delete this.cache[key];\r\n return Bluebird.resolve(has);\r\n }\r\n}"],"sourceRoot":"/source/"} \ No newline at end of file diff --git a/dist/lib/caches/NoOpCache.js b/dist/lib/caches/NoOpCache.js index ce8b286..52a07e9 100644 --- a/dist/lib/caches/NoOpCache.js +++ b/dist/lib/caches/NoOpCache.js @@ -1,5 +1,5 @@ "use strict"; -var Bluebird = require("bluebird"); +const Bluebird = require("bluebird"); /** * A cache implementation which does not cache any received documents * and returns nothing when requested - mimicking an empty cache. @@ -7,20 +7,17 @@ var Bluebird = require("bluebird"); * This is the default cache used if one is not supplied and should * not impose any significant performance overhead. */ -var NoOpCache = (function () { - function NoOpCache() { - } - NoOpCache.prototype.set = function (key, object) { +class NoOpCache { + set(key, object) { return Bluebird.resolve(object); - }; - NoOpCache.prototype.get = function (key) { + } + get(key) { return Bluebird.resolve(); - }; - NoOpCache.prototype.clear = function (key) { + } + clear(key) { return Bluebird.resolve(false); - }; - return NoOpCache; -}()); + } +} exports.NoOpCache = NoOpCache; //# sourceMappingURL=NoOpCache.js.map diff --git a/dist/lib/caches/NoOpCache.js.map b/dist/lib/caches/NoOpCache.js.map index e00ff94..7e083bb 100644 --- a/dist/lib/caches/NoOpCache.js.map +++ b/dist/lib/caches/NoOpCache.js.map @@ -1 +1 @@ -{"version":3,"sources":["lib/caches/NoOpCache.ts"],"names":[],"mappings":";AACA,IAAY,QAAQ,WAAM,UAAU,CAAC,CAAA;AAErC;;;;;;GAMG;AACH;IAAA;IAYA,CAAC;IAXG,uBAAG,GAAH,UAAO,GAAW,EAAE,MAAS;QACzB,MAAM,CAAC,QAAQ,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;IACpC,CAAC;IAED,uBAAG,GAAH,UAAO,GAAW;QACd,MAAM,CAAC,QAAQ,CAAC,OAAO,EAAE,CAAC;IAC9B,CAAC;IAED,yBAAK,GAAL,UAAM,GAAW;QACb,MAAM,CAAC,QAAQ,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;IACnC,CAAC;IACL,gBAAC;AAAD,CAZA,AAYC,IAAA;AAZY,iBAAS,YAYrB,CAAA","file":"lib/caches/NoOpCache.js","sourcesContent":["import {Cache} from \"../Cache\";\r\nimport * as Bluebird from \"bluebird\";\r\n\r\n/**\r\n * A cache implementation which does not cache any received documents\r\n * and returns nothing when requested - mimicking an empty cache.\r\n *\r\n * This is the default cache used if one is not supplied and should\r\n * not impose any significant performance overhead.\r\n */\r\nexport class NoOpCache implements Cache {\r\n set(key: string, object: T): Bluebird {\r\n return Bluebird.resolve(object);\r\n }\r\n\r\n get(key: string): Bluebird {\r\n return Bluebird.resolve();\r\n }\r\n\r\n clear(key: string): Bluebird {\r\n return Bluebird.resolve(false);\r\n }\r\n}"],"sourceRoot":"/source/"} \ No newline at end of file +{"version":3,"sources":["lib/caches/NoOpCache.ts"],"names":[],"mappings":";AACA,MAAY,QAAQ,WAAM,UAAU,CAAC,CAAA;AAErC;;;;;;GAMG;AACH;IACI,GAAG,CAAI,GAAW,EAAE,MAAS;QACzB,MAAM,CAAC,QAAQ,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;IACpC,CAAC;IAED,GAAG,CAAI,GAAW;QACd,MAAM,CAAC,QAAQ,CAAC,OAAO,EAAE,CAAC;IAC9B,CAAC;IAED,KAAK,CAAC,GAAW;QACb,MAAM,CAAC,QAAQ,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;IACnC,CAAC;AACL,CAAC;AAZY,iBAAS,YAYrB,CAAA","file":"lib/caches/NoOpCache.js","sourcesContent":["import {Cache} from \"../Cache\";\r\nimport * as Bluebird from \"bluebird\";\r\n\r\n/**\r\n * A cache implementation which does not cache any received documents\r\n * and returns nothing when requested - mimicking an empty cache.\r\n *\r\n * This is the default cache used if one is not supplied and should\r\n * not impose any significant performance overhead.\r\n */\r\nexport class NoOpCache implements Cache {\r\n set(key: string, object: T): Bluebird {\r\n return Bluebird.resolve(object);\r\n }\r\n\r\n get(key: string): Bluebird {\r\n return Bluebird.resolve();\r\n }\r\n\r\n clear(key: string): Bluebird {\r\n return Bluebird.resolve(false);\r\n }\r\n}"],"sourceRoot":"/source/"} \ No newline at end of file diff --git a/dist/lib/utils/ObjectID.js b/dist/lib/utils/ObjectID.js index 32f4deb..c72fcd7 100644 --- a/dist/lib/utils/ObjectID.js +++ b/dist/lib/utils/ObjectID.js @@ -1,5 +1,5 @@ "use strict"; -var MongoDB = require("mongodb"); +const MongoDB = require("mongodb"); /** * Converts a string to an ObjectID instance - a shortcut for require("mongodb").ObjectID.createFromHexString * diff --git a/dist/lib/utils/ObjectID.js.map b/dist/lib/utils/ObjectID.js.map index f209d6f..e8019a7 100644 --- a/dist/lib/utils/ObjectID.js.map +++ b/dist/lib/utils/ObjectID.js.map @@ -1 +1 @@ -{"version":3,"sources":["lib/utils/ObjectID.ts"],"names":[],"mappings":";AAAA,IAAY,OAAO,WAAM,SAAS,CAAC,CAAA;AAEnC;;;;;;;;;;;;GAYG;AACH,oBAA2B,KAAa;IACvC,MAAM,CAAC,OAAO,CAAC,QAAQ,CAAC,mBAAmB,CAAC,KAAK,CAAC,CAAC;AACpD,CAAC;AAFe,kBAAU,aAEzB,CAAA","file":"lib/utils/ObjectID.js","sourcesContent":["import * as MongoDB from \"mongodb\";\r\n\r\n/**\r\n * Converts a string to an ObjectID instance - a shortcut for require(\"mongodb\").ObjectID.createFromHexString\r\n *\r\n * @param value The string representation of the ObjectID you wish to create.\r\n * @returns A MongoDB ObjectID instance equivalent to the string you provided.\r\n *\r\n * You should be aware that this method performs no validation on the received string, MongoDB's ObjectID requires\r\n * that it either be a 12 byte UTF8 string, or a 24 byte hexadecimal string in order to be converted correctly.\r\n *\r\n * This method removes the need for your application to directly depend on MongoDB's Node.js client library,\r\n * which helps clean up your code a bit and reduces the headache of maintaining two different versions of the\r\n * library (since Iridium also has one).\r\n */\r\nexport function toObjectID(value: string): MongoDB.ObjectID {\r\n\treturn MongoDB.ObjectID.createFromHexString(value);\r\n}"],"sourceRoot":"/source/"} \ No newline at end of file +{"version":3,"sources":["lib/utils/ObjectID.ts"],"names":[],"mappings":";AAAA,MAAY,OAAO,WAAM,SAAS,CAAC,CAAA;AAEnC;;;;;;;;;;;;GAYG;AACH,oBAA2B,KAAa;IACvC,MAAM,CAAC,OAAO,CAAC,QAAQ,CAAC,mBAAmB,CAAC,KAAK,CAAC,CAAC;AACpD,CAAC;AAFe,kBAAU,aAEzB,CAAA","file":"lib/utils/ObjectID.js","sourcesContent":["import * as MongoDB from \"mongodb\";\r\n\r\n/**\r\n * Converts a string to an ObjectID instance - a shortcut for require(\"mongodb\").ObjectID.createFromHexString\r\n *\r\n * @param value The string representation of the ObjectID you wish to create.\r\n * @returns A MongoDB ObjectID instance equivalent to the string you provided.\r\n *\r\n * You should be aware that this method performs no validation on the received string, MongoDB's ObjectID requires\r\n * that it either be a 12 byte UTF8 string, or a 24 byte hexadecimal string in order to be converted correctly.\r\n *\r\n * This method removes the need for your application to directly depend on MongoDB's Node.js client library,\r\n * which helps clean up your code a bit and reduces the headache of maintaining two different versions of the\r\n * library (since Iridium also has one).\r\n */\r\nexport function toObjectID(value: string): MongoDB.ObjectID {\r\n\treturn MongoDB.ObjectID.createFromHexString(value);\r\n}"],"sourceRoot":"/source/"} \ No newline at end of file diff --git a/dist/lib/utils/Omnom.js b/dist/lib/utils/Omnom.js index 21de1e2..8c53f8d 100644 --- a/dist/lib/utils/Omnom.js +++ b/dist/lib/utils/Omnom.js @@ -1,28 +1,22 @@ "use strict"; -var _ = require("lodash"); -var MongoDB = require("mongodb"); -var Omnom = (function () { - function Omnom(options) { - if (options === void 0) { options = {}; } +const _ = require("lodash"); +const MongoDB = require("mongodb"); +class Omnom { + constructor(options = {}) { this.options = options; this._changes = {}; } - Object.defineProperty(Omnom.prototype, "changes", { - get: function () { - return this._changes; - }, - enumerable: true, - configurable: true - }); - Omnom.prototype.diff = function (original, modified) { + get changes() { + return this._changes; + } + diff(original, modified) { this.onObject(original, modified); return this; - }; - Omnom.diff = function (original, modified, options) { + } + static diff(original, modified, options) { return new Omnom(options).diff(original, modified).changes; - }; - Omnom.prototype.onObject = function (original, modified, changePath) { - var _this = this; + } + onObject(original, modified, changePath) { if (original === undefined || original === null) return (original !== modified) && this.set(changePath, modified); if (typeof original === "number" && typeof modified === "number" && original !== modified) { @@ -36,20 +30,20 @@ var Omnom = (function () { return !original.equals(modified) && this.set(changePath, modified); if (!_.isPlainObject(original) || !_.isPlainObject(modified)) return !_.isEqual(original, modified) && this.set(changePath, modified); - _.forOwn(modified, function (value, key) { + _.forOwn(modified, (value, key) => { // Handle array diffs in their own special way if (Array.isArray(value) && Array.isArray(original[key])) - _this.onArray(original[key], value, _this.resolve(changePath, key)); + this.onArray(original[key], value, this.resolve(changePath, key)); else - _this.onObject(original[key], value, _this.resolve(changePath, key)); + this.onObject(original[key], value, this.resolve(changePath, key)); }, this); // Unset removed properties - _.forOwn(original, function (value, key) { + _.forOwn(original, (value, key) => { if (modified[key] === undefined) - return _this.unset(_this.resolve(changePath, key)); + return this.unset(this.resolve(changePath, key)); }, this); - }; - Omnom.prototype.onArray = function (original, modified, changePath) { + } + onArray(original, modified, changePath) { // Check if we can get from original => modified using just pulls if (original.length > modified.length) { return this.onSmallerArray(original, modified, changePath); @@ -60,12 +54,11 @@ var Omnom = (function () { } // Otherwise, we need to use $set to generate the new array return this.onSimilarArray(original, modified, changePath); - }; - Omnom.prototype.onSmallerArray = function (original, modified, changePath) { - var _this = this; - var pulls = []; - var i = 0; - var j = 0; + } + onSmallerArray(original, modified, changePath) { + let pulls = []; + let i = 0; + let j = 0; for (; i < original.length && j < modified.length; i++) { if (this.almostEqual(original[i], modified[j])) j++; @@ -78,32 +71,32 @@ var Omnom = (function () { if (pulls.length === 1) return this.pull(changePath, pulls[0]); // We can complete using just pulls - return pulls.forEach(function (pull) { return _this.pull(changePath, pull); }); + return pulls.forEach((pull) => this.pull(changePath, pull)); } else return this.set(changePath, modified); - }; - Omnom.prototype.onLargerArray = function (original, modified, changePath) { - var canPush = true; - for (var i = 0; i < original.length; i++) + } + onLargerArray(original, modified, changePath) { + let canPush = true; + for (let i = 0; i < original.length; i++) if (this.almostEqual(original[i], modified[i]) < 1) { canPush = false; break; } if (canPush) { - for (var i = original.length; i < modified.length; i++) + for (let i = original.length; i < modified.length; i++) this.push(changePath, modified[i]); return; } return this.onSimilarArray(original, modified, changePath); - }; - Omnom.prototype.onSimilarArray = function (original, modified, changePath) { + } + onSimilarArray(original, modified, changePath) { // Check how many manipulations would need to be performed, if it's more than half the array size // then rather re-create the array - var sets = []; - var partials = []; - for (var i = 0; i < modified.length; i++) { - var equality = this.almostEqual(original[i], modified[i]); + let sets = []; + let partials = []; + for (let i = 0; i < modified.length; i++) { + let equality = this.almostEqual(original[i], modified[i]); if (equality === 0) sets.push(i); else if (equality < 1) @@ -111,27 +104,27 @@ var Omnom = (function () { } if (sets.length > modified.length / 2) return this.set(changePath, modified); - for (var i = 0; i < sets.length; i++) + for (let i = 0; i < sets.length; i++) this.set(this.resolve(changePath, sets[i].toString()), modified[sets[i]]); - for (var i = 0; i < partials.length; i++) + for (let i = 0; i < partials.length; i++) this.onObject(original[partials[i]], modified[partials[i]], this.resolve(changePath, partials[i].toString())); - }; - Omnom.prototype.set = function (path, value) { + } + set(path, value) { if (!this.changes.$set) this.changes.$set = {}; this.changes.$set[path] = value; - }; - Omnom.prototype.unset = function (path) { + } + unset(path) { if (!this.changes.$unset) this.changes.$unset = {}; this.changes.$unset[path] = 1; - }; - Omnom.prototype.inc = function (path, value) { + } + inc(path, value) { if (!this.changes.$inc) this.changes.$inc = {}; this.changes.$inc[path] = value; - }; - Omnom.prototype.push = function (path, value) { + } + push(path, value) { if (!this.changes.$push) this.changes.$push = {}; if (this.changes.$push[path]) { @@ -142,8 +135,8 @@ var Omnom = (function () { } else this.changes.$push[path] = value; - }; - Omnom.prototype.pull = function (path, value) { + } + pull(path, value) { if (!this.changes.$pull) this.changes.$pull = {}; if (this.changes.$pullAll && this.changes.$pullAll[path]) { @@ -157,43 +150,38 @@ var Omnom = (function () { return; } this.changes.$pull[path] = value; - }; - Omnom.prototype.pullAll = function (path, values) { + } + pullAll(path, values) { if (!this.changes.$pullAll) this.changes.$pullAll = {}; this.changes.$pullAll[path] = values; - }; - Omnom.prototype.resolve = function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i - 0] = arguments[_i]; - } - var validArguments = []; + } + resolve(...args) { + let validArguments = []; args.forEach(function (arg) { if (arg) validArguments.push(arg); }); return validArguments.join("."); - }; - Omnom.prototype.almostEqual = function (o1, o2) { + } + almostEqual(o1, o2) { if (!_.isPlainObject(o1) || !_.isPlainObject(o2)) return o1 == o2 ? 1 : 0; - var object1KeyIndex, object1Keys = Object.keys(o1); - var object2Keys = Object.keys(o2); - var commonKeys = []; + let object1KeyIndex, object1Keys = Object.keys(o1); + let object2Keys = Object.keys(o2); + let commonKeys = []; for (object1KeyIndex = 0; object1KeyIndex < object1Keys.length; object1KeyIndex++) if (~object2Keys.indexOf(object1Keys[object1KeyIndex])) commonKeys.push(object1Keys[object1KeyIndex]); - var totalKeys = object1Keys.length + object2Keys.length - commonKeys.length; - var keysDifference = totalKeys - commonKeys.length; - var requiredChanges = 0; - for (var i = 0; i < commonKeys.length; i++) + let totalKeys = object1Keys.length + object2Keys.length - commonKeys.length; + let keysDifference = totalKeys - commonKeys.length; + let requiredChanges = 0; + for (let i = 0; i < commonKeys.length; i++) if (this.almostEqual(o1[commonKeys[i]], o2[commonKeys[i]]) < 1) requiredChanges++; return 1 - (keysDifference / totalKeys) - (requiredChanges / commonKeys.length); - }; - return Omnom; -}()); + } +} exports.Omnom = Omnom; //# sourceMappingURL=Omnom.js.map diff --git a/dist/lib/utils/Omnom.js.map b/dist/lib/utils/Omnom.js.map index f55af58..5480f01 100644 --- a/dist/lib/utils/Omnom.js.map +++ b/dist/lib/utils/Omnom.js.map @@ -1 +1 @@ -{"version":3,"sources":["lib/utils/Omnom.ts"],"names":[],"mappings":";AAAA,IAAY,CAAC,WAAM,QAAQ,CAAC,CAAA;AAC5B,IAAY,OAAO,WAAM,SAAS,CAAC,CAAA;AAEnC;IACI,eAAmB,OAEb;QAFM,uBAEN,GAFM,YAEN;QAFa,YAAO,GAAP,OAAO,CAEpB;QACF,IAAI,CAAC,QAAQ,GAAG,EAAE,CAAC;IACvB,CAAC;IAUD,sBAAI,0BAAO;aAAX;YAQI,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC;QACzB,CAAC;;;OAAA;IAMD,oBAAI,GAAJ,UAAK,QAAa,EAAE,QAAa;QAC7B,IAAI,CAAC,QAAQ,CAAC,QAAQ,EAAE,QAAQ,CAAC,CAAC;QAClC,MAAM,CAAC,IAAI,CAAC;IAChB,CAAC;IAcM,UAAI,GAAX,UAAY,QAAa,EAAE,QAAa,EAAE,OAEzC;QACG,MAAM,CAAC,IAAI,KAAK,CAAC,OAAO,CAAC,CAAC,IAAI,CAAC,QAAQ,EAAE,QAAQ,CAAC,CAAC,OAAO,CAAC;IAC/D,CAAC;IAMO,wBAAQ,GAAhB,UAAiB,QAAa,EAAE,QAAa,EAAE,UAAmB;QAAlE,iBA8BC;QA7BG,EAAE,CAAC,CAAC,QAAQ,KAAK,SAAS,IAAI,QAAQ,KAAK,IAAI,CAAC;YAC5C,MAAM,CAAC,CAAC,QAAQ,KAAK,QAAQ,CAAC,IAAI,IAAI,CAAC,GAAG,CAAC,UAAU,EAAE,QAAQ,CAAC,CAAC;QAErE,EAAE,CAAC,CAAC,OAAO,QAAQ,KAAK,QAAQ,IAAI,OAAO,QAAQ,KAAK,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AAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;gBAAC,eAAe,EAAE,CAAC;QAEtF,MAAM,CAAC,CAAC,GAAG,CAAC,cAAc,GAAG,SAAS,CAAC,GAAG,CAAC,eAAe,GAAG,UAAU,CAAC,MAAM,CAAC,CAAC;IACpF,CAAC;IACL,YAAC;AAAD,CA7PA,AA6PC,IAAA;AA7PY,aAAK,QA6PjB,CAAA","file":"lib/utils/Omnom.js","sourcesContent":["import * as _ from \"lodash\";\r\nimport * as MongoDB from \"mongodb\";\r\n\r\nexport class Omnom {\r\n constructor(public options: {\r\n atomicNumbers?: boolean;\r\n } = {}) {\r\n this._changes = {};\r\n }\r\n\r\n private _changes: {\r\n $set?: any;\r\n $unset?: any;\r\n $inc?: any;\r\n $push?: any;\r\n $pull?: any;\r\n $pullAll?: any;\r\n };\r\n get changes(): {\r\n $set?: any;\r\n $unset?: any;\r\n $inc?: any;\r\n $push?: any;\r\n $pull?: any;\r\n $pullAll?: any;\r\n } {\r\n return this._changes;\r\n }\r\n\r\n diff(original: number, modified: number): Omnom;\r\n diff(original: [any], modified: any[]): Omnom;\r\n diff(original: MongoDB.ObjectID, modified: MongoDB.ObjectID): Omnom;\r\n diff(original: Object, modified: Object): Omnom;\r\n diff(original: any, modified: any): Omnom {\r\n this.onObject(original, modified);\r\n return this;\r\n }\r\n\r\n static diff(original: number, modified: number, options?: {\r\n atomicNumbers?: boolean;\r\n });\r\n static diff(original: [any], modified: any[], options?: {\r\n atomicNumbers?: boolean;\r\n });\r\n static diff(original: MongoDB.ObjectID, modified: MongoDB.ObjectID, options?: {\r\n atomicNumbers?: boolean;\r\n });\r\n static diff(original: Object, modified: Object, options?: {\r\n atomicNumbers?: boolean;\r\n });\r\n static diff(original: any, modified: any, options?: {\r\n atomicNumbers?: boolean;\r\n }) {\r\n return new Omnom(options).diff(original, modified).changes;\r\n }\r\n\r\n private onObject(original: number, modified: number, changePath?: string): void;\r\n private onObject(original: [any], modified: any[], changePath?: string): void;\r\n private onObject(original: MongoDB.ObjectID, modified: MongoDB.ObjectID, changePath?: string): void;\r\n private onObject(original: Object, modified: Object, changePath?: string): void;\r\n private onObject(original: any, modified: any, changePath?: string): void {\r\n if (original === undefined || original === null)\r\n return (original !== modified) && this.set(changePath, modified);\r\n\r\n if (typeof original === \"number\" && typeof modified === \"number\" && original !== modified) {\r\n if (this.options.atomicNumbers) return this.inc(changePath, modified - original);\r\n return this.set(changePath, modified);\r\n }\r\n\r\n if (Array.isArray(original) && Array.isArray(modified))\r\n return this.onArray(original, modified, changePath);\r\n\r\n if (original instanceof MongoDB.ObjectID && modified instanceof MongoDB.ObjectID)\r\n return !original.equals(modified) && this.set(changePath, modified);\r\n\r\n if (!_.isPlainObject(original) || !_.isPlainObject(modified))\r\n return !_.isEqual(original, modified) && this.set(changePath, modified);\r\n\r\n _.forOwn(modified, (value, key) => {\r\n // Handle array diffs in their own special way\r\n if (Array.isArray(value) && Array.isArray(original[key])) this.onArray(original[key], value, this.resolve(changePath, key));\r\n\r\n // Otherwise, just keep going\r\n else this.onObject(original[key], value, this.resolve(changePath, key));\r\n }, this);\r\n\r\n // Unset removed properties\r\n _.forOwn(original, (value, key) => {\r\n if (modified[key] === undefined) return this.unset(this.resolve(changePath, key));\r\n }, this);\r\n }\r\n\r\n private onArray(original: any[], modified: any[], changePath: string): void {\r\n // Check if we can get from original => modified using just pulls\r\n if (original.length > modified.length) {\r\n return this.onSmallerArray(original, modified, changePath);\r\n }\r\n\r\n // Check if we can get from original => modified using just pushes\r\n if (original.length < modified.length) {\r\n return this.onLargerArray(original, modified, changePath);\r\n }\r\n\r\n // Otherwise, we need to use $set to generate the new array\r\n return this.onSimilarArray(original, modified, changePath);\r\n }\r\n\r\n private onSmallerArray(original: any[], modified: any[], changePath: string): void {\r\n let pulls = [];\r\n let i = 0;\r\n let j = 0;\r\n \r\n for (; i < original.length && j < modified.length; i++) {\r\n if (this.almostEqual(original[i], modified[j])) j++;\r\n else pulls.push(original[i]);\r\n }\r\n\r\n for (; i < original.length; i++)\r\n pulls.push(original[i]);\r\n\r\n if (j === modified.length) {\r\n if (pulls.length === 1) return this.pull(changePath, pulls[0]);\r\n // We can complete using just pulls\r\n return pulls.forEach((pull) => this.pull(changePath, pull));\r\n }\r\n\r\n // If we have a smaller target array than our source, we will need to re-create it\r\n // regardless (if we want to do so in a single operation anyway)\r\n else return this.set(changePath, modified);\r\n }\r\n \r\n private onLargerArray(original: any[], modified: any[], changePath: string): void {\r\n let canPush = true;\r\n for (let i = 0; i < original.length; i++)\r\n if (this.almostEqual(original[i], modified[i]) < 1) {\r\n canPush = false;\r\n break;\r\n }\r\n\r\n if (canPush) {\r\n for (let i = original.length; i < modified.length; i++)\r\n this.push(changePath, modified[i]);\r\n return;\r\n }\r\n \r\n return this.onSimilarArray(original, modified, changePath);\r\n }\r\n \r\n private onSimilarArray(original: any[], modified: any[], changePath: string): void {\r\n // Check how many manipulations would need to be performed, if it's more than half the array size\r\n // then rather re-create the array\r\n let sets = [];\r\n let partials = [];\r\n for (let i = 0; i < modified.length; i++) {\r\n let equality = this.almostEqual(original[i], modified[i]);\r\n if (equality === 0) sets.push(i);\r\n else if (equality < 1) partials.push(i);\r\n }\r\n\r\n if (sets.length > modified.length / 2)\r\n return this.set(changePath, modified);\r\n\r\n for (let i = 0; i < sets.length; i++)\r\n this.set(this.resolve(changePath, sets[i].toString()), modified[sets[i]]);\r\n\r\n for (let i = 0; i < partials.length; i++)\r\n this.onObject(original[partials[i]], modified[partials[i]], this.resolve(changePath, partials[i].toString()));\r\n }\r\n\r\n private set(path: string, value: any) {\r\n if (!this.changes.$set)\r\n this.changes.$set = {};\r\n\r\n this.changes.$set[path] = value;\r\n }\r\n\r\n private unset(path: string) {\r\n if (!this.changes.$unset)\r\n this.changes.$unset = {};\r\n\r\n this.changes.$unset[path] = 1;\r\n }\r\n\r\n private inc(path: string, value: number) {\r\n if (!this.changes.$inc)\r\n this.changes.$inc = {};\r\n\r\n this.changes.$inc[path] = value;\r\n }\r\n\r\n private push(path: string, value: any) {\r\n if (!this.changes.$push)\r\n this.changes.$push = {};\r\n\r\n if (this.changes.$push[path]) {\r\n if (this.changes.$push[path].$each)\r\n this.changes.$push[path].$each.push(value);\r\n else\r\n this.changes.$push[path] = { $each: [this.changes.$push[path], value] };\r\n } else this.changes.$push[path] = value;\r\n }\r\n\r\n private pull(path: string, value: any) {\r\n if (!this.changes.$pull)\r\n this.changes.$pull = {};\r\n\r\n if (this.changes.$pullAll && this.changes.$pullAll[path]) {\r\n return this.changes.$pullAll[path].push(value);\r\n }\r\n\r\n if (this.changes.$pull[path]) {\r\n this.pullAll(path, [this.changes.$pull[path], value]);\r\n delete this.changes.$pull[path];\r\n if (_.keys(this.changes.$pull).length === 0)\r\n delete this.changes.$pull;\r\n return;\r\n }\r\n\r\n this.changes.$pull[path] = value;\r\n }\r\n\r\n private pullAll(path: string, values: any[]) {\r\n if (!this.changes.$pullAll)\r\n this.changes.$pullAll = {};\r\n\r\n this.changes.$pullAll[path] = values;\r\n }\r\n\r\n private resolve(...args) {\r\n let validArguments = [];\r\n args.forEach(function (arg) {\r\n if (arg) validArguments.push(arg);\r\n });\r\n return validArguments.join(\".\");\r\n }\r\n\r\n private almostEqual(o1: Object, o2: Object);\r\n private almostEqual(o1: any, o2: any) {\r\n if (!_.isPlainObject(o1) || !_.isPlainObject(o2)) return o1 == o2 ? 1 : 0;\r\n\r\n let object1KeyIndex, object1Keys = Object.keys(o1);\r\n let object2Keys = Object.keys(o2);\r\n\r\n let commonKeys = [];\r\n for (object1KeyIndex = 0; object1KeyIndex < object1Keys.length; object1KeyIndex++)\r\n if (~object2Keys.indexOf(object1Keys[object1KeyIndex])) commonKeys.push(object1Keys[object1KeyIndex]);\r\n\r\n let totalKeys = object1Keys.length + object2Keys.length - commonKeys.length;\r\n let keysDifference = totalKeys - commonKeys.length;\r\n\r\n let requiredChanges = 0;\r\n for (let i = 0; i < commonKeys.length; i++)\r\n if (this.almostEqual(o1[commonKeys[i]], o2[commonKeys[i]]) < 1) requiredChanges++;\r\n\r\n return 1 - (keysDifference / totalKeys) - (requiredChanges / commonKeys.length);\r\n }\r\n}"],"sourceRoot":"/source/"} \ No newline at end of file +{"version":3,"sources":["lib/utils/Omnom.ts"],"names":[],"mappings":";AAAA,MAAY,CAAC,WAAM,QAAQ,CAAC,CAAA;AAC5B,MAAY,OAAO,WAAM,SAAS,CAAC,CAAA;AAEnC;IACI,YAAmB,OAAO,GAEtB,EAAE;QAFa,YAAO,GAAP,OAAO,CAEpB;QACF,IAAI,CAAC,QAAQ,GAAG,EAAE,CAAC;IACvB,CAAC;IAUD,IAAI,OAAO;QAQP,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC;IACzB,CAAC;IAMD,IAAI,CAAC,QAAa,EAAE,QAAa;QAC7B,IAAI,CAAC,QAAQ,CAAC,QAAQ,EAAE,QAAQ,CAAC,CAAC;QAClC,MAAM,CAAC,IAAI,CAAC;IAChB,CAAC;IAcD,OAAO,IAAI,CAAC,QAAa,EAAE,QAAa,EAAE,OAEzC;QACG,MAAM,CAAC,IAAI,KAAK,CAAC,OAAO,CAAC,CAAC,IAAI,CAAC,QAAQ,EAAE,QAAQ,CAAC,CAAC,OAAO,CAAC;IAC/D,CAAC;IAMO,QAAQ,CAAC,QAAa,EAAE,QAAa,EAAE,UAAmB;QAC9D,EAAE,CAAC,CAAC,QAAQ,KAAK,SAAS,IAAI,QAAQ,KAAK,IAAI,CAAC;YAC5C,MAAM,CAAC,CAAC,QAAQ,KAAK,QAAQ,CAAC,IAAI,IAAI,CAAC,GAAG,CAAC,UAAU,EAAE,QAAQ,CAAC,CAAC;QAErE,EAAE,CAAC,CAAC,OAAO,QAAQ,KAAK,QAAQ,IAAI,OAAO,QAAQ,KAAK,QAAQ,IAAI,QAAQ,KAAK,QAAQ,CAAC,CAAC,CAAC;YACxF,EAAE,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,aAAa,CAAC;gBAAC,MAAM,CAAC,IAAI,CAAC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nom {\r\n constructor(public options: {\r\n atomicNumbers?: boolean;\r\n } = {}) {\r\n this._changes = {};\r\n }\r\n\r\n private _changes: {\r\n $set?: any;\r\n $unset?: any;\r\n $inc?: any;\r\n $push?: any;\r\n $pull?: any;\r\n $pullAll?: any;\r\n };\r\n get changes(): {\r\n $set?: any;\r\n $unset?: any;\r\n $inc?: any;\r\n $push?: any;\r\n $pull?: any;\r\n $pullAll?: any;\r\n } {\r\n return this._changes;\r\n }\r\n\r\n diff(original: number, modified: number): Omnom;\r\n diff(original: [any], modified: any[]): Omnom;\r\n diff(original: MongoDB.ObjectID, modified: MongoDB.ObjectID): Omnom;\r\n diff(original: Object, modified: Object): Omnom;\r\n diff(original: any, modified: any): Omnom {\r\n this.onObject(original, modified);\r\n return this;\r\n }\r\n\r\n static diff(original: number, modified: number, options?: {\r\n atomicNumbers?: boolean;\r\n });\r\n static diff(original: [any], modified: any[], options?: {\r\n atomicNumbers?: boolean;\r\n });\r\n static diff(original: MongoDB.ObjectID, modified: MongoDB.ObjectID, options?: {\r\n atomicNumbers?: boolean;\r\n });\r\n static diff(original: Object, modified: Object, options?: {\r\n atomicNumbers?: boolean;\r\n });\r\n static diff(original: any, modified: any, options?: {\r\n atomicNumbers?: boolean;\r\n }) {\r\n return new Omnom(options).diff(original, modified).changes;\r\n }\r\n\r\n private onObject(original: number, modified: number, changePath?: string): void;\r\n private onObject(original: [any], modified: any[], changePath?: string): void;\r\n private onObject(original: MongoDB.ObjectID, modified: MongoDB.ObjectID, changePath?: string): void;\r\n private onObject(original: Object, modified: Object, changePath?: string): void;\r\n private onObject(original: any, modified: any, changePath?: string): void {\r\n if (original === undefined || original === null)\r\n return (original !== modified) && this.set(changePath, modified);\r\n\r\n if (typeof original === \"number\" && typeof modified === \"number\" && original !== modified) {\r\n if (this.options.atomicNumbers) return this.inc(changePath, modified - original);\r\n return this.set(changePath, modified);\r\n }\r\n\r\n if (Array.isArray(original) && Array.isArray(modified))\r\n return this.onArray(original, modified, changePath);\r\n\r\n if (original instanceof MongoDB.ObjectID && modified instanceof MongoDB.ObjectID)\r\n return !original.equals(modified) && this.set(changePath, modified);\r\n\r\n if (!_.isPlainObject(original) || !_.isPlainObject(modified))\r\n return !_.isEqual(original, modified) && this.set(changePath, modified);\r\n\r\n _.forOwn(modified, (value, key) => {\r\n // Handle array diffs in their own special way\r\n if (Array.isArray(value) && Array.isArray(original[key])) this.onArray(original[key], value, this.resolve(changePath, key));\r\n\r\n // Otherwise, just keep going\r\n else this.onObject(original[key], value, this.resolve(changePath, key));\r\n }, this);\r\n\r\n // Unset removed properties\r\n _.forOwn(original, (value, key) => {\r\n if (modified[key] === undefined) return this.unset(this.resolve(changePath, key));\r\n }, this);\r\n }\r\n\r\n private onArray(original: any[], modified: any[], changePath: string): void {\r\n // Check if we can get from original => modified using just pulls\r\n if (original.length > modified.length) {\r\n return this.onSmallerArray(original, modified, changePath);\r\n }\r\n\r\n // Check if we can get from original => modified using just pushes\r\n if (original.length < modified.length) {\r\n return this.onLargerArray(original, modified, changePath);\r\n }\r\n\r\n // Otherwise, we need to use $set to generate the new array\r\n return this.onSimilarArray(original, modified, changePath);\r\n }\r\n\r\n private onSmallerArray(original: any[], modified: any[], changePath: string): void {\r\n let pulls = [];\r\n let i = 0;\r\n let j = 0;\r\n \r\n for (; i < original.length && j < modified.length; i++) {\r\n if (this.almostEqual(original[i], modified[j])) j++;\r\n else pulls.push(original[i]);\r\n }\r\n\r\n for (; i < original.length; i++)\r\n pulls.push(original[i]);\r\n\r\n if (j === modified.length) {\r\n if (pulls.length === 1) return this.pull(changePath, pulls[0]);\r\n // We can complete using just pulls\r\n return pulls.forEach((pull) => this.pull(changePath, pull));\r\n }\r\n\r\n // If we have a smaller target array than our source, we will need to re-create it\r\n // regardless (if we want to do so in a single operation anyway)\r\n else return this.set(changePath, modified);\r\n }\r\n \r\n private onLargerArray(original: any[], modified: any[], changePath: string): void {\r\n let canPush = true;\r\n for (let i = 0; i < original.length; i++)\r\n if (this.almostEqual(original[i], modified[i]) < 1) {\r\n canPush = false;\r\n break;\r\n }\r\n\r\n if (canPush) {\r\n for (let i = original.length; i < modified.length; i++)\r\n this.push(changePath, modified[i]);\r\n return;\r\n }\r\n \r\n return this.onSimilarArray(original, modified, changePath);\r\n }\r\n \r\n private onSimilarArray(original: any[], modified: any[], changePath: string): void {\r\n // Check how many manipulations would need to be performed, if it's more than half the array size\r\n // then rather re-create the array\r\n let sets = [];\r\n let partials = [];\r\n for (let i = 0; i < modified.length; i++) {\r\n let equality = this.almostEqual(original[i], modified[i]);\r\n if (equality === 0) sets.push(i);\r\n else if (equality < 1) partials.push(i);\r\n }\r\n\r\n if (sets.length > modified.length / 2)\r\n return this.set(changePath, modified);\r\n\r\n for (let i = 0; i < sets.length; i++)\r\n this.set(this.resolve(changePath, sets[i].toString()), modified[sets[i]]);\r\n\r\n for (let i = 0; i < partials.length; i++)\r\n this.onObject(original[partials[i]], modified[partials[i]], this.resolve(changePath, partials[i].toString()));\r\n }\r\n\r\n private set(path: string, value: any) {\r\n if (!this.changes.$set)\r\n this.changes.$set = {};\r\n\r\n this.changes.$set[path] = value;\r\n }\r\n\r\n private unset(path: string) {\r\n if (!this.changes.$unset)\r\n this.changes.$unset = {};\r\n\r\n this.changes.$unset[path] = 1;\r\n }\r\n\r\n private inc(path: string, value: number) {\r\n if (!this.changes.$inc)\r\n this.changes.$inc = {};\r\n\r\n this.changes.$inc[path] = value;\r\n }\r\n\r\n private push(path: string, value: any) {\r\n if (!this.changes.$push)\r\n this.changes.$push = {};\r\n\r\n if (this.changes.$push[path]) {\r\n if (this.changes.$push[path].$each)\r\n this.changes.$push[path].$each.push(value);\r\n else\r\n this.changes.$push[path] = { $each: [this.changes.$push[path], value] };\r\n } else this.changes.$push[path] = value;\r\n }\r\n\r\n private pull(path: string, value: any) {\r\n if (!this.changes.$pull)\r\n this.changes.$pull = {};\r\n\r\n if (this.changes.$pullAll && this.changes.$pullAll[path]) {\r\n return this.changes.$pullAll[path].push(value);\r\n }\r\n\r\n if (this.changes.$pull[path]) {\r\n this.pullAll(path, [this.changes.$pull[path], value]);\r\n delete this.changes.$pull[path];\r\n if (_.keys(this.changes.$pull).length === 0)\r\n delete this.changes.$pull;\r\n return;\r\n }\r\n\r\n this.changes.$pull[path] = value;\r\n }\r\n\r\n private pullAll(path: string, values: any[]) {\r\n if (!this.changes.$pullAll)\r\n this.changes.$pullAll = {};\r\n\r\n this.changes.$pullAll[path] = values;\r\n }\r\n\r\n private resolve(...args) {\r\n let validArguments = [];\r\n args.forEach(function (arg) {\r\n if (arg) validArguments.push(arg);\r\n });\r\n return validArguments.join(\".\");\r\n }\r\n\r\n private almostEqual(o1: Object, o2: Object);\r\n private almostEqual(o1: any, o2: any) {\r\n if (!_.isPlainObject(o1) || !_.isPlainObject(o2)) return o1 == o2 ? 1 : 0;\r\n\r\n let object1KeyIndex, object1Keys = Object.keys(o1);\r\n let object2Keys = Object.keys(o2);\r\n\r\n let commonKeys = [];\r\n for (object1KeyIndex = 0; object1KeyIndex < object1Keys.length; object1KeyIndex++)\r\n if (~object2Keys.indexOf(object1Keys[object1KeyIndex])) commonKeys.push(object1Keys[object1KeyIndex]);\r\n\r\n let totalKeys = object1Keys.length + object2Keys.length - commonKeys.length;\r\n let keysDifference = totalKeys - commonKeys.length;\r\n\r\n let requiredChanges = 0;\r\n for (let i = 0; i < commonKeys.length; i++)\r\n if (this.almostEqual(o1[commonKeys[i]], o2[commonKeys[i]]) < 1) requiredChanges++;\r\n\r\n return 1 - (keysDifference / totalKeys) - (requiredChanges / commonKeys.length);\r\n }\r\n}"],"sourceRoot":"/source/"} \ No newline at end of file diff --git a/dist/main.d.ts b/dist/main.d.ts index a098df5..50e82e2 100644 --- a/dist/main.d.ts +++ b/dist/main.d.ts @@ -1,3074 +1,3201 @@ // 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; -} +// 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 -export class Promise implements Thenable { +class Bluebird implements Bluebird.Thenable, Bluebird.Inspection { /** - * 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(). + * 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 : (value?: R | Thenable) => void, reject: (error?: any) => void) => void); + constructor(callback: (resolve: (thenableOrResult: R | Bluebird.Thenable) => void, reject: (error: any) => void) => void); /** - * 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. + * 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. * - * @param onFulfilled called when/if "promise" resolves - * @param onRejected called when/if "promise" rejects + * Alias `.caught();` for compatibility with earlier ECMAScript version. */ - then (onFulfilled?: (value: R) => U | Thenable, onRejected?: (error: any) => U | Thenable): Promise; - then (onFulfilled?: (value: R) => U | Thenable, onRejected?: (error: any) => void): Promise; + catch(onReject?: (error: any) => R | Bluebird.Thenable | void | Bluebird.Thenable): Bluebird; + catch(onReject?: (error: any) => U | Bluebird.Thenable): Bluebird; /** - * Sugar for promise.then(undefined, onRejected) + * 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. * - * @param onRejected called when/if "promise" rejects + * 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 (onRejected?: (error: any) => U | Thenable): Promise; + 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; /** - * Make a new promise from the thenable. - * A thenable is promise-like in as far as it has a "then" method. + * 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. */ - static resolve (): Promise; - static resolve (value: R | Thenable): Promise; + error(onReject: (reason: any) => U | Bluebird.Thenable): Bluebird; /** - * Make a promise that rejects to obj. For consistency and debugging (eg stack traces), obj should be an instanceof Error + * 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. */ - static reject (error: any): Promise; + finally(handler: () => U | Bluebird.Thenable): Bluebird; + + lastly(handler: () => U | Bluebird.Thenable): Bluebird; /** - * 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. + * 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. */ - 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; + bind(thisArg: any): Bluebird; /** - * Make a Promise that fulfills when any item fulfills, and rejects if any item rejects. + * Like `.then()`, but any unhandled rejection that ends up here will be thrown as an error. */ - static race (promises: (R | Thenable)[]): Promise; -} + done(onFulfilled?: (value: R) => U | Bluebird.Thenable, onRejected?: (error: any) => U | Bluebird.Thenable): void; -/** - * 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'; -} + /** + * Like `.finally()`, but not called for rejections. + */ + tap(onFulFill: (value: R) => Bluebird.Thenable): Bluebird; + tap(onFulfill: (value: R) => U): 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 + /** + * Same as calling `Promise.delay(ms, this)`. + */ + delay(ms: number): Bluebird; -// Documentation : http://mongodb.github.io/node-mongodb-native/2.1/api/ + /** + * 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; -// Use typings to install this type definition https://github.com/typings/typings + /** + * 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; -import {EventEmitter} from 'events'; -import {Promise} from '~iridium~mongodb~es6-promise'; + /** + * See if this `promise` has been fulfilled. + */ + isFulfilled(): boolean; -// Class documentation : http://mongodb.github.io/node-mongodb-native/2.1/api/MongoClient.html -export class MongoClient { - constructor(); + /** + * See if this `promise` has been rejected. + */ + isRejected(): 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 still defer. + */ + isPending(): boolean; - connect(uri: string, callback: MongoCallback): void; - connect(uri: string, options?: MongoClientOptions): Promise; - connect(uri: string, options: MongoClientOptions, callback: MongoCallback): void; -} + /** + * See if this `promise` is resolved -> either fulfilled or rejected. + */ + isResolved(): boolean; -export interface MongoCallback { - (error: MongoError, result: T): void; -} + /** + * Get the fulfillment value of the underlying promise. Throws if the promise isn't fulfilled yet. + * + * throws `TypeError` + */ + value(): R; -// 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; -} + /** + * 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/MongoClient.html#.connect -export interface MongoClientOptions { - uri_decode_auth?: boolean; - db?: DbCreateOptions; - server?: ServerOptions; - replSet?: ReplSetOptions; - mongos?: MongosOptions; - promiseLibrary?: Object; -} + /** + * 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; -// 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].call(obj, arg...); + * }); + * + */ + call(propertyName: string, ...args: any[]): 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; -} + /** + * 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; -//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; -} + /** + * 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; -//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; -} + /** + * 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/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; -} + /** + * Convert to String. + */ + toString(): string; -//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; -} + /** + * This is implicitly called by `JSON.stringify` when serializing the object. Returns a serialized representation of the `Promise`. + */ + toJSON(): Object; -// 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); + /** + * 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; - serverConfig: Server | ReplSet | Mongos; - bufferMaxEntries: number; - databaseName: string; - options: any; - native_parser: boolean; - slaveOk: boolean; - writeConcern: any; + /** + * 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; - // 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.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; - //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.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; - //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.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; -// 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.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; - connections(): Array; -} + /** + * 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; -// Deprecated http://mongodb.github.io/node-mongodb-native/2.1/api/ReplSet.html -export class ReplSet extends EventEmitter { - constructor(servers: Array, options?: ReplSetOptions); + /** + * 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; - connections(): Array; -} + /** + * 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; -// Deprecated http://mongodb.github.io/node-mongodb-native/2.1/api/ReplSet.html -export class Mongos extends EventEmitter { - constructor(servers: Array, options?: MongosOptions); + /** + * 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; - 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[]; -} - -//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; -} + static attempt(fn: () => R | Bluebird.Thenable): 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 }; -} + /** + * 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; -//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; -} + /** + * 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; -// 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; -} + /** + * 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/Admin.html#addUser -export interface AddUserOptions { - w?: number | string; - wtimeout?: number; - j?: boolean; - fsync: boolean; - customData?: Object; - roles?: 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/Admin.html#removeUser -export interface FSyncOptions { - w?: number | string; - wtimeout?: number; - j?: boolean; - fsync?: boolean -} + /** + * 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; -// Class documentation : http://mongodb.github.io/node-mongodb-native/2.1/api/ObjectID.html -export class ObjectID { - constructor(s?: string | number); + /** + * Sugar for `Promise.resolve(undefined).bind(thisArg);`. See `.bind()`. + */ + static bind(thisArg: any): Bluebird; - generationTime: number; + /** + * See if `value` is a trusted Promise. + */ + static is(value: any): boolean; - // 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; -} + /** + * 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/Binary.html -export class Binary { - constructor(buffer: Buffer, subType?: 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; - 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 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; - // 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); + /** + * 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; - valueOf(): 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; -//http://mongodb.github.io/node-mongodb-native/2.1/api/Long.html -export class Long { - constructor(low: number, high: 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; - static MAX_VALUE: Long; - static MIN_VALUE: Long; - static NEG_ONE: Long; - static ONE: Long; - static ZERO: Long; + /** + * 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; - static fromBits(lowBits: number, highBits: number): Long; - static fromInt(value: number): Long; - static fromNumber(value: number): Long; - static fromString(str: string, radix?: number): Long; + /** + * 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; - 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; -} + /** + * 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; -//http://mongodb.github.io/node-mongodb-native/2.1/api/MaxKey.html -export class MaxKey { } + /** + * 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; -//http://mongodb.github.io/node-mongodb-native/2.1/api/MinKey.html -export class MinKey { } + /** + * 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; -//http://mongodb.github.io/node-mongodb-native/2.1/api/Timestamp.html -export class Timestamp { - constructor(low: number, high: number); + /** + * 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; - static MAX_VALUE: Timestamp; - static MIN_VALUE: Timestamp; - static NEG_ONE: Timestamp; - static ONE: Timestamp; - static ZERO: Timestamp; + /** + * 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; - static fromBits(lowBits: number, highBits: number): Timestamp; - static fromInt(value: number): Timestamp; - static fromNumber(value: number): Timestamp; - static fromString(str: string, radix?: number): Timestamp; + // variadic array + /** @deprecated use .all instead */ + static join(...values: (R | Bluebird.Thenable)[]): Bluebird; - 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; -} + /** + * 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; -// 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; -} + // promise of array with values + static map(values: Bluebird.Thenable, mapper: (item: R, index: number, arrayLength: number) => U | Bluebird.Thenable, options?: Bluebird.ConcurrencyOption): Bluebird; -// 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 -} + // array with promises of value + static map(values: Bluebird.Thenable[], mapper: (item: R, index: number, arrayLength: number) => U | Bluebird.Thenable, options?: Bluebird.ConcurrencyOption): Bluebird; -//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; -} + // array with values + static map(values: R[], mapper: (item: R, index: number, arrayLength: number) => U | Bluebird.Thenable, options?: Bluebird.ConcurrencyOption): Bluebird; -//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; -} + /** + * 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; -//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; -} + // 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; -//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; -} + // 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; -//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; -} + // array with values + static reduce(values: R[], reducer: (total: U, current: R, index: number, arrayLength: number) => U | Bluebird.Thenable, initialValue?: U): Bluebird; -//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; -} + /** + * 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; -//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; -} + // promise of array with values + static filter(values: Bluebird.Thenable, filterer: (item: R, index: number, arrayLength: number) => boolean | Bluebird.Thenable, option?: Bluebird.ConcurrencyOption): Bluebird; -//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; -} + // array with promises of value + static filter(values: Bluebird.Thenable[], filterer: (item: R, index: number, arrayLength: number) => boolean | Bluebird.Thenable, option?: Bluebird.ConcurrencyOption): Bluebird; -//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; -} + // array with values + static filter(values: R[], filterer: (item: R, index: number, arrayLength: number) => boolean | Bluebird.Thenable, option?: Bluebird.ConcurrencyOption): Bluebird; -//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; -} + /** + * 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/Code.html -export class Code { - constructor(code: string | Function, scope?: Object) - code: string | Function; - scope: any; -} + /** + * 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; -//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; -} + /** + * 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/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; -} + /** + * 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; -//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; + /** + * 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; - getInsertedIds(): Array; - getLastOp(): Object; - getRawResponse(): Object; - getUpsertedIdAt(index: number): Object; - getUpsertedIds(): Array; - getWriteConcernError(): WriteConcernError; - getWriteErrorAt(index: number): WriteError; - getWriteErrorCount(): number; - getWriteErrors(): Array; - hasWriteErrors(): boolean; + /** + * 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; } -//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; -} +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; + } -//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; -} + /** + * 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 { } -//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; -} + /** + * Signals that an operation has timed out. Used as a custom cancellation reason in `.timeout`. + */ + export class TimeoutError extends Error { } -//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; -} + /** + * 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/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; -} + /** + * 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#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 -} + /** + * returned by `Bluebird.disposer()`. + */ + export class Disposer { + } -//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 } -} + 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#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 -} + 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#~insertOneWriteOpResult -export interface InsertOneWriteOpResult { - insertedCount: number; - ops: Array; - insertedId: ObjectID; - connection: any; - result: { ok: number, n: number } -} + /** + * 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#parallelCollectionScan -export interface ParallelCollectionScanOptions { - readPreference?: ReadPreference | string; - batchSize?: number; - numCursors?: number; - raw?: boolean; -} + /** + * 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#replaceOne -export interface ReplaceOneOptions { - upsert?: boolean; - w?: number | string; - wtimeout?: number; - j?: boolean; - bypassDocumentValidation?: boolean; + /** + * 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; + } + + export interface Inspection { + /** + * See if the underlying promise was fulfilled at the creation time of this inspection object. + */ + isFulfilled(): boolean; + + /** + * See if the underlying promise was rejected at the creation time of this inspection object. + */ + isRejected(): boolean; + + /** + * See if the underlying promise was defer at the creation time of this inspection object. + */ + isPending(): boolean; + + /** + * 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; + + /** + * 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; + } + + /** + * 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/Collection.html#~updateWriteOpResult -export interface UpdateWriteOpResult { - result: { ok: number, n: number, nModified: number }; - connection: any; - matchedCount: number; - modifiedCount: number; - upsertedCount: number; - upsertedId: { _id: ObjectID }; +export = Bluebird; +} +declare module '~iridium~bluebird' { +import main = require('~iridium~bluebird/bluebird'); +export = main; } -//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 +// 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/Collection.html#~WriteOpResult -export interface WriteOpResult { - ops: Array; - connection: any; - result: any; +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); + + /** + * 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; + + /** + * Sugar for promise.then(undefined, onRejected) + * + * @param onRejected called when/if "promise" rejects + */ + catch (onRejected?: (error: any) => U | Thenable): Promise; + + /** + * 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; + + /** + * 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; + + /** + * 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; + + /** + * 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/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; +/** + * 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'; } -export interface Writable { } -export interface Stream { } +// 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 -//http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#~resultCallback -export type CursorResult = any | void | boolean; +// Documentation : http://mongodb.github.io/node-mongodb-native/2.1/api/ -//http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html -export interface Cursor extends Readable, NodeJS.EventEmitter { +// Use typings to install this type definition https://github.com/typings/typings - 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; -} +import {EventEmitter} from 'events'; +import {Promise} from '~iridium~mongodb~es6-promise'; -//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; -} +// 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#~iteratorCallback -export interface IteratorCallback { - (doc: any): void; -} + 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#~endCallback -export interface EndCallback { - (error: MongoError): void; + connect(uri: string, callback: MongoCallback): void; + connect(uri: string, options?: MongoClientOptions): Promise; + connect(uri: string, options: MongoClientOptions, callback: MongoCallback): 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; +export interface MongoCallback { + (error: MongoError, result: T): 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'; +// 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; } -// 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/MongoClient.html#.connect +export interface MongoClientOptions { + uri_decode_auth?: boolean; + db?: DbCreateOptions; + server?: ServerOptions; + replSet?: ReplSetOptions; + mongos?: MongosOptions; + promiseLibrary?: Object; } -// 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'; +// 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 }; } -// 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; -} +// 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; } -declare module 'iridium/dist/lib/Cursor' { -export * from '~iridium/dist/lib/Cursor'; + +//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; } -// 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'; +//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; } -// 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/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; } -// 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'; +//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; } -// 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'; -} +// 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); -// 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'; -} + serverConfig: Server | ReplSet | Mongos; + bufferMaxEntries: number; + databaseName: string; + options: any; + native_parser: boolean; + slaveOk: boolean; + writeConcern: any; -// Generated by typings -// Source: dist/lib/Model.d.ts -declare module '~iridium/dist/lib/Model' { -import * as MongoDB from '~iridium~mongodb'; -import * as Bluebird from '~iridium~bluebird'; -import * as Skmatc from '~iridium~skmatc'; -import { Core } from '~iridium/dist/lib/Core'; -import { Schema } from '~iridium/dist/lib/Schema'; -import { Hooks } from '~iridium/dist/lib/Hooks'; -import { CacheDirector } from '~iridium/dist/lib/CacheDirector'; -import * as General from '~iridium/dist/lib/General'; -import { Cursor } from '~iridium/dist/lib/Cursor'; -import * as Index from '~iridium/dist/lib/Index'; -import * as ModelOptions from '~iridium/dist/lib/ModelOptions'; -import { ModelCache } from '~iridium/dist/lib/ModelCache'; -import { ModelHelpers } from '~iridium/dist/lib/ModelHelpers'; -import { ModelHandlers } from '~iridium/dist/lib/ModelHandlers'; -import * as ModelInterfaces from '~iridium/dist/lib/ModelInterfaces'; -import { InstanceImplementation } from '~iridium/dist/lib/InstanceInterface'; -import { Transforms } from '~iridium/dist/lib/Transforms'; -import * as AggregationPipeline from '~iridium/dist/lib/Aggregate'; -/** - * An Iridium Model which represents a structured MongoDB collection. - * Models expose the methods you will generally use to query those collections, and ensure that - * the results of those queries are returned as {TInstance} instances. - * - * @param TDocument The interface used to determine the schema of documents in the collection. - * @param TInstance The interface or class used to represent collection documents in the JS world. - * - * @class - */ -export class Model { - /** - * Creates a new Iridium model representing a given ISchema and backed by a collection whose name is specified - * @param core The Iridium core that this model should use for database access - * @param instanceType The class which will be instantiated for each document retrieved from the database - * @constructor - */ - constructor(core: Core, instanceType: InstanceImplementation); - /** - * Loads any externally available properties (generally accessed using public getters/setters). - */ - private loadExternal(instanceType); - /** - * Loads any internally (protected/private) properties and helpers only used within Iridium itself. - */ - private loadInternal(); - /** - * Process any callbacks and plugin delegation for the creation of this model. - * It will generally be called whenever a new Iridium Core is created, however is - * more specifically tied to the lifespan of the models themselves. - */ - private onNewModel(); - private _helpers; - /** - * Provides helper methods used by Iridium for common tasks - * @returns A set of helper methods which are used within Iridium for common tasks - */ - helpers: ModelHelpers; - private _handlers; - /** - * Provides helper methods used by Iridium for hook delegation and common processes - * @returns A set of helper methods which perform common event and response handling tasks within Iridium. - */ - handlers: ModelHandlers; - private _hooks; - /** - * Gets the even hooks subscribed on this model for a number of different state changes. - * These hooks are primarily intended to allow lifecycle manipulation logic to be added - * in the user's model definition, allowing tasks such as the setting of default values - * or automatic client-side joins to take place. - */ - hooks: Hooks; - private _schema; - /** - * Gets the schema dictating the data structure represented by this model. - * The schema is used by skmatc to validate documents before saving to the database, however - * until MongoDB 3.1 becomes widely available (with server side validation support) we are - * limited in our ability to validate certain types of updates. As such, these validations - * act more as a data-integrity check than anything else, unless you purely make use of Omnom - * updates within instances. - * @public - * @returns The defined validation schema for this model - */ - schema: Schema; - private _core; - /** - * Gets the Iridium core that this model is associated with. - * @public - * @returns The Iridium core that this model is bound to - */ - core: Core; - private _collection; - /** - * Gets the underlying MongoDB collection from which this model's documents are retrieved. - * You can make use of this object if you require any low level access to the MongoDB collection, - * however we recommend you make use of the Iridium methods whereever possible, as we cannot - * guarantee the accuracy of the type definitions for the underlying MongoDB driver. - * @public - * @returns {Collection} - */ - collection: MongoDB.Collection; - /** - * Gets the name of the underlying MongoDB collection from which this model's documents are retrieved - * @public - */ - /** - * Sets the name of the underlying MongoDB collection from which this model's documents are retrieved - * @public - */ - collectionName: string; - private _cacheDirector; - /** - * Gets the cache controller which dictates which queries will be cached, and under which key - * @public - * @returns {CacheDirector} - */ - cacheDirector: CacheDirector; - private _cache; - /** - * Gets the cache responsible for storing objects for quick retrieval under certain conditions - * @public - * @returns {ModelCache} - */ - cache: ModelCache; - private _Instance; - /** - * Gets the constructor responsible for creating instances for this model - */ - Instance: ModelInterfaces.ModelSpecificInstanceConstructor; - private _transforms; - /** - * Gets the transforms which are applied whenever a document is received from the database, or - * prior to storing a document in the database. Tasks such as converting an ObjectID to a string - * and vice versa are all listed in this object. - */ - transforms: Transforms; - private _validators; - /** - * Gets the custom validation types available for this model. These validators are added to the - * default skmatc validators, as well as those available through plugins, for use when checking - * your instances. - */ - validators: Skmatc.Validator[]; - private _indexes; - /** - * Gets the indexes which Iridium will manage on this model's database collection. - */ - indexes: (Index.Index | Index.IndexSpecification)[]; - /** - * Retrieves all documents in the collection and wraps them as instances - * @param {function(Error, TInstance[])} callback An optional callback which will be triggered when results are available - * @returns {Promise} - */ - find(): Cursor; - /** - * Returns all documents in the collection which match the conditions and wraps them as instances - * @param {Object} conditions The MongoDB query dictating which documents to return - * @returns {Promise} - */ - find(conditions: { - _id?: any; - [key: string]: any; - } | any): Cursor; - /** - * Returns all documents in the collection which match the conditions - * @param {Object} conditions The MongoDB query dictating which documents to return - * @param {Object} fields The fields to include or exclude from the document - * @returns {Promise} - */ - find(conditions: { - _id?: any; - [key: string]: any; - } | any, fields: { - [name: string]: number; - }): Cursor; - /** - * Retrieves a single document from the collection and wraps it as an instance - * @param {function(Error, TInstance)} callback An optional callback which will be triggered when a result is available - * @returns {Promise} - */ - get(callback?: General.Callback): Bluebird; - /** - * Retrieves a single document from the collection with the given ID and wraps it as an instance - * @param {any} id The document's unique _id field value in downstream format - * @param {function(Error, TInstance)} callback An optional callback which will be triggered when a result is available - * @returns {Promise} - */ - get(id: any, callback?: General.Callback): Bluebird; - /** - * Retrieves a single document from the collection which matches the conditions - * @param {Object} conditions The MongoDB query dictating which document to return - * @param {function(Error, TInstance)} callback An optional callback which will be triggered when a result is available - * @returns {Promise} - */ - get(conditions: { - _id?: any; - [key: string]: any; - }, callback?: General.Callback): Bluebird; - /** - * Retrieves a single document from the collection with the given ID and wraps it as an instance - * @param {any} id The document's unique _id field value in downstream format - * @param {QueryOptions} options The options dictating how this function behaves - * @param {function(Error, TInstance)} callback An optional callback which will be triggered when a result is available - * @returns {Promise} - */ - get(id: any, options: ModelOptions.QueryOptions, callback?: General.Callback): Bluebird; - /** - * Retrieves a single document from the collection which matches the conditions - * @param {Object} conditions The MongoDB query dictating which document to return - * @param {QueryOptions} options The options dictating how this function behaves - * @param {function(Error, TInstance)} callback An optional callback which will be triggered when a result is available - * @returns {Promise} - */ - get(conditions: { - _id?: any; - [key: string]: any; - }, options: ModelOptions.QueryOptions, callback?: General.Callback): Bluebird; - /** - * Retrieves a single document from the collection and wraps it as an instance - * @param {function(Error, TInstance)} callback An optional callback which will be triggered when a result is available - * @returns {Promise} - */ - findOne(callback?: General.Callback): Bluebird; - /** - * Retrieves a single document from the collection with the given ID and wraps it as an instance - * @param {any} id The document's unique _id field value in downstream format - * @param {function(Error, TInstance)} callback An optional callback which will be triggered when a result is available - * @returns {Promise} - */ - findOne(id: any, callback?: General.Callback): Bluebird; - /** - * Retrieves a single document from the collection which matches the conditions - * @param {Object} conditions The MongoDB query dictating which document to return - * @param {function(Error, TInstance)} callback An optional callback which will be triggered when a result is available - * @returns {Promise} - */ - findOne(conditions: { - _id?: any; - [key: string]: any; - }, callback?: General.Callback): Bluebird; - /** - * Retrieves a single document from the collection with the given ID and wraps it as an instance - * @param {any} id The document's unique _id field value in downstream format - * @param {QueryOptions} options The options dictating how this function behaves - * @param {function(Error, TInstance)} callback An optional callback which will be triggered when a result is available - * @returns {Promise} - */ - findOne(id: any, options: ModelOptions.QueryOptions, callback?: General.Callback): Bluebird; - /** - * Retrieves a single document from the collection which matches the conditions - * @param {Object} conditions The MongoDB query dictating which document to return - * @param {QueryOptions} options The options dictating how this function behaves - * @param {function(Error, TInstance)} callback An optional callback which will be triggered when a result is available - * @returns {Promise} - */ - findOne(conditions: { - _id?: any; - [key: string]: any; - }, options: ModelOptions.QueryOptions, callback?: General.Callback): Bluebird; - /** - * Inserts an object into the collection after validating it against this model's schema - * @param {Object} object The object to insert into the collection - * @param {function(Error, TInstance)} callback A callback which is triggered when the operation completes - * @returns {Promise} - */ - create(objects: TDocument, callback?: General.Callback): Bluebird; - /** - * Inserts an object into the collection after validating it against this model's schema - * @param {Object} object The object to insert into the collection - * @param {CreateOptions} options The options dictating how this function behaves - * @param {function(Error, TInstance)} callback A callback which is triggered when the operation completes - * @returns {Promise} - */ - create(objects: TDocument, options: ModelOptions.CreateOptions, callback?: General.Callback): Bluebird; - /** - * Inserts the objects into the collection after validating them against this model's schema - * @param {Object[]} objects The objects to insert into the collection - * @param {function(Error, TInstance)} callback A callback which is triggered when the operation completes - * @returns {Promise} - */ - create(objects: TDocument[], callback?: General.Callback): Bluebird; - /** - * Inserts the objects into the collection after validating them against this model's schema - * @param {Object[]} objects The objects to insert into the collection - * @param {CreateOptions} options The options dictating how this function behaves - * @param {function(Error, TInstance)} callback A callback which is triggered when the operation completes - * @returns {Promise} - */ - create(objects: TDocument[], options: ModelOptions.CreateOptions, callback?: General.Callback): Bluebird; - /** - * Inserts an object into the collection after validating it against this model's schema - * @param {Object} object The object to insert into the collection - * @param {function(Error, TInstance)} callback A callback which is triggered when the operation completes - * @returns {Promise} - */ - insert(objects: TDocument, callback?: General.Callback): Bluebird; - /** - * Inserts an object into the collection after validating it against this model's schema - * @param {Object} object The object to insert into the collection - * @param {CreateOptions} options The options dictating how this function behaves - * @param {function(Error, TInstance)} callback A callback which is triggered when the operation completes - * @returns {Promise} - */ - insert(objects: TDocument, options: ModelOptions.CreateOptions, callback?: General.Callback): Bluebird; - /** - * Inserts the objects into the collection after validating them against this model's schema - * @param {Object[]} objects The objects to insert into the collection - * @param {function(Error, TInstance[])} callback A callback which is triggered when the operation completes - * @returns {Promise} - */ - insert(objects: TDocument[], callback?: General.Callback): Bluebird; - /** - * Inserts the objects into the collection after validating them against this model's schema - * @param {Object[]} objects The objects to insert into the collection - * @param {CreateOptions} options The options dictating how this function behaves - * @param {function(Error, TInstance[])} callback A callback which is triggered when the operation completes - * @returns {Promise} - */ - insert(objects: TDocument[], options: ModelOptions.CreateOptions, callback?: General.Callback): Bluebird; - /** - * Updates the documents in the backing collection which match the conditions using the given update instructions - * @param {Object} conditions The conditions which determine which documents will be updated - * @param {Object} changes The changes to make to the documents - * @param {function(Error, Number)} callback A callback which is triggered when the operation completes - */ - update(conditions: { - _id?: any; - [key: string]: any; - } | any, changes: any, callback?: General.Callback): Bluebird; - /** - * Updates the documents in the backing collection which match the conditions using the given update instructions - * @param {Object} conditions The conditions which determine which documents will be updated - * @param {Object} changes The changes to make to the documents - * @param {UpdateOptions} options The options which dictate how this function behaves - * @param {function(Error, Number)} callback A callback which is triggered when the operation completes - */ - update(conditions: { - _id?: any; - [key: string]: any; - } | any, changes: any, options: ModelOptions.UpdateOptions, callback?: General.Callback): Bluebird; - /** - * Counts the number of documents in the collection - * @param {function(Error, Number)} callback A callback which is triggered when the operation completes - * @returns {Promise} - */ - count(callback?: General.Callback): Bluebird; - /** - * Counts the number of documents in the collection which match the conditions provided - * @param {Object} conditions The conditions which determine whether an object is counted or not - * @param {function(Error, Number)} callback A callback which is triggered when the operation completes - * @returns {Promise} - */ - count(conditions: { - _id?: any; - [key: string]: any; - } | any, callback?: General.Callback): Bluebird; - /** - * Removes all documents from the collection - * @param {function(Error, Number)} callback A callback which is triggered when the operation completes - * @returns {Promise} - */ - remove(callback?: General.Callback): Bluebird; - /** - * Removes all documents from the collection which match the conditions - * @param {Object} conditions The conditions determining whether an object is removed or not - * @param {function(Error, Number)} callback A callback which is triggered when the operation completes - * @returns {Promise} - */ - remove(conditions: { - _id?: any; - [key: string]: any; - } | any, callback?: General.Callback): Bluebird; - /** - * Removes all documents from the collection which match the conditions - * @param {Object} conditions The conditions determining whether an object is removed or not - * @param {Object} options The options controlling the way in which the function behaves - * @param {function(Error, Number)} callback A callback which is triggered when the operation completes - * @returns {Promise} - */ - remove(conditions: { - _id?: any; - [key: string]: any; - }, options: ModelOptions.RemoveOptions, callback?: General.Callback): Bluebird; - aggregate(pipeline: AggregationPipeline.Stage[]): Bluebird; - /** - * Ensures that the given index is created for the collection - * @param {Object} specification The index specification object used by MongoDB - * @param {function(Error, String)} callback A callback which is triggered when the operation completes - * @returns {Promise} The name of the index - */ - ensureIndex(specification: Index.IndexSpecification, callback?: General.Callback): Bluebird; - /** - * Ensures that the given index is created for the collection - * @param {Object} specification The index specification object used by MongoDB - * @param {MongoDB.IndexOptions} options The options dictating how the index is created and behaves - * @param {function(Error, String)} callback A callback which is triggered when the operation completes - * @returns {Promise} The name of the index - */ - ensureIndex(specification: Index.IndexSpecification, options: MongoDB.IndexOptions, callback?: General.Callback): Bluebird; - /** - * Ensures that all indexes defined in the model's options are created - * @param {function(Error, String[])} callback A callback which is triggered when the operation completes - * @returns {Promise} The names of the indexes - */ - ensureIndexes(callback?: General.Callback): 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 - */ - 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'; -} + // 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; -// 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'; + //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; } -// 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); +// 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); - /** - * 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; + connections(): Array; +} - /** - * 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; +// Deprecated http://mongodb.github.io/node-mongodb-native/2.1/api/ReplSet.html +export class ReplSet extends EventEmitter { + constructor(servers: Array, options?: ReplSetOptions); - /** - * 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; + connections(): Array; +} - /** - * 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; +// Deprecated http://mongodb.github.io/node-mongodb-native/2.1/api/ReplSet.html +export class Mongos extends EventEmitter { + constructor(servers: Array, options?: MongosOptions); - /** - * 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; + 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[]; +} - lastly(handler: () => U | Bluebird.Thenable): 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 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; +// 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 }; +} - /** - * 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; +//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; +} - /** - * Like `.finally()`, but not called for rejections. - */ - tap(onFulFill: (value: R) => Bluebird.Thenable): Bluebird; - tap(onFulfill: (value: R) => U): 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; +} - /** - * Same as calling `Promise.delay(ms, this)`. - */ - delay(ms: number): 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[] +} - /** - * 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; +//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 +} + +// Class documentation : http://mongodb.github.io/node-mongodb-native/2.1/api/ObjectID.html +export class ObjectID { + constructor(s?: string | number); - /** - * 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; + generationTime: number; - /** - * See if this `promise` has been fulfilled. - */ - isFulfilled(): boolean; + // 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; +} - /** - * See if this `promise` has been rejected. - */ - isRejected(): boolean; +// Class documentation : http://mongodb.github.io/node-mongodb-native/2.1/api/Binary.html +export class Binary { + constructor(buffer: Buffer, subType?: number); - /** - * See if this `promise` is still defer. - */ - isPending(): boolean; + 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; - /** - * See if this `promise` is resolved -> either fulfilled or rejected. - */ - isResolved(): boolean; + // 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); - /** - * Get the fulfillment value of the underlying promise. Throws if the promise isn't fulfilled yet. - * - * throws `TypeError` - */ - value(): R; + valueOf(): number; +} - /** - * 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/Long.html +export class Long { + constructor(low: number, high: number); - /** - * 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; + static MAX_VALUE: Long; + static MIN_VALUE: Long; + static NEG_ONE: Long; + static ONE: Long; + static ZERO: Long; - /** - * This is a convenience method for doing: - * - * - * promise.then(function(obj){ - * return obj[propertyName].call(obj, arg...); - * }); - * - */ - call(propertyName: string, ...args: any[]): 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; - /** - * 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; + 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; +} - /** - * 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; +//http://mongodb.github.io/node-mongodb-native/2.1/api/MaxKey.html +export class MaxKey { } - /** - * 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/MinKey.html +export class MinKey { } - /** - * Convert to String. - */ - toString(): string; +//http://mongodb.github.io/node-mongodb-native/2.1/api/Timestamp.html +export class Timestamp { + constructor(low: number, high: number); - /** - * This is implicitly called by `JSON.stringify` when serializing the object. Returns a serialized representation of the `Promise`. - */ - toJSON(): Object; + static MAX_VALUE: Timestamp; + static MIN_VALUE: Timestamp; + static NEG_ONE: Timestamp; + static ONE: Timestamp; + static ZERO: Timestamp; - /** - * 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; + static fromBits(lowBits: number, highBits: number): Timestamp; + static fromInt(value: number): Timestamp; + static fromNumber(value: number): Timestamp; + static fromString(str: string, radix?: number): Timestamp; - /** - * 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; + 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; +} - /** - * 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; +// 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; +} - /** - * 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; +// 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 +} - /** - * 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/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; +} - /** - * 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; +//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; +} - /** - * 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; +//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; +} - /** - * 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; +//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; +} - /** - * 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; +//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; +} - /** - * 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; +//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; +} - /** - * 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; +//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; +} - /** - * 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; +//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; +} - static attempt(fn: () => R | Bluebird.Thenable): Bluebird; +//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; +} - /** - * 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; +//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; +} - /** - * 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; +//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; +} - /** - * 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/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; +} - /** - * 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/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; +} - /** - * 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; +//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; - /** - * Sugar for `Promise.resolve(undefined).bind(thisArg);`. See `.bind()`. - */ - static bind(thisArg: any): Bluebird; + getInsertedIds(): Array; + getLastOp(): Object; + getRawResponse(): Object; + getUpsertedIdAt(index: number): Object; + getUpsertedIds(): Array; + getWriteConcernError(): WriteConcernError; + getWriteErrorAt(index: number): WriteError; + getWriteErrorCount(): number; + getWriteErrors(): Array; + hasWriteErrors(): boolean; +} - /** - * See if `value` is a trusted Promise. - */ - static is(value: any): 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; +} - /** - * 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; +//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; +} - /** - * 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; +//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; +} - /** - * 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; +//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; +} - /** - * 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; +//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; +} - /** - * 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; +//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 +} - /** - * 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; +//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 } +} - /** - * 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; +//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 +} - /** - * 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/Collection.html#~insertOneWriteOpResult +export interface InsertOneWriteOpResult { + insertedCount: number; + ops: Array; + insertedId: ObjectID; + connection: any; + result: { ok: number, n: 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; +//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; +} - /** - * 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; +//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; +} - /** - * 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; +//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 }; +} - /** - * 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; +//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 +} - /** - * 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; +//http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#~WriteOpResult +export interface WriteOpResult { + ops: Array; + connection: any; + result: any; +} - // variadic array - /** @deprecated use .all instead */ - static join(...values: (R | Bluebird.Thenable)[]): Bluebird; +//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; +} - /** - * 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; +export interface Writable { } +export interface Stream { } - // promise of array with values - static map(values: Bluebird.Thenable, mapper: (item: R, index: number, arrayLength: number) => U | Bluebird.Thenable, options?: Bluebird.ConcurrencyOption): Bluebird; +//http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#~resultCallback +export type CursorResult = any | void | boolean; - // array with promises of value - static map(values: Bluebird.Thenable[], mapper: (item: R, index: number, arrayLength: number) => U | Bluebird.Thenable, options?: Bluebird.ConcurrencyOption): Bluebird; +//http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html +export interface Cursor extends Readable, NodeJS.EventEmitter { - // array with values - static map(values: R[], mapper: (item: R, index: number, arrayLength: number) => U | Bluebird.Thenable, options?: Bluebird.ConcurrencyOption): Bluebird; + 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; +} - /** - * 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; +//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; +} - // 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; +//http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#~iteratorCallback +export interface IteratorCallback { + (doc: any): void; +} - // 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; +//http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#~endCallback +export interface EndCallback { + (error: MongoError): void; +} - // array with values - static reduce(values: R[], reducer: (total: U, current: R, index: number, arrayLength: number) => U | Bluebird.Thenable, initialValue?: U): Bluebird; +//http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#~resultCallback +export type AggregationCursorResult = any | void; - /** - * 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; +//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; +} - // promise of array with values - static filter(values: Bluebird.Thenable, filterer: (item: R, index: number, arrayLength: number) => boolean | Bluebird.Thenable, option?: Bluebird.ConcurrencyOption): Bluebird; +//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'; +} - // array with promises of value - static filter(values: Bluebird.Thenable[], filterer: (item: R, index: number, arrayLength: number) => boolean | Bluebird.Thenable, option?: Bluebird.ConcurrencyOption): Bluebird; +// 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'; +} - // array with values - static filter(values: R[], filterer: (item: R, index: number, arrayLength: number) => boolean | Bluebird.Thenable, option?: Bluebird.ConcurrencyOption): Bluebird; +// 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'; +} - /** - * 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; +// 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'; +} - /** - * 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; +// 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'; +} - /** - * 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; +// 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'; +} - /** - * 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; +// 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'; +} - /** - * 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; +// 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'; +} - /** - * 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; +// 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 | PromiseLike | 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 | PromiseLike | 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 | PromiseLike | 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 | PromiseLike | 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'; } -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; - } +// 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'; +} - export interface Resolver { +// Generated by typings +// Source: dist/lib/Model.d.ts +declare module '~iridium/dist/lib/Model' { +import * as MongoDB from '~iridium~mongodb'; +import * as Bluebird from '~iridium~bluebird'; +import * as Skmatc from '~iridium~skmatc'; +import { Core } from '~iridium/dist/lib/Core'; +import { Schema } from '~iridium/dist/lib/Schema'; +import { Hooks } from '~iridium/dist/lib/Hooks'; +import { CacheDirector } from '~iridium/dist/lib/CacheDirector'; +import * as General from '~iridium/dist/lib/General'; +import { Cursor } from '~iridium/dist/lib/Cursor'; +import * as Index from '~iridium/dist/lib/Index'; +import * as ModelOptions from '~iridium/dist/lib/ModelOptions'; +import { ModelCache } from '~iridium/dist/lib/ModelCache'; +import { ModelHelpers } from '~iridium/dist/lib/ModelHelpers'; +import { ModelHandlers } from '~iridium/dist/lib/ModelHandlers'; +import * as ModelInterfaces from '~iridium/dist/lib/ModelInterfaces'; +import { InstanceImplementation } from '~iridium/dist/lib/InstanceInterface'; +import { Transforms } from '~iridium/dist/lib/Transforms'; +import * as AggregationPipeline from '~iridium/dist/lib/Aggregate'; +/** + * An Iridium Model which represents a structured MongoDB collection. + * Models expose the methods you will generally use to query those collections, and ensure that + * the results of those queries are returned as {TInstance} instances. + * + * @param TDocument The interface used to determine the schema of documents in the collection. + * @param TInstance The interface or class used to represent collection documents in the JS world. + * + * @class + */ +export class Model { + /** + * Creates a new Iridium model representing a given ISchema and backed by a collection whose name is specified + * @param core The Iridium core that this model should use for database access + * @param instanceType The class which will be instantiated for each document retrieved from the database + * @constructor + */ + constructor(core: Core, instanceType: InstanceImplementation); + /** + * Loads any externally available properties (generally accessed using public getters/setters). + */ + private loadExternal(instanceType); + /** + * Loads any internally (protected/private) properties and helpers only used within Iridium itself. + */ + private loadInternal(); + /** + * Process any callbacks and plugin delegation for the creation of this model. + * It will generally be called whenever a new Iridium Core is created, however is + * more specifically tied to the lifespan of the models themselves. + */ + private onNewModel(); + private _helpers; + /** + * Provides helper methods used by Iridium for common tasks + * @returns A set of helper methods which are used within Iridium for common tasks + */ + helpers: ModelHelpers; + private _handlers; + /** + * Provides helper methods used by Iridium for hook delegation and common processes + * @returns A set of helper methods which perform common event and response handling tasks within Iridium. + */ + handlers: ModelHandlers; + private _hooks; + /** + * Gets the even hooks subscribed on this model for a number of different state changes. + * These hooks are primarily intended to allow lifecycle manipulation logic to be added + * in the user's model definition, allowing tasks such as the setting of default values + * or automatic client-side joins to take place. + */ + hooks: Hooks; + private _schema; + /** + * Gets the schema dictating the data structure represented by this model. + * The schema is used by skmatc to validate documents before saving to the database, however + * until MongoDB 3.1 becomes widely available (with server side validation support) we are + * limited in our ability to validate certain types of updates. As such, these validations + * act more as a data-integrity check than anything else, unless you purely make use of Omnom + * updates within instances. + * @public + * @returns The defined validation schema for this model + */ + schema: Schema; + private _core; + /** + * Gets the Iridium core that this model is associated with. + * @public + * @returns The Iridium core that this model is bound to + */ + core: Core; + private _collection; + /** + * Gets the underlying MongoDB collection from which this model's documents are retrieved. + * You can make use of this object if you require any low level access to the MongoDB collection, + * however we recommend you make use of the Iridium methods whereever possible, as we cannot + * guarantee the accuracy of the type definitions for the underlying MongoDB driver. + * @public + * @returns {Collection} + */ + collection: MongoDB.Collection; + /** + * Gets the name of the underlying MongoDB collection from which this model's documents are retrieved + * @public + */ + /** + * Sets the name of the underlying MongoDB collection from which this model's documents are retrieved + * @public + */ + collectionName: string; + private _cacheDirector; + /** + * Gets the cache controller which dictates which queries will be cached, and under which key + * @public + * @returns {CacheDirector} + */ + cacheDirector: CacheDirector; + private _cache; + /** + * Gets the cache responsible for storing objects for quick retrieval under certain conditions + * @public + * @returns {ModelCache} + */ + cache: ModelCache; + private _Instance; + /** + * Gets the constructor responsible for creating instances for this model + */ + Instance: ModelInterfaces.ModelSpecificInstanceConstructor; + private _transforms; + /** + * Gets the transforms which are applied whenever a document is received from the database, or + * prior to storing a document in the database. Tasks such as converting an ObjectID to a string + * and vice versa are all listed in this object. + */ + transforms: Transforms; + private _validators; + /** + * Gets the custom validation types available for this model. These validators are added to the + * default skmatc validators, as well as those available through plugins, for use when checking + * your instances. + */ + validators: Skmatc.Validator[]; + private _indexes; + /** + * Gets the indexes which Iridium will manage on this model's database collection. + */ + indexes: (Index.Index | Index.IndexSpecification)[]; + /** + * Retrieves all documents in the collection and wraps them as instances + * @param {function(Error, TInstance[])} callback An optional callback which will be triggered when results are available + * @returns {Promise} + */ + find(): Cursor; /** - * Returns a reference to the controlled promise that can be passed to clients. + * Returns all documents in the collection which match the conditions and wraps them as instances + * @param {Object} conditions The MongoDB query dictating which documents to return + * @returns {Promise} + */ + find(conditions: { + _id?: any; + [key: string]: any; + } | any): Cursor; + /** + * Returns all documents in the collection which match the conditions + * @param {Object} conditions The MongoDB query dictating which documents to return + * @param {Object} fields The fields to include or exclude from the document + * @returns {Promise} + */ + find(conditions: { + _id?: any; + [key: string]: any; + } | any, fields: { + [name: string]: number; + }): Cursor; + /** + * Retrieves a single document from the collection and wraps it as an instance + * @param {function(Error, TInstance)} callback An optional callback which will be triggered when a result is available + * @returns {Promise} + */ + get(callback?: General.Callback): Bluebird; + /** + * Retrieves a single document from the collection with the given ID and wraps it as an instance + * @param {any} id The document's unique _id field value in downstream format + * @param {function(Error, TInstance)} callback An optional callback which will be triggered when a result is available + * @returns {Promise} + */ + get(id: any, callback?: General.Callback): Bluebird; + /** + * Retrieves a single document from the collection which matches the conditions + * @param {Object} conditions The MongoDB query dictating which document to return + * @param {function(Error, TInstance)} callback An optional callback which will be triggered when a result is available + * @returns {Promise} + */ + get(conditions: { + _id?: any; + [key: string]: any; + }, callback?: General.Callback): Bluebird; + /** + * Retrieves a single document from the collection with the given ID and wraps it as an instance + * @param {any} id The document's unique _id field value in downstream format + * @param {QueryOptions} options The options dictating how this function behaves + * @param {function(Error, TInstance)} callback An optional callback which will be triggered when a result is available + * @returns {Promise} + */ + get(id: any, options: ModelOptions.QueryOptions, callback?: General.Callback): Bluebird; + /** + * Retrieves a single document from the collection which matches the conditions + * @param {Object} conditions The MongoDB query dictating which document to return + * @param {QueryOptions} options The options dictating how this function behaves + * @param {function(Error, TInstance)} callback An optional callback which will be triggered when a result is available + * @returns {Promise} + */ + get(conditions: { + _id?: any; + [key: string]: any; + }, options: ModelOptions.QueryOptions, callback?: General.Callback): Bluebird; + /** + * Retrieves a single document from the collection and wraps it as an instance + * @param {function(Error, TInstance)} callback An optional callback which will be triggered when a result is available + * @returns {Promise} + */ + findOne(callback?: General.Callback): Bluebird; + /** + * Retrieves a single document from the collection with the given ID and wraps it as an instance + * @param {any} id The document's unique _id field value in downstream format + * @param {function(Error, TInstance)} callback An optional callback which will be triggered when a result is available + * @returns {Promise} + */ + findOne(id: any, callback?: General.Callback): Bluebird; + /** + * Retrieves a single document from the collection which matches the conditions + * @param {Object} conditions The MongoDB query dictating which document to return + * @param {function(Error, TInstance)} callback An optional callback which will be triggered when a result is available + * @returns {Promise} + */ + findOne(conditions: { + _id?: any; + [key: string]: any; + }, callback?: General.Callback): Bluebird; + /** + * Retrieves a single document from the collection with the given ID and wraps it as an instance + * @param {any} id The document's unique _id field value in downstream format + * @param {QueryOptions} options The options dictating how this function behaves + * @param {function(Error, TInstance)} callback An optional callback which will be triggered when a result is available + * @returns {Promise} + */ + findOne(id: any, options: ModelOptions.QueryOptions, callback?: General.Callback): Bluebird; + /** + * Retrieves a single document from the collection which matches the conditions + * @param {Object} conditions The MongoDB query dictating which document to return + * @param {QueryOptions} options The options dictating how this function behaves + * @param {function(Error, TInstance)} callback An optional callback which will be triggered when a result is available + * @returns {Promise} + */ + findOne(conditions: { + _id?: any; + [key: string]: any; + }, options: ModelOptions.QueryOptions, callback?: General.Callback): Bluebird; + /** + * Inserts an object into the collection after validating it against this model's schema + * @param {Object} object The object to insert into the collection + * @param {function(Error, TInstance)} callback A callback which is triggered when the operation completes + * @returns {Promise} + */ + create(objects: TDocument, callback?: General.Callback): Bluebird; + /** + * Inserts an object into the collection after validating it against this model's schema + * @param {Object} object The object to insert into the collection + * @param {CreateOptions} options The options dictating how this function behaves + * @param {function(Error, TInstance)} callback A callback which is triggered when the operation completes + * @returns {Promise} + */ + create(objects: TDocument, options: ModelOptions.CreateOptions, callback?: General.Callback): Bluebird; + /** + * Inserts the objects into the collection after validating them against this model's schema + * @param {Object[]} objects The objects to insert into the collection + * @param {function(Error, TInstance)} callback A callback which is triggered when the operation completes + * @returns {Promise} + */ + create(objects: TDocument[], callback?: General.Callback): Bluebird; + /** + * Inserts the objects into the collection after validating them against this model's schema + * @param {Object[]} objects The objects to insert into the collection + * @param {CreateOptions} options The options dictating how this function behaves + * @param {function(Error, TInstance)} callback A callback which is triggered when the operation completes + * @returns {Promise} + */ + create(objects: TDocument[], options: ModelOptions.CreateOptions, callback?: General.Callback): Bluebird; + /** + * Inserts an object into the collection after validating it against this model's schema + * @param {Object} object The object to insert into the collection + * @param {function(Error, TInstance)} callback A callback which is triggered when the operation completes + * @returns {Promise} + */ + insert(objects: TDocument, callback?: General.Callback): Bluebird; + /** + * Inserts an object into the collection after validating it against this model's schema + * @param {Object} object The object to insert into the collection + * @param {CreateOptions} options The options dictating how this function behaves + * @param {function(Error, TInstance)} callback A callback which is triggered when the operation completes + * @returns {Promise} + */ + insert(objects: TDocument, options: ModelOptions.CreateOptions, callback?: General.Callback): Bluebird; + /** + * Inserts the objects into the collection after validating them against this model's schema + * @param {Object[]} objects The objects to insert into the collection + * @param {function(Error, TInstance[])} callback A callback which is triggered when the operation completes + * @returns {Promise} + */ + insert(objects: TDocument[], callback?: General.Callback): Bluebird; + /** + * Inserts the objects into the collection after validating them against this model's schema + * @param {Object[]} objects The objects to insert into the collection + * @param {CreateOptions} options The options dictating how this function behaves + * @param {function(Error, TInstance[])} callback A callback which is triggered when the operation completes + * @returns {Promise} + */ + insert(objects: TDocument[], options: ModelOptions.CreateOptions, callback?: General.Callback): Bluebird; + /** + * Updates the documents in the backing collection which match the conditions using the given update instructions + * @param {Object} conditions The conditions which determine which documents will be updated + * @param {Object} changes The changes to make to the documents + * @param {function(Error, Number)} callback A callback which is triggered when the operation completes + */ + update(conditions: { + _id?: any; + [key: string]: any; + } | any, changes: any, callback?: General.Callback): Bluebird; + /** + * Updates the documents in the backing collection which match the conditions using the given update instructions + * @param {Object} conditions The conditions which determine which documents will be updated + * @param {Object} changes The changes to make to the documents + * @param {UpdateOptions} options The options which dictate how this function behaves + * @param {function(Error, Number)} callback A callback which is triggered when the operation completes + */ + update(conditions: { + _id?: any; + [key: string]: any; + } | any, changes: any, options: ModelOptions.UpdateOptions, callback?: General.Callback): Bluebird; + /** + * Counts the number of documents in the collection + * @param {function(Error, Number)} callback A callback which is triggered when the operation completes + * @returns {Promise} + */ + count(callback?: General.Callback): Bluebird; + /** + * Counts the number of documents in the collection which match the conditions provided + * @param {Object} conditions The conditions which determine whether an object is counted or not + * @param {function(Error, Number)} callback A callback which is triggered when the operation completes + * @returns {Promise} + */ + count(conditions: { + _id?: any; + [key: string]: any; + } | any, callback?: General.Callback): Bluebird; + /** + * Removes all documents from the collection + * @param {function(Error, Number)} callback A callback which is triggered when the operation completes + * @returns {Promise} + */ + remove(callback?: General.Callback): Bluebird; + /** + * Removes all documents from the collection which match the conditions + * @param {Object} conditions The conditions determining whether an object is removed or not + * @param {function(Error, Number)} callback A callback which is triggered when the operation completes + * @returns {Promise} + */ + remove(conditions: { + _id?: any; + [key: string]: any; + } | any, callback?: General.Callback): Bluebird; + /** + * Removes all documents from the collection which match the conditions + * @param {Object} conditions The conditions determining whether an object is removed or not + * @param {Object} options The options controlling the way in which the function behaves + * @param {function(Error, Number)} callback A callback which is triggered when the operation completes + * @returns {Promise} + */ + remove(conditions: { + _id?: any; + [key: string]: any; + }, options: ModelOptions.RemoveOptions, callback?: General.Callback): Bluebird; + aggregate(pipeline: AggregationPipeline.Stage[]): Bluebird; + /** + * Ensures that the given index is created for the collection + * @param {Object} specification The index specification object used by MongoDB + * @param {function(Error, String)} callback A callback which is triggered when the operation completes + * @returns {Promise} The name of the index + */ + ensureIndex(specification: Index.IndexSpecification, callback?: General.Callback): Bluebird; + /** + * Ensures that the given index is created for the collection + * @param {Object} specification The index specification object used by MongoDB + * @param {MongoDB.IndexOptions} options The options dictating how the index is created and behaves + * @param {function(Error, String)} callback A callback which is triggered when the operation completes + * @returns {Promise} The name of the index + */ + ensureIndex(specification: Index.IndexSpecification, options: MongoDB.IndexOptions, callback?: General.Callback): Bluebird; + /** + * Ensures that all indexes defined in the model's options are created + * @param {function(Error, String[])} callback A callback which is triggered when the operation completes + * @returns {Promise} The names of the indexes + */ + ensureIndexes(callback?: General.Callback): 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 */ - promise: Bluebird; - + dropIndex(name: string, callback?: General.Callback): Bluebird; /** - * 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. + * 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(value: R): void; - resolve(): void; - + dropIndex(index: Index.IndexSpecification, callback?: General.Callback): Bluebird; /** - * Reject the underlying promise with `reason` as the rejection reason. + * 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(reason: any): void; + 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 { /** - * 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. + * @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. */ - // TODO specify resolver callback - callback: (err: any, value: R, ...values: R[]) => void; - } - - export interface Inspection { + (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 { /** - * See if the underlying promise was fulfilled at the creation time of this inspection object. + * @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. */ - isFulfilled(): boolean; - + (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 { /** - * See if the underlying promise was rejected at the creation time of this inspection object. + * Gets the current value of the property + * @returns The current value */ - isRejected(): boolean; - + (): 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 { /** - * See if the underlying promise was defer at the creation time of this inspection object. + * Sets the value to the provided one + * @param value The new value to set */ - isPending(): boolean; - + (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 { /** - * 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` + * An optional getter which can be used to retrieve the property's value */ - value(): R; - + get?: PropertyGetter; /** - * 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` + * An optional setter which can be used to set the property's value */ - reason(): any; - } - - /** - * 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; + set?: PropertySetter; +} +} +declare module 'iridium/dist/lib/General' { +export * from '~iridium/dist/lib/General'; } -export = Bluebird; +// 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; } -declare module '~iridium~bluebird' { -import main = require('~iridium~bluebird/bluebird'); -export = main; +export interface IndexSpecification { + [key: string]: number | string; +} +} +declare module 'iridium/dist/lib/Index' { +export * from '~iridium/dist/lib/Index'; } // Generated by typings @@ -3188,7 +3315,7 @@ export class Instance Promise | void; + }) => Promise | PromiseLike | void; /** * A function which is called whenever a document of this type is received from the database, prior to it being * wrapped by an Instance object. @@ -3196,7 +3323,7 @@ export class Instance Promise | void; + }) => Promise | PromiseLike | void; /** * A function which is called whenever a new instance has been created to wrap a document. * @param instance The instance which has been created. @@ -3205,7 +3332,7 @@ export class Instance>) => Promise | void; + }, any>>) => Promise | PromiseLike | void; /** * A function which is called whenever an instance's save() method is called to allow you to interrogate and/or manipulate * the changes which are being made. @@ -3217,7 +3344,7 @@ export class Instance>, changes: any) => Promise | void; + }, any>>, changes: any) => Promise | PromiseLike | void; /** * The name of the collection into which documents of this type are stored. */ @@ -3337,133 +3464,6 @@ 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' { @@ -3859,10 +3859,10 @@ export * from '~iridium/dist/lib/Configuration'; // Source: dist/lib/Hooks.d.ts declare module '~iridium/dist/lib/Hooks' { export interface Hooks { - onCreating?(document: TDocument): Promise | void; - onRetrieved?(document: TDocument): Promise | void; - onReady?(instance: TInstance): Promise | void; - onSaving?(instance: TInstance, changes: any): Promise | void; + onCreating?(document: TDocument): Promise | PromiseLike | void; + onRetrieved?(document: TDocument): Promise | PromiseLike | void; + onReady?(instance: TInstance): Promise | PromiseLike | void; + onSaving?(instance: TInstance, changes: any): Promise | PromiseLike | void; } } declare module 'iridium/dist/lib/Hooks' { diff --git a/tsconfig.json b/tsconfig.json index 2938511..6c07281 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -2,7 +2,7 @@ "compilerOptions": { "version": true, "module": "commonjs", - "target": "es5", + "target": "es6", "sourceMap": true, "declaration": true, "sourceRoot": "./lib", diff --git a/typings.json b/typings.json index 30d02a8..6580e52 100644 --- a/typings.json +++ b/typings.json @@ -4,7 +4,6 @@ "main": "dist/iridium.d.ts", "dependencies": { "bluebird": "registry:npm/bluebird#3.3.4+20160515010139", - "es6-promise": "registry:npm/es6-promise#3.0.0+20160211003958", "lodash": "registry:npm/lodash#4.0.0+20160416211519", "mongodb": "registry:npm/mongodb#2.1.0+20160422172506", "skmatc": "github:sierrasoftworks/skmatc#master" @@ -17,7 +16,6 @@ "mocha": "registry:dt/mocha#2.2.5+20160317120654" }, "globalDependencies": { - "es6-promise": "registry:dt/es6-promise#0.0.0+20160317120654", "node": "registry:dt/node#6.0.0+20160514165920" } } diff --git a/typings/globals/es6-promise/index.d.ts b/typings/globals/es6-promise/index.d.ts deleted file mode 100644 index c69a4b8..0000000 --- a/typings/globals/es6-promise/index.d.ts +++ /dev/null @@ -1,72 +0,0 @@ -// Generated by typings -// Source: https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/7de6c3dd94feaeb21f20054b9f30d5dabc5efabd/es6-promise/es6-promise.d.ts -interface Thenable { - then(onFulfilled?: (value: T) => U | Thenable, onRejected?: (error: any) => U | Thenable): Thenable; - then(onFulfilled?: (value: T) => U | Thenable, onRejected?: (error: any) => void): Thenable; - catch(onRejected?: (error: any) => U | Thenable): Thenable; -} - -declare 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 reject. - * 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?: T | Thenable) => void, reject: (error?: any) => void) => void); - - /** - * 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: T) => U | Thenable, onRejected?: (error: any) => U | Thenable): Promise; - then(onFulfilled?: (value: T) => U | Thenable, onRejected?: (error: any) => void): Promise; - - /** - * Sugar for promise.then(undefined, onRejected) - * - * @param onRejected called when/if "promise" rejects - */ - catch(onRejected?: (error: any) => U | Thenable): Promise; -} - -declare namespace Promise { - /** - * Make a new promise from the thenable. - * A thenable is promise-like in as far as it has a "then" method. - */ - function resolve(value?: T | Thenable): Promise; - - /** - * Make a promise that rejects to obj. For consistency and debugging (eg stack traces), obj should be an instanceof Error - */ - function reject(error: any): Promise; - function reject(error: T): 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. - */ - function all(promises: (T | Thenable)[]): Promise; - - /** - * Make a Promise that fulfills when any item fulfills, and rejects if any item rejects. - */ - function race(promises: (T | Thenable)[]): Promise; -} - -declare module 'es6-promise' { - var foo: typeof Promise; // Temp variable to reference Promise in local context - namespace rsvp { - export var Promise: typeof foo; - } - export = rsvp; -} \ No newline at end of file diff --git a/typings/globals/es6-promise/typings.json b/typings/globals/es6-promise/typings.json deleted file mode 100644 index 878d25e..0000000 --- a/typings/globals/es6-promise/typings.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "resolution": "main", - "tree": { - "src": "https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/7de6c3dd94feaeb21f20054b9f30d5dabc5efabd/es6-promise/es6-promise.d.ts", - "raw": "registry:dt/es6-promise#0.0.0+20160317120654", - "typings": "https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/7de6c3dd94feaeb21f20054b9f30d5dabc5efabd/es6-promise/es6-promise.d.ts" - } -} diff --git a/typings/index.d.ts b/typings/index.d.ts index 6dbf4ae..314d407 100644 --- a/typings/index.d.ts +++ b/typings/index.d.ts @@ -1,4 +1,3 @@ -/// /// /// ///