From 625397de5afd705f345e5f074f9c1519f1fb6431 Mon Sep 17 00:00:00 2001 From: Benjamin Pannell Date: Thu, 30 Jul 2015 13:03:05 +0200 Subject: [PATCH 01/24] Added support and tests for a toObjectID helper method --- dist/index.js | 2 ++ dist/index.js.map | 2 +- dist/lib/utils/ObjectID.js | 8 ++++++++ dist/lib/utils/ObjectID.js.map | 1 + index.ts | 5 ++++- lib/utils/ObjectID.ts | 6 ++++++ test/Utilities.ts | 19 +++++++++++++++++++ 7 files changed, 41 insertions(+), 2 deletions(-) create mode 100644 dist/lib/utils/ObjectID.js create mode 100644 dist/lib/utils/ObjectID.js.map create mode 100644 lib/utils/ObjectID.ts create mode 100644 test/Utilities.ts diff --git a/dist/index.js b/dist/index.js index 117df64..a8af2c9 100644 --- a/dist/index.js +++ b/dist/index.js @@ -21,5 +21,7 @@ var NoOpCache_1 = require('./lib/caches/NoOpCache'); exports.NoOpCache = NoOpCache_1.default; var IDDirector_1 = require('./lib/cacheControllers/IDDirector'); exports.CacheOnID = IDDirector_1.default; +var ObjectID_1 = require('./lib/utils/ObjectID'); +exports.toObjectID = ObjectID_1.toObjectID; //# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/dist/index.js.map b/dist/index.js.map index ef316a3..7e3cc62 100644 --- a/dist/index.js.map +++ b/dist/index.js.map @@ -1 +1 @@ -{"version":3,"sources":["index.ts"],"names":[],"mappings":";;;AAAA,qBAAiB,YAAY,CAAC,CAAA;AAGtB,YAAI,kBAHkB;AAC9B,sBAAkB,aAAa,CAAC,CAAA;AAElB,aAAK,mBAFa;AAChC,yBAAqB,gBAAgB,CAAC,CAAA;AACjB,gBAAQ,sBADS;AAGtC,iBAAc,kBAAkB,CAAC,EAAA;AAEjC,iBAAc,eAAe,CAAC,EAAA;AAC9B,iBAAc,cAAc,CAAC,EAAA;AAC7B,iBAAc,aAAa,CAAC,EAAA;AAC5B,iBAAc,qBAAqB,CAAC,EAAA;AACpC,iBAAc,oBAAoB,CAAC,EAAA;AACnC,iBAAc,qBAAqB,CAAC,EAAA;AACpC,iBAAc,aAAa,CAAC,EAAA;AAE5B,4BAAwB,0BAA0B,CAAC,CAAA;AAE3C,mBAAW,yBAFgC;AACnD,0BAAsB,wBAAwB,CAAC,CAAA;AAC1B,iBAAS,uBADiB;AAG/C,2BAAuB,mCAAmC,CAAC,CAAA;AACrC,iBAAS,wBAD4B;AAC1B","file":"index.js","sourcesContent":["import Core from './lib/Core';\r\nimport Model from './lib/Model';\r\nimport Instance from './lib/Instance';\r\nexport {Core, Model, Instance};\r\n\r\nexport * from './lib/Decorators';\r\n\r\nexport * from './lib/Plugins';\r\nexport * from './lib/Schema';\r\nexport * from './lib/Cache';\r\nexport * from './lib/CacheDirector';\r\nexport * from './lib/ModelOptions';\r\nexport * from './lib/Configuration';\r\nexport * from './lib/Hooks';\r\n\r\nimport MemoryCache from './lib/caches/MemoryCache';\r\nimport NoOpCache from './lib/caches/NoOpCache';\r\nexport {MemoryCache, NoOpCache};\r\n\r\nimport IDDirector from './lib/cacheControllers/IDDirector';\r\nexport {IDDirector as CacheOnID};"],"sourceRoot":"/source/"} \ No newline at end of file +{"version":3,"sources":["index.ts"],"names":[],"mappings":";;;AAAA,qBAAiB,YAAY,CAAC,CAAA;AAGtB,YAAI,kBAHkB;AAC9B,sBAAkB,aAAa,CAAC,CAAA;AAElB,aAAK,mBAFa;AAChC,yBAAqB,gBAAgB,CAAC,CAAA;AACjB,gBAAQ,sBADS;AAGtC,iBAAc,kBAAkB,CAAC,EAAA;AAEjC,iBAAc,eAAe,CAAC,EAAA;AAC9B,iBAAc,cAAc,CAAC,EAAA;AAC7B,iBAAc,aAAa,CAAC,EAAA;AAC5B,iBAAc,qBAAqB,CAAC,EAAA;AACpC,iBAAc,oBAAoB,CAAC,EAAA;AACnC,iBAAc,qBAAqB,CAAC,EAAA;AACpC,iBAAc,aAAa,CAAC,EAAA;AAE5B,4BAAwB,0BAA0B,CAAC,CAAA;AAE3C,mBAAW,yBAFgC;AACnD,0BAAsB,wBAAwB,CAAC,CAAA;AAC1B,iBAAS,uBADiB;AAG/C,2BAAuB,mCAAmC,CAAC,CAAA;AACrC,iBAAS,wBAD4B;AAG3D,yBAAyB,sBAAsB,CAAC,CAAA;AACxC,kBAAU,yBAD8B;AAC5B","file":"index.js","sourcesContent":["import Core from './lib/Core';\r\nimport Model from './lib/Model';\r\nimport Instance from './lib/Instance';\r\nexport {Core, Model, Instance};\r\n\r\nexport * from './lib/Decorators';\r\n\r\nexport * from './lib/Plugins';\r\nexport * from './lib/Schema';\r\nexport * from './lib/Cache';\r\nexport * from './lib/CacheDirector';\r\nexport * from './lib/ModelOptions';\r\nexport * from './lib/Configuration';\r\nexport * from './lib/Hooks';\r\n\r\nimport MemoryCache from './lib/caches/MemoryCache';\r\nimport NoOpCache from './lib/caches/NoOpCache';\r\nexport {MemoryCache, NoOpCache};\r\n\r\nimport IDDirector from './lib/cacheControllers/IDDirector';\r\nexport {IDDirector as CacheOnID};\r\n\r\nimport {toObjectID} from './lib/utils/ObjectID';\r\nexport {toObjectID};"],"sourceRoot":"/source/"} \ No newline at end of file diff --git a/dist/lib/utils/ObjectID.js b/dist/lib/utils/ObjectID.js new file mode 100644 index 0000000..e12f2ae --- /dev/null +++ b/dist/lib/utils/ObjectID.js @@ -0,0 +1,8 @@ +/// +var MongoDB = require('mongodb'); +function toObjectID(value) { + return MongoDB.ObjectID.createFromHexString(value); +} +exports.toObjectID = toObjectID; + +//# sourceMappingURL=../../lib/utils/ObjectID.js.map \ No newline at end of file diff --git a/dist/lib/utils/ObjectID.js.map b/dist/lib/utils/ObjectID.js.map new file mode 100644 index 0000000..3a29101 --- /dev/null +++ b/dist/lib/utils/ObjectID.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["lib/utils/ObjectID.ts"],"names":["toObjectID"],"mappings":"AAAA,AACA,+CAD+C;AAC/C,IAAO,OAAO,WAAW,SAAS,CAAC,CAAC;AAEpC,oBAA2B,KAAa;IACvCA,MAAMA,CAACA,OAAOA,CAACA,QAAQA,CAACA,mBAAmBA,CAACA,KAAKA,CAACA,CAACA;AACpDA,CAACA;AAFe,kBAAU,aAEzB,CAAA","file":"lib/utils/ObjectID.js","sourcesContent":["/// \r\nimport MongoDB = require('mongodb');\r\n\r\nexport function toObjectID(value: string): MongoDB.ObjectID {\r\n\treturn MongoDB.ObjectID.createFromHexString(value);\r\n}"],"sourceRoot":"/source/"} \ No newline at end of file diff --git a/index.ts b/index.ts index 5e7f8df..c7b3fb6 100644 --- a/index.ts +++ b/index.ts @@ -18,4 +18,7 @@ import NoOpCache from './lib/caches/NoOpCache'; export {MemoryCache, NoOpCache}; import IDDirector from './lib/cacheControllers/IDDirector'; -export {IDDirector as CacheOnID}; \ No newline at end of file +export {IDDirector as CacheOnID}; + +import {toObjectID} from './lib/utils/ObjectID'; +export {toObjectID}; \ No newline at end of file diff --git a/lib/utils/ObjectID.ts b/lib/utils/ObjectID.ts new file mode 100644 index 0000000..73d4ee1 --- /dev/null +++ b/lib/utils/ObjectID.ts @@ -0,0 +1,6 @@ +/// +import MongoDB = require('mongodb'); + +export function toObjectID(value: string): MongoDB.ObjectID { + return MongoDB.ObjectID.createFromHexString(value); +} \ No newline at end of file diff --git a/test/Utilities.ts b/test/Utilities.ts new file mode 100644 index 0000000..f9f1424 --- /dev/null +++ b/test/Utilities.ts @@ -0,0 +1,19 @@ +/// +import * as Iridium from '../index'; +import MongoDB = require('mongodb'); + +describe("Utilities", () => { + describe("toObjectID", () => { + it("should convert hex strings to ObjectIDs", () => { + let oID = Iridium.toObjectID("aaaaaaaaaaaaaaaaaaaaaaaa"); + chai.expect(oID).to.be.instanceOf(MongoDB.ObjectID); + chai.expect(oID.toHexString()).to.eql("aaaaaaaaaaaaaaaaaaaaaaaa"); + }); + + it("should throw an error if your string is not a valid ObjectID", () => { + chai.expect(() => { + Iridium.toObjectID("aaaaaaaaaaaaaaaa"); + }).to.throw; + }); + }); +}) \ No newline at end of file From ab6904eeac7464f6df4b8b6d4c2ae29de1196afd Mon Sep 17 00:00:00 2001 From: Benjamin Pannell Date: Thu, 30 Jul 2015 13:03:20 +0200 Subject: [PATCH 02/24] Version 5.8.0 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index d7382be..e4cabcf 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "iridium", - "version": "5.7.5", + "version": "5.8.0", "author": "Benjamin Pannell ", "description": "A custom lightweight ORM for MongoDB designed for power-users", "license": "MIT", From f5926ce6c35b66e0e653eb0e85333cb4def21b9a Mon Sep 17 00:00:00 2001 From: Benjamin Pannell Date: Thu, 30 Jul 2015 13:03:21 +0200 Subject: [PATCH 03/24] Updated CHANGELOG --- CHANGELOG.md | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2eac3ea..bd5b7f3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,10 +1,15 @@ ## [Working Changes](https://github.com/sierrasoftworks/iridium) +- [ab6904e](https://github.com/sierrasoftworks/iridium/commit/ab6904e) Version 5.8.0 +- [625397d](https://github.com/sierrasoftworks/iridium/commit/625397d) Added support and tests for a toObjectID helper method +- [4ebd33d](https://github.com/sierrasoftworks/iridium/commit/4ebd33d) (origin/master, origin/HEAD) Updated CHANGELOG + +## [v5.7.5](https://github.com/sierrasoftworks/iridium/tree/v5.7.5) - [b5cb543](https://github.com/sierrasoftworks/iridium/commit/b5cb543) Version 5.7.5 - [ff0e292](https://github.com/sierrasoftworks/iridium/commit/ff0e292) Show release branch badges - [fe2e60a](https://github.com/sierrasoftworks/iridium/commit/fe2e60a) Fixed behaviour of Omnom when unsetting properties - [228f7ce](https://github.com/sierrasoftworks/iridium/commit/228f7ce) Added Omnom tests for $unset -- [2e27c23](https://github.com/sierrasoftworks/iridium/commit/2e27c23) (origin/master, origin/HEAD) Added a contribution information file +- [2e27c23](https://github.com/sierrasoftworks/iridium/commit/2e27c23) Added a contribution information file - [e360587](https://github.com/sierrasoftworks/iridium/commit/e360587) Updated CHANGELOG ## [v5.7.4](https://github.com/sierrasoftworks/iridium/tree/v5.7.4) From 445ebb6df24716716dd153ad1a4ecc6ed8055f48 Mon Sep 17 00:00:00 2001 From: Benjamin Pannell Date: Tue, 4 Aug 2015 11:38:42 +0200 Subject: [PATCH 04/24] Added support and tests for the MongoDB aggregate operation --- dist/lib/Aggregate.js | 3 ++ dist/lib/Aggregate.js.map | 1 + dist/lib/AggregationPipeline.js | 3 ++ dist/lib/AggregationPipeline.js.map | 1 + dist/lib/Model.js | 10 +++++ dist/lib/Model.js.map | 2 +- lib/Aggregate.ts | 5 +++ lib/Model.ts | 52 ++++++++++++++---------- test/Aggregate.ts | 63 +++++++++++++++++++++++++++++ 9 files changed, 118 insertions(+), 22 deletions(-) create mode 100644 dist/lib/Aggregate.js create mode 100644 dist/lib/Aggregate.js.map create mode 100644 dist/lib/AggregationPipeline.js create mode 100644 dist/lib/AggregationPipeline.js.map create mode 100644 lib/Aggregate.ts create mode 100644 test/Aggregate.ts diff --git a/dist/lib/Aggregate.js b/dist/lib/Aggregate.js new file mode 100644 index 0000000..1bf79e7 --- /dev/null +++ b/dist/lib/Aggregate.js @@ -0,0 +1,3 @@ +/// + +//# sourceMappingURL=../lib/Aggregate.js.map \ No newline at end of file diff --git a/dist/lib/Aggregate.js.map b/dist/lib/Aggregate.js.map new file mode 100644 index 0000000..043d6c5 --- /dev/null +++ b/dist/lib/Aggregate.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["lib/Aggregate.ts"],"names":[],"mappings":"AAAA,4CAA4C;AAI3C","file":"lib/Aggregate.js","sourcesContent":["/// \r\n\r\nexport interface Stage {\r\n\r\n}"],"sourceRoot":"/source/"} \ No newline at end of file diff --git a/dist/lib/AggregationPipeline.js b/dist/lib/AggregationPipeline.js new file mode 100644 index 0000000..f03e706 --- /dev/null +++ b/dist/lib/AggregationPipeline.js @@ -0,0 +1,3 @@ + + +//# sourceMappingURL=../lib/AggregationPipeline.js.map \ No newline at end of file diff --git a/dist/lib/AggregationPipeline.js.map b/dist/lib/AggregationPipeline.js.map new file mode 100644 index 0000000..313d2b7 --- /dev/null +++ b/dist/lib/AggregationPipeline.js.map @@ -0,0 +1 @@ +{"version":3,"sources":[],"names":[],"mappings":"","file":"lib/AggregationPipeline.js","sourcesContent":[],"sourceRoot":"/source/"} \ No newline at end of file diff --git a/dist/lib/Model.js b/dist/lib/Model.js index 1684517..3f40388 100644 --- a/dist/lib/Model.js +++ b/dist/lib/Model.js @@ -429,6 +429,16 @@ var Model = (function () { return Bluebird.resolve(count); }).nodeify(callback); }; + Model.prototype.aggregate = function (pipeline) { + var _this = this; + return new Bluebird(function (resolve, reject) { + _this.collection.aggregate(pipeline, function (err, results) { + if (err) + return reject(err); + return resolve(results); + }); + }); + }; Model.prototype.ensureIndex = function (specification, options, callback) { var _this = this; if (typeof options == 'function') { diff --git a/dist/lib/Model.js.map b/dist/lib/Model.js.map index e8b54d1..c00e023 100644 --- a/dist/lib/Model.js.map +++ b/dist/lib/Model.js.map @@ -1 +1 @@ -{"version":3,"sources":["lib/Model.ts"],"names":["Model","Model.constructor","Model.loadExternal","Model.loadInternal","Model.onNewModel","Model.helpers","Model.handlers","Model.hooks","Model.schema","Model.core","Model.collection","Model.collectionName","Model.cacheDirector","Model.cache","Model.Instance","Model.transforms","Model.validators","Model.indexes","Model.find","Model.get","Model.findOne","Model.create","Model.insert","Model.update","Model.count","Model.remove","Model.ensureIndex","Model.ensureIndexes","Model.dropIndex","Model.dropIndexes"],"mappings":"AAAA,AACA,4CAD4C;AAC5C,IAAO,OAAO,WAAW,SAAS,CAAC,CAAC;AACpC,IAAO,QAAQ,WAAW,UAAU,CAAC,CAAC;AAEtC,IAAO,CAAC,WAAW,QAAQ,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Model.js","sourcesContent":["/// \r\nimport MongoDB = require('mongodb');\r\nimport Bluebird = require('bluebird');\r\nimport util = require('util');\r\nimport _ = require('lodash');\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 noOpCache from './caches/NoOpCache';\r\nimport memoryCache from './caches/MemoryCache';\r\nimport idCacheController from './cacheControllers/IDDirector';\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\n\r\n/**\r\n * An Iridium Model which represents a structured MongoDB collection\r\n * @class\r\n */\r\nexport default 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 {Iridium} core The Iridium core that this model should use for database access\r\n * @param {ModelInterfaces.InstanceImplementation} instanceType The class which will be instantiated for each document retrieved from the database\r\n * @returns {Model}\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 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'] = {\r\n fromDB: value => value._bsontype == 'ObjectID' ? new MongoDB.ObjectID(value.id).toHexString() : value,\r\n toDB: value => value && typeof value === 'string' ? new MongoDB.ObjectID(value) : value\r\n };\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 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 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 {ModelHelpers}\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 {ModelHandlers}\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 * @returns {Hooks}\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 ISchema dictating the data structure represented by this model\r\n * @public\r\n * @returns {schema}\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 {Iridium}\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 * @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: { [property: string]: { fromDB: (value: any) => any; toDB: (value: any) => any; } };\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 get validators() {\r\n return this._validators;\r\n }\r\n \r\n private _indexes: (Index.Index | Index.IndexSpecification)[];\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 /**\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(callback);\r\n }\r\n}\r\n"],"sourceRoot":"/source/"} \ No newline at end of file +{"version":3,"sources":["lib/Model.ts"],"names":["Model","Model.constructor","Model.loadExternal","Model.loadInternal","Model.onNewModel","Model.helpers","Model.handlers","Model.hooks","Model.schema","Model.core","Model.collection","Model.collectionName","Model.cacheDirector","Model.cache","Model.Instance","Model.transforms","Model.validators","Model.indexes","Model.find","Model.get","Model.findOne","Model.create","Model.insert","Model.update","Model.count","Model.remove","Model.aggregate","Model.ensureIndex","Model.ensureIndexes","Model.dropIndex","Model.dropIndexes"],"mappings":"AAAA,AACA,4CAD4C;AAC5C,IAAO,OAAO,WAAW,SAAS,CAAC,CAAC;AACpC,IAAO,QAAQ,WAAW,UAAU,CAAC,CAAC;AAEtC,IAAO,CAAC,WAAW,QAAQ,CAAC,CAAC;AAE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OA,EAAEA,MAAMA;YACrCA,KAAIA,CAACA,UAAUA,CAACA,cAAcA,CAACA,UAACA,GAAGA,EAAEA,KAAKA;gBACtCA,EAAEA,CAACA,CAACA,GAAGA,CAACA;oBAACA,MAAMA,CAACA,MAAMA,CAACA,GAAGA,CAACA,CAACA;gBAC5BA,MAAMA,CAACA,OAAOA,CAACA,KAAKA,CAACA,CAACA;YAC1BA,CAACA,CAACA,CAACA;QACPA,CAACA,CAACA,CAACA,OAAOA,CAACA,QAAQA,CAACA,CAACA;IACzBA,CAACA;IACL9B,YAACA;AAADA,CA7qBA,AA6qBCA,IAAA;AA7qBD,uBA6qBC,CAAA","file":"lib/Model.js","sourcesContent":["/// \r\nimport MongoDB = require('mongodb');\r\nimport Bluebird = require('bluebird');\r\nimport util = require('util');\r\nimport _ = require('lodash');\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 noOpCache from './caches/NoOpCache';\r\nimport memoryCache from './caches/MemoryCache';\r\nimport idCacheController from './cacheControllers/IDDirector';\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 * as AggregationPipeline from './Aggregate';\r\n\r\n/**\r\n * An Iridium Model which represents a structured MongoDB collection\r\n * @class\r\n */\r\nexport default 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 {Iridium} core The Iridium core that this model should use for database access\r\n * @param {ModelInterfaces.InstanceImplementation} instanceType The class which will be instantiated for each document retrieved from the database\r\n * @returns {Model}\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 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'] = {\r\n fromDB: value => value._bsontype == 'ObjectID' ? new MongoDB.ObjectID(value.id).toHexString() : value,\r\n toDB: value => value && typeof value === 'string' ? new MongoDB.ObjectID(value) : value\r\n };\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 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 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 {ModelHelpers}\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 {ModelHandlers}\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 * @returns {Hooks}\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 ISchema dictating the data structure represented by this model\r\n * @public\r\n * @returns {schema}\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 {Iridium}\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 * @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: { [property: string]: { fromDB: (value: any) => any; toDB: (value: any) => any; } };\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 get validators() {\r\n return this._validators;\r\n }\r\n\r\n private _indexes: (Index.Index | Index.IndexSpecification)[];\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(callback);\r\n }\r\n}\r\n"],"sourceRoot":"/source/"} \ No newline at end of file diff --git a/lib/Aggregate.ts b/lib/Aggregate.ts new file mode 100644 index 0000000..a91bf6a --- /dev/null +++ b/lib/Aggregate.ts @@ -0,0 +1,5 @@ +/// + +export interface Stage { + +} \ No newline at end of file diff --git a/lib/Model.ts b/lib/Model.ts index 1016357..6d01026 100644 --- a/lib/Model.ts +++ b/lib/Model.ts @@ -27,6 +27,7 @@ import ModelHandlers from './ModelHandlers'; import * as ModelInterfaces from './ModelInterfaces'; import ModelSpecificInstance from './ModelSpecificInstance'; import InstanceImplementation from './InstanceInterface'; +import * as AggregationPipeline from './Aggregate'; /** * An Iridium Model which represents a structured MongoDB collection @@ -45,14 +46,14 @@ export default class Model { if (typeof instanceType != 'function') throw new Error("You failed to provide a valid instance constructor for this model"); if (typeof instanceType.collection != 'string' || !instanceType.collection) throw new Error("You failed to provide a valid collection name for this model"); if (!_.isPlainObject(instanceType.schema) || instanceType.schema._id === undefined) throw new Error("You failed to provide a valid schema for this model"); - + this._core = core; - + this.loadExternal(instanceType); this.onNewModel(); this.loadInternal(); } - + private loadExternal(instanceType: InstanceImplementation) { this._collection = instanceType.collection; this._schema = instanceType.schema; @@ -61,9 +62,9 @@ export default class Model { this._transforms = instanceType.transforms || {}; this._validators = instanceType.validators || []; this._indexes = instanceType.indexes || []; - + if(!this._schema._id) this._schema._id = MongoDB.ObjectID; - + if(this._schema._id === MongoDB.ObjectID && !this._transforms['_id']) this._transforms['_id'] = { fromDB: value => value._bsontype == 'ObjectID' ? new MongoDB.ObjectID(value.id).toHexString() : value, @@ -75,13 +76,13 @@ export default class Model { else this._Instance = instanceType.bind(undefined, this); } - + private loadInternal() { this._cache = new ModelCache(this); this._helpers = new ModelHelpers(this); this._handlers = new ModelHandlers(this); } - + private onNewModel() { this._core.plugins.forEach(plugin => plugin.newModel && plugin.newModel(this)); } @@ -103,9 +104,9 @@ export default class Model { get handlers(): ModelHandlers { return this._handlers; } - + private _hooks: Hooks = {}; - + /** * Gets the even hooks subscribed on this model for a number of different state changes * @returns {Hooks} @@ -144,7 +145,7 @@ export default class Model { if (!this.core.connection) throw new Error("Iridium Core not connected to a database."); return this.core.connection.collection(this._collection); } - + /** * Gets the name of the underlying MongoDB collection from which this model's documents are retrieved * @public @@ -189,25 +190,25 @@ export default class Model { get Instance(): ModelInterfaces.ModelSpecificInstanceConstructor { return this._Instance; } - + private _transforms: { [property: string]: { fromDB: (value: any) => any; toDB: (value: any) => any; } }; - + get transforms() { return this._transforms; } - + private _validators: Skmatc.Validator[]; - + get validators() { return this._validators; } - + private _indexes: (Index.Index | Index.IndexSpecification)[]; - + get indexes() { return this._indexes; } - + /** * Retrieves all documents in the collection and wraps them as instances * @param {function(Error, TInstance[])} callback An optional callback which will be triggered when results are available @@ -497,7 +498,7 @@ export default class Model { callback = >options; options = {}; } - + options = options || {}; if (!_.isPlainObject(conditions)) conditions = { @@ -587,12 +588,12 @@ export default 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; - + if (typeof options === 'function') { callback = >options; options = {}; } - + if (typeof conds == 'function') { callback = >conds; options = {}; @@ -601,7 +602,7 @@ export default class Model { conditions = conditions || {}; options = options || {}; - + _.defaults(options, { w: 'majority' }); @@ -625,6 +626,15 @@ export default class Model { }).nodeify(callback); } + aggregate(pipeline: AggregationPipeline.Stage[]): Bluebird { + return new Bluebird((resolve, reject) => { + this.collection.aggregate(pipeline, (err, results) => { + if(err) return reject(err); + return resolve(results); + }); + }); + } + /** * Ensures that the given index is created for the collection * @param {Object} specification The index specification object used by MongoDB diff --git a/test/Aggregate.ts b/test/Aggregate.ts new file mode 100644 index 0000000..889ba4d --- /dev/null +++ b/test/Aggregate.ts @@ -0,0 +1,63 @@ +/// +import * as Iridium from '../index'; +import MongoDB = require('mongodb'); +import Cursor from '../lib/Cursor'; +import Promise = require('bluebird'); +import _ = require('lodash'); + +interface TestDocument { + _id?: string; + group: string; + score: number; +} + +class Test extends Iridium.Instance implements TestDocument { + static collection = 'test'; + static schema: Iridium.Schema = { + _id: MongoDB.ObjectID, + group: String, + score: Number + }; + + _id: string; + group: string; + score: number; +} + +describe("Model", () => { + let core = new Iridium.Core({ database: 'test' }); + + before(() => core.connect()); + + + describe("aggregate()", () => { + let model = new Iridium.Model(core, Test); + + beforeEach(() => { + return core.connect().then(() => model.remove()).then(() => model.insert([ + { group: 'A', score: 10 }, + { group: 'B', score: 11 }, + { group: 'C', score: 12 }, + { group: 'A', score: 13 }, + { group: 'B', score: 14 } + ])); + }); + + it("should correctly pass through the aggregation pipeline", () => { + return chai.expect(model.aggregate([ + { $group: { _id: '$group', score: { $sum: "$score" } } } + ])).to.eventually.exist.and.have.length(3); + }); + + it("should allow you to specify the type of the resulting documents", () => { + return model.aggregate<{ _id: string; score: number; }>([ + { $match: { group: 'A' } }, + { $group: { _id: '$group', score: { $sum: "$score" } } } + ]).then(results => { + chai.expect(results).to.exist.and.have.length(1); + chai.expect(results[0]._id).to.eql('A'); + chai.expect(results[0].score).to.eql(23); + }); + }); + }); +}); \ No newline at end of file From 5f326fdc030418229b70cad67553c564fb9f96e9 Mon Sep 17 00:00:00 2001 From: Benjamin Pannell Date: Tue, 4 Aug 2015 11:38:59 +0200 Subject: [PATCH 05/24] Clean up the references.d.ts file before bumping the version --- build/version.js | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/build/version.js b/build/version.js index 96f24bf..8cbc5c4 100644 --- a/build/version.js +++ b/build/version.js @@ -14,11 +14,11 @@ function getPackageJsonVersion() { gulp.task('version-bump', function () { var args = minimist(process.argv); - + var options = {}; if (semver.valid(args.version)) options.version = args.version; else options.type = args.version; - + return gulp.src(['./package.json']) .pipe(bump(options).on('error', gutil.log)) .pipe(gulp.dest('./')); @@ -45,6 +45,7 @@ gulp.task('version-push-tags', function (cb) { gulp.task('version', function (callback) { runSequence( + 'postpublish', 'version-bump', 'version-commit', 'version-tag', From 431bb0bcda1e109431a3332ffd24bbae86c0669d Mon Sep 17 00:00:00 2001 From: Benjamin Pannell Date: Tue, 4 Aug 2015 11:39:13 +0200 Subject: [PATCH 06/24] Version 5.9.0 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index e4cabcf..e231b12 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "iridium", - "version": "5.8.0", + "version": "5.9.0", "author": "Benjamin Pannell ", "description": "A custom lightweight ORM for MongoDB designed for power-users", "license": "MIT", From 465cc858bec334a8fb3d457ff7cd880212831723 Mon Sep 17 00:00:00 2001 From: Benjamin Pannell Date: Tue, 4 Aug 2015 11:39:13 +0200 Subject: [PATCH 07/24] Updated CHANGELOG --- CHANGELOG.md | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bd5b7f3..fd64646 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,8 +1,14 @@ ## [Working Changes](https://github.com/sierrasoftworks/iridium) +- [431bb0b](https://github.com/sierrasoftworks/iridium/commit/431bb0b) Version 5.9.0 +- [5f326fd](https://github.com/sierrasoftworks/iridium/commit/5f326fd) Clean up the references.d.ts file before bumping the version +- [445ebb6](https://github.com/sierrasoftworks/iridium/commit/445ebb6) Added support and tests for the MongoDB aggregate operation +- [f5926ce](https://github.com/sierrasoftworks/iridium/commit/f5926ce) (origin/master, origin/HEAD) Updated CHANGELOG + +## [v5.8.0](https://github.com/sierrasoftworks/iridium/tree/v5.8.0) - [ab6904e](https://github.com/sierrasoftworks/iridium/commit/ab6904e) Version 5.8.0 - [625397d](https://github.com/sierrasoftworks/iridium/commit/625397d) Added support and tests for a toObjectID helper method -- [4ebd33d](https://github.com/sierrasoftworks/iridium/commit/4ebd33d) (origin/master, origin/HEAD) Updated CHANGELOG +- [4ebd33d](https://github.com/sierrasoftworks/iridium/commit/4ebd33d) Updated CHANGELOG ## [v5.7.5](https://github.com/sierrasoftworks/iridium/tree/v5.7.5) - [b5cb543](https://github.com/sierrasoftworks/iridium/commit/b5cb543) Version 5.7.5 From 179516cc9241e9ec1780b11b86119006c84508a3 Mon Sep 17 00:00:00 2001 From: Benjamin Pannell Date: Tue, 18 Aug 2015 07:59:50 +0200 Subject: [PATCH 08/24] Added additional error information for instance updates Should assist in debugging application level errors for which MongoDB returns obscure error codes which lack context... --- dist/lib/Instance.js | 9 ++++++++- dist/lib/Instance.js.map | 2 +- lib/Instance.ts | 29 +++++++++++++++++++---------- 3 files changed, 28 insertions(+), 12 deletions(-) diff --git a/dist/lib/Instance.js b/dist/lib/Instance.js index e05f48e..f3d5dab 100644 --- a/dist/lib/Instance.js +++ b/dist/lib/Instance.js @@ -91,12 +91,19 @@ var Instance = (function () { else { return new Bluebird(function (resolve, reject) { _this._model.collection.updateOne(conditions, changes, { w: 'majority' }, function (err, changed) { - if (err) + if (err) { + err['conditions'] = conditions; + err['changes'] = changes; return reject(err); + } return resolve(changed); }); }); } + }, function (err) { + err['original'] = _this._original; + err['modified'] = _this._modified; + return Bluebird.reject(err); }).then(function (changed) { conditions = { _id: _this._modified._id }; if (!changed) diff --git a/dist/lib/Instance.js.map b/dist/lib/Instance.js.map index 564e3c4..fac7993 100644 --- a/dist/lib/Instance.js.map +++ b/dist/lib/Instance.js.map @@ -1 +1 @@ -{"version":3,"sources":["lib/Instance.ts"],"names":["Instance","Instance.constructor","Instance.document","Instance.save","Instance.update","Instance.refresh","Instance.delete","Instance.remove","Instance.first","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BAAQA,GAARA;QACIW,MAAMA,CAACA,IAAIA,CAACA,SAASA,CAACA,IAAIA,CAACA,QAAQA,EAAEA,IAAIA,EAAEA,CAACA,CAACA,CAACA;IAClDA,CAACA;IA1QMX,eAAMA,GAAWA;QACpBA,GAAGA,EAAEA,KAAKA;KACbA,CAACA;IAEKA,mBAAUA,GAAuBA;QACpCA,MAAMA,CAACA,MAAMA,CAACA,UAAAA,MAAMA,IAAIA,OAAAA,MAAMA,KAAKA,OAAOA,CAACA,QAAQA,EAA3BA,CAA2BA,EAAEA,UAASA,MAAMA,EAAEA,IAAIA;YACtE,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,IAAI,IAAI,IAAI,YAAY,OAAO,CAAC,QAAQ,IAAI,CAAC,IAAI,CAAC,SAAS,KAAK,UAAU,IAAI,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC;QAChH,CAAC,EAAEA,EAAEA,IAAIA,EAAEA,qBAAqBA,EAAEA,CAACA;KACtCA,CAACA;IAEKA,mBAAUA,GAAwFA,EAExGA,CAACA;IAGKA,gBAAOA,GAA+CA,EAAEA,CAACA;IA4PpEA,eAACA;AAADA,CA3TA,AA2TCA,IAAA;AA3TD,0BA2TC,CAAA","file":"lib/Instance.js","sourcesContent":["/// \r\nimport 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\n\r\nimport _ = require('lodash');\r\nimport MongoDB = require('mongodb');\r\nimport Bluebird = require('bluebird');\r\nimport skmatc = require('skmatc');\r\n\r\nexport default class Instance {\r\n /**\r\n * Creates a new instance which represents the given document as a type of model\r\n * @param {model.Model} model The model that the document represents\r\n * @param {TSchema} document The document which should be wrapped by this instance\r\n * @param {Boolean} isNew Whether the document is new (doesn't exist in the database) or not\r\n * @param {Boolean} isPartial Whether the document has only a subset of its fields populated\r\n * @description\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\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 = _.cloneDeep(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 static onCreating: (document: { _id?: any }) => void;\r\n static onRetrieved: (document: { _id?: any }) => void;\r\n static onReady: (instance: Instance<{ _id?: any }, Instance<{ _id?: any }, any>>) => void;\r\n static onSaving: (instance: Instance<{ _id?: any }, Instance<{ _id?: any }, any>>, changes: any) => void;\r\n \r\n static collection: string;\r\n \r\n static schema: Schema = {\r\n _id: false\r\n };\r\n \r\n static validators: Skmatc.Validator[] = [\r\n skmatc.create(schema => schema === MongoDB.ObjectID, function(schema, data) {\r\n return this.assert(!data || data instanceof MongoDB.ObjectID || (data._bsontype === 'ObjectID' && data.id));\r\n }, { name: 'ObjectID validation' })\r\n ];\r\n \r\n static transforms: { [property: string]: { fromDB: (value: any) => any; toDB: (value: any) => any; } } = {\r\n \r\n };\r\n \r\n static cache: CacheDirector;\r\n static indexes: (Index.Index | Index.IndexSpecification)[] = [];\r\n static identifier: {\r\n apply(fromSource: any): any;\r\n reverse(toSource: any): any;\r\n };\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 = _.cloneDeep(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 = _.cloneDeep(this._original);\r\n var modified = _.cloneDeep(this._modified);\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) return reject(err);\r\n return resolve(changed);\r\n });\r\n });\r\n }\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 = _.cloneDeep(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 = _.cloneDeep(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 = _.cloneDeep(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 = _.cloneDeep(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 {any[]} collection The collection from which to retrieve the element\r\n * @param {function(any, Number): Boolean} predicate The function which determines whether to select an element\r\n * @returns {any}\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 {Object} collection The collection from which to retrieve the element\r\n * @param {function(any, String): Boolean} predicate The function which determines whether to select an element\r\n * @returns {any}\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 {any[]} collection The collection from which elements will be plucked\r\n * @param {function(any, Number): Boolean} predicate The function which determines the elements to be plucked\r\n * @returns {any[]}\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 {Object} collection The collection from which elements will be plucked\r\n * @param {function(any, String): Boolean} predicate The function which determines the elements to be plucked\r\n * @returns {Object}\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":["Instance","Instance.constructor","Instance.document","Instance.save","Instance.update","Instance.refresh","Instance.delete","Instance.remove","Instance.first","Instance.select","Instance.toJSON","Instance.toString"],"mappings":"AAUA,IAAO,CAAC,WAAW,QAAQ,CAAC,CAAC;AAC7B,IAAO,OAAO,WAAW,SAAS,CAAC,CAAC;AACpC,IAAO,QAAQ,WAAW,UAAU,CAAC,CAAC;AACtC,IAAO,MAAM,WAAW,QAAQ,CAAC,CAAC;AAElC;IACIA;;;;;;;;;;;OAWGA;IACHA,kBAAYA,KAAkCA,EAAEA,QAAmBA,EAAEA,KAAqBA,EAAEA,SAA0BA;QAb1HC,iBAoUCA;QAvTwEA,qBAAqBA,GAArBA,YAAqBA;QAAEA,yBAA0BA,GAA1BA,iBAA0BA;QAClHA,IAAIA,CAACA,MAAMA,GAAGA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EA,OAAgBA;wBAClGA,EAAEA,CAAAA,CAACA,GAAGA,CAACA,CAACA,CAACA;4BACLA,GAAGA,CAACA,YAAYA,CAACA,GAAGA,UAAUA,CAACA;4BAC/BA,GAAGA,CAACA,SAASA,CAACA,GAAGA,OAAOA,CAACA;4BACzBA,MAAMA,CAACA,MAAMA,CAACA,GAAGA,CAACA,CAACA;wBACvBA,CAACA;wBAEDA,MAAMA,CAACA,OAAOA,CAACA,OAAOA,CAACA,CAACA;oBAC5BA,CAACA,CAACA,CAACA;gBACPA,CAACA,CAACA,CAACA;YACPA,CAACA;QACLA,CAACA,EAAEA,UAAAA,GAAGA;YACFA,GAAGA,CAACA,UAAUA,CAACA,GAAGA,KAAIA,CAACA,SAASA,CAACA;YACjCA,GAAGA,CAACA,UAAUA,CAACA,GAAGA,KAAIA,CAACA,SAASA,CAACA;YACjCA,MAAMA,CAACA,QAAQA,CAACA,MAAMA,CAACA,GAAGA,CAACA,CAACA;QAChCA,CAACA,CAACA,CAACA,IAAIA,CAACA,UAACA,OAAgBA;YACrBA,UAAUA,GAAGA,EAAEA,GAAGA,EAAEA,KAAIA,CAACA,SAASA,CAACA,GAAGA,EAAEA,CAACA;YACzCA,EAAEA,CAACA,CAACA,CAACA,OAAOA,CAACA;gBAACA,MAAMA,CAACA,KAAIA,CAACA,SAASA,CAACA;YAEpCA,MAAMA,CAACA,IAAIA,QAAQA,CAAYA,UAACA,OAAOA,EAAEA,MAAMA;gBAC3CA,KAAIA,CAACA,MAAMA,CAACA,UAAUA,CAACA,OAAOA,CAACA,UAAUA,EAAEA,UAACA,GAAUA,EAAEA,MAAMA;oBAC1DA,EAAEA,CAACA,CAACA,GAAGA,CAACA;wBAACA,MAAMA,CAACA,MAAMA,CAACA,GAAGA,CAACA,CAACA;oBAC5BA,MAAMA,CAACA,OAAOA,CAACA,MAAMA,CAACA,CAACA;gBAC3BA,CAACA,CAACA,CAACA;YACPA,CAACA,CAACA,CAACA;QACPA,CAACA,CAACA,CAACA,IA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A,CAACA,QAAQA,EAAEA,IAAIA,EAAEA,CAACA,CAACA,CAACA;IAClDA,CAACA;IAnRMX,eAAMA,GAAWA;QACpBA,GAAGA,EAAEA,KAAKA;KACbA,CAACA;IAEKA,mBAAUA,GAAuBA;QACpCA,MAAMA,CAACA,MAAMA,CAACA,UAAAA,MAAMA,IAAIA,OAAAA,MAAMA,KAAKA,OAAOA,CAACA,QAAQA,EAA3BA,CAA2BA,EAAEA,UAASA,MAAMA,EAAEA,IAAIA;YACtE,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,IAAI,IAAI,IAAI,YAAY,OAAO,CAAC,QAAQ,IAAI,CAAC,IAAI,CAAC,SAAS,KAAK,UAAU,IAAI,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC;QAChH,CAAC,EAAEA,EAAEA,IAAIA,EAAEA,qBAAqBA,EAAEA,CAACA;KACtCA,CAACA;IAEKA,mBAAUA,GAAwFA,EAExGA,CAACA;IAGKA,gBAAOA,GAA+CA,EAAEA,CAACA;IAqQpEA,eAACA;AAADA,CApUA,AAoUCA,IAAA;AApUD,0BAoUC,CAAA","file":"lib/Instance.js","sourcesContent":["/// \r\nimport 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\n\r\nimport _ = require('lodash');\r\nimport MongoDB = require('mongodb');\r\nimport Bluebird = require('bluebird');\r\nimport skmatc = require('skmatc');\r\n\r\nexport default class Instance {\r\n /**\r\n * Creates a new instance which represents the given document as a type of model\r\n * @param {model.Model} model The model that the document represents\r\n * @param {TSchema} document The document which should be wrapped by this instance\r\n * @param {Boolean} isNew Whether the document is new (doesn't exist in the database) or not\r\n * @param {Boolean} isPartial Whether the document has only a subset of its fields populated\r\n * @description\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\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 = _.cloneDeep(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 static onCreating: (document: { _id?: any }) => void;\r\n static onRetrieved: (document: { _id?: any }) => void;\r\n static onReady: (instance: Instance<{ _id?: any }, Instance<{ _id?: any }, any>>) => void;\r\n static onSaving: (instance: Instance<{ _id?: any }, Instance<{ _id?: any }, any>>, changes: any) => void;\r\n\r\n static collection: string;\r\n\r\n static schema: Schema = {\r\n _id: false\r\n };\r\n\r\n static validators: Skmatc.Validator[] = [\r\n skmatc.create(schema => schema === MongoDB.ObjectID, function(schema, data) {\r\n return this.assert(!data || data instanceof MongoDB.ObjectID || (data._bsontype === 'ObjectID' && data.id));\r\n }, { name: 'ObjectID validation' })\r\n ];\r\n\r\n static transforms: { [property: string]: { fromDB: (value: any) => any; toDB: (value: any) => any; } } = {\r\n\r\n };\r\n\r\n static cache: CacheDirector;\r\n static indexes: (Index.Index | Index.IndexSpecification)[] = [];\r\n static identifier: {\r\n apply(fromSource: any): any;\r\n reverse(toSource: any): any;\r\n };\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 = _.cloneDeep(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 = _.cloneDeep(this._original);\r\n var modified = _.cloneDeep(this._modified);\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 }, 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 = _.cloneDeep(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 = _.cloneDeep(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 = _.cloneDeep(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 = _.cloneDeep(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 {any[]} collection The collection from which to retrieve the element\r\n * @param {function(any, Number): Boolean} predicate The function which determines whether to select an element\r\n * @returns {any}\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 {Object} collection The collection from which to retrieve the element\r\n * @param {function(any, String): Boolean} predicate The function which determines whether to select an element\r\n * @returns {any}\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 {any[]} collection The collection from which elements will be plucked\r\n * @param {function(any, Number): Boolean} predicate The function which determines the elements to be plucked\r\n * @returns {any[]}\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 {Object} collection The collection from which elements will be plucked\r\n * @param {function(any, String): Boolean} predicate The function which determines the elements to be plucked\r\n * @returns {Object}\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 diff --git a/lib/Instance.ts b/lib/Instance.ts index e1b4daa..e65c6d1 100644 --- a/lib/Instance.ts +++ b/lib/Instance.ts @@ -58,30 +58,30 @@ export default class Instance { static onRetrieved: (document: { _id?: any }) => void; static onReady: (instance: Instance<{ _id?: any }, Instance<{ _id?: any }, any>>) => void; static onSaving: (instance: Instance<{ _id?: any }, Instance<{ _id?: any }, any>>, changes: any) => void; - + static collection: string; - + static schema: Schema = { _id: false }; - + static validators: Skmatc.Validator[] = [ skmatc.create(schema => schema === MongoDB.ObjectID, function(schema, data) { return this.assert(!data || data instanceof MongoDB.ObjectID || (data._bsontype === 'ObjectID' && data.id)); }, { name: 'ObjectID validation' }) ]; - + static transforms: { [property: string]: { fromDB: (value: any) => any; toDB: (value: any) => any; } } = { - + }; - + static cache: CacheDirector; static indexes: (Index.Index | Index.IndexSpecification)[] = []; static identifier: { apply(fromSource: any): any; reverse(toSource: any): any; }; - + /** * Saves any changes to this instance, using the built in diff algorithm to write the update query. * @param {function(Error, IInstance)} callback A callback which is triggered when the save operation completes @@ -119,7 +119,7 @@ export default class Instance { return Bluebird.resolve().then(() => { conditions = _.cloneDeep(conditions); _.merge(conditions, { _id: this._modified._id }); - + if (!changes) { var validation = this._model.helpers.validate(this._modified); if (validation.failed) return Bluebird.reject(validation.error).bind(this).nodeify(callback); @@ -149,11 +149,20 @@ export default class Instance { } else { return new Bluebird((resolve: (changed: boolean) => void, reject) => { this._model.collection.updateOne(conditions, changes, { w: 'majority' }, (err: Error, changed: boolean) => { - if (err) return reject(err); + if(err) { + err['conditions'] = conditions; + err['changes'] = changes; + return reject(err); + } + return resolve(changed); }); }); } + }, err => { + err['original'] = this._original; + err['modified'] = this._modified; + return Bluebird.reject(err); }).then((changed: boolean) => { conditions = { _id: this._modified._id }; if (!changed) return this._modified; @@ -170,7 +179,7 @@ export default class Instance { this._original = _.cloneDeep(this._modified); return Bluebird.resolve(this); } - + return this._model.handlers.documentReceived(conditions, latest, (value) => { this._isPartial = false; this._isNew = false; From 1e8bb041705710f2f9b1f91260fd4d758ac91ce1 Mon Sep 17 00:00:00 2001 From: Benjamin Pannell Date: Tue, 18 Aug 2015 08:00:02 +0200 Subject: [PATCH 09/24] Added an extra Onmom test --- test/Omnom.ts | 67 ++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 66 insertions(+), 1 deletion(-) diff --git a/test/Omnom.ts b/test/Omnom.ts index a8c4994..7995ce8 100644 --- a/test/Omnom.ts +++ b/test/Omnom.ts @@ -79,6 +79,71 @@ describe("Omnom",() => { chai.expect(Omnom.diff(oldObject, newObject)).to.exist.and.be.eql(expectedDiff); }); + it('should correctly diff deep objects', function () { + let oldObject = { + a: { + b: { + c: { + m: { + x: 1, + y: 2, + z: 'test' + } + }, + d: { + m: { + x: 1, + y: 2, + z: 'test' + } + }, + e: { + m: { + x: 1, + y: 2, + z: 'test' + } + } + } + } + }; + + let newObject = { + a: { + b: { + c: { + n: { + x: 1, + y: 2, + z: 'test' + } + }, + d: { + m: { + w: 1, + y: 2, + z: 'test' + } + }, + e: { + m: { + x: 1, + y: 4, + z: 'test' + } + } + } + } + }; + + let expectedDiff = { + $set: { 'a.b.c.n': { x: 1, y: 2, z: 'test' }, 'a.b.d.m.w': 1, 'a.b.e.m.y': 4 }, + $unset: { 'a.b.c.m': 1, 'a.b.d.m.x': 1 } + }; + + chai.expect(Omnom.diff(oldObject, newObject)).to.exist.and.be.eql(expectedDiff); + }); + it('should correctly diff ObjectIDs', function () { let oldID = new MongoDB.ObjectID(); let newID = MongoDB.ObjectID.createFromHexString(oldID.toHexString()); @@ -128,7 +193,7 @@ describe("Omnom",() => { a: 10, b: null }; - + let expectedDiff = { $set: { b: null } }; From 4efcdf104239b5c854c60513fe534e60d5d81912 Mon Sep 17 00:00:00 2001 From: Benjamin Pannell Date: Tue, 18 Aug 2015 08:00:53 +0200 Subject: [PATCH 10/24] Version 5.9.1 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index e231b12..5ae54fc 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "iridium", - "version": "5.9.0", + "version": "5.9.1", "author": "Benjamin Pannell ", "description": "A custom lightweight ORM for MongoDB designed for power-users", "license": "MIT", From 5a2dc37b912187c41a7bed75b6d32020c13a5ec7 Mon Sep 17 00:00:00 2001 From: Benjamin Pannell Date: Tue, 18 Aug 2015 08:00:53 +0200 Subject: [PATCH 11/24] Updated CHANGELOG --- CHANGELOG.md | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index fd64646..5d8ca67 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,9 +1,15 @@ ## [Working Changes](https://github.com/sierrasoftworks/iridium) +- [4efcdf1](https://github.com/sierrasoftworks/iridium/commit/4efcdf1) Version 5.9.1 +- [1e8bb04](https://github.com/sierrasoftworks/iridium/commit/1e8bb04) Added an extra Onmom test +- [179516c](https://github.com/sierrasoftworks/iridium/commit/179516c) Added additional error information for instance updates +- [465cc85](https://github.com/sierrasoftworks/iridium/commit/465cc85) (origin/master, origin/HEAD) Updated CHANGELOG + +## [v5.9.0](https://github.com/sierrasoftworks/iridium/tree/v5.9.0) - [431bb0b](https://github.com/sierrasoftworks/iridium/commit/431bb0b) Version 5.9.0 - [5f326fd](https://github.com/sierrasoftworks/iridium/commit/5f326fd) Clean up the references.d.ts file before bumping the version - [445ebb6](https://github.com/sierrasoftworks/iridium/commit/445ebb6) Added support and tests for the MongoDB aggregate operation -- [f5926ce](https://github.com/sierrasoftworks/iridium/commit/f5926ce) (origin/master, origin/HEAD) Updated CHANGELOG +- [f5926ce](https://github.com/sierrasoftworks/iridium/commit/f5926ce) Updated CHANGELOG ## [v5.8.0](https://github.com/sierrasoftworks/iridium/tree/v5.8.0) - [ab6904e](https://github.com/sierrasoftworks/iridium/commit/ab6904e) Version 5.8.0 From d11c8f30a496182e0cc53a5b388b173f79595754 Mon Sep 17 00:00:00 2001 From: Benjamin Pannell Date: Tue, 18 Aug 2015 08:13:44 +0200 Subject: [PATCH 12/24] Switch to Travis-CI container infrastucture This is just a test and may be reverted if the infrastructure doesn't prove to be stable or usable (since we test with MongoDB 3.x) --- .travis.yml | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/.travis.yml b/.travis.yml index 55b5b04..d59c5a3 100644 --- a/.travis.yml +++ b/.travis.yml @@ -2,6 +2,8 @@ language: node_js node_js: - "0.10" +sudo: false + services: - mongodb @@ -12,12 +14,14 @@ addons: code_climate: repo_token: 9c90177b42d39905ca635b1f6226580dab5799f87f172b66bab4e8df77b67a13 -before_install: - - sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10 - - echo 'deb http://repo.mongodb.org/apt/ubuntu precise/mongodb-org/3.0 multiverse' | sudo tee /etc/apt/sources.list.d/mongodb-org-3.0.list - - echo 'deb http://repo.mongodb.org/apt/ubuntu precise/mongodb-org/3.1 multiverse' | sudo tee /etc/apt/sources.list.d/mongodb-org-3.1.list - - sudo apt-get update - - sudo apt-get install -y mongodb-org mongodb-org-server mongodb-org-shell mongodb-org-tools + apt: + sources: + - mongodb-upstart + packages: + - mongodb-org + - mongodb-org-server + - mongodb-org-shell + - mongodb-org-tools before_script: - "until nc -z localhost 27017; do echo Waiting for MongoDB; sleep 1; done" From cefc0f42bf1efd7941429f1369c10093ec37f7ec Mon Sep 17 00:00:00 2001 From: Benjamin Pannell Date: Tue, 18 Aug 2015 08:20:29 +0200 Subject: [PATCH 13/24] Updated travis config to use MongoDB precise (3.x) Still waiting on travis-ci/apt-source-whitelist#13 before we can switch over to the container infrastructure --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index d59c5a3..f6416e3 100644 --- a/.travis.yml +++ b/.travis.yml @@ -16,7 +16,7 @@ addons: apt: sources: - - mongodb-upstart + - mongodb-precise packages: - mongodb-org - mongodb-org-server From 5261ea0de0df33ffa93203fedea6a2961bb20f62 Mon Sep 17 00:00:00 2001 From: Benjamin Pannell Date: Tue, 18 Aug 2015 16:25:08 +0200 Subject: [PATCH 14/24] Revert "Updated travis config to use MongoDB precise (3.x)" This reverts commit cefc0f42bf1efd7941429f1369c10093ec37f7ec. --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index f6416e3..d59c5a3 100644 --- a/.travis.yml +++ b/.travis.yml @@ -16,7 +16,7 @@ addons: apt: sources: - - mongodb-precise + - mongodb-upstart packages: - mongodb-org - mongodb-org-server From f6561749dab424b2fe60fa90f7bcecda4ae717c5 Mon Sep 17 00:00:00 2001 From: Benjamin Pannell Date: Tue, 18 Aug 2015 16:25:12 +0200 Subject: [PATCH 15/24] Revert "Switch to Travis-CI container infrastucture" This reverts commit d11c8f30a496182e0cc53a5b388b173f79595754. --- .travis.yml | 16 ++++++---------- 1 file changed, 6 insertions(+), 10 deletions(-) diff --git a/.travis.yml b/.travis.yml index d59c5a3..55b5b04 100644 --- a/.travis.yml +++ b/.travis.yml @@ -2,8 +2,6 @@ language: node_js node_js: - "0.10" -sudo: false - services: - mongodb @@ -14,14 +12,12 @@ addons: code_climate: repo_token: 9c90177b42d39905ca635b1f6226580dab5799f87f172b66bab4e8df77b67a13 - apt: - sources: - - mongodb-upstart - packages: - - mongodb-org - - mongodb-org-server - - mongodb-org-shell - - mongodb-org-tools +before_install: + - sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10 + - echo 'deb http://repo.mongodb.org/apt/ubuntu precise/mongodb-org/3.0 multiverse' | sudo tee /etc/apt/sources.list.d/mongodb-org-3.0.list + - echo 'deb http://repo.mongodb.org/apt/ubuntu precise/mongodb-org/3.1 multiverse' | sudo tee /etc/apt/sources.list.d/mongodb-org-3.1.list + - sudo apt-get update + - sudo apt-get install -y mongodb-org mongodb-org-server mongodb-org-shell mongodb-org-tools before_script: - "until nc -z localhost 27017; do echo Waiting for MongoDB; sleep 1; done" From b9c13fbcc8f521cf094f469b7f86be5928e4037e Mon Sep 17 00:00:00 2001 From: Benjamin Pannell Date: Tue, 18 Aug 2015 16:27:13 +0200 Subject: [PATCH 16/24] Updated changelog generation --- build/changelog.js | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/build/changelog.js b/build/changelog.js index 58d9769..b29b41b 100644 --- a/build/changelog.js +++ b/build/changelog.js @@ -3,9 +3,9 @@ var gulp = require('gulp'), git = require('gulp-git'), replace = require('gulp-replace'), path = require('path'); - + var repo = require('../package.json').repository.url; - + gulp.task('changelog', function(done) { git.exec({ args: 'log --oneline --decorate' }, function(err, stdout) { if(err) return done(err); @@ -13,16 +13,16 @@ gulp.task('changelog', function(done) { .pipe(replace(/.|\n/g, '')) .pipe(replace(/$/, stdout)) .pipe(replace(/#(\d+)/, '[#$1](' + repo + '/issues/$1)')) - .pipe(replace(/([a-f0-9]{7}) \(HEAD[^)]*\) (.+)/g, function(_, sha, comment) { - return '\n## [Working Changes](' + repo + ')' + - '\n- [' + sha + '](' + repo + '/commit/' + sha + ') ' + comment; - })) - .pipe(replace(/([a-f0-9]{7}) \(tag: ([^\s),]*)[^)]*\) (.+)/g, function(_, sha, tag, comment) { + .pipe(replace(/([a-f0-9]{7}) \((?:HEAD, )?tag: ([^\s),]*)[^)]*\) (.+)/g, function(_, sha, tag, comment) { var niceTag = tag; if(tag.indexOf('v') !== 0) niceTag = 'v' + tag; return '\n## [' + niceTag + '](' + repo + '/tree/' + tag + ')' + '\n- [' + sha + '](' + repo + '/commit/' + sha + ') ' + comment; })) + .pipe(replace(/([a-f0-9]{7}) \(HEAD[^)]*\) (.+)/g, function(_, sha, comment) { + return '\n## [Working Changes](' + repo + ')' + + '\n- [' + sha + '](' + repo + '/commit/' + sha + ') ' + comment; + })) .pipe(replace(/([a-f0-9]{7}) (.+)/g, '- [$1](' + repo + '/commit/$1) $2')) .pipe(gulp.dest('.'))); }); From b2cb440df264878165e052d6fed618a111122aa8 Mon Sep 17 00:00:00 2001 From: Benjamin Pannell Date: Tue, 18 Aug 2015 16:27:25 +0200 Subject: [PATCH 17/24] Fix for a strange set of behaviour with the last release --- lib/Instance.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/Instance.ts b/lib/Instance.ts index e65c6d1..f5e5107 100644 --- a/lib/Instance.ts +++ b/lib/Instance.ts @@ -159,7 +159,7 @@ export default class Instance { }); }); } - }, err => { + }).catch(err => { err['original'] = this._original; err['modified'] = this._modified; return Bluebird.reject(err); From 2438155e56e113d29498ca9ae2ed207e7f761de5 Mon Sep 17 00:00:00 2001 From: Benjamin Pannell Date: Tue, 18 Aug 2015 16:27:43 +0200 Subject: [PATCH 18/24] Version 5.9.2 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 5ae54fc..cf7bf1d 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "iridium", - "version": "5.9.1", + "version": "5.9.2", "author": "Benjamin Pannell ", "description": "A custom lightweight ORM for MongoDB designed for power-users", "license": "MIT", From 06971179cfe953897ab169a3f7a8f13e666a5bbb Mon Sep 17 00:00:00 2001 From: Benjamin Pannell Date: Tue, 18 Aug 2015 16:27:44 +0200 Subject: [PATCH 19/24] Updated CHANGELOG --- CHANGELOG.md | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5d8ca67..cb57299 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,9 +1,19 @@ -## [Working Changes](https://github.com/sierrasoftworks/iridium) +## [v5.9.2](https://github.com/sierrasoftworks/iridium/tree/v5.9.2) +- [2438155](https://github.com/sierrasoftworks/iridium/commit/2438155) Version 5.9.2 +- [b2cb440](https://github.com/sierrasoftworks/iridium/commit/b2cb440) Fix for a strange set of behaviour with the last release +- [b9c13fb](https://github.com/sierrasoftworks/iridium/commit/b9c13fb) Updated changelog generation +- [f656174](https://github.com/sierrasoftworks/iridium/commit/f656174) Revert "Switch to Travis-CI container infrastucture" +- [5261ea0](https://github.com/sierrasoftworks/iridium/commit/5261ea0) Revert "Updated travis config to use MongoDB precise (3.x)" +- [cefc0f4](https://github.com/sierrasoftworks/iridium/commit/cefc0f4) (origin/master, origin/HEAD, infrastructure/travisci-containers) Updated travis config to use MongoDB precise (3.x) +- [d11c8f3](https://github.com/sierrasoftworks/iridium/commit/d11c8f3) Switch to Travis-CI container infrastucture +- [5a2dc37](https://github.com/sierrasoftworks/iridium/commit/5a2dc37) Updated CHANGELOG + +## [v5.9.1](https://github.com/sierrasoftworks/iridium/tree/v5.9.1) - [4efcdf1](https://github.com/sierrasoftworks/iridium/commit/4efcdf1) Version 5.9.1 - [1e8bb04](https://github.com/sierrasoftworks/iridium/commit/1e8bb04) Added an extra Onmom test - [179516c](https://github.com/sierrasoftworks/iridium/commit/179516c) Added additional error information for instance updates -- [465cc85](https://github.com/sierrasoftworks/iridium/commit/465cc85) (origin/master, origin/HEAD) Updated CHANGELOG +- [465cc85](https://github.com/sierrasoftworks/iridium/commit/465cc85) Updated CHANGELOG ## [v5.9.0](https://github.com/sierrasoftworks/iridium/tree/v5.9.0) - [431bb0b](https://github.com/sierrasoftworks/iridium/commit/431bb0b) Version 5.9.0 From f7f9db17b08529234ed5e02188c1273d96f527ad Mon Sep 17 00:00:00 2001 From: Benjamin Pannell Date: Mon, 24 Aug 2015 07:45:41 +0200 Subject: [PATCH 20/24] Make core.connect async-safe (Fixes #15) Only a single MongoDB connection will be opened regardless of how many times connect is called, and regardless of the delay between calling connect and it actually resolving. --- dist/lib/Core.js | 8 +++++++- dist/lib/Core.js.map | 2 +- lib/Core.ts | 13 ++++++++++--- 3 files changed, 18 insertions(+), 5 deletions(-) diff --git a/dist/lib/Core.js b/dist/lib/Core.js index f39bfbb..b33ece0 100644 --- a/dist/lib/Core.js +++ b/dist/lib/Core.js @@ -133,10 +133,16 @@ var Core = (function () { return Bluebird.bind(this).then(function () { if (self._connection) return self._connection; - return mongoConnectAsyc(self.url); + if (self._connectPromise) + return this._connectPromise; + return self._connectPromise = mongoConnectAsyc(self.url); }).then(function (db) { self._connection = db; + self._connectPromise = null; return self; + }, function (err) { + self._connectPromise = null; + return Bluebird.reject(err); }).nodeify(callback); }; /** diff --git a/dist/lib/Core.js.map b/dist/lib/Core.js.map index 5ed979e..748658e 100644 --- a/dist/lib/Core.js.map +++ b/dist/lib/Core.js.map @@ -1 +1 @@ -{"version":3,"sources":["lib/Core.ts"],"names":["Core","Core.constructor","Core.plugins","Core.settings","Core.connection","Core.url","Core.cache","Core.register","Core.connect","Core.close","Core.express"],"mappings":"AAAA,AACA,4CAD4C;AAC5C,IAAO,QAAQ,WAAW,UAAU,CAAC,CAAC;AACtC,IAAO,OAAO,WAAW,SAAS,CAAC,CAAC;AACpC,IAAO,CAAC,WAAW,QAAQ,CAAC,CAAC;AAW7B,wBAAqC,sBAAsB,CAAC,CAAA;AAG5D,0BAAsB,oBAAoB,CAAC,CAAA;AAG3C,IAAI,gBAAgB,GAAG,QAAQ,CAAC,SAAS,CAAC,OAAO,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC;AAEvE;IAcIA,cAAYA,GAA2BA,EAAEA,MAAsBA;QAiBvDC,aAAQA,GAAaA,EAAEA,CAACA;QAIxBA,WAAMA,GAAUA,IAAIA,mBAASA,EAAEA,CAACA;QAnBpCA,IAAIA,IAAIA,GAAGA,KAAKA,CAACA,SAASA,CAACA,KAAKA,CAACA,IAAIA,CAACA,SAASA,EAAEA,CAACA,CAACA,CAACA;QACpDA,GAAGA,GAAGA,MAAMA,GAAGA,IAAIA,CAACA;QACpBA,GAAGA,CAACA,CAACA,GAAGA,CAACA,CAACA,GAAGA,CAACA,EAAEA,CAACA,GAAGA,IAAIA,CAACA,MAAMA,EAAEA,CAACA,EAAEA,EAAEA,CAACA;YACnCA,EAAEA,CAACA,CAACA,OAAOA,IAAIA,CAACA,CAACA,CAACA,IAAIA,QAAQA,CAACA;gBAC3BA,GAAGA,GAAGA,IAAIA,CAACA,CAACA,CAACA,CAACA;YAClBA,IAAIA,CAACA,EAAEA,CAACA,CAACA,OAAOA,IAAIA,CAACA,CAACA,CAACA,IAAIA,QAAQA,CAACA;gBAChCA,M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WAAW,CAAC;gBAAC,MAAM,CAAC,IAAI,CAAC;YACnC,IAAI,IAAI,GAAe,IAAI,CAAC,WAAW,CAAC;YACxC,IAAI,CAAC,WAAW,GAAG,IAAI,CAAC;YACxB,IAAI,CAAC,KAAK,EAAE,CAAC;YACb,MAAM,CAAC,IAAI,CAAC;QAChB,CAAC,CAACA,CAACA;IACPA,CAACA;IAEDT;;;;OAIGA;IACHA,sBAAOA,GAAPA;QACIU,MAAMA,CAACA,iBAAwBA,CAACA,IAAIA,CAACA,CAACA;IAC1CA,CAACA;IACLV,WAACA;AAADA,CAzKA,AAyKCA,IAAA;AAzKD,sBAyKC,CAAA","file":"lib/Core.js","sourcesContent":["/// \r\nimport 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\nvar mongoConnectAsyc = Bluebird.promisify(MongoDB.MongoClient.connect);\r\n\r\nexport default 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 _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 /**\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 var self = this;\r\n return Bluebird.bind(this).then(function() {\r\n if (self._connection) return self._connection;\r\n return mongoConnectAsyc(self.url);\r\n }).then(function(db: MongoDB.Db) {\r\n self._connection = db;\r\n return self;\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 var self = this;\r\n return Bluebird.bind(this).then(function() {\r\n if (!self._connection) return this;\r\n var conn: MongoDB.Db = self._connection;\r\n self._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"],"sourceRoot":"/source/"} \ No newline at end of file +{"version":3,"sources":["lib/Core.ts"],"names":["Core","Core.constructor","Core.plugins","Core.settings","Core.connection","Core.url","Core.cache","Core.register","Core.connect","Core.close","Core.express"],"mappings":"AAAA,AACA,4CAD4C;AAC5C,IAAO,QAAQ,WAAW,UAAU,CAAC,CAAC;AACtC,IAAO,OAAO,WAAW,SAAS,CAAC,CAAC;AACpC,IAAO,CAAC,WAAW,QAAQ,CAAC,CAAC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AI,CAAC,WAAW,GAAG,IAAI,CAAC;YACxB,IAAI,CAAC,KAAK,EAAE,CAAC;YACb,MAAM,CAAC,IAAI,CAAC;QAChB,CAAC,CAACA,CAACA;IACPA,CAACA;IAEDT;;;;OAIGA;IACHA,sBAAOA,GAAPA;QACIU,MAAMA,CAACA,iBAAwBA,CAACA,IAAIA,CAACA,CAACA;IAC1CA,CAACA;IACLV,WAACA;AAADA,CAhLA,AAgLCA,IAAA;AAhLD,sBAgLC,CAAA","file":"lib/Core.js","sourcesContent":["/// \r\nimport 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\nvar mongoConnectAsyc = Bluebird.promisify(MongoDB.MongoClient.connect);\r\n\r\nexport default 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 _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 var self = this;\r\n return Bluebird.bind(this).then(function() {\r\n if (self._connection) return self._connection;\r\n if (self._connectPromise) return this._connectPromise;\r\n return self._connectPromise = mongoConnectAsyc(self.url);\r\n }).then(function(db: MongoDB.Db) {\r\n self._connection = db;\r\n self._connectPromise = null;\r\n return self;\r\n }, function(err) {\r\n self._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 var self = this;\r\n return Bluebird.bind(this).then(function() {\r\n if (!self._connection) return this;\r\n var conn: MongoDB.Db = self._connection;\r\n self._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"],"sourceRoot":"/source/"} \ No newline at end of file diff --git a/lib/Core.ts b/lib/Core.ts index d6822bb..71f3d69 100644 --- a/lib/Core.ts +++ b/lib/Core.ts @@ -50,13 +50,15 @@ export default class Core { this._url = uri; this._config = config; } - + private _plugins: Plugin[] = []; private _url: string; private _config: Configuration; private _connection: MongoDB.Db; private _cache: Cache = new NoOpCache(); - + + private _connectPromise: Bluebird; + /** * Gets the plugins registered with this Iridium Core * @returns {[Iridium.Plugin]} @@ -159,10 +161,15 @@ export default class Core { var self = this; return Bluebird.bind(this).then(function() { if (self._connection) return self._connection; - return mongoConnectAsyc(self.url); + if (self._connectPromise) return this._connectPromise; + return self._connectPromise = mongoConnectAsyc(self.url); }).then(function(db: MongoDB.Db) { self._connection = db; + self._connectPromise = null; return self; + }, function(err) { + self._connectPromise = null; + return Bluebird.reject(err); }).nodeify(callback); } From d5653126cfa2a204b8d02af8d894f2f12b597d9a Mon Sep 17 00:00:00 2001 From: Benjamin Pannell Date: Mon, 24 Aug 2015 07:46:14 +0200 Subject: [PATCH 21/24] Include compiled fix from 5.9.2 --- dist/lib/Instance.js | 2 +- dist/lib/Instance.js.map | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/dist/lib/Instance.js b/dist/lib/Instance.js index f3d5dab..d16dd2b 100644 --- a/dist/lib/Instance.js +++ b/dist/lib/Instance.js @@ -100,7 +100,7 @@ var Instance = (function () { }); }); } - }, function (err) { + }).catch(function (err) { err['original'] = _this._original; err['modified'] = _this._modified; return Bluebird.reject(err); diff --git a/dist/lib/Instance.js.map b/dist/lib/Instance.js.map index fac7993..9d902e7 100644 --- a/dist/lib/Instance.js.map +++ b/dist/lib/Instance.js.map @@ -1 +1 @@ -{"version":3,"sources":["lib/Instance.ts"],"names":["Instance","Instance.constructor","Instance.document","Instance.save","Instance.update","Instance.refresh","Instance.delete","Instance.remove","Instance.first","Instance.select","Instance.toJSON","Instance.toString"],"mappings":"AAUA,IAAO,CAAC,WAAW,QAAQ,CAAC,CAAC;AAC7B,IAAO,OAAO,WAAW,SAAS,CAAC,CAAC;AACpC,IAAO,QAAQ,WAAW,UAAU,CAAC,CAAC;AACtC,IAAO,MAAM,WAAW,QAAQ,CAAC,CAAC;AAElC;IACIA;;;;;;;;;;;OAWGA;IACHA,kBAAYA,KAAkCA,EAAEA,QAAmBA,EAAEA,KAAqBA,EAAEA,SAA0BA;QAb1HC,iBAoUCA;QA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;IACzBA,CAACA;IAEDV;;;OAGGA;IACHA,2BAAQA,GAARA;QACIW,MAAMA,CAACA,IAAIA,CAACA,SAASA,CAACA,IAAIA,CAACA,QAAQA,EAAEA,IAAIA,EAAEA,CAACA,CAACA,CAACA;IAClDA,CAACA;IAnRMX,eAAMA,GAAWA;QACpBA,GAAGA,EAAEA,KAAKA;KACbA,CAACA;IAEKA,mBAAUA,GAAuBA;QACpCA,MAAMA,CAACA,MAAMA,CAACA,UAAAA,MAAMA,IAAIA,OAAAA,MAAMA,KAAKA,OAAOA,CAACA,QAAQA,EAA3BA,CAA2BA,EAAEA,UAASA,MAAMA,EAAEA,IAAIA;YACtE,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,IAAI,IAAI,IAAI,YAAY,OAAO,CAAC,QAAQ,IAAI,CAAC,IAAI,CAAC,SAAS,KAAK,UAAU,IAAI,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC;QAChH,CAAC,EAAEA,EAAEA,IAAIA,EAAEA,qBAAqBA,EAAEA,CAACA;KACtCA,CAACA;IAEKA,mBAAUA,GAAwFA,EAExGA,CAACA;IAGKA,gBAAOA,GAA+CA,EAAEA,CAACA;IAqQpEA,eAACA;AAADA,CApUA,AAoUCA,IAAA;AApUD,0BAoUC,CAAA","file":"lib/Instance.js","sourcesContent":["/// \r\nimport 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\n\r\nimport _ = require('lodash');\r\nimport MongoDB = require('mongodb');\r\nimport Bluebird = require('bluebird');\r\nimport skmatc = require('skmatc');\r\n\r\nexport default class Instance {\r\n /**\r\n * Creates a new instance which represents the given document as a type of model\r\n * @param {model.Model} model The model that the document represents\r\n * @param {TSchema} document The document which should be wrapped by this instance\r\n * @param {Boolean} isNew Whether the document is new (doesn't exist in the database) or not\r\n * @param {Boolean} isPartial Whether the document has only a subset of its fields populated\r\n * @description\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\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 = _.cloneDeep(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 static onCreating: (document: { _id?: any }) => void;\r\n static onRetrieved: (document: { _id?: any }) => void;\r\n static onReady: (instance: Instance<{ _id?: any }, Instance<{ _id?: any }, any>>) => void;\r\n static onSaving: (instance: Instance<{ _id?: any }, Instance<{ _id?: any }, any>>, changes: any) => void;\r\n\r\n static collection: string;\r\n\r\n static schema: Schema = {\r\n _id: false\r\n };\r\n\r\n static validators: Skmatc.Validator[] = [\r\n skmatc.create(schema => schema === MongoDB.ObjectID, function(schema, data) {\r\n return this.assert(!data || data instanceof MongoDB.ObjectID || (data._bsontype === 'ObjectID' && data.id));\r\n }, { name: 'ObjectID validation' })\r\n ];\r\n\r\n static transforms: { [property: string]: { fromDB: (value: any) => any; toDB: (value: any) => any; } } = {\r\n\r\n };\r\n\r\n static cache: CacheDirector;\r\n static indexes: (Index.Index | Index.IndexSpecification)[] = [];\r\n static identifier: {\r\n apply(fromSource: any): any;\r\n reverse(toSource: any): any;\r\n };\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 = _.cloneDeep(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 = _.cloneDeep(this._original);\r\n var modified = _.cloneDeep(this._modified);\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 }, 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 = _.cloneDeep(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 = _.cloneDeep(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 = _.cloneDeep(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 = _.cloneDeep(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 {any[]} collection The collection from which to retrieve the element\r\n * @param {function(any, Number): Boolean} predicate The function which determines whether to select an element\r\n * @returns {any}\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 {Object} collection The collection from which to retrieve the element\r\n * @param {function(any, String): Boolean} predicate The function which determines whether to select an element\r\n * @returns {any}\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 {any[]} collection The collection from which elements will be plucked\r\n * @param {function(any, Number): Boolean} predicate The function which determines the elements to be plucked\r\n * @returns {any[]}\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 {Object} collection The collection from which elements will be plucked\r\n * @param {function(any, String): Boolean} predicate The function which determines the elements to be plucked\r\n * @returns {Object}\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":["Instance","Instance.constructor","Instance.document","Instance.save","Instance.update","Instance.refresh","Instance.delete","Instance.remove","Instance.first","Instance.select","Instance.toJSON","Instance.toString"],"mappings":"AAUA,IAAO,CAAC,WAAW,QAAQ,CAAC,CAAC;AAC7B,IAAO,OAAO,WAAW,SAAS,CAAC,CAAC;AACpC,IAAO,QAAQ,WAAW,UAAU,CAAC,CAAC;AACtC,IAAO,MAAM,WAAW,QAAQ,CAAC,CAAC;AAElC;IACIA;;;;;;;;;;;OAWGA;IACHA,kBAAYA,KAAkCA,EAAEA,QAAmB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OAGGA;IACHA,yBAAMA,GAANA;QACIU,MAAMA,CAACA,IAAIA,CAACA,QAAQA,CAACA;IACzBA,CAACA;IAEDV;;;OAGGA;IACHA,2BAAQA,GAARA;QACIW,MAAMA,CAACA,IAAIA,CAACA,SAASA,CAACA,IAAIA,CAACA,QAAQA,EAAEA,IAAIA,EAAEA,CAACA,CAACA,CAACA;IAClDA,CAACA;IAnRMX,eAAMA,GAAWA;QACpBA,GAAGA,EAAEA,KAAKA;KACbA,CAACA;IAEKA,mBAAUA,GAAuBA;QACpCA,MAAMA,CAACA,MAAMA,CAACA,UAAAA,MAAMA,IAAIA,OAAAA,MAAMA,KAAKA,OAAOA,CAACA,QAAQA,EAA3BA,CAA2BA,EAAEA,UAASA,MAAMA,EAAEA,IAAIA;YACtE,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,IAAI,IAAI,IAAI,YAAY,OAAO,CAAC,QAAQ,IAAI,CAAC,IAAI,CAAC,SAAS,KAAK,UAAU,IAAI,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC;QAChH,CAAC,EAAEA,EAAEA,IAAIA,EAAEA,qBAAqBA,EAAEA,CAACA;KACtCA,CAACA;IAEKA,mBAAUA,GAAwFA,EAExGA,CAACA;IAGKA,gBAAOA,GAA+CA,EAAEA,CAACA;IAqQpEA,eAACA;AAADA,CApUA,AAoUCA,IAAA;AApUD,0BAoUC,CAAA","file":"lib/Instance.js","sourcesContent":["/// \r\nimport 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\n\r\nimport _ = require('lodash');\r\nimport MongoDB = require('mongodb');\r\nimport Bluebird = require('bluebird');\r\nimport skmatc = require('skmatc');\r\n\r\nexport default class Instance {\r\n /**\r\n * Creates a new instance which represents the given document as a type of model\r\n * @param {model.Model} model The model that the document represents\r\n * @param {TSchema} document The document which should be wrapped by this instance\r\n * @param {Boolean} isNew Whether the document is new (doesn't exist in the database) or not\r\n * @param {Boolean} isPartial Whether the document has only a subset of its fields populated\r\n * @description\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\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 = _.cloneDeep(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 static onCreating: (document: { _id?: any }) => void;\r\n static onRetrieved: (document: { _id?: any }) => void;\r\n static onReady: (instance: Instance<{ _id?: any }, Instance<{ _id?: any }, any>>) => void;\r\n static onSaving: (instance: Instance<{ _id?: any }, Instance<{ _id?: any }, any>>, changes: any) => void;\r\n\r\n static collection: string;\r\n\r\n static schema: Schema = {\r\n _id: false\r\n };\r\n\r\n static validators: Skmatc.Validator[] = [\r\n skmatc.create(schema => schema === MongoDB.ObjectID, function(schema, data) {\r\n return this.assert(!data || data instanceof MongoDB.ObjectID || (data._bsontype === 'ObjectID' && data.id));\r\n }, { name: 'ObjectID validation' })\r\n ];\r\n\r\n static transforms: { [property: string]: { fromDB: (value: any) => any; toDB: (value: any) => any; } } = {\r\n\r\n };\r\n\r\n static cache: CacheDirector;\r\n static indexes: (Index.Index | Index.IndexSpecification)[] = [];\r\n static identifier: {\r\n apply(fromSource: any): any;\r\n reverse(toSource: any): any;\r\n };\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 = _.cloneDeep(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 = _.cloneDeep(this._original);\r\n var modified = _.cloneDeep(this._modified);\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 = _.cloneDeep(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 = _.cloneDeep(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 = _.cloneDeep(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 = _.cloneDeep(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 {any[]} collection The collection from which to retrieve the element\r\n * @param {function(any, Number): Boolean} predicate The function which determines whether to select an element\r\n * @returns {any}\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 {Object} collection The collection from which to retrieve the element\r\n * @param {function(any, String): Boolean} predicate The function which determines whether to select an element\r\n * @returns {any}\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 {any[]} collection The collection from which elements will be plucked\r\n * @param {function(any, Number): Boolean} predicate The function which determines the elements to be plucked\r\n * @returns {any[]}\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 {Object} collection The collection from which elements will be plucked\r\n * @param {function(any, String): Boolean} predicate The function which determines the elements to be plucked\r\n * @returns {Object}\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 From 09bfb5347d9f1d4400e08e8b653cc9a39bb7b82a Mon Sep 17 00:00:00 2001 From: Benjamin Pannell Date: Mon, 24 Aug 2015 07:48:54 +0200 Subject: [PATCH 22/24] Make use of arrow functions in Core (Closes #16) --- dist/lib/Core.js | 32 ++++++++++++++++---------------- dist/lib/Core.js.map | 2 +- lib/Core.ts | 30 ++++++++++++++---------------- 3 files changed, 31 insertions(+), 33 deletions(-) diff --git a/dist/lib/Core.js b/dist/lib/Core.js index b33ece0..bf2fa90 100644 --- a/dist/lib/Core.js +++ b/dist/lib/Core.js @@ -129,19 +129,19 @@ var Core = (function () { * @returns {Promise} */ Core.prototype.connect = function (callback) { - var self = this; + var _this = this; return Bluebird.bind(this).then(function () { - if (self._connection) - return self._connection; - if (self._connectPromise) - return this._connectPromise; - return self._connectPromise = mongoConnectAsyc(self.url); + if (_this._connection) + return _this._connection; + if (_this._connectPromise) + return _this._connectPromise; + return _this._connectPromise = mongoConnectAsyc(_this.url); }).then(function (db) { - self._connection = db; - self._connectPromise = null; - return self; + _this._connection = db; + _this._connectPromise = null; + return _this; }, function (err) { - self._connectPromise = null; + _this._connectPromise = null; return Bluebird.reject(err); }).nodeify(callback); }; @@ -150,14 +150,14 @@ var Core = (function () { * @type {Promise} */ Core.prototype.close = function () { - var self = this; + var _this = this; return Bluebird.bind(this).then(function () { - if (!self._connection) - return this; - var conn = self._connection; - self._connection = null; + if (!_this._connection) + return _this; + var conn = _this._connection; + _this._connection = null; conn.close(); - return this; + return _this; }); }; /** diff --git a/dist/lib/Core.js.map b/dist/lib/Core.js.map index 748658e..bf26fc8 100644 --- a/dist/lib/Core.js.map +++ b/dist/lib/Core.js.map @@ -1 +1 @@ -{"version":3,"sources":["lib/Core.ts"],"names":["Core","Core.constructor","Core.plugins","Core.settings","Core.connection","Core.url","Core.cache","Core.register","Core.connect","Core.close","Core.express"],"mappings":"AAAA,AACA,4CAD4C;AAC5C,IAAO,QAAQ,WAAW,UAAU,CAAC,CAAC;AACtC,IAAO,OAAO,WAAW,SAAS,CAAC,CAAC;AACpC,IAAO,CAAC,WAAW,QAAQ,CAAC,CAAC;AAW7B,wBAAqC,sBAAsB,CAAC,CAAA;AAG5D,0BAAsB,oBAAoB,CAAC,CAAA;AAG3C,IAAI,gBAAgB,GAAG,QAAQ,CAAC,SAAS,CAAC,OAAO,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC;AAEvE;IAcIA,cAAYA,GAA2BA,EAAEA,MAAsBA;QAiBvDC,aAAQ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IAC1CA,CAACA;IACLV,WAACA;AAADA,CAhLA,AAgLCA,IAAA;AAhLD,sBAgLC,CAAA","file":"lib/Core.js","sourcesContent":["/// \r\nimport 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\nvar mongoConnectAsyc = Bluebird.promisify(MongoDB.MongoClient.connect);\r\n\r\nexport default 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 _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 var self = this;\r\n return Bluebird.bind(this).then(function() {\r\n if (self._connection) return self._connection;\r\n if (self._connectPromise) return this._connectPromise;\r\n return self._connectPromise = mongoConnectAsyc(self.url);\r\n }).then(function(db: MongoDB.Db) {\r\n self._connection = db;\r\n self._connectPromise = null;\r\n return self;\r\n }, function(err) {\r\n self._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 var self = this;\r\n return Bluebird.bind(this).then(function() {\r\n if (!self._connection) return this;\r\n var conn: MongoDB.Db = self._connection;\r\n self._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"],"sourceRoot":"/source/"} \ No newline at end of file +{"version":3,"sources":["lib/Core.ts"],"names":["Core","Core.constructor","Core.plugins","Core.settings","Core.connection","Core.url","Core.cache","Core.register","Core.connect","Core.close","Core.express"],"mappings":"AAAA,AACA,4CAD4C;AAC5C,IAAO,QAAQ,WAAW,UAAU,CAAC,CAAC;AACtC,IAAO,OAAO,WAAW,SAAS,CAAC,CAAC;AACpC,IAAO,CAAC,WAAW,QAAQ,CAAC,CAAC;AAW7B,wBAAqC,sBAAsB,CAAC,CAAA;AAG5D,0BAAsB,oBAAoB,CAAC,CAAA;AAG3C,IAAI,gBAAgB,GAAG,QAAQ,CAAC,SAAS,CAAC,OAAO,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC;AAEvE;IAcIA,cAAYA,GAA2BA,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A,GAAPA;QACIU,MAAMA,CAACA,iBAAwBA,CAACA,IAAIA,CAACA,CAACA;IAC1CA,CAACA;IACLV,WAACA;AAADA,CA9KA,AA8KCA,IAAA;AA9KD,sBA8KC,CAAA","file":"lib/Core.js","sourcesContent":["/// \r\nimport 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\nvar mongoConnectAsyc = Bluebird.promisify(MongoDB.MongoClient.connect);\r\n\r\nexport default 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 _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.bind(this).then(() => {\r\n if (this._connection) return this._connection;\r\n if (this._connectPromise) return this._connectPromise;\r\n return this._connectPromise = mongoConnectAsyc(this.url);\r\n }).then((db: MongoDB.Db) => {\r\n this._connection = db;\r\n this._connectPromise = null;\r\n return this;\r\n }, (err) => {\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.bind(this).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"],"sourceRoot":"/source/"} \ No newline at end of file diff --git a/lib/Core.ts b/lib/Core.ts index 71f3d69..7271eab 100644 --- a/lib/Core.ts +++ b/lib/Core.ts @@ -158,17 +158,16 @@ export default class Core { * @returns {Promise} */ connect(callback?: (err: Error, core: Core) => any): Bluebird { - var self = this; - return Bluebird.bind(this).then(function() { - if (self._connection) return self._connection; - if (self._connectPromise) return this._connectPromise; - return self._connectPromise = mongoConnectAsyc(self.url); - }).then(function(db: MongoDB.Db) { - self._connection = db; - self._connectPromise = null; - return self; - }, function(err) { - self._connectPromise = null; + return Bluebird.bind(this).then(() => { + if (this._connection) return this._connection; + if (this._connectPromise) return this._connectPromise; + return this._connectPromise = mongoConnectAsyc(this.url); + }).then((db: MongoDB.Db) => { + this._connection = db; + this._connectPromise = null; + return this; + }, (err) => { + this._connectPromise = null; return Bluebird.reject(err); }).nodeify(callback); } @@ -178,11 +177,10 @@ export default class Core { * @type {Promise} */ close(): Bluebird { - var self = this; - return Bluebird.bind(this).then(function() { - if (!self._connection) return this; - var conn: MongoDB.Db = self._connection; - self._connection = null; + return Bluebird.bind(this).then(() => { + if (!this._connection) return this; + var conn: MongoDB.Db = this._connection; + this._connection = null; conn.close(); return this; }); From 375494a4cf8a19b3e89d5f9521a2d7af4e986510 Mon Sep 17 00:00:00 2001 From: Benjamin Pannell Date: Mon, 24 Aug 2015 07:49:20 +0200 Subject: [PATCH 23/24] Version 5.10.0 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index cf7bf1d..a12e0e6 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "iridium", - "version": "5.9.2", + "version": "5.10.0", "author": "Benjamin Pannell ", "description": "A custom lightweight ORM for MongoDB designed for power-users", "license": "MIT", From 99cc6cd8a842b0dd90e6b7858184d8c9190a6463 Mon Sep 17 00:00:00 2001 From: Benjamin Pannell Date: Mon, 24 Aug 2015 07:49:21 +0200 Subject: [PATCH 24/24] Updated CHANGELOG --- CHANGELOG.md | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index cb57299..491557b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,11 +1,18 @@ +## [v5.10.0](https://github.com/sierrasoftworks/iridium/tree/v5.10.0) +- [375494a](https://github.com/sierrasoftworks/iridium/commit/375494a) Version 5.10.0 +- [09bfb53](https://github.com/sierrasoftworks/iridium/commit/09bfb53) (origin/master, origin/HEAD) Make use of arrow functions in Core (Closes [#16](https://github.com/sierrasoftworks/iridium/issues/16)) +- [d565312](https://github.com/sierrasoftworks/iridium/commit/d565312) Include compiled fix from 5.9.2 +- [f7f9db1](https://github.com/sierrasoftworks/iridium/commit/f7f9db1) Make core.connect async-safe (Fixes #15) +- [0697117](https://github.com/sierrasoftworks/iridium/commit/0697117) Updated CHANGELOG + ## [v5.9.2](https://github.com/sierrasoftworks/iridium/tree/v5.9.2) - [2438155](https://github.com/sierrasoftworks/iridium/commit/2438155) Version 5.9.2 - [b2cb440](https://github.com/sierrasoftworks/iridium/commit/b2cb440) Fix for a strange set of behaviour with the last release - [b9c13fb](https://github.com/sierrasoftworks/iridium/commit/b9c13fb) Updated changelog generation - [f656174](https://github.com/sierrasoftworks/iridium/commit/f656174) Revert "Switch to Travis-CI container infrastucture" - [5261ea0](https://github.com/sierrasoftworks/iridium/commit/5261ea0) Revert "Updated travis config to use MongoDB precise (3.x)" -- [cefc0f4](https://github.com/sierrasoftworks/iridium/commit/cefc0f4) (origin/master, origin/HEAD, infrastructure/travisci-containers) Updated travis config to use MongoDB precise (3.x) +- [cefc0f4](https://github.com/sierrasoftworks/iridium/commit/cefc0f4) (infrastructure/travisci-containers) Updated travis config to use MongoDB precise (3.x) - [d11c8f3](https://github.com/sierrasoftworks/iridium/commit/d11c8f3) Switch to Travis-CI container infrastucture - [5a2dc37](https://github.com/sierrasoftworks/iridium/commit/5a2dc37) Updated CHANGELOG @@ -74,7 +81,7 @@ ## [v5.5.5](https://github.com/sierrasoftworks/iridium/tree/5.5.5) - [0a71f20](https://github.com/sierrasoftworks/iridium/commit/0a71f20) Version 5.5.5 - [6de8a3f](https://github.com/sierrasoftworks/iridium/commit/6de8a3f) Merge branch 'master' into release -- [a98752e](https://github.com/sierrasoftworks/iridium/commit/a98752e) Automatically prep _references.d.ts during publish (Fixes [#11](https://github.com/sierrasoftworks/iridium/issues/11)) +- [a98752e](https://github.com/sierrasoftworks/iridium/commit/a98752e) Automatically prep _references.d.ts during publish (Fixes #11) ## [v5.6.0](https://github.com/sierrasoftworks/iridium/tree/5.6.0) - [95dec95](https://github.com/sierrasoftworks/iridium/commit/95dec95) Version 5.6.0