From 702976a79daf1e4d6c8e8b127e37015a60118e62 Mon Sep 17 00:00:00 2001 From: Benjamin Pannell Date: Fri, 11 Mar 2016 09:44:00 +0200 Subject: [PATCH] refactor: Eschew var for let wherever possible --- dist/lib/Core.js.map | 2 +- dist/lib/Cursor.js.map | 2 +- dist/lib/Instance.js.map | 2 +- dist/lib/Model.js.map | 2 +- dist/lib/ModelHelpers.js.map | 2 +- dist/lib/ModelSpecificInstance.js.map | 2 +- dist/lib/caches/MemoryCache.js.map | 2 +- lib/Core.ts | 10 +++++----- lib/Cursor.ts | 8 ++++---- lib/Instance.ts | 22 +++++++++++----------- lib/Model.ts | 26 +++++++++++++------------- lib/ModelHelpers.ts | 8 ++++---- lib/ModelSpecificInstance.ts | 2 +- lib/caches/MemoryCache.ts | 2 +- 14 files changed, 46 insertions(+), 46 deletions(-) diff --git a/dist/lib/Core.js.map b/dist/lib/Core.js.map index 48ab525..55bb216 100644 --- a/dist/lib/Core.js.map +++ b/dist/lib/Core.js.map @@ -1 +1 @@ -{"version":3,"sources":["lib/Core.ts"],"names":[],"mappings":";AAAA,IAAO,QAAQ,WAAW,UAAU,CAAC,CAAC;AACtC,IAAO,OAAO,WAAW,SAAS,CAAC,CAAC;AACpC,IAAO,CAAC,WAAW,QAAQ,CAAC,CAAC;AAW7B,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,IAA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AAA","file":"lib/Core.js","sourcesContent":["import Bluebird = require('bluebird');\r\nimport MongoDB = require('mongodb');\r\nimport _ = require('lodash');\r\nimport http = require('http');\r\nimport events = require('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 var args = Array.prototype.slice.call(arguments, 0);\r\n uri = config = null;\r\n for (var 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 var 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 var 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 var 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 +{"version":3,"sources":["lib/Core.ts"],"names":[],"mappings":";AAAA,IAAO,QAAQ,WAAW,UAAU,CAAC,CAAC;AACtC,IAAO,OAAO,WAAW,SAAS,CAAC,CAAC;AACpC,IAAO,CAAC,WAAW,QAAQ,CAAC,CAAC;AAW7B,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,CAAC,EAAE,CAAC,CAAC,OAAO,IAAI,CAAC,CAAC,CAAC,IAAI,QAAQ,CAAC;gBAChC,MAAM,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC;QACzB,CAAC;QAED,EAAE,CAAC,CAAC,CAA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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 Bluebird = require('bluebird');\r\nimport MongoDB = require('mongodb');\r\nimport _ = require('lodash');\r\nimport http = require('http');\r\nimport events = require('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.map b/dist/lib/Cursor.js.map index 054e708..808368d 100644 --- a/dist/lib/Cursor.js.map +++ b/dist/lib/Cursor.js.map @@ -1 +1 @@ -{"version":3,"sources":["lib/Cursor.ts"],"names":[],"mappings":";AAGA,IAAO,QAAQ,WAAW,UAAU,CAAC,CAAC;AAGtC;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AC,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC;IACzB,CAAC;IAED;;;OAGG;IACH,uBAAM,GAAN;QACI,IAAI,CAAC,MAAM,CAAC,MAAM,EAAE,CAAC;QACrB,MAAM,CAAC,IAAI,CAAC;IAChB,CAAC;IAED;;;;OAIG;IACH,qBAAI,GAAJ,UAAK,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,sBAAK,GAAL,UAAM,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,qBAAI,GAAJ,UAAK,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,yBAAQ,GAAR,UAAS,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;IACL,aAAC;AAAD,CAvKA,AAuKC,IAAA;AAvKY,cAAM,SAuKlB,CAAA","file":"lib/Cursor.js","sourcesContent":["import {Model} from './Model';\r\nimport General = require('./General');\r\nimport MongoDB = require('mongodb');\r\nimport Bluebird = require('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 var 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 var helpers = this.model.helpers;\r\n return new Bluebird((resolve, reject) => {\r\n var 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 var 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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,CAAC,QAAQ,EAAE,KAAK,EAAE,SAAS,CAAC,EAA3D,CAA2D,CAAC,CAAC;QACzK,CAAC,CAAC,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC;IACzB,CAAC;IAED;;;OAGG;IACH,uBAAM,GAAN;QACI,IAAI,CAAC,MAAM,CAAC,MAAM,EAAE,CAAC;QACrB,MAAM,CAAC,IAAI,CAAC;IAChB,CAAC;IAED;;;;OAIG;IACH,qBAAI,GAAJ,UAAK,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,sBAAK,GAAL,UAAM,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,qBAAI,GAAJ,UAAK,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,yBAAQ,GAAR,UAAS,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;IACL,aAAC;AAAD,CAvKA,AAuKC,IAAA;AAvKY,cAAM,SAuKlB,CAAA","file":"lib/Cursor.js","sourcesContent":["import {Model} from './Model';\r\nimport General = require('./General');\r\nimport MongoDB = require('mongodb');\r\nimport Bluebird = require('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/Instance.js.map b/dist/lib/Instance.js.map index cd4fdec..bf6049a 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,IAAO,CAAC,WAAW,QAAQ,CAAC,CAAC;AAE7B,IAAO,QAAQ,WAAW,UAAU,CAAC,CAAC;AAGtC;;;;;;;;;;;;;GAaG;AACH;IACI;;;;;;;OAOG;IACH,kBAAY,KAAkC,EAAE,QAAmB,EAAE,KAAqB,EAAE,SAA0B;QAT1H,iBAoWC;QA3VwE,qBAAqB,GAArB,YAAqB;QAAE,yBAA0B,GAA1B,iBAA0B;QAClH,IAAI,CAAC,MAAM,GAAG,KAAK,CAAC;QAEpB,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC,KAAK,CAAC;QACtB,IAAI,CAAC,UAAU,GAAG,SAAS,CAAC;QAC5B,IAAI,CAAC,SAAS,GAAG,QAAQ,CAAC;QAC1B,IAAI,CAAC,SAAS,GAAG,KAAK,CAAC,OAAO,CAAC,aAAa,CAAC,QAAQ,CAAC,CAAC;QAEvD,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,OAAO,EAAC,UAAC,MAAc;YACrC,EAAE,CAAC,CAAC,MAAM,CAAC,WAAW,CAAC;gBAAC,MAAM,CAAC,WAAW,CAAC,KAAI,EAAE,KAAK,CAAC,CAAC;QAC5D,CAAC,CAAC,CAAC;IACP,CAAC;IAWD,sBAAI,8BAAQ;QAHZ;;WAEG;aACH;YACI,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC;QAC1B,CAAC;;;OAAA;IAuFD,uBAAI,GAAJ;QAAA,iBAuFC;QAvFI,cAAc;aAAd,WAAc,CAAd,sBAAc,CAAd,IAAc;YAA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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 _ = require('lodash');\r\nimport MongoDB = require('mongodb');\r\nimport Bluebird = require('bluebird');\r\nimport Skmatc = require('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.Thenable | 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.Thenable | 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.Thenable | 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.Thenable | 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 var callback: General.Callback = null;\r\n var changes: any = null;\r\n var 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 var 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 var original = this._model.helpers.cloneDocument(this._original);\r\n var 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: Error, changed: boolean) => {\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);\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.findOne(conditions, (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 var 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.findOne(conditions,(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 var 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.remove(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 var 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 var isArray = Array.isArray(collection);\r\n var 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":[],"m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BAAO,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 _ = require('lodash');\r\nimport MongoDB = require('mongodb');\r\nimport Bluebird = require('bluebird');\r\nimport Skmatc = require('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.Thenable | 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.Thenable | 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.Thenable | 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.Thenable | 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: Error, changed: boolean) => {\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);\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.findOne(conditions, (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.findOne(conditions,(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.remove(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.map b/dist/lib/Model.js.map index 8faec39..242c634 100644 --- a/dist/lib/Model.js.map +++ b/dist/lib/Model.js.map @@ -1 +1 @@ -{"version":3,"sources":["lib/Model.ts"],"names":[],"mappings":";AAAA,IAAO,OAAO,WAAW,SAAS,CAAC,CAAC;AACpC,IAAO,QAAQ,WAAW,UAAU,CAAC,CAAC;AAEtC,IAAO,CAAC,WAAW,QAAQ,C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AAC,GAAG,EAAE,MAAsB;gBACxD,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,2BAAW,GAAX,UAAY,QAAoC;QAAhD,iBAOC;QANG,MAAM,CAAC,IAAI,QAAQ,CAAM,UAAC,OAAO,EAAE,MAAM;YACrC,KAAI,CAAC,UAAU,CAAC,cAAc,CAAC,UAAC,GAAG,EAAE,KAAK;gBACtC,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,CA3sBA,AA2sBC,IAAA;AA3sBY,aAAK,QA2sBjB,CAAA","file":"lib/Model.js","sourcesContent":["import MongoDB = require('mongodb');\r\nimport Bluebird = require('bluebird');\r\nimport util = require('util');\r\nimport _ = require('lodash');\r\nimport Skmatc = require('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 fields = fields || {};\r\n\r\n if (!_.isPlainObject(conditions)) conditions = { _id: conditions };\r\n conditions = this._helpers.convertToDB(conditions);\r\n\r\n var cursor = this.collection.find(conditions, {\r\n fields: fields\r\n });\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 var conditions: { _id?: any, [key: string]: any } = null;\r\n var options: ModelOptions.QueryOptions = null;\r\n var callback: General.Callback = null;\r\n\r\n for (var 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 this.collection.findOne(conditions, {\r\n fields: options.fields,\r\n skip: options.skip,\r\n sort: options.sort,\r\n limit: options.limit\r\n },(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 var objects: TDocument[];\r\n var options: ModelOptions.CreateOptions = {};\r\n var 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 var queryOptions = { w: options.w, upsert: options.upsert, new: true };\r\n\r\n if (options.upsert) {\r\n var docs = this._handlers.creatingDocuments(objects);\r\n return docs.map((object: { _id: any; }) => {\r\n return new Bluebird((resolve, reject) => {\r\n this.collection.findAndModify({ _id: object._id }, [\"_id\"], object, queryOptions,(err, result) => {\r\n if (err) return reject(err);\r\n return resolve(result);\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 var 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 var 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 this.collection.remove(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.ensureIndex(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 var 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.dropAllIndexes((err, count) => {\r\n if (err) return reject(err);\r\n return resolve(count);\r\n });\r\n }).nodeify(call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,EAAE,CAAC,IAAK,OAAA,CAAC,GAAG,GAAG,GAAG,CAAC,EAAX,CAAW,CAAC,CAAC;QAC5I,CAAC;QAED,MAAM,CAAC,IAAI,QAAQ,CAAU,UAAC,OAAO,EAAE,MAAM;YACzC,KAAI,CAAC,UAAU,CAAC,SAAS,CAAC,KAAK,EAAC,UAAC,GAAG,EAAE,MAAsB;gBACxD,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,2BAAW,GAAX,UAAY,QAAoC;QAAhD,iBAOC;QANG,MAAM,CAAC,IAAI,QAAQ,CAAM,UAAC,OAAO,EAAE,MAAM;YACrC,KAAI,CAAC,UAAU,CAAC,cAAc,CAAC,UAAC,GAAG,EAAE,KAAK;gBACtC,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,CA3sBA,AA2sBC,IAAA;AA3sBY,aAAK,QA2sBjB,CAAA","file":"lib/Model.js","sourcesContent":["import MongoDB = require('mongodb');\r\nimport Bluebird = require('bluebird');\r\nimport util = require('util');\r\nimport _ = require('lodash');\r\nimport Skmatc = require('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 fields = fields || {};\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 fields: fields\r\n });\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 this.collection.findOne(conditions, {\r\n fields: options.fields,\r\n skip: options.skip,\r\n sort: options.sort,\r\n limit: options.limit\r\n },(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.findAndModify({ _id: object._id }, [\"_id\"], object, queryOptions,(err, result) => {\r\n if (err) return reject(err);\r\n return resolve(result);\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 this.collection.remove(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.ensureIndex(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.dropAllIndexes((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/ModelHelpers.js.map b/dist/lib/ModelHelpers.js.map index d17f026..dba367c 100644 --- a/dist/lib/ModelHelpers.js.map +++ b/dist/lib/ModelHelpers.js.map @@ -1 +1 @@ -{"version":3,"sources":["lib/ModelHelpers.ts"],"names":[],"mappings":";AAAA,IAAO,OAAO,WAAW,SAAS,CAAC,CAAC;AAEpC,IAAO,MAAM,WAAW,QAAQ,CAAC,CAAC;AAClC,sBAAoB,eAAe,CAAC,CAAA;AACpC,IAAO,CAAC,WAAW,QAAQ,CAAC,CAAC;AAG7B;;;;;GAKG;AACH;IACI,sBAAmB,KAAkC;QADzD,iBAkIC;QAjIsB,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,UAAA,SAAS,IAAI,OAAA,KAAI,CAAC,UAAU,CAAC,QAAQ,CAAC,SAAS,CAAC,EAAnC,CAAmC,CAAC,CAAC;IAC/E,CAAC;IAID;;;;OAIG;IACH,+BAAQ,GAAR,UAAS,QAAmB;QACxB,MAAM,CAAC,IAAI,CAAC,UAAU,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC;IAC9C,CAAC;IAED;;;;;;OAMG;IACH,mCAAY,GAAZ,UAAa,QAAmB,EAAE,KAAe,EAAE,SAAmB;QAClE,MAAM,CAAC,IAAI,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,QAAQ,EAAE,KAAK,EAAE,SAAS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C,KAAK;YACpC,EAAE,CAAA,CAAC,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;gBACxB,MAAM,CAAC,KAAK,CAAC;YACjB,CAAC;YAED,EAAE,CAAA,CAAC,KAAK,YAAY,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC;gBACjC,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,sCAAe,GAAf,UAAmB,QAAW;QAC1B,MAAM,CAAC,IAAI,CAAC,aAAa,CAAC,QAAQ,CAAC,CAAC;IACxC,CAAC;IACL,mBAAC;AAAD,CAlIA,AAkIC,IAAA;AAlIY,oBAAY,eAkIxB,CAAA","file":"lib/ModelHelpers.js","sourcesContent":["import MongoDB = require('mongodb');\r\nimport {Model} from './Model';\r\nimport Skmatc = require('skmatc');\r\nimport {Omnom} from './utils/Omnom';\r\nimport _ = require('lodash');\r\nimport Bluebird = require('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 (var 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 (var 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 var 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 var 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,IAAO,OAAO,WAAW,SAAS,CAAC,CAAC;AAEpC,IAAO,MAAM,WAAW,QAAQ,CAAC,CAAC;AAClC,sBAAoB,eAAe,CAAC,CAAA;AACpC,IAAO,CAAC,WAAW,QAAQ,CAAC,CAAC;AAG7B;;;;;GAKG;AACH;IACI,sBAAmB,KAAkC;QADzD,iBAkIC;QAjIsB,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,UAAA,SAAS,IAAI,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I,CAAC,aAAa,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC;IAC5C,CAAC;IAED;;;;OAIG;IACH,2BAAI,GAAJ,UAAK,QAAmB,EAAE,QAAmB;QACzC,IAAI,KAAK,GAAG,IAAI,aAAK,EAAE,CAAC;QACxB,KAAK,CAAC,IAAI,CAAC,QAAQ,EAAE,QAAQ,CAAC,CAAC;QAC/B,MAAM,CAAC,KAAK,CAAC,OAAO,CAAC;IACzB,CAAC;IAED;;;;;OAKG;IACH,oCAAa,GAAb,UAAiB,QAAW;QACxB,MAAM,CAAC,CAAC,CAAC,aAAa,CAAC,QAAQ,EAAE,UAAC,KAAK;YACpC,EAAE,CAAA,CAAC,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;gBACxB,MAAM,CAAC,KAAK,CAAC;YACjB,CAAC;YAED,EAAE,CAAA,CAAC,KAAK,YAAY,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC;gBACjC,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,sCAAe,GAAf,UAAmB,QAAW;QAC1B,MAAM,CAAC,IAAI,CAAC,aAAa,CAAC,QAAQ,CAAC,CAAC;IACxC,CAAC;IACL,mBAAC;AAAD,CAlIA,AAkIC,IAAA;AAlIY,oBAAY,eAkIxB,CAAA","file":"lib/ModelHelpers.js","sourcesContent":["import MongoDB = require('mongodb');\r\nimport {Model} from './Model';\r\nimport Skmatc = require('skmatc');\r\nimport {Omnom} from './utils/Omnom';\r\nimport _ = require('lodash');\r\nimport Bluebird = require('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.map b/dist/lib/ModelSpecific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ACrB,CAAC,CAAC;QACP,CAAC;QAED,MAAM,CAAC,cAAc,CAAC,WAAW,CAAC,SAAS,EAAE,QAAQ,EAAE;YACnD,GAAG,EAAE;gBACD,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAC;YACpC,CAAC;YACD,GAAG,EAAE,UAAU,KAAK;gBAChB,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,GAAG,KAAK,CAAC;YACrC,CAAC;YACD,UAAU,EAAE,IAAI;SACnB,CAAC,CAAC;IACP,CAAC,CAAC,CAAC;IAEH,MAAM,CAAM,WAAW,CAAC;AAC5B,CAAC;AAjCe,6BAAqB,wBAiCpC,CAAA","file":"lib/ModelSpecificInstance.js","sourcesContent":["import {Model} from './Model';\r\nimport {InstanceImplementation} from './InstanceInterface';\r\nimport {ModelSpecificInstanceConstructor} from './ModelInterfaces';\r\nimport util = require('util');\r\nimport _ = require('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 var constructor = function (doc: TDocument, isNew?: boolean, isPartial?: boolean) {\r\n instanceType.call(this, model, doc, isNew, isPartial);\r\n };\r\n\r\n util.inherits(constructor, instanceType);\r\n\r\n _.each(Object.keys(model.schema),(property) => {\r\n if (model.transforms.hasOwnProperty(property)) {\r\n return Object.defineProperty(constructor.prototype, property, {\r\n get: function () {\r\n return model.transforms[property].fromDB(this._modified[property], property, model);\r\n },\r\n set: function (value) {\r\n this._modified[property] = model.transforms[property].toDB(value, property, model);\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n }\r\n\r\n Object.defineProperty(constructor.prototype, property, {\r\n get: function () {\r\n return this._modified[property];\r\n },\r\n set: function (value) {\r\n this._modified[property] = value;\r\n },\r\n enumerable: true\r\n });\r\n });\r\n\r\n return constructor;\r\n}\r\n"],"sourceRoot":"/source/"} \ No newline at end of file +{"version":3,"sources":["lib/ModelSpecificInstance.ts"],"names":[],"mappings":";AAGA,IAAO,IAAI,WAAW,MAAM,CAAC,CAAC;AAC9B,IAAO,CAAC,WAAW,QAAQ,CAAC,CAAC;AAE7B;;;;;;;;;;;GAWG;AACH,+BAAkF,KAAkC,EAAE,YAA0D;IAC5K,IAAI,WAAW,GAAG,UAAU,GAAc,EAAE,KAAe,EAAE,SAAmB;QAC5E,YAAY,CAAC,IAAI,CAAC,IAAI,EAAE,KAAK,EAAE,GAAG,EAAE,KAAK,EAAE,SAAS,CAAC,CAAC;IAC1D,CAAC,CAAC;IAEF,IAAI,CAAC,QAAQ,CAAC,WAAW,EAAE,YAAY,CAAC,CAAC;IAEzC,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,EAAC,UAAC,QAAQ;QACtC,EAAE,CAAC,CAAC,KAAK,CAAC,UAAU,CAAC,cAAc,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC;YAC5C,MAAM,CAAC,MAAM,CAAC,cAAc,CAAC,WAAW,CAAC,SAAS,EAAE,QAAQ,EAAE;gBAC1D,GAAG,EAAE;oBACD,MAAM,CAAC,KAAK,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,EAAE,QAAQ,EAAE,KAAK,CAAC,CAAC;gBACxF,CAAC;gBACD,GAAG,EAAE,UAAU,KAAK;oBAChB,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,GAAG,KAAK,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC,IAAI,CAAC,KAAK,EAAE,QAAQ,EAAE,KAAK,CAAC,CAAC;gBACvF,CAAC;gBACD,UAAU,EAAE,IAAI;gBAChB,YAAY,EAAE,IAAI;aACrB,CAAC,CAAC;QACP,CAAC;QAED,MAAM,CAAC,cAAc,CAAC,WAAW,CAAC,SAAS,EAAE,QAAQ,EAAE;YACnD,GAAG,EAAE;gBACD,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAC;YACpC,CAAC;YACD,GAAG,EAAE,UAAU,KAAK;gBAChB,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,GAAG,KAAK,CAAC;YACrC,CAAC;YACD,UAAU,EAAE,IAAI;SACnB,CAAC,CAAC;IACP,CAAC,CAAC,CAAC;IAEH,MAAM,CAAM,WAAW,CAAC;AAC5B,CAAC;AAjCe,6BAAqB,wBAiCpC,CAAA","file":"lib/ModelSpecificInstance.js","sourcesContent":["import {Model} from './Model';\r\nimport {InstanceImplementation} from './InstanceInterface';\r\nimport {ModelSpecificInstanceConstructor} from './ModelInterfaces';\r\nimport util = require('util');\r\nimport _ = require('lodash');\r\n\r\n/**\r\n * Creates a new subclass of the given instanceType which correctly performs property transforms\r\n * and associates the instance with the correct model when instantiated.\r\n *\r\n * @param TDocument The interface representing the structure of the documents found in the database.\r\n * @param TInstance The interface or class representing the documents after they have been wrapped in an instance.\r\n *\r\n * @param model The model which instances should be associated with when the resulting constructor is used.\r\n * @param instanceType The constructor used to create new instances of type TInstance.\r\n *\r\n * @internal\r\n */\r\nexport function ModelSpecificInstance(model: Model, instanceType: InstanceImplementation): ModelSpecificInstanceConstructor {\r\n let constructor = function (doc: TDocument, isNew?: boolean, isPartial?: boolean) {\r\n instanceType.call(this, model, doc, isNew, isPartial);\r\n };\r\n\r\n util.inherits(constructor, instanceType);\r\n\r\n _.each(Object.keys(model.schema),(property) => {\r\n if (model.transforms.hasOwnProperty(property)) {\r\n return Object.defineProperty(constructor.prototype, property, {\r\n get: function () {\r\n return model.transforms[property].fromDB(this._modified[property], property, model);\r\n },\r\n set: function (value) {\r\n this._modified[property] = model.transforms[property].toDB(value, property, model);\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n }\r\n\r\n Object.defineProperty(constructor.prototype, property, {\r\n get: function () {\r\n return this._modified[property];\r\n },\r\n set: function (value) {\r\n this._modified[property] = value;\r\n },\r\n enumerable: true\r\n });\r\n });\r\n\r\n return constructor;\r\n}\r\n"],"sourceRoot":"/source/"} \ No newline at end of file diff --git a/dist/lib/caches/MemoryCache.js.map b/dist/lib/caches/MemoryCache.js.map index 99bc39a..f9b1ff6 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,IAAO,QAAQ,WAAW,UAAU,CAAC,CAAC;AAGtC;;;;;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 Bluebird = require('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 var 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,IAAO,QAAQ,WAAW,UAAU,CAAC,CAAC;AAGtC;;;;;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 Bluebird = require('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/lib/Core.ts b/lib/Core.ts index 214d070..4db4f59 100644 --- a/lib/Core.ts +++ b/lib/Core.ts @@ -40,9 +40,9 @@ export class Core { constructor(uri: string, config?: Configuration); constructor(uri: string | Configuration, config?: Configuration) { - 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') @@ -97,7 +97,7 @@ export class Core { */ get url(): string { if (this._url) return this._url; - var url: string = 'mongodb://'; + let url: string = 'mongodb://'; if (this._config.username) { url += this._config.username; @@ -106,7 +106,7 @@ export class Core { url += '@'; } - var hosts = []; + let hosts = []; if (this._config.host) { if (this._config.port) @@ -191,7 +191,7 @@ export class Core { close(): Bluebird { return Bluebird.resolve().then(() => { if (!this._connection) return this; - var conn: MongoDB.Db = this._connection; + let conn: MongoDB.Db = this._connection; this._connection = null; conn.close(); return this; diff --git a/lib/Cursor.ts b/lib/Cursor.ts index d04cc35..d78cdf4 100644 --- a/lib/Cursor.ts +++ b/lib/Cursor.ts @@ -44,7 +44,7 @@ export class Cursor { * @return {Promise} A promise which is resolved when all operations have been dispatched */ forEach(handler: (instance: TInstance) => void, callback?: General.Callback): Bluebird { - var helpers = this.model.helpers; + let helpers = this.model.helpers; return new Bluebird((resolve, reject) => { this.cursor.forEach((item: TDocument) => { this.model.handlers.documentReceived(this.conditions, item, function () { return helpers.wrapDocument.apply(helpers, arguments); }).then(handler); @@ -62,9 +62,9 @@ export class Cursor { * @return {Promise} A promise which is fulfilled with the results of the transformations */ map(transform: (instance: TInstance) => TResult | Bluebird, callback?: General.Callback): Bluebird { - var helpers = this.model.helpers; + let helpers = this.model.helpers; return new Bluebird((resolve, reject) => { - var promises: Bluebird[] = []; + let promises: Bluebird[] = []; this.cursor.forEach((item: TDocument) => { promises.push(this.model.handlers.documentReceived(this.conditions, item, function () { return helpers.wrapDocument.apply(helpers, arguments); }) .then(<(instance) => TResult>transform)); @@ -81,7 +81,7 @@ export class Cursor { * @return {Promise} A promise which resolves with the instances returned by the query */ toArray(callback?: General.Callback): Bluebird { - var helpers = this.model.helpers; + let helpers = this.model.helpers; return new Bluebird((resolve, reject) => { this.cursor.toArray((err, results: any[]) => { if (err) return reject(err); diff --git a/lib/Instance.ts b/lib/Instance.ts index 7087d77..48f2d4e 100644 --- a/lib/Instance.ts +++ b/lib/Instance.ts @@ -149,9 +149,9 @@ export class Instance { */ save(conditions: Object, changes: Object, callback?: General.Callback): Bluebird; save(...args: any[]): Bluebird { - var callback: General.Callback = null; - var changes: any = null; - var conditions: any = {}; + let callback: General.Callback = null; + let changes: any = null; + let conditions: any = {}; Array.prototype.slice.call(args, 0).reverse().forEach((arg) => { if (typeof arg == 'function') callback = arg; @@ -166,11 +166,11 @@ export class Instance { _.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); + let original = this._model.helpers.cloneDocument(this._original); + let modified = this._model.helpers.cloneDocument(this._modified); modified = this._model.helpers.transformToDB(modified, { document: true }); @@ -252,7 +252,7 @@ export class Instance { * @returns {Promise} */ refresh(callback?: General.Callback): Bluebird { - var conditions = { _id: this._original._id }; + let conditions = { _id: this._original._id }; return Bluebird.resolve().then(() => { return new Bluebird((resolve, reject) => { @@ -295,7 +295,7 @@ export class Instance { * @returns {Promise} */ remove(callback?: General.Callback): Bluebird { - var conditions = { _id: this._original._id }; + let conditions = { _id: this._original._id }; return Bluebird.resolve().then(() => { if (this._isNew) return 0; @@ -329,7 +329,7 @@ export class Instance { */ first(collection: { [key: string]: T }, predicate: General.Predicate): T; first(collection: T[]| { [key: string]: T }, predicate: General.Predicate): T { - var result = null; + let result = null; _.each(collection,(value: T, key) => { if (predicate.call(this, value, key)) { @@ -356,8 +356,8 @@ export class Instance { */ select(collection: { [key: string]: T }, predicate: General.Predicate): { [key: string]: T }; select(collection: T[]| { [key: string]: T }, predicate: General.Predicate): any { - var isArray = Array.isArray(collection); - var results: any = isArray ? [] : {}; + let isArray = Array.isArray(collection); + let results: any = isArray ? [] : {}; _.each(collection,(value: T, key) => { if (predicate.call(this, value, key)) { diff --git a/lib/Model.ts b/lib/Model.ts index fe664df..25a2604 100644 --- a/lib/Model.ts +++ b/lib/Model.ts @@ -268,7 +268,7 @@ export class Model { if (!_.isPlainObject(conditions)) conditions = { _id: conditions }; conditions = this._helpers.convertToDB(conditions); - var cursor = this.collection.find(conditions, { + let cursor = this.collection.find(conditions, { fields: fields }); @@ -352,11 +352,11 @@ export class Model { */ findOne(conditions: { _id?: any, [key: string]: any }, options: ModelOptions.QueryOptions, callback?: General.Callback): Bluebird; findOne(...args: any[]): Bluebird { - var conditions: { _id?: any, [key: string]: any } = null; - var options: ModelOptions.QueryOptions = null; - var callback: General.Callback = null; + let conditions: { _id?: any, [key: string]: any } = null; + let options: ModelOptions.QueryOptions = null; + let callback: General.Callback = null; - for (var argI = 0; argI < args.length; argI++) { + for (let argI = 0; argI < args.length; argI++) { if (typeof args[argI] == 'function') callback = callback || args[argI]; else if (_.isPlainObject(args[argI])) { if (conditions) options = args[argI]; @@ -460,9 +460,9 @@ export class Model { */ insert(objects: TDocument[], options: ModelOptions.CreateOptions, callback?: General.Callback): Bluebird; insert(objs: TDocument | TDocument[], ...args: any[]): Bluebird { - var objects: TDocument[]; - var options: ModelOptions.CreateOptions = {}; - var callback: General.Callback = null; + let objects: TDocument[]; + let options: ModelOptions.CreateOptions = {}; + let callback: General.Callback = null; if (typeof args[0] == 'function') callback = args[0]; else { options = args[0]; @@ -481,10 +481,10 @@ export class Model { }); return Bluebird.resolve().then(() => { - var queryOptions = { w: options.w, upsert: options.upsert, new: true }; + let queryOptions = { w: options.w, upsert: options.upsert, new: true }; if (options.upsert) { - var docs = this._handlers.creatingDocuments(objects); + let docs = this._handlers.creatingDocuments(objects); return docs.map((object: { _id: any; }) => { return new Bluebird((resolve, reject) => { this.collection.findAndModify({ _id: object._id }, ["_id"], object, queryOptions,(err, result) => { @@ -574,7 +574,7 @@ export class Model { */ count(conditions: { _id?: any, [key: string]: any } | any, callback?: General.Callback): Bluebird; count(conds?: any, callback?: General.Callback): Bluebird { - var conditions: { _id?: any, [key: string]: any } = <{ _id?: any, [key: string]: any }>conds; + let conditions: { _id?: any, [key: string]: any } = <{ _id?: any, [key: string]: any }>conds; if (typeof conds == 'function') { callback = >conds; conditions = {}; @@ -620,7 +620,7 @@ export class Model { */ remove(conditions: { _id?: any, [key: string]: any }, options: ModelOptions.RemoveOptions, callback?: General.Callback): Bluebird; remove(conds?: any, options?: ModelOptions.RemoveOptions, callback?: General.Callback): Bluebird { - var conditions: { _id?: any, [key: string]: any } = <{ _id?: any, [key: string]: any }>conds; + let conditions: { _id?: any, [key: string]: any } = <{ _id?: any, [key: string]: any }>conds; if (typeof options === 'function') { callback = >options; @@ -723,7 +723,7 @@ export class Model { */ dropIndex(index: Index.IndexSpecification, callback?: General.Callback): Bluebird; dropIndex(specification: string | Index.IndexSpecification, callback?: General.Callback): Bluebird { - var index: string; + let index: string; if (typeof (specification) === 'string') index = specification; else { diff --git a/lib/ModelHelpers.ts b/lib/ModelHelpers.ts index 9036523..eace87e 100644 --- a/lib/ModelHelpers.ts +++ b/lib/ModelHelpers.ts @@ -52,7 +52,7 @@ export class ModelHelpers { 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); @@ -76,7 +76,7 @@ export class ModelHelpers { 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); @@ -94,7 +94,7 @@ export class ModelHelpers { * @returns {any} A new document cloned from the original and transformed */ convertToDB(document: T, options: TransformOptions = { properties: true }): T { - var doc: T = this.cloneDocument(document); + let doc: T = this.cloneDocument(document); return this.transformToDB(doc, options); } @@ -104,7 +104,7 @@ export class ModelHelpers { * @param {any} modified The document after changes were made */ diff(original: TDocument, modified: TDocument): any { - var omnom = new Omnom(); + let omnom = new Omnom(); omnom.diff(original, modified); return omnom.changes; } diff --git a/lib/ModelSpecificInstance.ts b/lib/ModelSpecificInstance.ts index ad1af25..237309b 100644 --- a/lib/ModelSpecificInstance.ts +++ b/lib/ModelSpecificInstance.ts @@ -17,7 +17,7 @@ import _ = require('lodash'); * @internal */ export function ModelSpecificInstance(model: Model, instanceType: InstanceImplementation): ModelSpecificInstanceConstructor { - var constructor = function (doc: TDocument, isNew?: boolean, isPartial?: boolean) { + let constructor = function (doc: TDocument, isNew?: boolean, isPartial?: boolean) { instanceType.call(this, model, doc, isNew, isPartial); }; diff --git a/lib/caches/MemoryCache.ts b/lib/caches/MemoryCache.ts index de158d5..67ff6f5 100644 --- a/lib/caches/MemoryCache.ts +++ b/lib/caches/MemoryCache.ts @@ -20,7 +20,7 @@ export class MemoryCache implements Cache { } clear(key: string) : Bluebird { - var has = this.cache.hasOwnProperty(key); + let has = this.cache.hasOwnProperty(key); if(has) delete this.cache[key]; return Bluebird.resolve(has); }