From c5595815603746d1aae4d4a0fbb646b52da8fcff Mon Sep 17 00:00:00 2001 From: Benjamin Pannell Date: Sun, 30 Aug 2015 16:14:37 +0200 Subject: [PATCH 01/22] Added TypeDoc dependency --- package.json | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/package.json b/package.json index d7382be..0aa3e76 100644 --- a/package.json +++ b/package.json @@ -44,25 +44,26 @@ "chai-fuzzy": "^1.5.0", "codeclimate-test-reporter": "~0.0.4", "coveralls": "^2.11.2", - "minimist": "^1.1.1", - "semver": "^4.3.6", - "gulp": "^3.9.0", "del": "^1.2.0", - "require-dir": "~0.3.0", - "run-sequence": "^1.1.0", - "gulp-typescript": "^2.7.6", - "gulp-sourcemaps": "^1.5.2", - "gulp-plumber": "^1.0.1", - "gulp-mocha": "^2.1.1", - "gulp-util": "^3.0.5", + "gulp": "^3.9.0", "gulp-bump": "~0.3.1", "gulp-git": "^1.2.4", "gulp-istanbul": "~0.10.0", + "gulp-mocha": "^2.1.1", + "gulp-plumber": "^1.0.1", "gulp-replace": "~0.5.3", + "gulp-sourcemaps": "^1.5.2", + "gulp-typescript": "^2.7.6", + "gulp-util": "^3.0.5", "istanbul": "~0.3.13", "jshint": "^2.7.0", + "minimist": "^1.1.1", "mocha": "^2.2.4", + "require-dir": "~0.3.0", + "run-sequence": "^1.1.0", + "semver": "^4.3.6", "tick": "~0.1.1", + "typedoc": "^0.3.8", "typescript": "^1.5.0-beta", "underscore": "^1.8.3" }, From 54ad8565e9dce5c1eb144b9e4e74fe8dbd87f40d Mon Sep 17 00:00:00 2001 From: Benjamin Pannell Date: Sun, 30 Aug 2015 16:56:58 +0200 Subject: [PATCH 02/22] Updated a variety of files to better support TypeDoc --- index.ts | 6 +++--- lib/Core.ts | 12 ++++++------ lib/Cursor.ts | 2 +- lib/Decorators.ts | 4 ++-- lib/Instance.ts | 6 +++--- lib/InstanceInterface.ts | 7 ++----- lib/Middleware.ts | 2 +- lib/Model.ts | 16 ++++++++-------- lib/ModelCache.ts | 4 ++-- lib/ModelHandlers.ts | 8 ++++---- lib/ModelHelpers.ts | 4 ++-- lib/ModelOptions.ts | 4 ++-- lib/ModelSpecificInstance.ts | 6 +++--- lib/Plugins.ts | 4 ++-- lib/middleware/Express.ts | 2 +- 15 files changed, 42 insertions(+), 45 deletions(-) diff --git a/index.ts b/index.ts index 5e7f8df..2f41515 100644 --- a/index.ts +++ b/index.ts @@ -1,6 +1,6 @@ -import Core from './lib/Core'; -import Model from './lib/Model'; -import Instance from './lib/Instance'; +import {Core} from './lib/Core'; +import {Model} from './lib/Model'; +import {Instance} from './lib/Instance'; export {Core, Model, Instance}; export * from './lib/Decorators'; diff --git a/lib/Core.ts b/lib/Core.ts index d6822bb..da831eb 100644 --- a/lib/Core.ts +++ b/lib/Core.ts @@ -7,8 +7,8 @@ import events = require('events'); import {Configuration} from './Configuration'; import {Plugin} from './Plugins'; -import Model from './Model'; -import Instance from './Instance'; +import {Model} from './Model'; +import {Instance} from './Instance'; import {MiddlewareFactory} from './Middleware'; import * as ExpressMiddleware from './middleware/Express'; @@ -18,9 +18,7 @@ import {Cache} from './Cache'; import NoOpCache from './caches/NoOpCache'; import MemoryCache from './caches/MemoryCache'; -var mongoConnectAsyc = Bluebird.promisify(MongoDB.MongoClient.connect); - -export default class Core { +export class Core { /** * Creates a new Iridium Core instance connected to the specified MongoDB instance * @param {Iridium.IridiumConfiguration} config The config object defining the database to connect to @@ -51,6 +49,8 @@ export default class Core { this._config = config; } + private mongoConnectAsyc = Bluebird.promisify(MongoDB.MongoClient.connect); + private _plugins: Plugin[] = []; private _url: string; private _config: Configuration; @@ -159,7 +159,7 @@ export default class Core { var self = this; return Bluebird.bind(this).then(function() { if (self._connection) return self._connection; - return mongoConnectAsyc(self.url); + return this.mongoConnectAsyc(self.url); }).then(function(db: MongoDB.Db) { self._connection = db; return self; diff --git a/lib/Cursor.ts b/lib/Cursor.ts index 9d3a6c7..89485c5 100644 --- a/lib/Cursor.ts +++ b/lib/Cursor.ts @@ -1,5 +1,5 @@ /// -import Model from './Model'; +import {Model} from './Model'; import General = require('./General'); import MongoDB = require('mongodb'); import Bluebird = require('bluebird'); diff --git a/lib/Decorators.ts b/lib/Decorators.ts index 0b041b8..38c0da9 100644 --- a/lib/Decorators.ts +++ b/lib/Decorators.ts @@ -2,10 +2,10 @@ import MongoDB = require('mongodb'); import _ = require('lodash'); import skmatc = require('skmatc'); -import Instance from './Instance'; +import {Instance} from './Instance'; import {Index, IndexSpecification} from './Index'; import {Schema} from './Schema'; -import InstanceImplementation from './InstanceInterface'; +import {InstanceImplementation} from './InstanceInterface'; export function Collection(name: string) { return function(target: InstanceImplementation) { diff --git a/lib/Instance.ts b/lib/Instance.ts index e1b4daa..29ca0e6 100644 --- a/lib/Instance.ts +++ b/lib/Instance.ts @@ -1,6 +1,6 @@ /// -import Core from './Core'; -import Model from './Model'; +import {Core} from './Core'; +import {Model} from './Model'; import {Plugin} from './Plugins'; import {CacheDirector} from './CacheDirector'; import * as General from './General'; @@ -13,7 +13,7 @@ import MongoDB = require('mongodb'); import Bluebird = require('bluebird'); import skmatc = require('skmatc'); -export default class Instance { +export class Instance { /** * Creates a new instance which represents the given document as a type of model * @param {model.Model} model The model that the document represents diff --git a/lib/InstanceInterface.ts b/lib/InstanceInterface.ts index 96a9045..e0b20a6 100644 --- a/lib/InstanceInterface.ts +++ b/lib/InstanceInterface.ts @@ -1,13 +1,10 @@ /// -import Iridium from './Core'; import {Schema} from './Schema'; -import Model from './Model'; +import {Model} from './Model'; import * as Index from './Index'; import {CacheDirector} from './CacheDirector'; -export default InstanceImplementation; - -interface InstanceImplementation { +export interface InstanceImplementation { new (model: Model, doc: TDocument, isNew?: boolean, isPartial?: boolean): TInstance; collection: string; diff --git a/lib/Middleware.ts b/lib/Middleware.ts index dc6001b..8c90655 100644 --- a/lib/Middleware.ts +++ b/lib/Middleware.ts @@ -1,5 +1,5 @@ /// -import Core from './Core'; +import {Core} from './Core'; export interface MiddlewareFactory { (core: Core): T; diff --git a/lib/Model.ts b/lib/Model.ts index 1016357..5050f3c 100644 --- a/lib/Model.ts +++ b/lib/Model.ts @@ -4,8 +4,8 @@ import Bluebird = require('bluebird'); import util = require('util'); import _ = require('lodash'); -import Core from './Core'; -import Instance from './Instance'; +import {Core} from './Core'; +import {Instance} from './Instance'; import {Schema} from './Schema'; import {Hooks} from './Hooks'; import {Plugin} from './Plugins'; @@ -21,18 +21,18 @@ import memoryCache from './caches/MemoryCache'; import idCacheController from './cacheControllers/IDDirector'; import Omnom from './utils/Omnom'; -import ModelCache from './ModelCache'; -import ModelHelpers from './ModelHelpers'; -import ModelHandlers from './ModelHandlers'; +import {ModelCache} from './ModelCache'; +import {ModelHelpers} from './ModelHelpers'; +import {ModelHandlers} from './ModelHandlers'; import * as ModelInterfaces from './ModelInterfaces'; -import ModelSpecificInstance from './ModelSpecificInstance'; -import InstanceImplementation from './InstanceInterface'; +import {ModelSpecificInstance} from './ModelSpecificInstance'; +import {InstanceImplementation} from './InstanceInterface'; /** * An Iridium Model which represents a structured MongoDB collection * @class */ -export default class Model { +export class Model { /** * Creates a new Iridium model representing a given ISchema and backed by a collection whose name is specified * @param {Iridium} core The Iridium core that this model should use for database access diff --git a/lib/ModelCache.ts b/lib/ModelCache.ts index 919e9fd..5113b8b 100644 --- a/lib/ModelCache.ts +++ b/lib/ModelCache.ts @@ -1,8 +1,8 @@ /// -import Model from './Model'; +import {Model} from './Model'; import Bluebird = require('bluebird'); -export default class ModelCache { +export class ModelCache { constructor(public model: Model) { } diff --git a/lib/ModelHandlers.ts b/lib/ModelHandlers.ts index 9f7da3b..2bb976b 100644 --- a/lib/ModelHandlers.ts +++ b/lib/ModelHandlers.ts @@ -1,15 +1,15 @@ /// -import Core from './Core'; +import {Core} from './Core'; import {Schema} from './Schema'; -import Model from './Model'; -import ModelCache from './ModelCache'; +import {Model} from './Model'; +import {ModelCache} from './ModelCache'; import * as ModelOptions from './ModelOptions'; import _ = require('lodash'); import MongoDB = require('mongodb'); import Bluebird = require('bluebird'); -export default class ModelHandlers { +export class ModelHandlers { constructor(public model: Model) { } diff --git a/lib/ModelHelpers.ts b/lib/ModelHelpers.ts index 64f63bf..454d38d 100644 --- a/lib/ModelHelpers.ts +++ b/lib/ModelHelpers.ts @@ -1,12 +1,12 @@ /// import MongoDB = require('mongodb'); -import Model from './Model'; +import {Model} from './Model'; import skmatc = require('skmatc'); import Omnom from './utils/Omnom'; import _ = require('lodash'); import Bluebird = require('bluebird'); -export default class ModelHelpers { +export class ModelHelpers { constructor(public model: Model) { this._validator = new skmatc(model.schema); model.validators.forEach(validator => this._validator.register(validator)); diff --git a/lib/ModelOptions.ts b/lib/ModelOptions.ts index 3def824..d8ff82f 100644 --- a/lib/ModelOptions.ts +++ b/lib/ModelOptions.ts @@ -1,7 +1,7 @@ /// import MongoDB = require('mongodb'); -import Index = require('./Index'); -import Hooks = require('./Hooks'); +import * as Index from './Index'; +import {Hooks} from './Hooks'; import {CacheDirector} from './CacheDirector'; import * as General from './General'; diff --git a/lib/ModelSpecificInstance.ts b/lib/ModelSpecificInstance.ts index 103db35..fc8c35e 100644 --- a/lib/ModelSpecificInstance.ts +++ b/lib/ModelSpecificInstance.ts @@ -1,10 +1,10 @@ /// -import Model from './Model'; -import InstanceImplementation from './InstanceInterface'; +import {Model} from './Model'; +import {InstanceImplementation} from './InstanceInterface'; import util = require('util'); import _ = require('lodash'); -export default function ModelSpecificInstance(model: Model, instanceType: InstanceImplementation): new (doc: TDocument, isNew?: boolean, isPartial?: boolean) => TInstance { +export function ModelSpecificInstance(model: Model, instanceType: InstanceImplementation): new (doc: TDocument, isNew?: boolean, isPartial?: boolean) => TInstance { var constructor = function (doc: TDocument, isNew?: boolean, isPartial?: boolean) { instanceType.call(this, model, doc, isNew, isPartial); }; diff --git a/lib/Plugins.ts b/lib/Plugins.ts index 59c130a..3697502 100644 --- a/lib/Plugins.ts +++ b/lib/Plugins.ts @@ -1,6 +1,6 @@ /// -import core = require('./Core'); -import Model from './Model'; +import {Core} from './Core'; +import {Model} from './Model'; export interface Plugin { newModel? (model: Model); diff --git a/lib/middleware/Express.ts b/lib/middleware/Express.ts index af39cdc..6bcee5f 100644 --- a/lib/middleware/Express.ts +++ b/lib/middleware/Express.ts @@ -1,7 +1,7 @@ /// import http = require('http'); import {MiddlewareFactory} from '../Middleware'; -import Core from '../Core'; +import {Core} from '../Core'; export default function ExpressMiddlewareFactory(core: Core): ExpressMiddleware { return function (req: http.ServerRequest, res: http.ServerResponse, next:(err?: Error, route?: String) => void) { From ea6d0997187dca4d131804d4a84ca4f710ab4e45 Mon Sep 17 00:00:00 2001 From: Benjamin Pannell Date: Sun, 30 Aug 2015 16:57:11 +0200 Subject: [PATCH 03/22] Added TypeDoc documentation compilation step --- .gitignore | 3 ++- build/doc.js | 20 ++++++++++++++++++++ build/paths.js | 10 +++++++++- package.json | 1 + 4 files changed, 32 insertions(+), 2 deletions(-) create mode 100644 build/doc.js diff --git a/.gitignore b/.gitignore index c85e9a7..5973c21 100644 --- a/.gitignore +++ b/.gitignore @@ -12,4 +12,5 @@ node_modules/ coverage/ typings/DefinitelyTyped/**/*.d.ts .tscache -dist/test/ \ No newline at end of file +dist/test/ +doc \ No newline at end of file diff --git a/build/doc.js b/build/doc.js new file mode 100644 index 0000000..ba5d0c7 --- /dev/null +++ b/build/doc.js @@ -0,0 +1,20 @@ +var gulp = require('gulp'), + typedoc = require('gulp-typedoc'); + +var paths = require('./paths'); + +gulp.task('doc', function() { + return gulp.src(paths.docSourceFiles).pipe(typedoc({ + module: 'commonjs', + target: 'es5', + mode: 'modules', + entryPoint: 'iridium', + + out: './doc', + + name: "Iridium", + plugin: ['decorator'], + ignoreCompilerErrors: true, + version: true + })); +}); \ No newline at end of file diff --git a/build/paths.js b/build/paths.js index 6d5cb9f..a0e1460 100644 --- a/build/paths.js +++ b/build/paths.js @@ -10,5 +10,13 @@ module.exports = { builtTestFiles: 'dist/test/*.js', builtFiles: ["dist/lib/**/*.js", "dist/index.js"], - testSupportFiles: ['dist/test/support/chai'] + testSupportFiles: ['dist/test/support/chai'], + + docSourceFiles: [ + "index.ts" + // "lib/Core.ts", + // "lib/Model.ts", + // "lib/Instance.ts", + // "lib/Instance.ts" + ] }; \ No newline at end of file diff --git a/package.json b/package.json index 0aa3e76..0ded930 100644 --- a/package.json +++ b/package.json @@ -53,6 +53,7 @@ "gulp-plumber": "^1.0.1", "gulp-replace": "~0.5.3", "gulp-sourcemaps": "^1.5.2", + "gulp-typedoc": "^1.2.1", "gulp-typescript": "^2.7.6", "gulp-util": "^3.0.5", "istanbul": "~0.3.13", From 138e448b72d31f0789bc553c4b74130f5e9220b4 Mon Sep 17 00:00:00 2001 From: Benjamin Pannell Date: Sun, 30 Aug 2015 16:57:19 +0200 Subject: [PATCH 04/22] Removed legacy documentation --- doc/Migrating from 4.x to 5.x.md | 145 ------------------------------- 1 file changed, 145 deletions(-) delete mode 100644 doc/Migrating from 4.x to 5.x.md diff --git a/doc/Migrating from 4.x to 5.x.md b/doc/Migrating from 4.x to 5.x.md deleted file mode 100644 index 840d71f..0000000 --- a/doc/Migrating from 4.x to 5.x.md +++ /dev/null @@ -1,145 +0,0 @@ -# Migrating from v4.x to v5.x -There have been some major architectural changes to Iridium between v4.x and v5.x - most significant being the switch -to TypeScript over JavaScript. This serves two primary purposes, the first being that we can finally provide true -IntelliSense support without having to hack around the limitations of individual editors, and the second being that -both Iridium and applications you write which make use of it are far less likely to contain errors as a result of -poor API usage. - -Part of this transition required changes to the way certain things are handled by Iridium, those changes are detailed -in the [Architectural Changes](#architectural_changes) section. - -## First things first -This isn't a small update (like the one from v2.x to v3.x or v3.x to v4.x) and will **definitely** require changes to your application -if you wish to make use of it. We will be supporting the 3.x branch for a short time, providing bug and security fixes -as necessary, however new features will not be backported. - -We recommend that you **do not upgrade existing applications** to the 4.x branch unless you've got a lot of time on your -hands or are using TypeScript already. If however you are set on doing so, you will need to change the following things. - -## The Performance Difference -With the new architecture it is a lot easier to reason about how V8's compiler will optimize objects, helping to make -sure that performance is significantly better than Iridium's already high level. - -Running the benchmark scripts from v4.x and v5.x, (which run the same combination of 10 000 inserts, finds and removes) -we saw the following results. - -### Iridium 4.x Benchmark -``` -MongoDB 10000 Inserts { w: 1 } - => 412ms -Iridium 10000 Inserts { w: 1, wrap: false } - => 1124ms (2.7x slower) -Iridium 10000 Inserts { w: 1, wrap: true } - => 1700ms (4.2x slower) - -MongoDB find() - => 83ms -Iridium find() { wrap: false } - => 216ms (2.6x slower) -Iridium find() { wrap: true } - => 669ms (8.06x slower) - -MongoDB remove() - => 151ms -Iridium remove() - => 147ms (about the same) -``` - -### Iridium 5.x Benchmark -``` -Running benchmark with intensity of 10000 -MongoDB inserting: 368ms -Iridium inserting: 920ms (2.5x slower) -Iridium Instances inserting: 1151ms (3.1x slower) - -MongoDB finding: 87ms -Iridium finding: 268ms (3.1x slower) -Iridium Instances finding: 344ms (4.0x slower) - -MongoDB removing: 182ms -Iridium Instances removing: 159ms (about the same) -Iridium removing: 158ms (about the same) -``` - -As you can see, with the exception of the unwrapped find() method, we see an across-the-board improvement in performance -of up to 100% (most significant when wrapping documents in the new Instance type). We're very happy with these gains, and -keep in mind that these v5.x benchmarks were run before any optmization work has begun on the 5.x branch - things are -definitely looking good. - -## Architectural Changes -The biggest change between v4.x and v5.x is that Iridium is now primarily developed in TypeScript. Yes, you read that -correctly, [TypeScript](http://www.typescriptlang.org). I'll be perfectly honest with you, it was my intention to do -so from the get go but when I started Iridium it simply wasn't mature enough (v0.9 at the time) to support many of the -features I wanted to implement. - -With the latest version of TypeScript (v1.4) the building blocks were finally available and so I set about rewriting -Iridium the way I wanted to write it initially. This has meant a couple of changes to the way you do certain things -which you may like or dislike depending on how you decide to use Iridium. - -The biggest difference is that the `Instance` type which used to wrap documents to provide methods such as `save()` -has now been decoupled from the `Model` type (which wraps a MongoDB collection). This means that it is now possible -to develop your own custom instance types to replace Iridum's default one if you wish, but it also is the result of -a change in the way Models are defined. - -In Iridium v4.x you would define a model's properties and methods through the options object like this: - -```javascript -var model = new Iridium.Model(core, 'collection', { - id: false, - fullname: String -}, { - methods: { - jump: function() { } - }, - virtuals: { - avatar: function() { }, - password: { - get: function() { }, - set: function(value) { } - } - } -}); -``` - -This worked well from a JavaScript perspective but made it incredibly difficult for your IDE to figure out what was -going on. For starters, the `avatar()` function's `this` at design time would point to the `virtuals: {}` object -and there was no tangible relationship between the created instances and the methods, virtuals or properties defined -in the model. - -In Iridium v5.x we've changed things up a bit, using TypeScript generics you can now specify an interface which describes -the documents present in the collection, as well as a class which will be used to wrap those documents. It's actually -easier than you'd think since Iridium provides a number of useful helpers. - -```typescript -interface CollectionDocument { - id: string; - fullname: string; -} - -class CollectionInstance extends Iridium.Instance { - id: string; - fullname: string; - jump() { } - get avatar() { } - get password() { } - set password() { } -} - -var model = new Iridium.Model(core, CollectionInstance, 'collection', { - id: false, - fullname: String -}); -``` - -So, what's changed? Well, we've defined an interface which describes our collection documents - this allows your IDE -to provide contextual completion on any method which expects a document property. -So `model.create({ id: 'test', fullname: 'Test User' })` for example will provide hints for `id` and `fullname` - making -your life significantly easier. - -We've also defined a class called `CollectionInstance` which extends the default Iridium Instance type (to gain `save()` -and friends) which is then passed into our model's constructor in the `instanceType` field. From there on everything is -pretty much identical to Iridium 4.x - with the obvious removal of the `methods` and `virtuals` options since they are -no longer required. - -The best part is, you still get to keep all the same great performance you got with Iridium 4.x - with a massive boost -in developer productivity as a result of having inline assistance from your IDE. From d92fce452070999e44e39633bceba080a7aae111 Mon Sep 17 00:00:00 2001 From: Benjamin Pannell Date: Sun, 30 Aug 2015 17:10:53 +0200 Subject: [PATCH 05/22] Ensure that documentation is generated correctly --- build/doc.js | 2 +- build/paths.js | 25 ++++++++++++++++++++----- index.ts | 6 +++--- lib/Core.ts | 6 +++--- lib/Model.ts | 4 ---- lib/cacheControllers/IDDirector.ts | 2 +- lib/caches/MemoryCache.ts | 2 +- lib/caches/NoOpCache.ts | 2 +- lib/middleware/Express.ts | 2 +- 9 files changed, 31 insertions(+), 20 deletions(-) diff --git a/build/doc.js b/build/doc.js index ba5d0c7..a51100e 100644 --- a/build/doc.js +++ b/build/doc.js @@ -7,7 +7,7 @@ gulp.task('doc', function() { return gulp.src(paths.docSourceFiles).pipe(typedoc({ module: 'commonjs', target: 'es5', - mode: 'modules', + mode: 'file', entryPoint: 'iridium', out: './doc', diff --git a/build/paths.js b/build/paths.js index a0e1460..d461b0f 100644 --- a/build/paths.js +++ b/build/paths.js @@ -13,10 +13,25 @@ module.exports = { testSupportFiles: ['dist/test/support/chai'], docSourceFiles: [ - "index.ts" - // "lib/Core.ts", - // "lib/Model.ts", - // "lib/Instance.ts", - // "lib/Instance.ts" + "lib/Core.ts", + "lib/Model.ts", + "lib/Instance.ts", + + "lib/Decorators.ts", + + "lib/Plugins.ts", + "lib/Schema.ts", + "lib/Cache.ts", + "lib/CacheDirector.ts", + "lib/ModelOptions.ts", + "lib/Configuration.ts", + "lib/Hooks.ts", + + "lib/caches/MemoryCache.ts", + "lib/caches/NoOpCache.ts", + + "lib/cacheControllers/IDDirector.ts", + + "lib/utils/ObjectID.ts" ] }; \ No newline at end of file diff --git a/index.ts b/index.ts index 4bc7586..a93db85 100644 --- a/index.ts +++ b/index.ts @@ -13,11 +13,11 @@ export * from './lib/ModelOptions'; export * from './lib/Configuration'; export * from './lib/Hooks'; -import MemoryCache from './lib/caches/MemoryCache'; -import NoOpCache from './lib/caches/NoOpCache'; +import {MemoryCache} from './lib/caches/MemoryCache'; +import {NoOpCache} from './lib/caches/NoOpCache'; export {MemoryCache, NoOpCache}; -import IDDirector from './lib/cacheControllers/IDDirector'; +import {IDDirector} from './lib/cacheControllers/IDDirector'; export {IDDirector as CacheOnID}; import {toObjectID} from './lib/utils/ObjectID'; diff --git a/lib/Core.ts b/lib/Core.ts index 5cd7fa0..effabe1 100644 --- a/lib/Core.ts +++ b/lib/Core.ts @@ -12,11 +12,11 @@ import {Instance} from './Instance'; import {MiddlewareFactory} from './Middleware'; import * as ExpressMiddleware from './middleware/Express'; -import ExpressMiddlewareFactory from './middleware/Express'; +import {ExpressMiddlewareFactory} from './middleware/Express'; import {Cache} from './Cache'; -import NoOpCache from './caches/NoOpCache'; -import MemoryCache from './caches/MemoryCache'; +import {NoOpCache} from './caches/NoOpCache'; +import {MemoryCache} from './caches/MemoryCache'; export class Core { /** diff --git a/lib/Model.ts b/lib/Model.ts index 0909618..a248b45 100644 --- a/lib/Model.ts +++ b/lib/Model.ts @@ -16,10 +16,6 @@ import Cursor from './Cursor'; import * as Index from './Index'; import * as ModelOptions from './ModelOptions'; -import noOpCache from './caches/NoOpCache'; -import memoryCache from './caches/MemoryCache'; -import idCacheController from './cacheControllers/IDDirector'; - import Omnom from './utils/Omnom'; import {ModelCache} from './ModelCache'; import {ModelHelpers} from './ModelHelpers'; diff --git a/lib/cacheControllers/IDDirector.ts b/lib/cacheControllers/IDDirector.ts index 293bf30..f823b2a 100644 --- a/lib/cacheControllers/IDDirector.ts +++ b/lib/cacheControllers/IDDirector.ts @@ -2,7 +2,7 @@ import {CacheDirector} from '../CacheDirector'; import MongoDB = require('mongodb'); -export default class IDCacheDirector implements CacheDirector{ +export class CacheOnID implements CacheDirector{ valid(object: { _id: any }) { return !!object._id; } diff --git a/lib/caches/MemoryCache.ts b/lib/caches/MemoryCache.ts index 9ffd135..22f8a2f 100644 --- a/lib/caches/MemoryCache.ts +++ b/lib/caches/MemoryCache.ts @@ -2,7 +2,7 @@ import Bluebird = require('bluebird'); import {Cache} from '../Cache'; -export default class MemoryCache implements Cache { +export class MemoryCache implements Cache { private cache: any = {}; set(key: string, value: T): Bluebird { diff --git a/lib/caches/NoOpCache.ts b/lib/caches/NoOpCache.ts index 0f5f469..3bedaa3 100644 --- a/lib/caches/NoOpCache.ts +++ b/lib/caches/NoOpCache.ts @@ -2,7 +2,7 @@ import {Cache} from '../Cache'; import Bluebird = require('bluebird'); -export default class NoOpCache implements Cache { +export class NoOpCache implements Cache { set(key: string, object: T): Bluebird { return Bluebird.resolve(object); } diff --git a/lib/middleware/Express.ts b/lib/middleware/Express.ts index 6bcee5f..2c407f5 100644 --- a/lib/middleware/Express.ts +++ b/lib/middleware/Express.ts @@ -3,7 +3,7 @@ import http = require('http'); import {MiddlewareFactory} from '../Middleware'; import {Core} from '../Core'; -export default function ExpressMiddlewareFactory(core: Core): ExpressMiddleware { +export function ExpressMiddlewareFactory(core: Core): ExpressMiddleware { return function (req: http.ServerRequest, res: http.ServerResponse, next:(err?: Error, route?: String) => void) { core.connect().then(function() { Object.defineProperty(req, 'db', { From 5d05863673ca2231b595f7d1e55065cc27d4ab72 Mon Sep 17 00:00:00 2001 From: Benjamin Pannell Date: Sun, 30 Aug 2015 20:00:46 +0200 Subject: [PATCH 06/22] Restructuring and a massive amount of extra documentation for TypeDoc --- lib/Core.ts | 7 ++ lib/Cursor.ts | 9 ++- lib/Decorators.ts | 63 +++++++++++++++++ lib/General.ts | 45 ++++++++++++ lib/Instance.ts | 103 +++++++++++++++++++-------- lib/InstanceInterface.ts | 79 ++++++++++++++++++++- lib/Middleware.ts | 4 ++ lib/Model.ts | 72 ++++++++++++++----- lib/ModelCache.ts | 5 ++ lib/ModelHandlers.ts | 8 +++ lib/ModelHelpers.ts | 8 ++- lib/ModelInterfaces.ts | 12 ++++ lib/ModelOptions.ts | 108 ++++++++++++++++++++++++++--- lib/ModelSpecificInstance.ts | 15 +++- lib/Transforms.ts | 25 +++++++ lib/cacheControllers/IDDirector.ts | 6 ++ lib/caches/MemoryCache.ts | 6 ++ lib/caches/NoOpCache.ts | 7 ++ lib/middleware/Express.ts | 11 +++ lib/utils/ObjectID.ts | 13 ++++ lib/utils/Omnom.ts | 2 +- 21 files changed, 552 insertions(+), 56 deletions(-) create mode 100644 lib/Transforms.ts diff --git a/lib/Core.ts b/lib/Core.ts index effabe1..5cafdf6 100644 --- a/lib/Core.ts +++ b/lib/Core.ts @@ -18,6 +18,13 @@ import {Cache} from './Cache'; import {NoOpCache} from './caches/NoOpCache'; import {MemoryCache} from './caches/MemoryCache'; +/** + * The Iridium Core, responsible for managing the connection to the database as well + * as any plugins you are making use of. + * + * Generally you will subclass this to provide your own custom core with the models you + * make use of within your application. + */ export class Core { /** * Creates a new Iridium Core instance connected to the specified MongoDB instance diff --git a/lib/Cursor.ts b/lib/Cursor.ts index 89485c5..dedf099 100644 --- a/lib/Cursor.ts +++ b/lib/Cursor.ts @@ -5,7 +5,14 @@ import MongoDB = require('mongodb'); import Bluebird = require('bluebird'); import * as Index from './Index'; -export default class Cursor { +/** + * An Iridium collection cursor which allows the itteration through documents + * in the collection, automatically wrapping them in the correct instance type. + * + * @param TDocument The interface representing the collection's documents + * @param TInstance The interface or class used to represent the wrapped documents. + */ +export class Cursor { /** * Creates a new Iridium cursor which wraps a MongoDB cursor object * @param {Model} model The Iridium model that this cursor belongs to diff --git a/lib/Decorators.ts b/lib/Decorators.ts index 38c0da9..da97fb6 100644 --- a/lib/Decorators.ts +++ b/lib/Decorators.ts @@ -7,25 +7,69 @@ import {Index, IndexSpecification} from './Index'; import {Schema} from './Schema'; import {InstanceImplementation} from './InstanceInterface'; +/** + * Specifies the name of the collection to which this instance's documents should be sent. + * @param name The name of the MongoDB collection to store the documents in. + * + * This decorator replaces the use of the static collection property on instance implementation + * classes. If your transpiler does not support decorators then you are free to make use of the + * property instead. + */ export function Collection(name: string) { return function(target: InstanceImplementation) { target.collection = name; }; } +/** + * Specifies a MongoDB collection level index to be managed by Iridium for this instance type. + * More than one instance of this decorator may be used if you wish to specify multiple indexes. + * @param spec The formal index specification which defines the properties and ordering used in the index. + * @param options The options dictating the way in which the index behaves. + * + * This decorator replaces the use of the static indexes property on instance implementation + * classes. If your transpiler does not support decorators then you are free to make use of the + * property instead. + */ export function Index(spec: IndexSpecification, options?: MongoDB.IndexOptions) { return function(target: InstanceImplementation) { target.indexes = (target.indexes || []).concat({ spec: spec, options: options || {} }); } } +/** + * Specifies a custom validator to be made available for this collection's schema. + * More than one instance of this decorator may be used if you wish to specify multiple validators. + * @param forType The value in the schema which will be delegated to this function for validation. + * @param validate A function which calls this.assert(condition) to determine whether a schema node is valid or not. + * + * This decorator replaces the use of the static validators property on instance implementation + * classes. If your transpiler does not support decorators then you are free to make use of the + * property instead. + */ export function Validate(forType: any, validate: (schema: any, data: any, path: string) => Skmatc.Result) { return function(target: InstanceImplementation) { target.validators = (target.validators || []).concat(skmatc.create(schema => schema === forType, validate)); } } +/** + * Specifies the schema type for the property this decorator is applied to. This can be used to replace the + * static schema property on your instance. Multiple instances of this decorator can be applied, but no more + * than one per property. + * + * @param asType The schema validation type to make use of for this property + * @param required Whether this property is required to have a value or not, defaults to true. + */ export function Property(asType: any, required?: boolean): (target: { constructor: Function }, name: string) => void; +/** + * Specifies the schema type for a property with the given name on the class this decorator is applied to. This + * can either compliment or replace the static schema property on your instance class. + * + * @param name The name of the property that is being targetted + * @param asType The schema validation type to make use of for this property + * @param required Whether this property is required to have a value or not, defaults to true. + */ export function Property(name: string, asType: any, required?: boolean): (target: Function) => void; export function Property(...args: any[]): (target: any, name?: string) => void { let name = null, @@ -49,6 +93,17 @@ export function Property(...args: any[]): (target: any, name?: string) => void { } } +/** + * Specifies a custom transform to be applied to the property this decorator is applied to. + * + * @param fromDB The function used to convert values from the database for the application. + * @param toDB The function used to convert values from the application to the form used in the database. + * + * This decorator can either compliment or replace the static transforms property on your instance + * class, however only one transform can be applied to any property at a time. + * If your transpiler does not support decorators then you are free to make use of the + * property instead. + */ export function Transform(fromDB: (value: any) => any, toDB: (value: any) => any) { return function(target: any, property: string) { target.constructor.transforms = _.clone(target.constructor.transforms || {}) @@ -59,6 +114,14 @@ export function Transform(fromDB: (value: any) => any, toDB: (value: any) => any }; } + +/** + * Specifies that this property should be treated as an ObjectID, with the requisite validator and transforms. + * + * This decorator applies an ObjectID validator to the property, which ensures that values sent to the database + * are instances of the MongoDB ObjectID type, as well as applying a transform operation which converts ObjectIDs + * to strings for your application, and then converts strings back to ObjectIDs for the database. + */ export function ObjectID(target: { constructor: typeof Instance }, name: string) { Property(MongoDB.ObjectID)(target, name); Transform( diff --git a/lib/General.ts b/lib/General.ts index 0fe4bb1..d8a6728 100644 --- a/lib/General.ts +++ b/lib/General.ts @@ -1,21 +1,66 @@ /// + +/** + * A method which is called once an asynchronous operation has completed, an alternative + * to using Promises. + * @param T The type of object returned by the asynchronous operation. + */ export interface Callback { + /** + * @param err The error object, if one occurred, otherwise null if the operation completed successfully. + * @param object The result of the asynchronous operation if it completed successfully. If err is defined, the presence of this value is unknown. + */ (err: Error, object?: T): void; } +/** + * A method which is used to determine whether a value within a collection meets a set of criteria. + * @param T The type of item in the collection. + */ export interface Predicate { + /** + * @param object The value of the item in the collection + * @param key The key, if one is available, under which the item appeared within the collection + * @returns A true-y value if the item met the predicate conditions, false-y values if it did not. + */ (object: T, key?: string): boolean; } +/** + * A method which is called to retrieve a value of the given type. + * @param T The type of value to be retrieved. + */ export interface PropertyGetter { + /** + * Gets the current value of the property + * @returns The current value + */ (): T; } +/** + * A method which is called to set a value of the given type. + * @param T The type of value to set + */ export interface PropertySetter { + /** + * Sets the value to the provided one + * @param value The new value to set + */ (value: T): void; } +/** + * A compound property which provides either a getter, setter or both. + * @param T The type of objects stored in the property + */ export interface Property { + /** + * An optional getter which can be used to retrieve the property's value + */ get?: PropertyGetter; + /** + * An optional setter which can be used to set the property's value + */ set?: PropertySetter; } \ No newline at end of file diff --git a/lib/Instance.ts b/lib/Instance.ts index edb715e..643e49a 100644 --- a/lib/Instance.ts +++ b/lib/Instance.ts @@ -7,24 +7,35 @@ import * as General from './General'; import * as ModelInterfaces from './ModelInterfaces'; import * as Index from './Index'; import {Schema} from './Schema'; +import {Transforms} from './Transforms'; import _ = require('lodash'); import MongoDB = require('mongodb'); import Bluebird = require('bluebird'); import skmatc = require('skmatc'); +/** + * The default Iridium Instance implementation which provides methods for saving, refreshing and + * removing the wrapped document from the collection, as well as integrating with Omnom, our + * built in document diff processor which allows clean, atomic, document updates to be performed + * without needing to write the update queries yourself. + * + * @param TDocument The interface representing the structure of the documents in the collection. + * @param TInstance The type of instance which wraps the documents, generally the subclass of this class. + * + * This class will be subclassed automatically by Iridium to create a model specific instance + * which takes advantage of some of v8's optimizations to boost performance significantly. + * The instance returned by the model, and all of this instance's methods, will be of type + * TInstance - which should represent the merger of TSchema and IInstance for best results. + */ export class Instance { /** * Creates a new instance which represents the given document as a type of model - * @param {model.Model} model The model that the document represents - * @param {TSchema} document The document which should be wrapped by this instance - * @param {Boolean} isNew Whether the document is new (doesn't exist in the database) or not - * @param {Boolean} isPartial Whether the document has only a subset of its fields populated - * @description - * This class will be subclassed automatically by Iridium to create a model specific instance - * which takes advantage of some of v8's optimizations to boost performance significantly. - * The instance returned by the model, and all of this instance's methods, will be of type - * TInstance - which should represent the merger of TSchema and IInstance for best results. + * @param model The model that dictates the collection the document originated from as well as how validations are performed. + * @param document The document which should be wrapped by this instance + * @param isNew Whether the document is new (doesn't exist in the database) or not + * @param isPartial Whether the document has only a subset of its fields populated + * */ constructor(model: Model, document: TDocument, isNew: boolean = true, isPartial: boolean = false) { this._model = model; @@ -54,34 +65,72 @@ export class Instance { [name: string]: any; + /** + * A function which is called whenever a new document is in the process of being inserted into the database. + * @param document The document which will be inserted into the database. + */ static onCreating: (document: { _id?: any }) => void; + + /** + * A function which is called whenever a document of this type is received from the database, prior to it being + * wrapped by an Instance object. + * @param document The document that was retrieved from the database. + */ static onRetrieved: (document: { _id?: any }) => void; + + /** + * A function which is called whenever a new instance has been created to wrap a document. + * @param instance The instance which has been created. + */ static onReady: (instance: Instance<{ _id?: any }, Instance<{ _id?: any }, any>>) => void; + + /** + * A function which is called whenever an instance's save() method is called to allow you to interrogate and/or manipulate + * the changes which are being made. + * + * @param instance The instance to which the changes are being made + * @param changes The MongoDB change object describing the changes being made to the document. + */ static onSaving: (instance: Instance<{ _id?: any }, Instance<{ _id?: any }, any>>, changes: any) => void; + /** + * The name of the collection into which documents of this type are stored. + */ static collection: string; + /** + * The schema used to validate documents of this type before being stored in the database. + */ static schema: Schema = { _id: false }; + /** + * Additional which should be made available for use in the schema definition for this instance. + */ 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; } } = { + /** + * The transformations which should be applied to properties of documents of this type. + */ + static transforms: Transforms = { }; + /** + * The cache director used to derive unique cache keys for documents of this type. + */ static cache: CacheDirector; + + /** + * The indexes which should be managed by Iridium for the collection used by this type. + */ 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 @@ -269,16 +318,16 @@ export class Instance { /** * Retrieves the first element in an enumerable collection which matches the predicate - * @param {any[]} collection The collection from which to retrieve the element - * @param {function(any, Number): Boolean} predicate The function which determines whether to select an element - * @returns {any} + * @param collection The collection from which to retrieve the element + * @param predicate The function which determines whether to select an element + * @returns The first element in the array which matched the predicate. */ first(collection: T[], predicate: General.Predicate): T; /** * Retrieves the first element in an enumerable collection which matches the predicate - * @param {Object} collection The collection from which to retrieve the element - * @param {function(any, String): Boolean} predicate The function which determines whether to select an element - * @returns {any} + * @param collection The collection from which to retrieve the element + * @param predicate The function which determines whether to select an element + * @returns The first element in the object which matched the predicate. */ first(collection: { [key: string]: T }, predicate: General.Predicate): T; first(collection: T[]| { [key: string]: T }, predicate: General.Predicate): T { @@ -296,16 +345,16 @@ export class Instance { /** * Retrieves a number of elements from an enumerable collection which match the predicate - * @param {any[]} collection The collection from which elements will be plucked - * @param {function(any, Number): Boolean} predicate The function which determines the elements to be plucked - * @returns {any[]} + * @param collection The collection from which elements will be plucked + * @param predicate The function which determines the elements to be plucked + * @returns A new array containing the elements in the array which matched the predicate. */ select(collection: T[], predicate: General.Predicate): T[]; /** * Retrieves a number of elements from an enumerable collection which match the predicate - * @param {Object} collection The collection from which elements will be plucked - * @param {function(any, String): Boolean} predicate The function which determines the elements to be plucked - * @returns {Object} + * @param collection The collection from which elements will be plucked + * @param predicate The function which determines the elements to be plucked + * @returns An object with the properties from the collection which matched the predicate. */ select(collection: { [key: string]: T }, predicate: General.Predicate): { [key: string]: T }; select(collection: T[]| { [key: string]: T }, predicate: General.Predicate): any { diff --git a/lib/InstanceInterface.ts b/lib/InstanceInterface.ts index e0b20a6..a49a7c1 100644 --- a/lib/InstanceInterface.ts +++ b/lib/InstanceInterface.ts @@ -3,20 +3,97 @@ import {Schema} from './Schema'; import {Model} from './Model'; import * as Index from './Index'; import {CacheDirector} from './CacheDirector'; +import {Transforms} from './Transforms'; +/** + * This interface dictates the format of an instance class which wraps documents received + * from the database for a specific Iridium model. + * + * @param TDocument The interface representing the documents stored in the database, after being passed through the transforms pipeline. + * @param TInstance The type of object which is instantiated when calling this implementation's constructor. + * + * It is important to note that, when implementing this interface, each of the properties and methods + * should be exposed statically. That is, you would expose the collection property as a static variable + * on the instance implementation, since prototype methods and variables become available to consumers of the + * instance itself. + */ export interface InstanceImplementation { + /** + * A constructor which creates a new instance tied to the given model and representing the given document. + * @param model The Iridium Model which this instance should be tied to, gives the instance access to the database collection and any other context it requires. + * @param doc The document this instance should wrap from the database. This provides the data context for the instance. + * @param isNew Whether this document is known to exist in the database or not, for example, if the instance was generated from user input and hasn't been saved yet. + * @param isPartial Whether the document which has been given to this instance had any field restrictions imposed on it during the query, and may therefore only contain partial data. + */ new (model: Model, doc: TDocument, isNew?: boolean, isPartial?: boolean): TInstance; + /** + * The name of the database collection from which documents are retrieved, and to which they are stored. + */ collection: string; + + /** + * The database schematic used for validation of instances prior to storing them in the database. + * This schematic should follow the guides set out in skmatc's documentation, and is used whenever + * you insert a new document into the collection or save an instance using the default instance type. + * Operations like update() (and by extension, save() when using the update operations) cannot be checked + * by skmatc for consistency and as a result will not have their data validated - be careful when making + * use of them as a result. + */ schema: Schema; + + /** + * Any additional indexes on the collection which should be managed by Iridium. + * This field is optional, but if provided allows you to make use of the model's ensureIndexes() method + * to automatically generate all specified indexes. + */ indexes?: (Index.Index | Index.IndexSpecification)[]; + /** + * An optional method which will be called whenever a document is about to be inserted into the database, + * allowing you to set default values and do any preprocessing you wish prior to the document being inserted. + */ onCreating? (document: TDocument): void; + + /** + * An optional method which is called whenever a new document is received from the model's collection and + * prior to the document being wrapped, can be used to perform preprocessing if necessary - however we recommend + * you rather make use of transforms for that task. + */ onRetrieved? (document: TDocument): void; + + /** + * An optional method which is called whenever a new document for this model has been wrapped in an instance. + */ onReady? (instance: TInstance): void; + + /** + * An optional method which is called prior to saving an instance, it is provided with the instance itself as + * well as the proposed changes to the instance. This allows you to make additional changes, such as updating + * a lastChanged property on the document, or abort changes by throwing an error. + */ onSaving? (instance: TInstance, changes: any): void; + /** + * The cache controller used to determine whether a document may be cached, as well as deriving a unique cache + * key for the document and similarly, for a query. This works in concert with the cache implementation itself + * to ensure that documents are cached in an intelligent manner. By default this will simply make use of the + * document's _id field as the cache key - however that behaviour may be modified if you wish to query on other + * properties instead. + */ cache?: CacheDirector; + + /** + * Any additional validation types you wish to make available for use within this model's database schema. This + * allows you to validate using conditions otherwise not available within skmatc itself. For more information + * on implementing a validator, take a look at the skmatc documentation on GitHub. + */ validators?: Skmatc.Validator[]; - transforms?: { [property: string]: { fromDB: (value: any) => any; toDB: (value: any) => any; } }; + + /** + * Any transform operations you would like to perform on documents received from the database, or prior to being + * sent to the database. These may include things such as converting ObjectIDs to strings for the application, and + * then back to ObjectIDs once they return to the database. + */ + transforms?: Transforms; } \ No newline at end of file diff --git a/lib/Middleware.ts b/lib/Middleware.ts index 8c90655..b1d7c74 100644 --- a/lib/Middleware.ts +++ b/lib/Middleware.ts @@ -1,6 +1,10 @@ /// import {Core} from './Core'; +/** + * Middlewares provided by Iridium, such as the Express one, derive from this interface. + * @internal + */ export interface MiddlewareFactory { (core: Core): T; } \ No newline at end of file diff --git a/lib/Model.ts b/lib/Model.ts index a248b45..cdb5a08 100644 --- a/lib/Model.ts +++ b/lib/Model.ts @@ -12,29 +12,35 @@ import {Plugin} from './Plugins'; import {Cache} from './Cache'; import {CacheDirector} from './CacheDirector'; import * as General from './General'; -import Cursor from './Cursor'; +import {Cursor} from './Cursor'; import * as Index from './Index'; import * as ModelOptions from './ModelOptions'; -import Omnom from './utils/Omnom'; +import {Omnom} from './utils/Omnom'; import {ModelCache} from './ModelCache'; import {ModelHelpers} from './ModelHelpers'; import {ModelHandlers} from './ModelHandlers'; import * as ModelInterfaces from './ModelInterfaces'; import {ModelSpecificInstance} from './ModelSpecificInstance'; import {InstanceImplementation} from './InstanceInterface'; +import {Transforms} from './Transforms'; import * as AggregationPipeline from './Aggregate'; /** - * An Iridium Model which represents a structured MongoDB collection + * An Iridium Model which represents a structured MongoDB collection. + * Models expose the methods you will generally use to query those collections, and ensure that + * the results of those queries are returned as {TInstance} instances. + * + * @param TDocument The interface used to determine the schema of documents in the collection. + * @param TInstance The interface or class used to represent collection documents in the JS world. + * * @class */ export class Model { /** * Creates a new Iridium model representing a given ISchema and backed by a collection whose name is specified - * @param {Iridium} core The Iridium core that this model should use for database access - * @param {ModelInterfaces.InstanceImplementation} instanceType The class which will be instantiated for each document retrieved from the database - * @returns {Model} + * @param core The Iridium core that this model should use for database access + * @param instanceType The class which will be instantiated for each document retrieved from the database * @constructor */ constructor(core: Core, instanceType: InstanceImplementation) { @@ -50,6 +56,9 @@ export class Model { this.loadInternal(); } + /** + * Loads any externally available properties (generally accessed using public getters/setters). + */ private loadExternal(instanceType: InstanceImplementation) { this._collection = instanceType.collection; this._schema = instanceType.schema; @@ -73,12 +82,20 @@ export class Model { this._Instance = instanceType.bind(undefined, this); } + /** + * Loads any internally (protected/private) properties and helpers only used within Iridium itself. + */ private loadInternal() { this._cache = new ModelCache(this); this._helpers = new ModelHelpers(this); this._handlers = new ModelHandlers(this); } + /** + * Process any callbacks and plugin delegation for the creation of this model. + * It will generally be called whenever a new Iridium Core is created, however is + * more specifically tied to the lifespan of the models themselves. + */ private onNewModel() { this._core.plugins.forEach(plugin => plugin.newModel && plugin.newModel(this)); } @@ -86,7 +103,7 @@ export class Model { private _helpers: ModelHelpers; /** * Provides helper methods used by Iridium for common tasks - * @returns {ModelHelpers} + * @returns A set of helper methods which are used within Iridium for common tasks */ get helpers(): ModelHelpers { return this._helpers; @@ -95,7 +112,7 @@ export class Model { private _handlers: ModelHandlers; /** * Provides helper methods used by Iridium for hook delegation and common processes - * @returns {ModelHandlers} + * @returns A set of helper methods which perform common event and response handling tasks within Iridium. */ get handlers(): ModelHandlers { return this._handlers; @@ -104,8 +121,10 @@ export class Model { private _hooks: Hooks = {}; /** - * Gets the even hooks subscribed on this model for a number of different state changes - * @returns {Hooks} + * Gets the even hooks subscribed on this model for a number of different state changes. + * These hooks are primarily intended to allow lifecycle manipulation logic to be added + * in the user's model definition, allowing tasks such as the setting of default values + * or automatic client-side joins to take place. */ get hooks(): Hooks { return this._hooks; @@ -113,9 +132,14 @@ export class Model { private _schema: Schema; /** - * Gets the ISchema dictating the data structure represented by this model + * Gets the schema dictating the data structure represented by this model. + * The schema is used by skmatc to validate documents before saving to the database, however + * until MongoDB 3.1 becomes widely available (with server side validation support) we are + * limited in our ability to validate certain types of updates. As such, these validations + * act more as a data-integrity check than anything else, unless you purely make use of Omnom + * updates within instances. * @public - * @returns {schema} + * @returns The defined validation schema for this model */ get schema(): Schema { return this._schema; @@ -123,9 +147,9 @@ export class Model { private _core: Core; /** - * Gets the Iridium core that this model is associated with + * Gets the Iridium core that this model is associated with. * @public - * @returns {Iridium} + * @returns The Iridium core that this model is bound to */ get core(): Core { return this._core; @@ -133,7 +157,10 @@ export class Model { private _collection: string; /** - * Gets the underlying MongoDB collection from which this model's documents are retrieved + * Gets the underlying MongoDB collection from which this model's documents are retrieved. + * You can make use of this object if you require any low level access to the MongoDB collection, + * however we recommend you make use of the Iridium methods whereever possible, as we cannot + * guarantee the accuracy of the type definitions for the underlying MongoDB driver. * @public * @returns {Collection} */ @@ -187,20 +214,33 @@ export class Model { return this._Instance; } - private _transforms: { [property: string]: { fromDB: (value: any) => any; toDB: (value: any) => any; } }; + private _transforms: Transforms; + /** + * Gets the transforms which are applied whenever a document is received from the database, or + * prior to storing a document in the database. Tasks such as converting an ObjectID to a string + * and vice versa are all listed in this object. + */ get transforms() { return this._transforms; } private _validators: Skmatc.Validator[]; + /** + * Gets the custom validation types available for this model. These validators are added to the + * default skmatc validators, as well as those available through plugins, for use when checking + * your instances. + */ get validators() { return this._validators; } private _indexes: (Index.Index | Index.IndexSpecification)[]; + /** + * Gets the indexes which Iridium will manage on this model's database collection. + */ get indexes() { return this._indexes; } diff --git a/lib/ModelCache.ts b/lib/ModelCache.ts index 5113b8b..cc335b0 100644 --- a/lib/ModelCache.ts +++ b/lib/ModelCache.ts @@ -2,6 +2,11 @@ import {Model} from './Model'; import Bluebird = require('bluebird'); +/** + * A centralized class which ties the cache and cache directors together in a cohesive way + * for use by Iridium. + * @internal + */ export class ModelCache { constructor(public model: Model) { diff --git a/lib/ModelHandlers.ts b/lib/ModelHandlers.ts index 2bb976b..79b7ad0 100644 --- a/lib/ModelHandlers.ts +++ b/lib/ModelHandlers.ts @@ -9,6 +9,14 @@ import _ = require('lodash'); import MongoDB = require('mongodb'); import Bluebird = require('bluebird'); +/** + * Provides a number of methods which are used to handle events that occur within + * the Iridium workflow - such as what happens when a document is received from + * the database, or how to handle the creation of new documents and saving of instances. + * + * Mostly this is for cache support, wrapping and hook triggering. + * @internal + */ export class ModelHandlers { constructor(public model: Model) { diff --git a/lib/ModelHelpers.ts b/lib/ModelHelpers.ts index 454d38d..ad04677 100644 --- a/lib/ModelHelpers.ts +++ b/lib/ModelHelpers.ts @@ -2,10 +2,16 @@ import MongoDB = require('mongodb'); import {Model} from './Model'; import skmatc = require('skmatc'); -import Omnom from './utils/Omnom'; +import {Omnom} from './utils/Omnom'; import _ = require('lodash'); import Bluebird = require('bluebird'); +/** + * A number of helper methods used commonly within Iridium, they provide a means to transform, + * validate, wrap and diff instances and documents. By keeping these methods in one place we + * help to improve testability and reduce code duplication (mouse abuse) throughout the codebase. + * @internal + */ export class ModelHelpers { constructor(public model: Model) { this._validator = new skmatc(model.schema); diff --git a/lib/ModelInterfaces.ts b/lib/ModelInterfaces.ts index 4378b88..0ead466 100644 --- a/lib/ModelInterfaces.ts +++ b/lib/ModelInterfaces.ts @@ -1,4 +1,16 @@ /// +/** + * The interface to which a prepared instance constructor should conform. When called with a document + * object, it should instantiate a new instance of type TInstance which is associated with its parent + * model. + * + * This is primarily used internally for prepared model instance constructors. + * + * @param TDocument The interface used to describe the structure of the documents found in the database collection. + * @param TInstance The interface or class used to wrap the documents returned from the database. + * + * @internal + */ export interface ModelSpecificInstanceConstructor { new (doc: TDocument, isNew?: boolean, isPartial?: boolean): TInstance; } \ No newline at end of file diff --git a/lib/ModelOptions.ts b/lib/ModelOptions.ts index d8ff82f..bc2cbd1 100644 --- a/lib/ModelOptions.ts +++ b/lib/ModelOptions.ts @@ -5,6 +5,10 @@ import {Hooks} from './Hooks'; import {CacheDirector} from './CacheDirector'; import * as General from './General'; +/** + * Options which can be used to control the way in which a query is executed + * against the MongoDB database. + */ export interface QueryOptions { cache?: boolean; fields?: { [name: string]: number }; @@ -13,30 +17,118 @@ export interface QueryOptions { sort?: Index.IndexSpecification; } +/** + * Options which can be used to control the way in which a document is created + * on the MongoDB server. + */ export interface CreateOptions { - w?: any; + /** + * The write concern, can either be a number from 0 to the number of nodes within + * the cluster, or 'majority' if you would like to wait for the majority of nodes + * within the cluster to confirm the write before returning. + * + * It is recommended that you set this to 'majority', however in all situations + * where you mind if data is lost, you should set it to at least 1. + */ + w?: string | number; + + /** + * The timeout in milliseconds before the write will be aborted by the MongoDB server + * and an error response (if the write concern is non-zero) is returned to the client. + */ wtimeout?: number; + + /** + * Whether to wait for the write to be commited to the server's journal (flushed to disk) + * or not. By specifying 1 here, you imply w:1 - howver this can be combined with w:'majority' + * to give excellent write reliability within a cluster, even across failures. + */ j?: number; + + /** + * Whether or not to serialize JavaScript functions which are provided as values. For security + * reasons it is probably best to set this to false, however it may come in handy under certain + * circumstances. + */ serializeFunctions?: boolean; + + /** + * Whether to generate document ObjectIDs within the client library or on the server, it is recommended + * that you leave this to default (false) unless you are making thousands of inserts per second from + * a single node and experiencing _id collisions. + */ forceServerObjectId?: boolean; + + /** + * Whether to perform an upsert operation if the document already exists. + */ upsert?: boolean; + + /** + * Whether to store the resulting document in the Iridium document cache to boost later retrieval times. + */ cache?: boolean; } export interface UpdateOptions { - w?: any; + /** + * The write concern, can either be a number from 0 to the number of nodes within + * the cluster, or 'majority' if you would like to wait for the majority of nodes + * within the cluster to confirm the write before returning. + * + * It is recommended that you set this to 'majority', however in all situations + * where you mind if data is lost, you should set it to at least 1. + */ + w?: string | number; + + /** + * The timeout in milliseconds before the write will be aborted by the MongoDB server + * and an error response (if the write concern is non-zero) is returned to the client. + */ wtimeout?: number; + + /** + * Whether to wait for the write to be commited to the server's journal (flushed to disk) + * or not. By specifying 1 here, you imply w:1 - howver this can be combined with w:'majority' + * to give excellent write reliability within a cluster, even across failures. + */ j?: boolean; + + /** + * Whether to perform an upsert operation if the document already exists. This can be combined + * with $setOnInsert to automatically create documents which do not exist in the database prior + * to making changes - and can be very handy for high-throughput systems. + */ upsert?: boolean; } export interface RemoveOptions { - w?: any; + /** + * The write concern, can either be a number from 0 to the number of nodes within + * the cluster, or 'majority' if you would like to wait for the majority of nodes + * within the cluster to confirm the write before returning. + * + * It is recommended that you set this to 'majority', however in all situations + * where you mind if data is lost, you should set it to at least 1. + */ + w?: string | number; + + /** + * The timeout in milliseconds before the write will be aborted by the MongoDB server + * and an error response (if the write concern is non-zero) is returned to the client. + */ wtimeout?: number; - j?: boolean; + + /** + * Whether to wait for the write to be commited to the server's journal (flushed to disk) + * or not. By specifying 1 here, you imply w:1 - howver this can be combined with w:'majority' + * to give excellent write reliability within a cluster, even across failures. + */ + j?: number; + + /** + * Whether to only remove the first document in the collection or not, by default this is false + * and any document matching the conditions will be removed. + */ single?: boolean; -} - -export interface Transforms { - [property: string]: { fromDB: (value: any) => any; toDB: (value: any) => any; }; } \ No newline at end of file diff --git a/lib/ModelSpecificInstance.ts b/lib/ModelSpecificInstance.ts index fc8c35e..21306e9 100644 --- a/lib/ModelSpecificInstance.ts +++ b/lib/ModelSpecificInstance.ts @@ -1,10 +1,23 @@ /// import {Model} from './Model'; import {InstanceImplementation} from './InstanceInterface'; +import {ModelSpecificInstanceConstructor} from './ModelInterfaces'; import util = require('util'); import _ = require('lodash'); -export function ModelSpecificInstance(model: Model, instanceType: InstanceImplementation): new (doc: TDocument, isNew?: boolean, isPartial?: boolean) => TInstance { +/** + * Creates a new subclass of the given instanceType which correctly performs property transforms + * and associates the instance with the correct model when instantiated. + * + * @param TDocument The interface representing the structure of the documents found in the database. + * @param TInstance The interface or class representing the documents after they have been wrapped in an instance. + * + * @param model The model which instances should be associated with when the resulting constructor is used. + * @param instanceType The constructor used to create new instances of type TInstance. + * + * @internal + */ +export function ModelSpecificInstance(model: Model, instanceType: InstanceImplementation): ModelSpecificInstanceConstructor { var constructor = function (doc: TDocument, isNew?: boolean, isPartial?: boolean) { instanceType.call(this, model, doc, isNew, isPartial); }; diff --git a/lib/Transforms.ts b/lib/Transforms.ts new file mode 100644 index 0000000..514cd1c --- /dev/null +++ b/lib/Transforms.ts @@ -0,0 +1,25 @@ +/// +export interface Transforms { + [property:string]: PropertyTransform; +} + +/** + * Converts the value of a property to and from its database representation. + */ +export interface PropertyTransform { + /** + * Converts a property's value from its database representation into one + * suitable for the application. + * @param value The value stored in the MongoDB database document. + * @returns A derived value which is more useful to the application. + */ + fromDB(value: any): any; + + /** + * Converts a property's value into a representation more suitable for + * the database. + * @param value The value used by the application. + * @returns The database optimized representation of the value. + */ + toDB(value: any): any; +} \ No newline at end of file diff --git a/lib/cacheControllers/IDDirector.ts b/lib/cacheControllers/IDDirector.ts index f823b2a..eab3166 100644 --- a/lib/cacheControllers/IDDirector.ts +++ b/lib/cacheControllers/IDDirector.ts @@ -2,6 +2,12 @@ import {CacheDirector} from '../CacheDirector'; import MongoDB = require('mongodb'); +/** + * Caches documents using their _id field as the unique cache key. This + * is useful if you primarily query your documents using their _id field, + * however can be suboptimal (or even a complete waste) if you use different + * types of queries. + */ export class CacheOnID implements CacheDirector{ valid(object: { _id: any }) { return !!object._id; diff --git a/lib/caches/MemoryCache.ts b/lib/caches/MemoryCache.ts index 22f8a2f..bda0c4c 100644 --- a/lib/caches/MemoryCache.ts +++ b/lib/caches/MemoryCache.ts @@ -2,6 +2,12 @@ import Bluebird = require('bluebird'); import {Cache} from '../Cache'; +/** + * A cache implementation which stores documents in an in-memory cache. + * + * Be aware that this is an incredibly simplistic implementation which doesn't manage + * memory usage at all and is very likely NOT suitable for production use. + */ export class MemoryCache implements Cache { private cache: any = {}; diff --git a/lib/caches/NoOpCache.ts b/lib/caches/NoOpCache.ts index 3bedaa3..a898871 100644 --- a/lib/caches/NoOpCache.ts +++ b/lib/caches/NoOpCache.ts @@ -2,6 +2,13 @@ import {Cache} from '../Cache'; import Bluebird = require('bluebird'); +/** + * A cache implementation which does not cache any received documents + * and returns nothing when requested - mimicking an empty cache. + * + * This is the default cache used if one is not supplied and should + * not impose any significant performance overhead. + */ export class NoOpCache implements Cache { set(key: string, object: T): Bluebird { return Bluebird.resolve(object); diff --git a/lib/middleware/Express.ts b/lib/middleware/Express.ts index 2c407f5..8e4f8e3 100644 --- a/lib/middleware/Express.ts +++ b/lib/middleware/Express.ts @@ -3,6 +3,13 @@ import http = require('http'); import {MiddlewareFactory} from '../Middleware'; import {Core} from '../Core'; +/** + * A factory method which creates Express/Connect compatible middleware functions to inject + * a 'db' field on your request objects as well as ensuring that the Iridium Core is connected + * to a MongoDB database before handling any requests. + * + * @internal + */ export function ExpressMiddlewareFactory(core: Core): ExpressMiddleware { return function (req: http.ServerRequest, res: http.ServerResponse, next:(err?: Error, route?: String) => void) { core.connect().then(function() { @@ -14,6 +21,10 @@ export function ExpressMiddlewareFactory(core: Core): ExpressMiddleware { }; } +/** + * An Express/Connect compatible middleware function which injects req.db and ensures that the Iridium Core + * has an active database connection before continuing the request handling process. + */ export interface ExpressMiddleware { (req: http.ServerRequest, res: http.ServerResponse, next:(err?: Error, route?: String) => void); } \ No newline at end of file diff --git a/lib/utils/ObjectID.ts b/lib/utils/ObjectID.ts index 73d4ee1..cd6e8d3 100644 --- a/lib/utils/ObjectID.ts +++ b/lib/utils/ObjectID.ts @@ -1,6 +1,19 @@ /// import MongoDB = require('mongodb'); +/** + * Converts a string to an ObjectID instance - a shortcut for require('mongodb').ObjectID.createFromHexString + * + * @param value The string representation of the ObjectID you wish to create. + * @returns A MongoDB ObjectID instance equivalent to the string you provided. + * + * You should be aware that this method performs no validation on the received string, MongoDB's ObjectID requires + * that it either be a 12 byte UTF8 string, or a 24 byte hexadecimal string in order to be converted correctly. + * + * This method removes the need for your application to directly depend on MongoDB's Node.js client library, + * which helps clean up your code a bit and reduces the headache of maintaining two different versions of the + * library (since Iridium also has one). + */ export function toObjectID(value: string): MongoDB.ObjectID { return MongoDB.ObjectID.createFromHexString(value); } \ No newline at end of file diff --git a/lib/utils/Omnom.ts b/lib/utils/Omnom.ts index 7fd1c72..6ec13ab 100644 --- a/lib/utils/Omnom.ts +++ b/lib/utils/Omnom.ts @@ -2,7 +2,7 @@ import _ = require('lodash'); import MongoDB = require('mongodb'); -export default class Omnom { +export class Omnom { constructor(public options: { atomicNumbers?: boolean; } = {}) { From c60b030aca702250a5c1325f9e8f16f792632cbf Mon Sep 17 00:00:00 2001 From: Benjamin Pannell Date: Sun, 30 Aug 2015 20:03:58 +0200 Subject: [PATCH 07/22] Exclude documentation website from NPM module --- .npmignore | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.npmignore b/.npmignore index c2fc0aa..6ecaf28 100644 --- a/.npmignore +++ b/.npmignore @@ -17,4 +17,5 @@ Gruntfile.js .jshintrc .gitattributes .gitignore -typings/DefinitelyTyped \ No newline at end of file +typings/DefinitelyTyped +doc/ \ No newline at end of file From 006da28679923fdfdb74a901a69c8e43cddaa9b8 Mon Sep 17 00:00:00 2001 From: Benjamin Pannell Date: Sun, 30 Aug 2015 20:13:06 +0200 Subject: [PATCH 08/22] Made the doc directory a git submodule for the gh-pages branch --- .gitmodules | 4 ++++ doc | 1 + 2 files changed, 5 insertions(+) create mode 100644 .gitmodules create mode 160000 doc diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000..05dfe9c --- /dev/null +++ b/.gitmodules @@ -0,0 +1,4 @@ +[submodule "doc"] + path = doc + url = git@github.com:sierrasoftworks/iridium.git + branch = gh-pages diff --git a/doc b/doc new file mode 160000 index 0000000..2283158 --- /dev/null +++ b/doc @@ -0,0 +1 @@ +Subproject commit 22831589ad48297d7541dd98cba7f0bfae1b08da From 711c490fe2bdcf33484ce55827fc0ca281dea55a Mon Sep 17 00:00:00 2001 From: Benjamin Pannell Date: Sun, 30 Aug 2015 21:08:38 +0200 Subject: [PATCH 09/22] Added gulp script to automatically update documentation --- build/doc.js | 35 ++++++++++++++++++++++++++++++++--- build/version.js | 1 + 2 files changed, 33 insertions(+), 3 deletions(-) diff --git a/build/doc.js b/build/doc.js index a51100e..4731963 100644 --- a/build/doc.js +++ b/build/doc.js @@ -1,9 +1,39 @@ var gulp = require('gulp'), - typedoc = require('gulp-typedoc'); + git = require('gulp-git'), + typedoc = require('gulp-typedoc'), + path = require('path'), + runSequence = require('run-sequence'), + fs = require('fs'); var paths = require('./paths'); gulp.task('doc', function() { + return runSequence('doc-compile', 'doc-submodule', 'doc-commit'); +}); + +gulp.task('doc-submodule', function(cb) { + fs.writeFile('doc/.git', 'gitdir: ../.git/modules/doc', cb); +}); + +gulp.task('doc-commit', function(cb) { + runSequence('doc-commit-changes', 'doc-commit-newdocs', cb); +}); + +gulp.task('doc-commit-changes', function() { + return gulp.src('doc') + .pipe(git.commit('Updated documentation')); +}); + +gulp.task('doc-commit-newdocs', function() { + return gulp.src('.') + .pipe(git.commit('Updated documentation')); +}); + +gulp.task('doc-push', function(cb) { + git.push('origin', 'gh-pages', { cwd: 'doc' }, cb); +}); + +gulp.task('doc-compile', function() { return gulp.src(paths.docSourceFiles).pipe(typedoc({ module: 'commonjs', target: 'es5', @@ -14,7 +44,6 @@ gulp.task('doc', function() { name: "Iridium", plugin: ['decorator'], - ignoreCompilerErrors: true, - version: true + ignoreCompilerErrors: false })); }); \ No newline at end of file diff --git a/build/version.js b/build/version.js index 8cbc5c4..1347c11 100644 --- a/build/version.js +++ b/build/version.js @@ -46,6 +46,7 @@ gulp.task('version-push-tags', function (cb) { gulp.task('version', function (callback) { runSequence( 'postpublish', + 'doc', 'version-bump', 'version-commit', 'version-tag', From 3dcd9c808c7260d2c03d81bcd9acaf9e2b44d49b Mon Sep 17 00:00:00 2001 From: Benjamin Pannell Date: Sun, 30 Aug 2015 21:44:10 +0200 Subject: [PATCH 10/22] Updated script to only commit doc changes if there are changes to be committed --- build/doc.js | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/build/doc.js b/build/doc.js index 4731963..0d27507 100644 --- a/build/doc.js +++ b/build/doc.js @@ -16,17 +16,20 @@ gulp.task('doc-submodule', function(cb) { }); gulp.task('doc-commit', function(cb) { - runSequence('doc-commit-changes', 'doc-commit-newdocs', cb); + git.exec({ args: 'diff-files', quiet: true, cwd: 'doc' }, function(err, stdout) { + if(err && err.code === 1) runSequence('doc-commit-changes', 'doc-commit-newdocs', cb); + else cb(); + }); }); gulp.task('doc-commit-changes', function() { - return gulp.src('doc') - .pipe(git.commit('Updated documentation')); + return gulp.src('.', { cwd: 'doc' }) + .pipe(git.commit('Updated documentation', { options: '--quiet', cwd: 'doc', quiet: true })); }); gulp.task('doc-commit-newdocs', function() { return gulp.src('.') - .pipe(git.commit('Updated documentation')); + .pipe(git.commit('Updated documentation', { options: '--quiet', quiet: true })); }); gulp.task('doc-push', function(cb) { From 47213a964f2e33d8b24fdb7935ecdd2eed338996 Mon Sep 17 00:00:00 2001 From: Benjamin Pannell Date: Sun, 30 Aug 2015 21:45:06 +0200 Subject: [PATCH 11/22] Updated doc script to push changes to gh-pages branch --- build/doc.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build/doc.js b/build/doc.js index 0d27507..1b12da2 100644 --- a/build/doc.js +++ b/build/doc.js @@ -17,7 +17,7 @@ gulp.task('doc-submodule', function(cb) { gulp.task('doc-commit', function(cb) { git.exec({ args: 'diff-files', quiet: true, cwd: 'doc' }, function(err, stdout) { - if(err && err.code === 1) runSequence('doc-commit-changes', 'doc-commit-newdocs', cb); + if(err && err.code === 1) runSequence('doc-commit-changes', 'doc-commit-newdocs', 'doc-push', cb); else cb(); }); }); From d37c8558773a6bb945da87fd3c577e2561206c1f Mon Sep 17 00:00:00 2001 From: Benjamin Pannell Date: Sun, 30 Aug 2015 21:45:28 +0200 Subject: [PATCH 12/22] Updated documentation --- doc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc b/doc index 2283158..7882954 160000 --- a/doc +++ b/doc @@ -1 +1 @@ -Subproject commit 22831589ad48297d7541dd98cba7f0bfae1b08da +Subproject commit 7882954b319fe99814d9230fee77f8fe8a53dba0 From db7c92cc639f124d936cac05e701d1bc2eab5bf3 Mon Sep 17 00:00:00 2001 From: Benjamin Pannell Date: Sun, 30 Aug 2015 21:47:29 +0200 Subject: [PATCH 13/22] Refactored doc gulp script --- build/doc.js | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/build/doc.js b/build/doc.js index 1b12da2..53d765d 100644 --- a/build/doc.js +++ b/build/doc.js @@ -8,26 +8,30 @@ var gulp = require('gulp'), var paths = require('./paths'); gulp.task('doc', function() { - return runSequence('doc-compile', 'doc-submodule', 'doc-commit'); + return runSequence('doc-build', 'doc-publish'); +}); + +gulp.task('doc-build', function() { + return runSequence('doc-compile', 'doc-submodule'); }); gulp.task('doc-submodule', function(cb) { fs.writeFile('doc/.git', 'gitdir: ../.git/modules/doc', cb); }); -gulp.task('doc-commit', function(cb) { +gulp.task('doc-publish', function(cb) { git.exec({ args: 'diff-files', quiet: true, cwd: 'doc' }, function(err, stdout) { - if(err && err.code === 1) runSequence('doc-commit-changes', 'doc-commit-newdocs', 'doc-push', cb); + if(err && err.code === 1) runSequence('doc-commit', 'doc-update-ref', 'doc-push', cb); else cb(); }); }); -gulp.task('doc-commit-changes', function() { +gulp.task('doc-commit', function() { return gulp.src('.', { cwd: 'doc' }) .pipe(git.commit('Updated documentation', { options: '--quiet', cwd: 'doc', quiet: true })); }); -gulp.task('doc-commit-newdocs', function() { +gulp.task('doc-update-ref', function() { return gulp.src('.') .pipe(git.commit('Updated documentation', { options: '--quiet', quiet: true })); }); From f02e1773963d11e3f45f10e47c72c10a1d75aca6 Mon Sep 17 00:00:00 2001 From: Benjamin Pannell Date: Sun, 30 Aug 2015 22:06:00 +0200 Subject: [PATCH 14/22] Updated documentation --- build/doc.js | 20 ++++++++++++++------ doc | 2 +- 2 files changed, 15 insertions(+), 7 deletions(-) diff --git a/build/doc.js b/build/doc.js index 53d765d..397f8d4 100644 --- a/build/doc.js +++ b/build/doc.js @@ -12,32 +12,40 @@ gulp.task('doc', function() { }); gulp.task('doc-build', function() { - return runSequence('doc-compile', 'doc-submodule'); + return runSequence('doc-checkout', 'doc-compile', ['doc-submodule', 'doc-attributes']); +}); + +gulp.task('doc-checkout', function(cb) { + return git.checkout('gh-pages', { cwd: 'doc', quiet: true }, cb); }); gulp.task('doc-submodule', function(cb) { fs.writeFile('doc/.git', 'gitdir: ../.git/modules/doc', cb); }); + +gulp.task('doc-attributes', function(cb) { + fs.writeFile('doc/.gitattributes', '* text=auto', cb); +}); gulp.task('doc-publish', function(cb) { - git.exec({ args: 'diff-files', quiet: true, cwd: 'doc' }, function(err, stdout) { + git.exec({ args: 'diff-files --quiet', quiet: true, cwd: 'doc' }, function(err, stdout) { if(err && err.code === 1) runSequence('doc-commit', 'doc-update-ref', 'doc-push', cb); else cb(); }); }); gulp.task('doc-commit', function() { - return gulp.src('.', { cwd: 'doc' }) - .pipe(git.commit('Updated documentation', { options: '--quiet', cwd: 'doc', quiet: true })); + return gulp.src('**', { cwd: 'doc' }) + .pipe(git.commit('Updated documentation', { cwd: 'doc' })); }); gulp.task('doc-update-ref', function() { return gulp.src('.') - .pipe(git.commit('Updated documentation', { options: '--quiet', quiet: true })); + .pipe(git.commit('Updated documentation')); }); gulp.task('doc-push', function(cb) { - git.push('origin', 'gh-pages', { cwd: 'doc' }, cb); + git.push('origin', 'gh-pages', cb); }); gulp.task('doc-compile', function() { diff --git a/doc b/doc index 7882954..ed8b5da 160000 --- a/doc +++ b/doc @@ -1 +1 @@ -Subproject commit 7882954b319fe99814d9230fee77f8fe8a53dba0 +Subproject commit ed8b5dadfc09044d06c6d64b060a63a9dbf4c7cd From 7c9cf0df7f69a2cb62593acf3048e3d24b7de13e Mon Sep 17 00:00:00 2001 From: Benjamin Pannell Date: Sun, 30 Aug 2015 22:07:18 +0200 Subject: [PATCH 15/22] Updated documentation --- build/doc.js | 2 +- doc | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/build/doc.js b/build/doc.js index 397f8d4..eeffa55 100644 --- a/build/doc.js +++ b/build/doc.js @@ -45,7 +45,7 @@ gulp.task('doc-update-ref', function() { }); gulp.task('doc-push', function(cb) { - git.push('origin', 'gh-pages', cb); + git.push('origin', 'gh-pages', { cwd: 'doc' }, cb); }); gulp.task('doc-compile', function() { diff --git a/doc b/doc index ed8b5da..3afe2b2 160000 --- a/doc +++ b/doc @@ -1 +1 @@ -Subproject commit ed8b5dadfc09044d06c6d64b060a63a9dbf4c7cd +Subproject commit 3afe2b260ef0dc8bca7ba9bafbb28a5b246f8c24 From 7b29f332ad831fb5eca9719245c36a028e62de26 Mon Sep 17 00:00:00 2001 From: Benjamin Pannell Date: Sun, 30 Aug 2015 22:22:28 +0200 Subject: [PATCH 16/22] Changed the submodule URL for docs --- .gitmodules | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.gitmodules b/.gitmodules index 05dfe9c..0409a30 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,4 +1,4 @@ [submodule "doc"] path = doc - url = git@github.com:sierrasoftworks/iridium.git + url = git://github.com/SierraSoftworks/Iridium.git branch = gh-pages From 89725a41ded0b867ab1d387bc9b881c913721b11 Mon Sep 17 00:00:00 2001 From: Benjamin Pannell Date: Sun, 30 Aug 2015 22:26:57 +0200 Subject: [PATCH 17/22] Fix a little issue with CI tests --- build/ci.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build/ci.js b/build/ci.js index e70b436..ce54436 100644 --- a/build/ci.js +++ b/build/ci.js @@ -7,7 +7,7 @@ var path = require('path'); var paths = require('./paths'); gulp.task('ci', function () { - return runSequence('build', 'ci-test'); + return runSequence('postpublish','build', 'ci-test'); }); gulp.task('ci-test', function () { From 39524f718a12f24752d1ac03c5c8486bcbe5667c Mon Sep 17 00:00:00 2001 From: Benjamin Pannell Date: Sun, 30 Aug 2015 22:34:55 +0200 Subject: [PATCH 18/22] Fixed a number of broken test fixtures --- build/paths.js | 1 + dist/index.js | 22 ++---- dist/index.js.map | 2 +- dist/lib/Core.js | 17 +++-- dist/lib/Core.js.map | 2 +- dist/lib/Cursor.js | 9 ++- dist/lib/Cursor.js.map | 2 +- dist/lib/Decorators.js | 46 ++++++++++++ dist/lib/Decorators.js.map | 2 +- dist/lib/General.js.map | 2 +- dist/lib/Instance.js | 42 ++++++++--- dist/lib/Instance.js.map | 2 +- dist/lib/InstanceInterface.js.map | 2 +- dist/lib/Middleware.js.map | 2 +- dist/lib/Model.js | 81 +++++++++++++++------ dist/lib/Model.js.map | 2 +- dist/lib/ModelCache.js | 7 +- dist/lib/ModelCache.js.map | 2 +- dist/lib/ModelHandlers.js | 10 ++- dist/lib/ModelHandlers.js.map | 2 +- dist/lib/ModelHelpers.js | 10 ++- dist/lib/ModelHelpers.js.map | 2 +- dist/lib/ModelInterfaces.js.map | 2 +- dist/lib/ModelOptions.js.map | 2 +- dist/lib/ModelSpecificInstance.js | 14 +++- dist/lib/ModelSpecificInstance.js.map | 2 +- dist/lib/Plugins.js.map | 2 +- dist/lib/Transforms.js | 3 + dist/lib/Transforms.js.map | 1 + dist/lib/cacheControllers/IDDirector.js | 22 ++++-- dist/lib/cacheControllers/IDDirector.js.map | 2 +- dist/lib/caches/MemoryCache.js | 8 +- dist/lib/caches/MemoryCache.js.map | 2 +- dist/lib/caches/NoOpCache.js | 9 ++- dist/lib/caches/NoOpCache.js.map | 2 +- dist/lib/middleware/Express.js | 9 ++- dist/lib/middleware/Express.js.map | 2 +- dist/lib/utils/ObjectID.js | 13 ++++ dist/lib/utils/ObjectID.js.map | 2 +- dist/lib/utils/Omnom.js | 2 +- dist/lib/utils/Omnom.js.map | 2 +- index.ts | 19 ++--- test/Aggregate.ts | 2 +- test/Model.ts | 3 +- test/Omnom.ts | 2 +- 45 files changed, 291 insertions(+), 105 deletions(-) create mode 100644 dist/lib/Transforms.js create mode 100644 dist/lib/Transforms.js.map diff --git a/build/paths.js b/build/paths.js index d461b0f..1163216 100644 --- a/build/paths.js +++ b/build/paths.js @@ -26,6 +26,7 @@ module.exports = { "lib/ModelOptions.ts", "lib/Configuration.ts", "lib/Hooks.ts", + "lib/Transforms.ts", "lib/caches/MemoryCache.ts", "lib/caches/NoOpCache.ts", diff --git a/dist/index.js b/dist/index.js index a8af2c9..db3a407 100644 --- a/dist/index.js +++ b/dist/index.js @@ -1,12 +1,9 @@ function __export(m) { for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; } -var Core_1 = require('./lib/Core'); -exports.Core = Core_1.default; -var Model_1 = require('./lib/Model'); -exports.Model = Model_1.default; -var Instance_1 = require('./lib/Instance'); -exports.Instance = Instance_1.default; +__export(require('./lib/Core')); +__export(require('./lib/Model')); +__export(require('./lib/Instance')); __export(require('./lib/Decorators')); __export(require('./lib/Plugins')); __export(require('./lib/Schema')); @@ -15,13 +12,10 @@ __export(require('./lib/CacheDirector')); __export(require('./lib/ModelOptions')); __export(require('./lib/Configuration')); __export(require('./lib/Hooks')); -var MemoryCache_1 = require('./lib/caches/MemoryCache'); -exports.MemoryCache = MemoryCache_1.default; -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; +__export(require('./lib/Transforms')); +__export(require('./lib/caches/MemoryCache')); +__export(require('./lib/caches/NoOpCache')); +__export(require('./lib/cacheControllers/IDDirector')); +__export(require('./lib/utils/ObjectID')); //# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/dist/index.js.map b/dist/index.js.map index 7e3cc62..f73fc6b 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;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 +{"version":3,"sources":["index.ts"],"names":[],"mappings":";;;AAAA,iBAAc,YAAY,CAAC,EAAA;AAC3B,iBAAc,aAAa,CAAC,EAAA;AAC5B,iBAAc,gBAAgB,CAAC,EAAA;AAE/B,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;AAC5B,iBAAc,kBAAkB,CAAC,EAAA;AAEjC,iBAAc,0BAA0B,CAAC,EAAA;AACzC,iBAAc,wBAAwB,CAAC,EAAA;AAEvC,iBAAc,mCAAmC,CAAC,EAAA;AAElD,iBAAc,sBAAsB,CAAC,EAAA","file":"index.js","sourcesContent":["export * from './lib/Core';\r\nexport * from './lib/Model';\r\nexport * from './lib/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\nexport * from './lib/Transforms';\r\n\r\nexport * from './lib/caches/MemoryCache';\r\nexport * from './lib/caches/NoOpCache';\r\n\r\nexport * from './lib/cacheControllers/IDDirector';\r\n\r\nexport * from './lib/utils/ObjectID';\r\n"],"sourceRoot":"/source/"} \ No newline at end of file diff --git a/dist/lib/Core.js b/dist/lib/Core.js index bf2fa90..4f112dd 100644 --- a/dist/lib/Core.js +++ b/dist/lib/Core.js @@ -4,11 +4,18 @@ var MongoDB = require('mongodb'); var _ = require('lodash'); var Express_1 = require('./middleware/Express'); var NoOpCache_1 = require('./caches/NoOpCache'); -var mongoConnectAsyc = Bluebird.promisify(MongoDB.MongoClient.connect); +/** + * The Iridium Core, responsible for managing the connection to the database as well + * as any plugins you are making use of. + * + * Generally you will subclass this to provide your own custom core with the models you + * make use of within your application. + */ var Core = (function () { function Core(uri, config) { + this.mongoConnectAsyc = Bluebird.promisify(MongoDB.MongoClient.connect); this._plugins = []; - this._cache = new NoOpCache_1.default(); + this._cache = new NoOpCache_1.NoOpCache(); var args = Array.prototype.slice.call(arguments, 0); uri = config = null; for (var i = 0; i < args.length; i++) { @@ -135,7 +142,7 @@ var Core = (function () { return _this._connection; if (_this._connectPromise) return _this._connectPromise; - return _this._connectPromise = mongoConnectAsyc(_this.url); + return _this._connectPromise = _this.mongoConnectAsyc(_this.url); }).then(function (db) { _this._connection = db; _this._connectPromise = null; @@ -166,10 +173,10 @@ var Core = (function () { * @returns {Iridium.ExpressMiddleware} */ Core.prototype.express = function () { - return Express_1.default(this); + return Express_1.ExpressMiddlewareFactory(this); }; return Core; })(); -exports.default = Core; +exports.Core = Core; //# sourceMappingURL=../lib/Core.js.map \ No newline at end of file diff --git a/dist/lib/Core.js.map b/dist/lib/Core.js.map index bf26fc8..f4049bc 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,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A,CAACA,QAAQA,CAACA,MAAMA,CAACA,GAAGA,CAACA,CAACA;QAChCA,CAACA,CAACA,CAACA,OAAOA,CAACA,QAAQA,CAACA,CAACA;IACzBA,CAACA;IAEDR;;;OAGGA;IACHA,oBAAKA,GAALA;QAAAS,iBAQCA;QAPGA,MAAMA,CAACA,QAAQA,CAACA,IAAIA,CAACA,IAAIA,CAACA,CAACA,IAAIA,CAACA;YAC5BA,EAAEA,CAACA,CAACA,CAACA,KAAIA,CAACA,WAAWA,CAACA;gBAACA,MAAMA,CAACA,KAAIA,CAACA;YACnCA,IAAIA,IAAIA,GAAeA,KAAIA,CAACA,WAAWA,CAACA;YACxCA,KAAIA,CAACA,WAAWA,GAAGA,IAAIA,CAACA;YACxBA,IAAIA,CAACA,KAAKA,EAAEA,CAACA;YACbA,MAAMA,CAACA,KAAIA,CAACA;QAChBA,CAACA,CAACA,CAACA;IACPA,CAACA;IAEDT;;;;OAIGA;IACHA,sBAAOA,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 +{"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,wBAAuC,sBAAsB,CAAC,CAAA;AAG9D,0BAAwB,oBAAoB,CAAC,CAAA;AAG7C;;;;;;GAMG;AACH;IAcIA,cAAYA,GAA2BA,EAAEA,MAAsBA;QAiBvDC,qBAAgBA,GAAGA,QAAQA,CAACA,SAASA,CAACA,OAAOA,CAACA,WAAWA,CAACA,OAAOA,CAACA,CAACA;QAEnEA,aAAQA,GAAaA,EAAEA,CAACA;QAIxBA,WAAMA,GAAUA,IAAIA,qBAASA,EAAEA,CAACA;QArBpCA,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,OAA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ACA,GAAGA;YACHA,KAAIA,CAACA,eAAeA,GAAGA,IAAIA,CAACA;YAC5BA,MAAMA,CAACA,QAAQA,CAACA,MAAMA,CAACA,GAAGA,CAACA,CAACA;QAChCA,CAACA,CAACA,CAACA,OAAOA,CAACA,QAAQA,CAACA,CAACA;IACzBA,CAACA;IAEDR;;;OAGGA;IACHA,oBAAKA,GAALA;QAAAS,iBAQCA;QAPGA,MAAMA,CAACA,QAAQA,CAACA,IAAIA,CAACA,IAAIA,CAACA,CAACA,IAAIA,CAACA;YAC5BA,EAAEA,CAACA,CAACA,CAACA,KAAIA,CAACA,WAAWA,CAACA;gBAACA,MAAMA,CAACA,KAAIA,CAACA;YACnCA,IAAIA,IAAIA,GAAeA,KAAIA,CAACA,WAAWA,CAACA;YACxCA,KAAIA,CAACA,WAAWA,GAAGA,IAAIA,CAACA;YACxBA,IAAIA,CAACA,KAAKA,EAAEA,CAACA;YACbA,MAAMA,CAACA,KAAIA,CAACA;QAChBA,CAACA,CAACA,CAACA;IACPA,CAACA;IAEDT;;;;OAIGA;IACHA,sBAAOA,GAAPA;QACIU,MAAMA,CAACA,kCAAwBA,CAACA,IAAIA,CAACA,CAACA;IAC1CA,CAACA;IACLV,WAACA;AAADA,CAhLA,AAgLCA,IAAA;AAhLY,YAAI,OAgLhB,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\n/**\r\n * The Iridium Core, responsible for managing the connection to the database as well\r\n * as any plugins you are making use of.\r\n * \r\n * Generally you will subclass this to provide your own custom core with the models you\r\n * make use of within your application.\r\n */\r\nexport class Core {\r\n /**\r\n * Creates a new Iridium Core instance connected to the specified MongoDB instance\r\n * @param {Iridium.IridiumConfiguration} config The config object defining the database to connect to\r\n * @constructs Core\r\n */\r\n constructor(config: Configuration);\r\n /**\r\n * Creates a new Iridium Core instance connected to the specified MongoDB instance\r\n * @param {String} url The URL of the MongoDB instance to connect to\r\n * @param {Iridium.IridiumConfiguration} config The config object made available as settings\r\n * @constructs Core\r\n */\r\n constructor(uri: string, config?: Configuration);\r\n constructor(uri: string | Configuration, config?: Configuration) {\r\n\r\n var args = Array.prototype.slice.call(arguments, 0);\r\n uri = config = null;\r\n for (var i = 0; i < args.length; i++) {\r\n if (typeof args[i] == 'string')\r\n uri = args[i];\r\n else if (typeof args[i] == 'object')\r\n config = args[i];\r\n }\r\n\r\n if (!uri && !config) throw new Error(\"Expected either a URI or config object to be supplied when initializing Iridium\");\r\n\r\n this._url = uri;\r\n this._config = config;\r\n }\r\n \r\n private mongoConnectAsyc = Bluebird.promisify(MongoDB.MongoClient.connect);\r\n \r\n private _plugins: Plugin[] = [];\r\n private _url: string;\r\n private _config: Configuration;\r\n private _connection: MongoDB.Db;\r\n private _cache: Cache = new NoOpCache();\r\n\r\n private _connectPromise: Bluebird;\r\n\r\n /**\r\n * Gets the plugins registered with this Iridium Core\r\n * @returns {[Iridium.Plugin]}\r\n */\r\n get plugins(): Plugin[] {\r\n return this._plugins;\r\n }\r\n\r\n /**\r\n * Gets the configuration specified in the construction of this\r\n * Iridium Core.\r\n * @returns {Iridium.Configuration}\r\n */\r\n get settings(): Configuration {\r\n return this._config;\r\n }\r\n\r\n /**\r\n * Gets the currently active database connection for this Iridium\r\n * Core.\r\n * @returns {MongoDB.Db}\r\n */\r\n get connection(): MongoDB.Db {\r\n return this._connection;\r\n }\r\n\r\n /**\r\n * Gets the URL used to connect to MongoDB\r\n * @returns {String}\r\n */\r\n get url(): string {\r\n if (this._url) return this._url;\r\n var url: string = 'mongodb://';\r\n\r\n if (this._config.username) {\r\n url += this._config.username;\r\n if (this._config.password)\r\n url += ':' + this._config.password;\r\n url += '@';\r\n }\r\n\r\n var hosts = [];\r\n\r\n if (this._config.host) {\r\n if (this._config.port)\r\n hosts.push(this._config.host + ':' + this._config.port);\r\n else\r\n hosts.push(this._config.host);\r\n }\r\n\r\n if (this._config.hosts) {\r\n _.each(this._config.hosts, (host) => {\r\n if (host.port)\r\n hosts.push(host.address + ':' + host.port);\r\n else if(this._config.port)\r\n hosts.push(host.address + ':' + this._config.port);\r\n else\r\n hosts.push(host.address);\r\n });\r\n }\r\n\r\n if (hosts.length)\r\n url += _.uniq(hosts).join(',');\r\n else\r\n url += 'localhost';\r\n\r\n url += '/' + this._config.database;\r\n\r\n return url;\r\n }\r\n\r\n /**\r\n * Gets the cache used to store objects retrieved from the database for performance reasons\r\n * @returns {cache}\r\n */\r\n get cache(): Cache {\r\n return this._cache;\r\n }\r\n\r\n set cache(value: Cache) {\r\n this._cache = value;\r\n }\r\n\r\n /**\r\n * Registers a new plugin with this Iridium Core\r\n * @param {Iridium.Plugin} plugin The plugin to register with this Iridium Core\r\n * @returns {Iridium.Core}\r\n */\r\n register(plugin: Plugin): Core {\r\n this.plugins.push(plugin);\r\n return this;\r\n }\r\n\r\n /**\r\n * Connects to the database server specified in the provided configuration\r\n * @param {function(Error, Iridium.Core)} [callback] A callback to be triggered once the connection is established.\r\n * @returns {Promise}\r\n */\r\n connect(callback?: (err: Error, core: Core) => any): Bluebird {\r\n return Bluebird.bind(this).then(() => {\r\n if (this._connection) return this._connection;\r\n if (this._connectPromise) return this._connectPromise;\r\n return this._connectPromise = this.mongoConnectAsyc(this.url);\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/dist/lib/Cursor.js b/dist/lib/Cursor.js index f0482b0..9418db3 100644 --- a/dist/lib/Cursor.js +++ b/dist/lib/Cursor.js @@ -1,4 +1,11 @@ var Bluebird = require('bluebird'); +/** + * An Iridium collection cursor which allows the itteration through documents + * in the collection, automatically wrapping them in the correct instance type. + * + * @param TDocument The interface representing the collection's documents + * @param TInstance The interface or class used to represent the wrapped documents. + */ var Cursor = (function () { /** * Creates a new Iridium cursor which wraps a MongoDB cursor object @@ -139,6 +146,6 @@ var Cursor = (function () { }; return Cursor; })(); -exports.default = Cursor; +exports.Cursor = Cursor; //# sourceMappingURL=../lib/Cursor.js.map \ No newline at end of file diff --git a/dist/lib/Cursor.js.map b/dist/lib/Cursor.js.map index f201972..a7e3c05 100644 --- a/dist/lib/Cursor.js.map +++ b/dist/lib/Cursor.js.map @@ -1 +1 @@ -{"version":3,"sources":["lib/Cursor.ts"],"names":["Cursor","Cursor.constructor","Cursor.count","Cursor.forEach","Cursor.map","Cursor.toArray","Cursor.next","Cursor.rewind","Cursor.sort","Cursor.limit","Cursor.skip"],"mappings":"AAIA,IAAO,QAAQ,WAAW,UAAU,CAAC,CAAC;AAGtC;IACIA;;;;;;OAMGA;IACHA,gBAAoBA,KAAkCA,EAAUA,UAAeA,EAASA,MAAsBA;QAA1FC,UAAKA,GAALA,KAAKA,CAA6BA;QAAUA,eAAUA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\nimport Model from './Model';\r\nimport General = require('./General');\r\nimport MongoDB = require('mongodb');\r\nimport Bluebird = require('bluebird');\r\nimport * as Index from './Index';\r\n\r\nexport default class Cursor {\r\n /**\r\n * Creates a new Iridium cursor which wraps a MongoDB cursor object\r\n * @param {Model} model The Iridium model that this cursor belongs to\r\n * @param {Object} conditions The conditions that resulte in this cursor being created\r\n * @param {MongoDB.Cursor} cursor The MongoDB native cursor object to be wrapped\r\n * @constructor\r\n */\r\n constructor(private model: Model, private conditions: any, public cursor: MongoDB.Cursor) {\r\n\r\n }\r\n\r\n /**\r\n * Counts the number of documents which are matched by this cursor\r\n * @param {function(Error, Number)} callback A callback which is triggered when the result is available\r\n * @return {Promise} A promise which will resolve with the number of documents matched by this cursor\r\n */\r\n count(callback?: General.Callback): Bluebird {\r\n return new Bluebird((resolve, reject) => {\r\n this.cursor.count(true,(err, count) => {\r\n if (err) return reject(err);\r\n return resolve(count);\r\n });\r\n }).nodeify(callback);\r\n }\r\n\r\n /**\r\n * Runs the specified handler over each instance in the query results\r\n * @param {function(Instance)} handler The handler which is triggered for each element in the query\r\n * @param {function(Error)} callback A callback which is triggered when all operations have been dispatched\r\n * @return {Promise} A promise which is resolved when all operations have been dispatched\r\n */\r\n forEach(handler: (instance: TInstance) => void, callback?: General.Callback): Bluebird {\r\n var helpers = this.model.helpers;\r\n return new Bluebird((resolve, reject) => {\r\n this.cursor.forEach((item: TDocument) => {\r\n this.model.handlers.documentReceived(this.conditions, item, function () { return helpers.wrapDocument.apply(helpers, arguments); }).then(handler);\r\n },(err) => {\r\n if (err) return reject(err);\r\n return resolve(null);\r\n });\r\n }).nodeify(callback);\r\n }\r\n\r\n /**\r\n * Runs the specified transform over each instance in the query results and returns the resulting transformed objects\r\n * @param {function(Instance): TResult} transform A handler which is used to transform the result objects\r\n * @param {function(Error, TResult[])} callback A callback which is triggered when the transformations are completed\r\n * @return {Promise} A promise which is fulfilled with the results of the transformations\r\n */\r\n map(transform: (instance: TInstance) => TResult | Bluebird, callback?: General.Callback): Bluebird {\r\n var helpers = this.model.helpers;\r\n return new Bluebird((resolve, reject) => {\r\n var promises: Bluebird[] = [];\r\n this.cursor.forEach((item: TDocument) => {\r\n promises.push(this.model.handlers.documentReceived(this.conditions, item, function () { return helpers.wrapDocument.apply(helpers, arguments); })\r\n .then(<(instance) => TResult>transform));\r\n },(err) => {\r\n if (err) return reject(err);\r\n return resolve(Bluebird.all(promises));\r\n });\r\n }).nodeify(callback);\r\n }\r\n\r\n /**\r\n * Retrieves all matching instances and returns them in an array\r\n * @param {function(Error, TInstance[])} callback A callback which is triggered with the resulting instances\r\n * @return {Promise} A promise which resolves with the instances returned by the query\r\n */\r\n toArray(callback?: General.Callback): Bluebird {\r\n var helpers = this.model.helpers;\r\n return new Bluebird((resolve, reject) => {\r\n this.cursor.toArray((err, results: any[]) => {\r\n if (err) return reject(err);\r\n return resolve(results);\r\n });\r\n }).map((document) => {\r\n return this.model.handlers.documentReceived(this.conditions, document, function () { return helpers.wrapDocument.apply(helpers, arguments); });\r\n }).nodeify(callback);\r\n }\r\n\r\n /**\r\n * Retrieves the next item in the results list\r\n * @param {function(Error, TInstance)} callback A callback which is triggered when the next item becomes available\r\n * @return {Promise} A promise which is resolved with the next item\r\n */\r\n next(callback?: General.Callback): Bluebird {\r\n return new Bluebird((resolve, reject) => {\r\n this.cursor.next((err, result: any) => {\r\n if (err) return reject(err);\r\n return resolve(result);\r\n });\r\n }).then((document) => {\r\n if (!document) return Bluebird.resolve(null);\r\n return this.model.handlers.documentReceived(this.conditions, document,(document, isNew?, isPartial?) => this.model.helpers.wrapDocument(document, isNew, isPartial));\r\n }).nodeify(callback);\r\n }\r\n\r\n /**\r\n * Returns a new cursor which behaves the same as this one did before any results were retrieved\r\n * @return {Cursor} The new cursor which starts at the beginning of the results\r\n */\r\n rewind(): Cursor {\r\n this.cursor.rewind();\r\n return this;\r\n }\r\n\r\n /**\r\n * Returns a new cursor which sorts its results by the given index expression\r\n * @param {model.IndexSpecification} sortExpression The index expression dictating the sort order and direction to use\r\n * @return {Cursor} The new cursor which sorts its results by the sortExpression\r\n */\r\n sort(sortExpression: Index.IndexSpecification): Cursor {\r\n return new Cursor(this.model, this.conditions, this.cursor.sort(sortExpression));\r\n }\r\n\r\n /**\r\n * Returns a new cursor which limits the number of returned results\r\n * @param {Number} limit The maximum number of results to return\r\n * @return {Cursor} The new cursor which will return a maximum number of results\r\n */\r\n limit(limit: number): Cursor {\r\n return new Cursor(this.model, this.conditions, this.cursor.limit(limit));\r\n }\r\n\r\n /**\r\n * Returns a new cursor which skips a number of results before it begins\r\n * returning any.\r\n * @param {Number} skip The number of results to skip before the cursor beings returning\r\n * @return {Cursor} The new cursor which skips a number of results\r\n */\r\n skip(skip: number): Cursor {\r\n return new Cursor(this.model, this.conditions, this.cursor.skip(skip));\r\n }\r\n}"],"sourceRoot":"/source/"} \ No newline at end of file +{"version":3,"sources":["lib/Cursor.ts"],"names":["Cursor","Cursor.constructor","Cursor.count","Cursor.forEach","Cursor.map","Cursor.toArray","Cursor.next","Cursor.rewind","Cursor.sort","Cursor.limit","Cursor.skip"],"mappings":"AAIA,IAAO,QAAQ,WAAW,UAAU,CAAC,CAAC;AAGtC;;;;;;GAMG;AACH;IACIA;;;;;;OAMGA;IACHA,gBAAoBA,KAAkCA,EAAUA,UAAeA,EAASA,MAAsBA;QAA1FC,UAAKA,GAALA,KAAKA,CAA6BA;QAAUA,eAAUA,GAAVA,UAAUA,CAAKA;QAASA,WAAMA,GAANA,MAAMA,CAAgBA;IAE9GA,CAACA;IAEDD;;;;OAIGA;IACHA,sBAAKA,GAALA,UAAMA,QAAmCA;QAAzCE,iBAOCA;QANGA,MAAMA,CAACA,IAAIA,QAAQA,CAASA,UAACA,OAAOA,EAAEA,MAAMA;YACxCA,KAAIA,CAACA,MAAMA,CAACA,KAAKA,CAACA,IAAIA,EAACA,UAACA,GAAGA,EAAEA,KAAKA;gBAC9BA,EAAEA,CAACA,CAACA,GAAGA,CAACA;oBAACA,M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GAANA;QACIO,IAAIA,CAACA,MAAMA,CAACA,MAAMA,EAAEA,CAACA;QACrBA,MAAMA,CAACA,IAAIA,CAACA;IAChBA,CAACA;IAEDP;;;;OAIGA;IACHA,qBAAIA,GAAJA,UAAKA,cAAwCA;QACzCQ,MAAMA,CAACA,IAAIA,MAAMA,CAACA,IAAIA,CAACA,KAAKA,EAAEA,IAAIA,CAACA,UAAUA,EAAEA,IAAIA,CAACA,MAAMA,CAACA,IAAIA,CAACA,cAAcA,CAACA,CAACA,CAACA;IACrFA,CAACA;IAEDR;;;;OAIGA;IACHA,sBAAKA,GAALA,UAAMA,KAAaA;QACfS,MAAMA,CAACA,IAAIA,MAAMA,CAACA,IAAIA,CAACA,KAAKA,EAAEA,IAAIA,CAACA,UAAUA,EAAEA,IAAIA,CAACA,MAAMA,CAACA,KAAKA,CAACA,KAAKA,CAACA,CAACA,CAACA;IAC7EA,CAACA;IAEDT;;;;;OAKGA;IACHA,qBAAIA,GAAJA,UAAKA,IAAYA;QACbU,MAAMA,CAACA,IAAIA,MAAMA,CAACA,IAAIA,CAACA,KAAKA,EAAEA,IAAIA,CAACA,UAAUA,EAAEA,IAAIA,CAACA,MAAMA,CAACA,IAAIA,CAACA,IAAIA,CAACA,CAACA,CAACA;IAC3EA,CAACA;IACLV,aAACA;AAADA,CAtIA,AAsICA,IAAA;AAtIY,cAAM,SAsIlB,CAAA","file":"lib/Cursor.js","sourcesContent":["/// \r\nimport {Model} from './Model';\r\nimport General = require('./General');\r\nimport MongoDB = require('mongodb');\r\nimport Bluebird = require('bluebird');\r\nimport * as Index from './Index';\r\n\r\n/**\r\n * An Iridium collection cursor which allows the itteration through documents\r\n * in the collection, automatically wrapping them in the correct instance type.\r\n * \r\n * @param TDocument The interface representing the collection's documents\r\n * @param TInstance The interface or class used to represent the wrapped documents.\r\n */\r\nexport class Cursor {\r\n /**\r\n * Creates a new Iridium cursor which wraps a MongoDB cursor object\r\n * @param {Model} model The Iridium model that this cursor belongs to\r\n * @param {Object} conditions The conditions that resulte in this cursor being created\r\n * @param {MongoDB.Cursor} cursor The MongoDB native cursor object to be wrapped\r\n * @constructor\r\n */\r\n constructor(private model: Model, private conditions: any, public cursor: MongoDB.Cursor) {\r\n\r\n }\r\n\r\n /**\r\n * Counts the number of documents which are matched by this cursor\r\n * @param {function(Error, Number)} callback A callback which is triggered when the result is available\r\n * @return {Promise} A promise which will resolve with the number of documents matched by this cursor\r\n */\r\n count(callback?: General.Callback): Bluebird {\r\n return new Bluebird((resolve, reject) => {\r\n this.cursor.count(true,(err, count) => {\r\n if (err) return reject(err);\r\n return resolve(count);\r\n });\r\n }).nodeify(callback);\r\n }\r\n\r\n /**\r\n * Runs the specified handler over each instance in the query results\r\n * @param {function(Instance)} handler The handler which is triggered for each element in the query\r\n * @param {function(Error)} callback A callback which is triggered when all operations have been dispatched\r\n * @return {Promise} A promise which is resolved when all operations have been dispatched\r\n */\r\n forEach(handler: (instance: TInstance) => void, callback?: General.Callback): Bluebird {\r\n var helpers = this.model.helpers;\r\n return new Bluebird((resolve, reject) => {\r\n this.cursor.forEach((item: TDocument) => {\r\n this.model.handlers.documentReceived(this.conditions, item, function () { return helpers.wrapDocument.apply(helpers, arguments); }).then(handler);\r\n },(err) => {\r\n if (err) return reject(err);\r\n return resolve(null);\r\n });\r\n }).nodeify(callback);\r\n }\r\n\r\n /**\r\n * Runs the specified transform over each instance in the query results and returns the resulting transformed objects\r\n * @param {function(Instance): TResult} transform A handler which is used to transform the result objects\r\n * @param {function(Error, TResult[])} callback A callback which is triggered when the transformations are completed\r\n * @return {Promise} A promise which is fulfilled with the results of the transformations\r\n */\r\n map(transform: (instance: TInstance) => TResult | Bluebird, callback?: General.Callback): Bluebird {\r\n var helpers = this.model.helpers;\r\n return new Bluebird((resolve, reject) => {\r\n var promises: Bluebird[] = [];\r\n this.cursor.forEach((item: TDocument) => {\r\n promises.push(this.model.handlers.documentReceived(this.conditions, item, function () { return helpers.wrapDocument.apply(helpers, arguments); })\r\n .then(<(instance) => TResult>transform));\r\n },(err) => {\r\n if (err) return reject(err);\r\n return resolve(Bluebird.all(promises));\r\n });\r\n }).nodeify(callback);\r\n }\r\n\r\n /**\r\n * Retrieves all matching instances and returns them in an array\r\n * @param {function(Error, TInstance[])} callback A callback which is triggered with the resulting instances\r\n * @return {Promise} A promise which resolves with the instances returned by the query\r\n */\r\n toArray(callback?: General.Callback): Bluebird {\r\n var helpers = this.model.helpers;\r\n return new Bluebird((resolve, reject) => {\r\n this.cursor.toArray((err, results: any[]) => {\r\n if (err) return reject(err);\r\n return resolve(results);\r\n });\r\n }).map((document) => {\r\n return this.model.handlers.documentReceived(this.conditions, document, function () { return helpers.wrapDocument.apply(helpers, arguments); });\r\n }).nodeify(callback);\r\n }\r\n\r\n /**\r\n * Retrieves the next item in the results list\r\n * @param {function(Error, TInstance)} callback A callback which is triggered when the next item becomes available\r\n * @return {Promise} A promise which is resolved with the next item\r\n */\r\n next(callback?: General.Callback): Bluebird {\r\n return new Bluebird((resolve, reject) => {\r\n this.cursor.next((err, result: any) => {\r\n if (err) return reject(err);\r\n return resolve(result);\r\n });\r\n }).then((document) => {\r\n if (!document) return Bluebird.resolve(null);\r\n return this.model.handlers.documentReceived(this.conditions, document,(document, isNew?, isPartial?) => this.model.helpers.wrapDocument(document, isNew, isPartial));\r\n }).nodeify(callback);\r\n }\r\n\r\n /**\r\n * Returns a new cursor which behaves the same as this one did before any results were retrieved\r\n * @return {Cursor} The new cursor which starts at the beginning of the results\r\n */\r\n rewind(): Cursor {\r\n this.cursor.rewind();\r\n return this;\r\n }\r\n\r\n /**\r\n * Returns a new cursor which sorts its results by the given index expression\r\n * @param {model.IndexSpecification} sortExpression The index expression dictating the sort order and direction to use\r\n * @return {Cursor} The new cursor which sorts its results by the sortExpression\r\n */\r\n sort(sortExpression: Index.IndexSpecification): Cursor {\r\n return new Cursor(this.model, this.conditions, this.cursor.sort(sortExpression));\r\n }\r\n\r\n /**\r\n * Returns a new cursor which limits the number of returned results\r\n * @param {Number} limit The maximum number of results to return\r\n * @return {Cursor} The new cursor which will return a maximum number of results\r\n */\r\n limit(limit: number): Cursor {\r\n return new Cursor(this.model, this.conditions, this.cursor.limit(limit));\r\n }\r\n\r\n /**\r\n * Returns a new cursor which skips a number of results before it begins\r\n * returning any.\r\n * @param {Number} skip The number of results to skip before the cursor beings returning\r\n * @return {Cursor} The new cursor which skips a number of results\r\n */\r\n skip(skip: number): Cursor {\r\n return new Cursor(this.model, this.conditions, this.cursor.skip(skip));\r\n }\r\n}"],"sourceRoot":"/source/"} \ No newline at end of file diff --git a/dist/lib/Decorators.js b/dist/lib/Decorators.js index 5bc857b..47a0345 100644 --- a/dist/lib/Decorators.js +++ b/dist/lib/Decorators.js @@ -2,18 +2,46 @@ var MongoDB = require('mongodb'); var _ = require('lodash'); var skmatc = require('skmatc'); +/** + * Specifies the name of the collection to which this instance's documents should be sent. + * @param name The name of the MongoDB collection to store the documents in. + * + * This decorator replaces the use of the static collection property on instance implementation + * classes. If your transpiler does not support decorators then you are free to make use of the + * property instead. + */ function Collection(name) { return function (target) { target.collection = name; }; } exports.Collection = Collection; +/** + * Specifies a MongoDB collection level index to be managed by Iridium for this instance type. + * More than one instance of this decorator may be used if you wish to specify multiple indexes. + * @param spec The formal index specification which defines the properties and ordering used in the index. + * @param options The options dictating the way in which the index behaves. + * + * This decorator replaces the use of the static indexes property on instance implementation + * classes. If your transpiler does not support decorators then you are free to make use of the + * property instead. + */ function Index(spec, options) { return function (target) { target.indexes = (target.indexes || []).concat({ spec: spec, options: options || {} }); }; } exports.Index = Index; +/** + * Specifies a custom validator to be made available for this collection's schema. + * More than one instance of this decorator may be used if you wish to specify multiple validators. + * @param forType The value in the schema which will be delegated to this function for validation. + * @param validate A function which calls this.assert(condition) to determine whether a schema node is valid or not. + * + * This decorator replaces the use of the static validators property on instance implementation + * classes. If your transpiler does not support decorators then you are free to make use of the + * property instead. + */ function Validate(forType, validate) { return function (target) { target.validators = (target.validators || []).concat(skmatc.create(function (schema) { return schema === forType; }, validate)); @@ -44,6 +72,17 @@ function Property() { }; } exports.Property = Property; +/** + * Specifies a custom transform to be applied to the property this decorator is applied to. + * + * @param fromDB The function used to convert values from the database for the application. + * @param toDB The function used to convert values from the application to the form used in the database. + * + * This decorator can either compliment or replace the static transforms property on your instance + * class, however only one transform can be applied to any property at a time. + * If your transpiler does not support decorators then you are free to make use of the + * property instead. + */ function Transform(fromDB, toDB) { return function (target, property) { target.constructor.transforms = _.clone(target.constructor.transforms || {}); @@ -54,6 +93,13 @@ function Transform(fromDB, toDB) { }; } exports.Transform = Transform; +/** + * Specifies that this property should be treated as an ObjectID, with the requisite validator and transforms. + * + * This decorator applies an ObjectID validator to the property, which ensures that values sent to the database + * are instances of the MongoDB ObjectID type, as well as applying a transform operation which converts ObjectIDs + * to strings for your application, and then converts strings back to ObjectIDs for the database. + */ function ObjectID(target, name) { Property(MongoDB.ObjectID)(target, name); Transform(function (value) { return value && value._bsontype == 'ObjectID' ? new MongoDB.ObjectID(value.id).toHexString() : value; }, function (value) { return value && typeof value === 'string' ? new MongoDB.ObjectID(value) : value; })(target, name); diff --git a/dist/lib/Decorators.js.map b/dist/lib/Decorators.js.map index ab2057f..a93fa2a 100644 --- a/dist/lib/Decorators.js.map +++ b/dist/lib/Decorators.js.map @@ -1 +1 @@ -{"version":3,"sources":["lib/Decorators.ts"],"names":["Collection","Index","Validate","Property","Transform","ObjectID"],"mappings":"AAAA,AACA,4CAD4C;AAC5C,IAAO,OAAO,WAAW,SAAS,CAAC,CAAC;AACpC,IAAO,CAAC,WAAW,QAAQ,CAAC,CAAC;AAC7B,IAAO,MAAM,WAAW,QAAQ,CAAC,CAAC;AAMlC,oBAA2B,IAAY;IACtCA,MAAMA,CAACA,UAASA,MAAwCA;QACvD,MAAM,CAAC,UAAU,GAAG,IAAI,CAAC;IAC1B,CAAC,CAACA;AACHA,CAACA;AAJe,kBAAU,aAIzB,CAAA;AAED,eAAsB,IAAwB,EAAE,OAA8B;IAC7EC,MAAMA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AKA,KAAKA,QAAQA,GAAGA,IAAIA,OAAOA,CAACA,QAAQA,CAACA,KAAKA,CAACA,GAAGA,KAAKA,EAAxEA,CAAwEA,CACjFA,CAACA,MAAMA,EAAEA,IAAIA,CAACA,CAACA;AACjBA,CAACA;AANe,gBAAQ,WAMvB,CAAA","file":"lib/Decorators.js","sourcesContent":["/// \r\nimport MongoDB = require('mongodb');\r\nimport _ = require('lodash');\r\nimport skmatc = require('skmatc');\r\nimport Instance from './Instance';\r\nimport {Index, IndexSpecification} from './Index';\r\nimport {Schema} from './Schema';\r\nimport InstanceImplementation from './InstanceInterface';\r\n\r\nexport function Collection(name: string) {\r\n\treturn function(target: InstanceImplementation) {\r\n\t\ttarget.collection = name;\r\n\t};\r\n}\r\n\r\nexport function Index(spec: IndexSpecification, options?: MongoDB.IndexOptions) {\r\n\treturn function(target: InstanceImplementation) {\r\n\t\ttarget.indexes = (target.indexes || []).concat({ spec: spec, options: options || {} });\r\n\t}\r\n}\r\n\r\nexport function Validate(forType: any, validate: (schema: any, data: any, path: string) => Skmatc.Result) {\r\n\treturn function(target: InstanceImplementation) {\r\n\t\ttarget.validators = (target.validators || []).concat(skmatc.create(schema => schema === forType, validate));\r\n\t}\r\n}\r\n\r\nexport function Property(asType: any, required?: boolean): (target: { constructor: Function }, name: string) => void;\r\nexport function Property(name: string, asType: any, required?: boolean): (target: Function) => void;\r\nexport function Property(...args: any[]): (target: any, name?: string) => void {\r\n\tlet name = null,\r\n\t\tasType = false,\r\n\t\trequired = true;\r\n\t\r\n\tif (args.length > 1 && typeof args[args.length - 1] === 'boolean')\r\n\t\trequired = args.pop();\r\n\t\r\n\treturn function(target: any, property?: string) {\r\n\t\tif (!property) name = args.shift();\r\n\t\telse {\r\n\t\t\tname = property;\r\n\t\t\ttarget = target.constructor;\r\n\t\t}\r\n\t\tasType = args.pop() || false;\r\n\t\t\r\n\t\ttarget.schema = _.clone(target.schema || {});\r\n\t\tif(!required && typeof asType !== 'boolean') target.schema[name] = { $required: required, $type: asType };\r\n\t\telse target.schema[name] = asType;\r\n\t}\r\n}\r\n\r\nexport function Transform(fromDB: (value: any) => any, toDB: (value: any) => any) {\r\n\treturn function(target: any, property: string) {\r\n\t\ttarget.constructor.transforms = _.clone(target.constructor.transforms || {})\r\n\t\ttarget.constructor.transforms[property] = {\r\n\t\t\tfromDB: fromDB,\r\n\t\t\ttoDB: toDB\r\n\t\t};\r\n\t};\r\n}\r\n\r\nexport function ObjectID(target: { constructor: typeof Instance }, name: string) {\r\n\tProperty(MongoDB.ObjectID)(target, name);\r\n\tTransform(\r\n\t\tvalue => value && value._bsontype == 'ObjectID' ? new MongoDB.ObjectID(value.id).toHexString() : value,\r\n\t\tvalue => value && typeof value === 'string' ? new MongoDB.ObjectID(value) : value\r\n\t)(target, name);\r\n}"],"sourceRoot":"/source/"} \ No newline at end of file +{"version":3,"sources":["lib/Decorators.ts"],"names":["Collection","Index","Validate","Property","Transform","ObjectID"],"mappings":"AAAA,AACA,4CAD4C;AAC5C,IAAO,OAAO,WAAW,SAAS,CAAC,CAAC;AACpC,IAAO,CAAC,WAAW,QAAQ,CAAC,CAAC;AAC7B,IAAO,MAAM,WAAW,QAAQ,CAAC,CAAC;AAMlC;;;;;;;GAOG;AACH,oBAA2B,IAAY;IACtCA,MAAMA,CAACA,UAASA,MAAwCA;QACvD,MAAM,CAAC,UAAU,GAAG,IAAI,CAAC;IAC1B,CAAC,CAACA;AACHA,CAACA;AAJe,kBAAU,aAIzB,CAAA;AAED;;;;;;;;;GASG;AACH,eAAsB,IAAwB,EAAE,OAA8B;IAC7EC,MAAMA,CAACA,UAASA,MAAuCA;QACtD,MAAM,CAAC,OAAO,GAAG,CAAC,MAAM,CAAC,OAAO,IAAI,EAAE,CAAC,CAAC,MAAM,CAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,OAAO,EAAE,OAAO,IAAI,EAAE,EAAE,CAAC,CAAC;IAC/F,CAAC,CAAAA;AACFA,CAACA;AAJe,aAAK,QAIpB,CAA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CAAA","file":"lib/Decorators.js","sourcesContent":["/// \r\nimport MongoDB = require('mongodb');\r\nimport _ = require('lodash');\r\nimport skmatc = require('skmatc');\r\nimport {Instance} from './Instance';\r\nimport {Index, IndexSpecification} from './Index';\r\nimport {Schema} from './Schema';\r\nimport {InstanceImplementation} from './InstanceInterface';\r\n\r\n/**\r\n * Specifies the name of the collection to which this instance's documents should be sent.\r\n * @param name The name of the MongoDB collection to store the documents in.\r\n * \r\n * This decorator replaces the use of the static collection property on instance implementation\r\n * classes. If your transpiler does not support decorators then you are free to make use of the\r\n * property instead.\r\n */\r\nexport function Collection(name: string) {\r\n\treturn function(target: InstanceImplementation) {\r\n\t\ttarget.collection = name;\r\n\t};\r\n}\r\n\r\n/**\r\n * Specifies a MongoDB collection level index to be managed by Iridium for this instance type.\r\n * More than one instance of this decorator may be used if you wish to specify multiple indexes.\r\n * @param spec The formal index specification which defines the properties and ordering used in the index.\r\n * @param options The options dictating the way in which the index behaves.\r\n * \r\n * This decorator replaces the use of the static indexes property on instance implementation\r\n * classes. If your transpiler does not support decorators then you are free to make use of the\r\n * property instead.\r\n */\r\nexport function Index(spec: IndexSpecification, options?: MongoDB.IndexOptions) {\r\n\treturn function(target: InstanceImplementation) {\r\n\t\ttarget.indexes = (target.indexes || []).concat({ spec: spec, options: options || {} });\r\n\t}\r\n}\r\n\r\n/**\r\n * Specifies a custom validator to be made available for this collection's schema.\r\n * More than one instance of this decorator may be used if you wish to specify multiple validators.\r\n * @param forType The value in the schema which will be delegated to this function for validation.\r\n * @param validate A function which calls this.assert(condition) to determine whether a schema node is valid or not.\r\n * \r\n * This decorator replaces the use of the static validators property on instance implementation\r\n * classes. If your transpiler does not support decorators then you are free to make use of the\r\n * property instead.\r\n */\r\nexport function Validate(forType: any, validate: (schema: any, data: any, path: string) => Skmatc.Result) {\r\n\treturn function(target: InstanceImplementation) {\r\n\t\ttarget.validators = (target.validators || []).concat(skmatc.create(schema => schema === forType, validate));\r\n\t}\r\n}\r\n\r\n/**\r\n * Specifies the schema type for the property this decorator is applied to. This can be used to replace the\r\n * static schema property on your instance. Multiple instances of this decorator can be applied, but no more\r\n * than one per property.\r\n * \r\n * @param asType The schema validation type to make use of for this property\r\n * @param required Whether this property is required to have a value or not, defaults to true. \r\n */\r\nexport function Property(asType: any, required?: boolean): (target: { constructor: Function }, name: string) => void;\r\n/**\r\n * Specifies the schema type for a property with the given name on the class this decorator is applied to. This\r\n * can either compliment or replace the static schema property on your instance class.\r\n * \r\n * @param name The name of the property that is being targetted\r\n * @param asType The schema validation type to make use of for this property\r\n * @param required Whether this property is required to have a value or not, defaults to true. \r\n */\r\nexport function Property(name: string, asType: any, required?: boolean): (target: Function) => void;\r\nexport function Property(...args: any[]): (target: any, name?: string) => void {\r\n\tlet name = null,\r\n\t\tasType = false,\r\n\t\trequired = true;\r\n\t\r\n\tif (args.length > 1 && typeof args[args.length - 1] === 'boolean')\r\n\t\trequired = args.pop();\r\n\t\r\n\treturn function(target: any, property?: string) {\r\n\t\tif (!property) name = args.shift();\r\n\t\telse {\r\n\t\t\tname = property;\r\n\t\t\ttarget = target.constructor;\r\n\t\t}\r\n\t\tasType = args.pop() || false;\r\n\t\t\r\n\t\ttarget.schema = _.clone(target.schema || {});\r\n\t\tif(!required && typeof asType !== 'boolean') target.schema[name] = { $required: required, $type: asType };\r\n\t\telse target.schema[name] = asType;\r\n\t}\r\n}\r\n\r\n/**\r\n * Specifies a custom transform to be applied to the property this decorator is applied to.\r\n * \r\n * @param fromDB The function used to convert values from the database for the application.\r\n * @param toDB The function used to convert values from the application to the form used in the database.\r\n * \r\n * This decorator can either compliment or replace the static transforms property on your instance\r\n * class, however only one transform can be applied to any property at a time.\r\n * If your transpiler does not support decorators then you are free to make use of the\r\n * property instead.\r\n */\r\nexport function Transform(fromDB: (value: any) => any, toDB: (value: any) => any) {\r\n\treturn function(target: any, property: string) {\r\n\t\ttarget.constructor.transforms = _.clone(target.constructor.transforms || {})\r\n\t\ttarget.constructor.transforms[property] = {\r\n\t\t\tfromDB: fromDB,\r\n\t\t\ttoDB: toDB\r\n\t\t};\r\n\t};\r\n}\r\n\r\n\r\n/**\r\n * Specifies that this property should be treated as an ObjectID, with the requisite validator and transforms.\r\n * \r\n * This decorator applies an ObjectID validator to the property, which ensures that values sent to the database\r\n * are instances of the MongoDB ObjectID type, as well as applying a transform operation which converts ObjectIDs\r\n * to strings for your application, and then converts strings back to ObjectIDs for the database.\r\n */\r\nexport function ObjectID(target: { constructor: typeof Instance }, name: string) {\r\n\tProperty(MongoDB.ObjectID)(target, name);\r\n\tTransform(\r\n\t\tvalue => value && value._bsontype == 'ObjectID' ? new MongoDB.ObjectID(value.id).toHexString() : value,\r\n\t\tvalue => value && typeof value === 'string' ? new MongoDB.ObjectID(value) : value\r\n\t)(target, name);\r\n}"],"sourceRoot":"/source/"} \ No newline at end of file diff --git a/dist/lib/General.js.map b/dist/lib/General.js.map index fd4eed7..ce272e2 100644 --- a/dist/lib/General.js.map +++ b/dist/lib/General.js.map @@ -1 +1 @@ -{"version":3,"sources":["lib/General.ts"],"names":[],"mappings":"AAAA,AACA,4CAD4C;AAoB3C","file":"lib/General.js","sourcesContent":["/// \r\nexport interface Callback {\r\n (err: Error, object?: T): void;\r\n}\r\n\r\nexport interface Predicate {\r\n (object: T, key?: string): boolean;\r\n}\r\n\r\nexport interface PropertyGetter {\r\n (): T;\r\n}\r\n\r\nexport interface PropertySetter {\r\n (value: T): void;\r\n}\r\n\r\nexport interface Property {\r\n get?: PropertyGetter;\r\n set?: PropertySetter;\r\n}"],"sourceRoot":"/source/"} \ No newline at end of file +{"version":3,"sources":["lib/General.ts"],"names":[],"mappings":"AAAA,4CAA4C;AAiE3C","file":"lib/General.js","sourcesContent":["/// \r\n\r\n/**\r\n * A method which is called once an asynchronous operation has completed, an alternative\r\n * to using Promises.\r\n * @param T The type of object returned by the asynchronous operation.\r\n */\r\nexport interface Callback {\r\n /**\r\n * @param err The error object, if one occurred, otherwise null if the operation completed successfully.\r\n * @param object The result of the asynchronous operation if it completed successfully. If err is defined, the presence of this value is unknown.\r\n */\r\n (err: Error, object?: T): void;\r\n}\r\n\r\n/**\r\n * A method which is used to determine whether a value within a collection meets a set of criteria.\r\n * @param T The type of item in the collection.\r\n */\r\nexport interface Predicate {\r\n /**\r\n * @param object The value of the item in the collection\r\n * @param key The key, if one is available, under which the item appeared within the collection\r\n * @returns A true-y value if the item met the predicate conditions, false-y values if it did not.\r\n */\r\n (object: T, key?: string): boolean;\r\n}\r\n\r\n/**\r\n * A method which is called to retrieve a value of the given type.\r\n * @param T The type of value to be retrieved.\r\n */\r\nexport interface PropertyGetter {\r\n /**\r\n * Gets the current value of the property\r\n * @returns The current value\r\n */\r\n (): T;\r\n}\r\n\r\n/**\r\n * A method which is called to set a value of the given type.\r\n * @param T The type of value to set\r\n */\r\nexport interface PropertySetter {\r\n /**\r\n * Sets the value to the provided one\r\n * @param value The new value to set\r\n */\r\n (value: T): void;\r\n}\r\n\r\n/**\r\n * A compound property which provides either a getter, setter or both.\r\n * @param T The type of objects stored in the property\r\n */\r\nexport interface Property {\r\n /**\r\n * An optional getter which can be used to retrieve the property's value\r\n */\r\n get?: PropertyGetter;\r\n /**\r\n * An optional setter which can be used to set the property's value\r\n */\r\n set?: PropertySetter;\r\n}"],"sourceRoot":"/source/"} \ No newline at end of file diff --git a/dist/lib/Instance.js b/dist/lib/Instance.js index d16dd2b..1817ffe 100644 --- a/dist/lib/Instance.js +++ b/dist/lib/Instance.js @@ -2,18 +2,28 @@ var _ = require('lodash'); var MongoDB = require('mongodb'); var Bluebird = require('bluebird'); var skmatc = require('skmatc'); +/** + * The default Iridium Instance implementation which provides methods for saving, refreshing and + * removing the wrapped document from the collection, as well as integrating with Omnom, our + * built in document diff processor which allows clean, atomic, document updates to be performed + * without needing to write the update queries yourself. + * + * @param TDocument The interface representing the structure of the documents in the collection. + * @param TInstance The type of instance which wraps the documents, generally the subclass of this class. + * + * This class will be subclassed automatically by Iridium to create a model specific instance + * which takes advantage of some of v8's optimizations to boost performance significantly. + * The instance returned by the model, and all of this instance's methods, will be of type + * TInstance - which should represent the merger of TSchema and IInstance for best results. + */ var Instance = (function () { /** * Creates a new instance which represents the given document as a type of model - * @param {model.Model} model The model that the document represents - * @param {TSchema} document The document which should be wrapped by this instance - * @param {Boolean} isNew Whether the document is new (doesn't exist in the database) or not - * @param {Boolean} isPartial Whether the document has only a subset of its fields populated - * @description - * This class will be subclassed automatically by Iridium to create a model specific instance - * which takes advantage of some of v8's optimizations to boost performance significantly. - * The instance returned by the model, and all of this instance's methods, will be of type - * TInstance - which should represent the merger of TSchema and IInstance for best results. + * @param model The model that dictates the collection the document originated from as well as how validations are performed. + * @param document The document which should be wrapped by this instance + * @param isNew Whether the document is new (doesn't exist in the database) or not + * @param isPartial Whether the document has only a subset of its fields populated + * */ function Instance(model, document, isNew, isPartial) { var _this = this; @@ -244,18 +254,30 @@ var Instance = (function () { Instance.prototype.toString = function () { return JSON.stringify(this.document, null, 2); }; + /** + * The schema used to validate documents of this type before being stored in the database. + */ Instance.schema = { _id: false }; + /** + * Additional which should be made available for use in the schema definition for this instance. + */ Instance.validators = [ skmatc.create(function (schema) { return schema === MongoDB.ObjectID; }, function (schema, data) { return this.assert(!data || data instanceof MongoDB.ObjectID || (data._bsontype === 'ObjectID' && data.id)); }, { name: 'ObjectID validation' }) ]; + /** + * The transformations which should be applied to properties of documents of this type. + */ Instance.transforms = {}; + /** + * The indexes which should be managed by Iridium for the collection used by this type. + */ Instance.indexes = []; return Instance; })(); -exports.default = Instance; +exports.Instance = Instance; //# sourceMappingURL=../lib/Instance.js.map \ No newline at end of file diff --git a/dist/lib/Instance.js.map b/dist/lib/Instance.js.map index 9d902e7..316587f 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","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A,MAAMA,CAACA,GAAGA,CAACA,CAACA;wBAC5BA,MAAMA,CAACA,OAAOA,CAAMA,CAACA,CAACA,GAAGA,CAACA,CAACA;oBAC/BA,CAACA,CAACA,CAACA;gBACPA,CAACA,CAACA,CAACA;YACPA,CAACA;YAACA,IAAIA,CAACA,CAACA;gBACJA,MAAMA,CAACA,IAAIA,QAAQA,CAAUA,UAACA,OAAmCA,EAAEA,MAAMA;oBACrEA,KAAIA,CAACA,MAAMA,CAACA,UAAUA,CAACA,SAASA,CAACA,UAAUA,EAAEA,OAAOA,EAAEA,EAAEA,CAACA,EAAEA,UAAUA,EAAEA,EAAEA,UAACA,GAAUA,EAAEA,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,CAACA,CAACA,KAAKA,CAACA,UAAAA,GAAGA;YACRA,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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BACnCA,EAAEA,CAACA,CAACA,OAAOA,CAACA;oBAACA,OAAOA,CAACA,IAAIA,CAACA,KAAKA,CAACA,CAACA;gBACjCA,IAAIA;oBAACA,OAAOA,CAACA,GAAGA,CAACA,GAAGA,KAAKA,CAACA;YAC9BA,CAACA;QACLA,CAACA,CAACA,CAACA;QAEHA,MAAMA,CAACA,OAAOA,CAACA;IACnBA,CAACA;IAEDT;;;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 +{"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":"AAWA,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;;;;;;;;;;;;;GAaG;AACH;IACIA;;;;;;;OAOGA;IACHA,kBAAYA,KAAkCA,EAAEA,QAAmBA,EAAEA,KAAqBA,EAAEA,SAA0BA;QAT1HC,iBAsWCA;QA7VwEA,qBAAqBA,GAArBA,YAAqBA;QAAEA,yBAA0BA,GAA1BA,iBAA0BA;QAClHA,IAAIA,CAACA,MAAMA,GAAGA,KAAKA,CAACA;QAEpBA,IAAIA,CAACA,MAAMA,GAAGA,CAACA,CAACA,KAAKA,CAACA;QACtBA,IAAIA,CAACA,UAAUA,GAAGA,SAASA,CAACA;QAC5BA,IAAIA,CAACA,SAASA,GAAGA,QAAQA,CAACA;QAC1BA,IAAIA,CAACA,SAASA,GAAGA,CAACA,CAACA,SAASA,CAAYA,QAAQA,CAACA,CAACA;QAElDA,CAACA,CAACA,IAAIA,CAACA,KAAKA,CAACA,IAAIA,CAACA,OAAOA,EAACA,UAACA,MAAcA;YACrCA,EAAEA,CAACA,CAACA,MAAMA,CAACA,WAAWA,CAACA;gBAACA,MAAMA,CAACA,WAAWA,CAACA,KAAIA,EAAEA,KAAKA,CAACA,CAACA;QAC5DA,CAACA,CAACA,CAACA;IACPA,CAACA;IAWDD,sBAAIA,8BAAQA;QAHZA;;WAEGA;aACHA;YACIE,MAAMA,CAACA,IAAIA,CAACA,SAASA,CAACA;QAC1BA,CAACA;;;OAAAF;IA2FDA,uBAAIA,GAAJA;QAAAG,iBAqFCA;QArFIA,cAAcA;aAAdA,WAAcA,CAAdA,sBAAcA,CAAdA,IAAcA;YAAdA,6BAAcA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;AAADA,CAtWA,AAsWCA,IAAA;AAtWY,gBAAQ,WAsWpB,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\nimport {Transforms} from './Transforms';\r\n\r\nimport _ = require('lodash');\r\nimport MongoDB = require('mongodb');\r\nimport Bluebird = require('bluebird');\r\nimport skmatc = require('skmatc');\r\n\r\n/**\r\n * The default Iridium Instance implementation which provides methods for saving, refreshing and\r\n * removing the wrapped document from the collection, as well as integrating with Omnom, our\r\n * built in document diff processor which allows clean, atomic, document updates to be performed\r\n * without needing to write the update queries yourself.\r\n * \r\n * @param TDocument The interface representing the structure of the documents in the collection.\r\n * @param TInstance The type of instance which wraps the documents, generally the subclass of this class.\r\n * \r\n * This class will be subclassed automatically by Iridium to create a model specific instance\r\n * which takes advantage of some of v8's optimizations to boost performance significantly.\r\n * The instance returned by the model, and all of this instance's methods, will be of type\r\n * TInstance - which should represent the merger of TSchema and IInstance for best results.\r\n */\r\nexport class Instance {\r\n /**\r\n * Creates a new instance which represents the given document as a type of model\r\n * @param model The model that dictates the collection the document originated from as well as how validations are performed.\r\n * @param document The document which should be wrapped by this instance\r\n * @param isNew Whether the document is new (doesn't exist in the database) or not\r\n * @param isPartial Whether the document has only a subset of its fields populated\r\n *\r\n */\r\n constructor(model: Model, document: TDocument, isNew: boolean = true, isPartial: boolean = false) {\r\n this._model = model;\r\n\r\n this._isNew = !!isNew;\r\n this._isPartial = isPartial;\r\n this._original = document;\r\n this._modified = _.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 /**\r\n * A function which is called whenever a new document is in the process of being inserted into the database.\r\n * @param document The document which will be inserted into the database.\r\n */\r\n static onCreating: (document: { _id?: any }) => void;\r\n \r\n /**\r\n * A function which is called whenever a document of this type is received from the database, prior to it being\r\n * wrapped by an Instance object.\r\n * @param document The document that was retrieved from the database.\r\n */\r\n static onRetrieved: (document: { _id?: any }) => void;\r\n \r\n /**\r\n * A function which is called whenever a new instance has been created to wrap a document.\r\n * @param instance The instance which has been created.\r\n */\r\n static onReady: (instance: Instance<{ _id?: any }, Instance<{ _id?: any }, any>>) => void;\r\n \r\n /**\r\n * A function which is called whenever an instance's save() method is called to allow you to interrogate and/or manipulate\r\n * the changes which are being made.\r\n * \r\n * @param instance The instance to which the changes are being made\r\n * @param changes The MongoDB change object describing the changes being made to the document.\r\n */\r\n static onSaving: (instance: Instance<{ _id?: any }, Instance<{ _id?: any }, any>>, changes: any) => void;\r\n\r\n /**\r\n * The name of the collection into which documents of this type are stored.\r\n */\r\n static collection: string;\r\n\r\n /**\r\n * The schema used to validate documents of this type before being stored in the database.\r\n */\r\n static schema: Schema = {\r\n _id: false\r\n };\r\n\r\n /**\r\n * Additional which should be made available for use in the schema definition for this instance.\r\n */\r\n static validators: Skmatc.Validator[] = [\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 /**\r\n * The transformations which should be applied to properties of documents of this type.\r\n */\r\n static transforms: Transforms = {\r\n\r\n };\r\n\r\n /**\r\n * The cache director used to derive unique cache keys for documents of this type.\r\n */\r\n static cache: CacheDirector;\r\n \r\n /**\r\n * The indexes which should be managed by Iridium for the collection used by this type.\r\n */\r\n static indexes: (Index.Index | Index.IndexSpecification)[] = [];\r\n \r\n /**\r\n * Saves any changes to this instance, using the built in diff algorithm to write the update query.\r\n * @param {function(Error, IInstance)} callback A callback which is triggered when the save operation completes\r\n * @returns {Promise}\r\n */\r\n save(callback?: General.Callback): Bluebird;\r\n /**\r\n * Saves the given changes to this instance and updates the instance to match the latest database document.\r\n * @param {Object} changes The MongoDB changes object to be used when updating this instance\r\n * @param {function(Error, IInstance)} callback A callback which is triggered when the save operation completes\r\n * @returns {Promise}\r\n */\r\n save(changes: Object, callback?: General.Callback): Bluebird;\r\n /**\r\n * Saves the given changes to this instance and updates the instance to match the latest database document.\r\n * @param {Object} conditions The conditions under which the update will take place - these will be merged with an _id query\r\n * @param {Object} changes The MongoDB changes object to be used when updating this instance\r\n * @param {function(Error, IInstance)} callback A callback which is triggered when the save operation completes\r\n * @returns {Promise}\r\n */\r\n save(conditions: Object, changes: Object, callback?: General.Callback): Bluebird;\r\n save(...args: any[]): Bluebird {\r\n var callback: General.Callback = null;\r\n var changes: any = null;\r\n var conditions: any = {};\r\n\r\n Array.prototype.slice.call(args, 0).reverse().forEach((arg) => {\r\n if (typeof arg == 'function') callback = arg;\r\n else if (typeof arg == 'object') {\r\n if (!changes) changes = arg;\r\n else conditions = arg;\r\n }\r\n });\r\n\r\n return Bluebird.resolve().then(() => {\r\n conditions = _.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 collection The collection from which to retrieve the element\r\n * @param predicate The function which determines whether to select an element\r\n * @returns The first element in the array which matched the predicate.\r\n */\r\n first(collection: T[], predicate: General.Predicate): T;\r\n /**\r\n * Retrieves the first element in an enumerable collection which matches the predicate\r\n * @param collection The collection from which to retrieve the element\r\n * @param predicate The function which determines whether to select an element\r\n * @returns The first element in the object which matched the predicate.\r\n */\r\n first(collection: { [key: string]: T }, predicate: General.Predicate): T;\r\n first(collection: T[]| { [key: string]: T }, predicate: General.Predicate): T {\r\n var result = null;\r\n\r\n _.each(collection,(value: T, key) => {\r\n if (predicate.call(this, value, key)) {\r\n result = value;\r\n return false;\r\n }\r\n });\r\n\r\n return result;\r\n }\r\n\r\n /**\r\n * Retrieves a number of elements from an enumerable collection which match the predicate\r\n * @param collection The collection from which elements will be plucked\r\n * @param predicate The function which determines the elements to be plucked\r\n * @returns A new array containing the elements in the array which matched the predicate.\r\n */\r\n select(collection: T[], predicate: General.Predicate): T[];\r\n /**\r\n * Retrieves a number of elements from an enumerable collection which match the predicate\r\n * @param collection The collection from which elements will be plucked\r\n * @param predicate The function which determines the elements to be plucked\r\n * @returns An object with the properties from the collection which matched the predicate.\r\n */\r\n select(collection: { [key: string]: T }, predicate: General.Predicate): { [key: string]: T };\r\n select(collection: T[]| { [key: string]: T }, predicate: General.Predicate): any {\r\n var isArray = Array.isArray(collection);\r\n var results: any = isArray ? [] : {};\r\n\r\n _.each(collection,(value: T, key) => {\r\n if (predicate.call(this, value, key)) {\r\n if (isArray) results.push(value);\r\n else results[key] = value;\r\n }\r\n });\r\n\r\n return results;\r\n }\r\n\r\n /**\r\n * Gets the JSON representation of this instance\r\n * @returns {TDocument}\r\n */\r\n toJSON(): any {\r\n return this.document;\r\n }\r\n\r\n /**\r\n * Gets a string representation of this instance\r\n * @returns {String}\r\n */\r\n toString(): string {\r\n return JSON.stringify(this.document, null, 2);\r\n }\r\n}"],"sourceRoot":"/source/"} \ No newline at end of file diff --git a/dist/lib/InstanceInterface.js.map b/dist/lib/InstanceInterface.js.map index 5661b62..5926ff6 100644 --- a/dist/lib/InstanceInterface.js.map +++ b/dist/lib/InstanceInterface.js.map @@ -1 +1 @@ -{"version":3,"sources":["lib/InstanceInterface.ts"],"names":[],"mappings":"AAwBC","file":"lib/InstanceInterface.js","sourcesContent":["/// \r\nimport Iridium from './Core';\r\nimport {Schema} from './Schema';\r\nimport Model from './Model';\r\nimport * as Index from './Index';\r\nimport {CacheDirector} from './CacheDirector';\r\n\r\nexport default InstanceImplementation;\r\n\r\ninterface InstanceImplementation {\r\n new (model: Model, doc: TDocument, isNew?: boolean, isPartial?: boolean): TInstance;\r\n \r\n collection: string;\r\n schema: Schema;\r\n indexes?: (Index.Index | Index.IndexSpecification)[];\r\n \r\n onCreating? (document: TDocument): void;\r\n onRetrieved? (document: TDocument): void;\r\n onReady? (instance: TInstance): void;\r\n onSaving? (instance: TInstance, changes: any): void;\r\n\r\n cache?: CacheDirector;\r\n validators?: Skmatc.Validator[];\r\n transforms?: { [property: string]: { fromDB: (value: any) => any; toDB: (value: any) => any; } };\r\n}"],"sourceRoot":"/source/"} \ No newline at end of file +{"version":3,"sources":["lib/InstanceInterface.ts"],"names":[],"mappings":"AAkGC","file":"lib/InstanceInterface.js","sourcesContent":["/// \r\nimport {Schema} from './Schema';\r\nimport {Model} from './Model';\r\nimport * as Index from './Index';\r\nimport {CacheDirector} from './CacheDirector';\r\nimport {Transforms} from './Transforms';\r\n\r\n/**\r\n * This interface dictates the format of an instance class which wraps documents received\r\n * from the database for a specific Iridium model.\r\n * \r\n * @param TDocument The interface representing the documents stored in the database, after being passed through the transforms pipeline.\r\n * @param TInstance The type of object which is instantiated when calling this implementation's constructor.\r\n * \r\n * It is important to note that, when implementing this interface, each of the properties and methods\r\n * should be exposed statically. That is, you would expose the collection property as a static variable\r\n * on the instance implementation, since prototype methods and variables become available to consumers of the\r\n * instance itself.\r\n */\r\nexport interface InstanceImplementation {\r\n /**\r\n * A constructor which creates a new instance tied to the given model and representing the given document.\r\n * @param model The Iridium Model which this instance should be tied to, gives the instance access to the database collection and any other context it requires.\r\n * @param doc The document this instance should wrap from the database. This provides the data context for the instance.\r\n * @param isNew Whether this document is known to exist in the database or not, for example, if the instance was generated from user input and hasn't been saved yet.\r\n * @param isPartial Whether the document which has been given to this instance had any field restrictions imposed on it during the query, and may therefore only contain partial data.\r\n */\r\n new (model: Model, doc: TDocument, isNew?: boolean, isPartial?: boolean): TInstance;\r\n \r\n /**\r\n * The name of the database collection from which documents are retrieved, and to which they are stored.\r\n */\r\n collection: string;\r\n\r\n /**\r\n * The database schematic used for validation of instances prior to storing them in the database.\r\n * This schematic should follow the guides set out in skmatc's documentation, and is used whenever\r\n * you insert a new document into the collection or save an instance using the default instance type.\r\n * Operations like update() (and by extension, save() when using the update operations) cannot be checked\r\n * by skmatc for consistency and as a result will not have their data validated - be careful when making\r\n * use of them as a result.\r\n */\r\n schema: Schema;\r\n \r\n /**\r\n * Any additional indexes on the collection which should be managed by Iridium.\r\n * This field is optional, but if provided allows you to make use of the model's ensureIndexes() method\r\n * to automatically generate all specified indexes.\r\n */\r\n indexes?: (Index.Index | Index.IndexSpecification)[];\r\n \r\n /**\r\n * An optional method which will be called whenever a document is about to be inserted into the database,\r\n * allowing you to set default values and do any preprocessing you wish prior to the document being inserted.\r\n */\r\n onCreating? (document: TDocument): void;\r\n \r\n /**\r\n * An optional method which is called whenever a new document is received from the model's collection and\r\n * prior to the document being wrapped, can be used to perform preprocessing if necessary - however we recommend\r\n * you rather make use of transforms for that task.\r\n */\r\n onRetrieved? (document: TDocument): void;\r\n \r\n /**\r\n * An optional method which is called whenever a new document for this model has been wrapped in an instance.\r\n */\r\n onReady? (instance: TInstance): void;\r\n \r\n /**\r\n * An optional method which is called prior to saving an instance, it is provided with the instance itself as\r\n * well as the proposed changes to the instance. This allows you to make additional changes, such as updating\r\n * a lastChanged property on the document, or abort changes by throwing an error.\r\n */\r\n onSaving? (instance: TInstance, changes: any): void;\r\n\r\n /**\r\n * The cache controller used to determine whether a document may be cached, as well as deriving a unique cache\r\n * key for the document and similarly, for a query. This works in concert with the cache implementation itself\r\n * to ensure that documents are cached in an intelligent manner. By default this will simply make use of the\r\n * document's _id field as the cache key - however that behaviour may be modified if you wish to query on other\r\n * properties instead.\r\n */\r\n cache?: CacheDirector;\r\n \r\n /**\r\n * Any additional validation types you wish to make available for use within this model's database schema. This\r\n * allows you to validate using conditions otherwise not available within skmatc itself. For more information\r\n * on implementing a validator, take a look at the skmatc documentation on GitHub.\r\n */\r\n validators?: Skmatc.Validator[];\r\n \r\n /**\r\n * Any transform operations you would like to perform on documents received from the database, or prior to being\r\n * sent to the database. These may include things such as converting ObjectIDs to strings for the application, and\r\n * then back to ObjectIDs once they return to the database.\r\n */\r\n transforms?: Transforms;\r\n}"],"sourceRoot":"/source/"} \ No newline at end of file diff --git a/dist/lib/Middleware.js.map b/dist/lib/Middleware.js.map index 4742047..05be03c 100644 --- a/dist/lib/Middleware.js.map +++ b/dist/lib/Middleware.js.map @@ -1 +1 @@ -{"version":3,"sources":["lib/Middleware.ts"],"names":[],"mappings":"AAKC","file":"lib/Middleware.js","sourcesContent":["/// \r\nimport Core from './Core';\r\n\r\nexport interface MiddlewareFactory {\r\n (core: Core): T;\r\n}"],"sourceRoot":"/source/"} \ No newline at end of file +{"version":3,"sources":["lib/Middleware.ts"],"names":[],"mappings":"AASC","file":"lib/Middleware.js","sourcesContent":["/// \r\nimport {Core} from './Core';\r\n\r\n/**\r\n * Middlewares provided by Iridium, such as the Express one, derive from this interface.\r\n * @internal\r\n */\r\nexport interface MiddlewareFactory {\r\n (core: Core): T;\r\n}"],"sourceRoot":"/source/"} \ No newline at end of file diff --git a/dist/lib/Model.js b/dist/lib/Model.js index 3f40388..618c5f3 100644 --- a/dist/lib/Model.js +++ b/dist/lib/Model.js @@ -10,20 +10,25 @@ var ModelHelpers_1 = require('./ModelHelpers'); var ModelHandlers_1 = require('./ModelHandlers'); var ModelSpecificInstance_1 = require('./ModelSpecificInstance'); /** - * An Iridium Model which represents a structured MongoDB collection + * An Iridium Model which represents a structured MongoDB collection. + * Models expose the methods you will generally use to query those collections, and ensure that + * the results of those queries are returned as {TInstance} instances. + * + * @param TDocument The interface used to determine the schema of documents in the collection. + * @param TInstance The interface or class used to represent collection documents in the JS world. + * * @class */ var Model = (function () { /** * Creates a new Iridium model representing a given ISchema and backed by a collection whose name is specified - * @param {Iridium} core The Iridium core that this model should use for database access - * @param {ModelInterfaces.InstanceImplementation} instanceType The class which will be instantiated for each document retrieved from the database - * @returns {Model} + * @param core The Iridium core that this model should use for database access + * @param instanceType The class which will be instantiated for each document retrieved from the database * @constructor */ function Model(core, instanceType) { this._hooks = {}; - if (!(core instanceof Core_1.default)) + if (!(core instanceof Core_1.Core)) throw new Error("You failed to provide a valid Iridium core for this model"); if (typeof instanceType != 'function') throw new Error("You failed to provide a valid instance constructor for this model"); @@ -36,6 +41,9 @@ var Model = (function () { this.onNewModel(); this.loadInternal(); } + /** + * Loads any externally available properties (generally accessed using public getters/setters). + */ Model.prototype.loadExternal = function (instanceType) { this._collection = instanceType.collection; this._schema = instanceType.schema; @@ -51,16 +59,24 @@ var Model = (function () { fromDB: function (value) { return value._bsontype == 'ObjectID' ? new MongoDB.ObjectID(value.id).toHexString() : value; }, toDB: function (value) { return value && typeof value === 'string' ? new MongoDB.ObjectID(value) : value; } }; - if (instanceType.prototype instanceof Instance_1.default) - this._Instance = ModelSpecificInstance_1.default(this, instanceType); + if (instanceType.prototype instanceof Instance_1.Instance) + this._Instance = ModelSpecificInstance_1.ModelSpecificInstance(this, instanceType); else this._Instance = instanceType.bind(undefined, this); }; + /** + * Loads any internally (protected/private) properties and helpers only used within Iridium itself. + */ Model.prototype.loadInternal = function () { - this._cache = new ModelCache_1.default(this); - this._helpers = new ModelHelpers_1.default(this); - this._handlers = new ModelHandlers_1.default(this); + this._cache = new ModelCache_1.ModelCache(this); + this._helpers = new ModelHelpers_1.ModelHelpers(this); + this._handlers = new ModelHandlers_1.ModelHandlers(this); }; + /** + * Process any callbacks and plugin delegation for the creation of this model. + * It will generally be called whenever a new Iridium Core is created, however is + * more specifically tied to the lifespan of the models themselves. + */ Model.prototype.onNewModel = function () { var _this = this; this._core.plugins.forEach(function (plugin) { return plugin.newModel && plugin.newModel(_this); }); @@ -68,7 +84,7 @@ var Model = (function () { Object.defineProperty(Model.prototype, "helpers", { /** * Provides helper methods used by Iridium for common tasks - * @returns {ModelHelpers} + * @returns A set of helper methods which are used within Iridium for common tasks */ get: function () { return this._helpers; @@ -79,7 +95,7 @@ var Model = (function () { Object.defineProperty(Model.prototype, "handlers", { /** * Provides helper methods used by Iridium for hook delegation and common processes - * @returns {ModelHandlers} + * @returns A set of helper methods which perform common event and response handling tasks within Iridium. */ get: function () { return this._handlers; @@ -89,8 +105,10 @@ var Model = (function () { }); Object.defineProperty(Model.prototype, "hooks", { /** - * Gets the even hooks subscribed on this model for a number of different state changes - * @returns {Hooks} + * Gets the even hooks subscribed on this model for a number of different state changes. + * These hooks are primarily intended to allow lifecycle manipulation logic to be added + * in the user's model definition, allowing tasks such as the setting of default values + * or automatic client-side joins to take place. */ get: function () { return this._hooks; @@ -100,9 +118,14 @@ var Model = (function () { }); Object.defineProperty(Model.prototype, "schema", { /** - * Gets the ISchema dictating the data structure represented by this model + * Gets the schema dictating the data structure represented by this model. + * The schema is used by skmatc to validate documents before saving to the database, however + * until MongoDB 3.1 becomes widely available (with server side validation support) we are + * limited in our ability to validate certain types of updates. As such, these validations + * act more as a data-integrity check than anything else, unless you purely make use of Omnom + * updates within instances. * @public - * @returns {schema} + * @returns The defined validation schema for this model */ get: function () { return this._schema; @@ -112,9 +135,9 @@ var Model = (function () { }); Object.defineProperty(Model.prototype, "core", { /** - * Gets the Iridium core that this model is associated with + * Gets the Iridium core that this model is associated with. * @public - * @returns {Iridium} + * @returns The Iridium core that this model is bound to */ get: function () { return this._core; @@ -124,7 +147,10 @@ var Model = (function () { }); Object.defineProperty(Model.prototype, "collection", { /** - * Gets the underlying MongoDB collection from which this model's documents are retrieved + * Gets the underlying MongoDB collection from which this model's documents are retrieved. + * You can make use of this object if you require any low level access to the MongoDB collection, + * however we recommend you make use of the Iridium methods whereever possible, as we cannot + * guarantee the accuracy of the type definitions for the underlying MongoDB driver. * @public * @returns {Collection} */ @@ -189,6 +215,11 @@ var Model = (function () { configurable: true }); Object.defineProperty(Model.prototype, "transforms", { + /** + * Gets the transforms which are applied whenever a document is received from the database, or + * prior to storing a document in the database. Tasks such as converting an ObjectID to a string + * and vice versa are all listed in this object. + */ get: function () { return this._transforms; }, @@ -196,6 +227,11 @@ var Model = (function () { configurable: true }); Object.defineProperty(Model.prototype, "validators", { + /** + * Gets the custom validation types available for this model. These validators are added to the + * default skmatc validators, as well as those available through plugins, for use when checking + * your instances. + */ get: function () { return this._validators; }, @@ -203,6 +239,9 @@ var Model = (function () { configurable: true }); Object.defineProperty(Model.prototype, "indexes", { + /** + * Gets the indexes which Iridium will manage on this model's database collection. + */ get: function () { return this._indexes; }, @@ -218,7 +257,7 @@ var Model = (function () { var cursor = this.collection.find(conditions, { fields: fields }); - return new Cursor_1.default(this, conditions, cursor); + return new Cursor_1.Cursor(this, conditions, cursor); }; Model.prototype.get = function () { var args = []; @@ -497,6 +536,6 @@ var Model = (function () { }; return Model; })(); -exports.default = Model; +exports.Model = Model; //# sourceMappingURL=../lib/Model.js.map \ No newline at end of file diff --git a/dist/lib/Model.js.map b/dist/lib/Model.js.map index c00e023..dd70524 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.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;AAE7B,qBAAiB,QAAQ,CAAC,CAAA;AAC1B,yBAAqB,YAAY,CAAC,CAAA;AAOlC,uBAAmB,UAAU,CAAC,CAAA;AAS9B,2BAAuB,c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AACA,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 +{"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;AAE7B,qBAAmB,QAAQ,CAAC,CAAA;AAC5B,yBAAuB,YAAY,CAAC,CAAA;AAOpC,uBAAqB,UAAU,CAAC,CAAA;AAKhC,2BAAyB,cAAc,CAAC,CAAA;AACxC,6BAA2B,gBAAgB,CAAC,CAAA;AAC5C,8BAA4B,iBAAiB,CAAC,CAAA;AAE9C,sCAAoC,yBAAyB,CAAC,CAAA;AAK9D;;;;;;;;;GASG;AACH;IACIA;;;;;OAKGA;IACHA,eAAYA,IAAUA,EAAEA,YAA0DA;QA2E1EC,WAAMA,GAAgCA,EAAEA,CAACA;QA1E7CA,EAAEA,CAACA,CAACA,CAACA,CAACA,IAAIA,YAAYA,WAAIA,CAACA,CAACA;YAACA,MAAMA,IAAIA,KAAKA,CAACA,2DAA2DA,CAACA,CAACA;QAC1GA,EAAEA,CAACA,CAACA,OAAOA,YAAYA,IAAIA,UAAUA,CAACA;YAACA,MAAMA,IAAIA,KAAKA,CAACA,mEAAmEA,CAACA,CAACA;QAC5HA,EAAEA,CAACA,CAACA,OAAOA,YAAYA,CAACA,UAAUA,IAAIA,QAAQA,IAAIA,CAACA,YAAYA,CAACA,UAAUA,CAACA;YAACA,MAAMA,IAAIA,KAAKA,CAACA,8DAA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,CAACA,CAACA;QAC5IA,CAACA;QAEDA,MAAMA,CAACA,IAAIA,QAAQA,CAAUA,UAACA,OAAOA,EAAEA,MAAMA;YACzCA,KAAIA,CAACA,UAAUA,CAACA,SAASA,CAACA,KAAKA,EAACA,UAACA,GAAGA,EAAEA,MAAsBA;gBACxDA,EAAEA,CAACA,CAACA,GAAGA,CAACA;oBAACA,MAAMA,CAACA,MAAMA,CAACA,GAAGA,CAACA,CAACA;gBAC5BA,MAAMA,CAACA,OAAOA,CAAMA,CAACA,CAACA,MAAMA,CAACA,EAAEA,CAACA,CAACA;YACrCA,CAACA,CAACA,CAACA;QACPA,CAACA,CAACA,CAACA,OAAOA,CAACA,QAAQA,CAACA,CAACA;IACzBA,CAACA;IAED7B;;;;OAIGA;IACHA,2BAAWA,GAAXA,UAAYA,QAAoCA;QAAhD8B,iBAOCA;QANGA,MAAMA,CAACA,IAAIA,QAAQA,CAAMA,UAACA,OAAOA,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,CA9sBA,AA8sBCA,IAAA;AA9sBY,aAAK,QA8sBjB,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 {Omnom} from './utils/Omnom';\r\nimport {ModelCache} from './ModelCache';\r\nimport {ModelHelpers} from './ModelHelpers';\r\nimport {ModelHandlers} from './ModelHandlers';\r\nimport * as ModelInterfaces from './ModelInterfaces';\r\nimport {ModelSpecificInstance} from './ModelSpecificInstance';\r\nimport {InstanceImplementation} from './InstanceInterface';\r\nimport {Transforms} from './Transforms';\r\nimport * as AggregationPipeline from './Aggregate';\r\n\r\n/**\r\n * An Iridium Model which represents a structured MongoDB collection.\r\n * Models expose the methods you will generally use to query those collections, and ensure that\r\n * the results of those queries are returned as {TInstance} instances.\r\n * \r\n * @param TDocument The interface used to determine the schema of documents in the collection.\r\n * @param TInstance The interface or class used to represent collection documents in the JS world.\r\n * \r\n * @class\r\n */\r\nexport class Model {\r\n /**\r\n * Creates a new Iridium model representing a given ISchema and backed by a collection whose name is specified\r\n * @param core The Iridium core that this model should use for database access\r\n * @param instanceType The class which will be instantiated for each document retrieved from the database\r\n * @constructor\r\n */\r\n constructor(core: Core, instanceType: InstanceImplementation) {\r\n if (!(core instanceof Core)) throw new Error(\"You failed to provide a valid Iridium core for this model\");\r\n if (typeof instanceType != 'function') throw new Error(\"You failed to provide a valid instance constructor for this model\");\r\n if (typeof instanceType.collection != 'string' || !instanceType.collection) throw new Error(\"You failed to provide a valid collection name for this model\");\r\n if (!_.isPlainObject(instanceType.schema) || instanceType.schema._id === undefined) throw new Error(\"You failed to provide a valid schema for this model\");\r\n\r\n this._core = core;\r\n\r\n this.loadExternal(instanceType);\r\n this.onNewModel();\r\n this.loadInternal();\r\n }\r\n\r\n /**\r\n * Loads any externally available properties (generally accessed using public getters/setters).\r\n */\r\n private loadExternal(instanceType: InstanceImplementation) {\r\n this._collection = instanceType.collection;\r\n this._schema = instanceType.schema;\r\n this._hooks = instanceType;\r\n this._cacheDirector = instanceType.cache;\r\n this._transforms = instanceType.transforms || {};\r\n this._validators = instanceType.validators || [];\r\n this._indexes = instanceType.indexes || [];\r\n\r\n if(!this._schema._id) this._schema._id = MongoDB.ObjectID;\r\n\r\n if(this._schema._id === MongoDB.ObjectID && !this._transforms['_id'])\r\n this._transforms['_id'] = {\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 /**\r\n * Loads any internally (protected/private) properties and helpers only used within Iridium itself.\r\n */\r\n private loadInternal() {\r\n this._cache = new ModelCache(this);\r\n this._helpers = new ModelHelpers(this);\r\n this._handlers = new ModelHandlers(this);\r\n }\r\n\r\n /**\r\n * Process any callbacks and plugin delegation for the creation of this model.\r\n * It will generally be called whenever a new Iridium Core is created, however is\r\n * more specifically tied to the lifespan of the models themselves.\r\n */\r\n private onNewModel() {\r\n this._core.plugins.forEach(plugin => plugin.newModel && plugin.newModel(this));\r\n }\r\n\r\n private _helpers: ModelHelpers;\r\n /**\r\n * Provides helper methods used by Iridium for common tasks\r\n * @returns A set of helper methods which are used within Iridium for common tasks\r\n */\r\n get helpers(): ModelHelpers {\r\n return this._helpers;\r\n }\r\n\r\n private _handlers: ModelHandlers;\r\n /**\r\n * Provides helper methods used by Iridium for hook delegation and common processes\r\n * @returns A set of helper methods which perform common event and response handling tasks within Iridium.\r\n */\r\n get handlers(): ModelHandlers {\r\n return this._handlers;\r\n }\r\n\r\n private _hooks: Hooks = {};\r\n\r\n /**\r\n * Gets the even hooks subscribed on this model for a number of different state changes.\r\n * These hooks are primarily intended to allow lifecycle manipulation logic to be added\r\n * in the user's model definition, allowing tasks such as the setting of default values\r\n * or automatic client-side joins to take place.\r\n */\r\n get hooks(): Hooks {\r\n return this._hooks;\r\n }\r\n\r\n private _schema: Schema;\r\n /**\r\n * Gets the schema dictating the data structure represented by this model.\r\n * The schema is used by skmatc to validate documents before saving to the database, however\r\n * until MongoDB 3.1 becomes widely available (with server side validation support) we are\r\n * limited in our ability to validate certain types of updates. As such, these validations\r\n * act more as a data-integrity check than anything else, unless you purely make use of Omnom\r\n * updates within instances.\r\n * @public\r\n * @returns The defined validation schema for this model\r\n */\r\n get schema(): Schema {\r\n return this._schema;\r\n }\r\n\r\n private _core: Core;\r\n /**\r\n * Gets the Iridium core that this model is associated with.\r\n * @public\r\n * @returns The Iridium core that this model is bound to\r\n */\r\n get core(): Core {\r\n return this._core;\r\n }\r\n\r\n private _collection: string;\r\n /**\r\n * Gets the underlying MongoDB collection from which this model's documents are retrieved.\r\n * You can make use of this object if you require any low level access to the MongoDB collection,\r\n * however we recommend you make use of the Iridium methods whereever possible, as we cannot\r\n * guarantee the accuracy of the type definitions for the underlying MongoDB driver.\r\n * @public\r\n * @returns {Collection}\r\n */\r\n get collection(): MongoDB.Collection {\r\n if (!this.core.connection) throw new Error(\"Iridium Core not connected to a database.\");\r\n return this.core.connection.collection(this._collection);\r\n }\r\n\r\n /**\r\n * Gets the name of the underlying MongoDB collection from which this model's documents are retrieved\r\n * @public\r\n */\r\n get collectionName(): string {\r\n return this._collection;\r\n }\r\n\r\n /**\r\n * Sets the name of the underlying MongoDB collection from which this model's documents are retrieved\r\n * @public\r\n */\r\n set collectionName(value: string) {\r\n this._collection = value;\r\n }\r\n\r\n private _cacheDirector: CacheDirector;\r\n /**\r\n * Gets the cache controller which dictates which queries will be cached, and under which key\r\n * @public\r\n * @returns {CacheDirector}\r\n */\r\n get cacheDirector(): CacheDirector {\r\n return this._cacheDirector;\r\n }\r\n\r\n private _cache: ModelCache;\r\n /**\r\n * Gets the cache responsible for storing objects for quick retrieval under certain conditions\r\n * @public\r\n * @returns {ModelCache}\r\n */\r\n get cache(): ModelCache {\r\n return this._cache;\r\n }\r\n\r\n private _Instance: ModelInterfaces.ModelSpecificInstanceConstructor;\r\n\r\n /**\r\n * Gets the constructor responsible for creating instances for this model\r\n */\r\n get Instance(): ModelInterfaces.ModelSpecificInstanceConstructor {\r\n return this._Instance;\r\n }\r\n\r\n private _transforms: Transforms;\r\n\r\n /**\r\n * Gets the transforms which are applied whenever a document is received from the database, or\r\n * prior to storing a document in the database. Tasks such as converting an ObjectID to a string\r\n * and vice versa are all listed in this object.\r\n */\r\n get transforms() {\r\n return this._transforms;\r\n }\r\n\r\n private _validators: Skmatc.Validator[];\r\n\r\n /**\r\n * Gets the custom validation types available for this model. These validators are added to the\r\n * default skmatc validators, as well as those available through plugins, for use when checking\r\n * your instances.\r\n */\r\n get validators() {\r\n return this._validators;\r\n }\r\n\r\n private _indexes: (Index.Index | Index.IndexSpecification)[];\r\n\r\n /**\r\n * Gets the indexes which Iridium will manage on this model's database collection.\r\n */\r\n get indexes() {\r\n return this._indexes;\r\n }\r\n\r\n /**\r\n * Retrieves all documents in the collection and wraps them as instances\r\n * @param {function(Error, TInstance[])} callback An optional callback which will be triggered when results are available\r\n * @returns {Promise}\r\n */\r\n find(): Cursor;\r\n /**\r\n * Returns all documents in the collection which match the conditions and wraps them as instances\r\n * @param {Object} conditions The MongoDB query dictating which documents to return\r\n * @returns {Promise}\r\n */\r\n find(conditions: { _id?: any, [key: string]: any } | any): Cursor;\r\n /**\r\n * Returns all documents in the collection which match the conditions\r\n * @param {Object} conditions The MongoDB query dictating which documents to return\r\n * @param {Object} fields The fields to include or exclude from the document\r\n * @returns {Promise}\r\n */\r\n find(conditions: { _id?: any, [key: string]: any } | any, fields: { [name: string]: number }): Cursor;\r\n find(conditions?: { _id?: any, [key: string]: any } | any, fields?: any): Cursor {\r\n conditions = conditions || {};\r\n fields = fields || {};\r\n\r\n if (!_.isPlainObject(conditions)) conditions = { _id: conditions };\r\n conditions = this._helpers.convertToDB(conditions);\r\n\r\n var cursor = this.collection.find(conditions, {\r\n fields: fields\r\n });\r\n\r\n return new Cursor(this, conditions, cursor);\r\n }\r\n\r\n /**\r\n * Retrieves a single document from the collection and wraps it as an instance\r\n * @param {function(Error, TInstance)} callback An optional callback which will be triggered when a result is available\r\n * @returns {Promise}\r\n */\r\n get(callback?: General.Callback): Bluebird;\r\n /**\r\n * Retrieves a single document from the collection with the given ID and wraps it as an instance\r\n * @param {any} id The document's unique _id field value in downstream format\r\n * @param {function(Error, TInstance)} callback An optional callback which will be triggered when a result is available\r\n * @returns {Promise}\r\n */\r\n get(id: any, callback?: General.Callback): Bluebird;\r\n /**\r\n * Retrieves a single document from the collection which matches the conditions\r\n * @param {Object} conditions The MongoDB query dictating which document to return\r\n * @param {function(Error, TInstance)} callback An optional callback which will be triggered when a result is available\r\n * @returns {Promise}\r\n */\r\n get(conditions: { _id?: any, [key: string]: any }, callback?: General.Callback): Bluebird;\r\n /**\r\n * Retrieves a single document from the collection with the given ID and wraps it as an instance\r\n * @param {any} id The document's unique _id field value in downstream format\r\n * @param {QueryOptions} options The options dictating how this function behaves\r\n * @param {function(Error, TInstance)} callback An optional callback which will be triggered when a result is available\r\n * @returns {Promise}\r\n */\r\n get(id: any, options: ModelOptions.QueryOptions, callback?: General.Callback): Bluebird;\r\n /**\r\n * Retrieves a single document from the collection which matches the conditions\r\n * @param {Object} conditions The MongoDB query dictating which document to return\r\n * @param {QueryOptions} options The options dictating how this function behaves\r\n * @param {function(Error, TInstance)} callback An optional callback which will be triggered when a result is available\r\n * @returns {Promise}\r\n */\r\n get(conditions: { _id?: any, [key: string]: any }, options: ModelOptions.QueryOptions, callback?: General.Callback): Bluebird;\r\n get(...args: any[]): Bluebird {\r\n return this.findOne.apply(this, args);\r\n }\r\n\r\n /**\r\n * Retrieves a single document from the collection and wraps it as an instance\r\n * @param {function(Error, TInstance)} callback An optional callback which will be triggered when a result is available\r\n * @returns {Promise}\r\n */\r\n findOne(callback?: General.Callback): Bluebird;\r\n /**\r\n * Retrieves a single document from the collection with the given ID and wraps it as an instance\r\n * @param {any} id The document's unique _id field value in downstream format\r\n * @param {function(Error, TInstance)} callback An optional callback which will be triggered when a result is available\r\n * @returns {Promise}\r\n */\r\n findOne(id: any, callback?: General.Callback): Bluebird;\r\n /**\r\n * Retrieves a single document from the collection which matches the conditions\r\n * @param {Object} conditions The MongoDB query dictating which document to return\r\n * @param {function(Error, TInstance)} callback An optional callback which will be triggered when a result is available\r\n * @returns {Promise}\r\n */\r\n findOne(conditions: { _id?: any, [key: string]: any }, callback?: General.Callback): Bluebird;\r\n /**\r\n * Retrieves a single document from the collection with the given ID and wraps it as an instance\r\n * @param {any} id The document's unique _id field value in downstream format\r\n * @param {QueryOptions} options The options dictating how this function behaves\r\n * @param {function(Error, TInstance)} callback An optional callback which will be triggered when a result is available\r\n * @returns {Promise}\r\n */\r\n findOne(id: any, options: ModelOptions.QueryOptions, callback?: General.Callback): Bluebird;\r\n /**\r\n * Retrieves a single document from the collection which matches the conditions\r\n * @param {Object} conditions The MongoDB query dictating which document to return\r\n * @param {QueryOptions} options The options dictating how this function behaves\r\n * @param {function(Error, TInstance)} callback An optional callback which will be triggered when a result is available\r\n * @returns {Promise}\r\n */\r\n findOne(conditions: { _id?: any, [key: string]: any }, options: ModelOptions.QueryOptions, callback?: General.Callback): Bluebird;\r\n findOne(...args: any[]): Bluebird {\r\n var conditions: { _id?: any, [key: string]: any } = null;\r\n var options: ModelOptions.QueryOptions = null;\r\n var callback: General.Callback = null;\r\n\r\n for (var argI = 0; argI < args.length; argI++) {\r\n if (typeof args[argI] == 'function') callback = callback || args[argI];\r\n else if (_.isPlainObject(args[argI])) {\r\n if (conditions) options = args[argI];\r\n else conditions = args[argI];\r\n }\r\n else conditions = { _id: args[argI] };\r\n }\r\n\r\n conditions = conditions || {};\r\n options = options || {};\r\n\r\n _.defaults(options, {\r\n cache: true\r\n });\r\n\r\n return Bluebird.resolve().bind(this).then(() => {\r\n conditions = this._helpers.convertToDB(conditions);\r\n\r\n return this._cache.get(conditions);\r\n }).then((cachedDocument: TDocument) => {\r\n if (cachedDocument) return cachedDocument;\r\n return new Bluebird((resolve, reject) => {\r\n this.collection.findOne(conditions, {\r\n fields: options.fields,\r\n skip: options.skip,\r\n sort: options.sort,\r\n limit: options.limit\r\n },(err, result) => {\r\n if (err) return reject(err);\r\n return resolve(result);\r\n });\r\n });\r\n }).then((document: TDocument) => {\r\n if (!document) return null;\r\n return this._handlers.documentReceived(conditions, document,(document, isNew?, isPartial?) => this._helpers.wrapDocument(document, isNew, isPartial), options);\r\n }).nodeify(callback);\r\n }\r\n\r\n /**\r\n * Inserts an object into the collection after validating it against this model's schema\r\n * @param {Object} object The object to insert into the collection\r\n * @param {function(Error, TInstance)} callback A callback which is triggered when the operation completes\r\n * @returns {Promise}\r\n */\r\n create(objects: TDocument, callback?: General.Callback): Bluebird;\r\n /**\r\n * Inserts an object into the collection after validating it against this model's schema\r\n * @param {Object} object The object to insert into the collection\r\n * @param {CreateOptions} options The options dictating how this function behaves\r\n * @param {function(Error, TInstance)} callback A callback which is triggered when the operation completes\r\n * @returns {Promise}\r\n */\r\n create(objects: TDocument, options: ModelOptions.CreateOptions, callback?: General.Callback): Bluebird;\r\n /**\r\n * Inserts the objects into the collection after validating them against this model's schema\r\n * @param {Object[]} objects The objects to insert into the collection\r\n * @param {function(Error, TInstance)} callback A callback which is triggered when the operation completes\r\n * @returns {Promise}\r\n */\r\n create(objects: TDocument[], callback?: General.Callback): Bluebird;\r\n /**\r\n * Inserts the objects into the collection after validating them against this model's schema\r\n * @param {Object[]} objects The objects to insert into the collection\r\n * @param {CreateOptions} options The options dictating how this function behaves\r\n * @param {function(Error, TInstance)} callback A callback which is triggered when the operation completes\r\n * @returns {Promise}\r\n */\r\n create(objects: TDocument[], options: ModelOptions.CreateOptions, callback?: General.Callback): Bluebird;\r\n create(...args: any[]): Bluebird {\r\n return this.insert.apply(this, args);\r\n }\r\n\r\n /**\r\n * Inserts an object into the collection after validating it against this model's schema\r\n * @param {Object} object The object to insert into the collection\r\n * @param {function(Error, TInstance)} callback A callback which is triggered when the operation completes\r\n * @returns {Promise}\r\n */\r\n insert(objects: TDocument, callback?: General.Callback): Bluebird;\r\n /**\r\n * Inserts an object into the collection after validating it against this model's schema\r\n * @param {Object} object The object to insert into the collection\r\n * @param {CreateOptions} options The options dictating how this function behaves\r\n * @param {function(Error, TInstance)} callback A callback which is triggered when the operation completes\r\n * @returns {Promise}\r\n */\r\n insert(objects: TDocument, options: ModelOptions.CreateOptions, callback?: General.Callback): Bluebird;\r\n /**\r\n * Inserts the objects into the collection after validating them against this model's schema\r\n * @param {Object[]} objects The objects to insert into the collection\r\n * @param {function(Error, TInstance[])} callback A callback which is triggered when the operation completes\r\n * @returns {Promise}\r\n */\r\n insert(objects: TDocument[], callback?: General.Callback): Bluebird;\r\n /**\r\n * Inserts the objects into the collection after validating them against this model's schema\r\n * @param {Object[]} objects The objects to insert into the collection\r\n * @param {CreateOptions} options The options dictating how this function behaves\r\n * @param {function(Error, TInstance[])} callback A callback which is triggered when the operation completes\r\n * @returns {Promise}\r\n */\r\n insert(objects: TDocument[], options: ModelOptions.CreateOptions, callback?: General.Callback): Bluebird;\r\n insert(objs: TDocument | TDocument[], ...args: any[]): Bluebird {\r\n var objects: TDocument[];\r\n var options: ModelOptions.CreateOptions = {};\r\n var callback: General.Callback = null;\r\n if (typeof args[0] == 'function') callback = args[0];\r\n else {\r\n options = args[0];\r\n callback = args[1];\r\n }\r\n\r\n if (Array.isArray(objs))\r\n objects = objs;\r\n else\r\n objects = [objs];\r\n\r\n options = options || {};\r\n _.defaults(options, {\r\n w: 'majority',\r\n forceServerObjectId: true\r\n });\r\n\r\n return Bluebird.resolve().then(() => {\r\n var queryOptions = { w: options.w, upsert: options.upsert, new: true };\r\n\r\n if (options.upsert) {\r\n var docs = this._handlers.creatingDocuments(objects);\r\n return docs.map((object: { _id: any; }) => {\r\n return new Bluebird((resolve, reject) => {\r\n this.collection.findAndModify({ _id: object._id }, [\"_id\"], object, queryOptions,(err, result) => {\r\n if (err) return reject(err);\r\n return resolve(result);\r\n });\r\n });\r\n });\r\n }\r\n else\r\n return this._handlers.creatingDocuments(objects).then(objects => _.chunk(objects, 1000)).map((objects: any[]) => {\r\n return new Bluebird((resolve, reject) => {\r\n this.collection.insertMany(objects, queryOptions,(err, result) => {\r\n if (err) return reject(err);\r\n return resolve(result.ops);\r\n });\r\n });\r\n }).then(results => _.flatten(results));\r\n }).map((inserted: any) => {\r\n return this._handlers.documentReceived(null, inserted,(document, isNew?, isPartial?) => this._helpers.wrapDocument(document, isNew, isPartial), { cache: options.cache });\r\n }).then((results: TInstance[]) => {\r\n if (Array.isArray(objs)) return results;\r\n return results[0];\r\n }).nodeify(callback);\r\n }\r\n\r\n /**\r\n * Updates the documents in the backing collection which match the conditions using the given update instructions\r\n * @param {Object} conditions The conditions which determine which documents will be updated\r\n * @param {Object} changes The changes to make to the documents\r\n * @param {function(Error, Number)} callback A callback which is triggered when the operation completes\r\n */\r\n update(conditions: { _id?: any, [key: string]: any } | any, changes: any, callback?: General.Callback): Bluebird;\r\n /**\r\n * Updates the documents in the backing collection which match the conditions using the given update instructions\r\n * @param {Object} conditions The conditions which determine which documents will be updated\r\n * @param {Object} changes The changes to make to the documents\r\n * @param {UpdateOptions} options The options which dictate how this function behaves\r\n * @param {function(Error, Number)} callback A callback which is triggered when the operation completes\r\n */\r\n update(conditions: { _id?: any, [key: string]: any } | any, changes: any, options: ModelOptions.UpdateOptions, callback?: General.Callback): Bluebird;\r\n update(conditions: { _id?: any, [key: string]: any } | any, changes: any, options?: ModelOptions.UpdateOptions, callback?: General.Callback): Bluebird {\r\n if (typeof options == 'function') {\r\n callback = >options;\r\n options = {};\r\n }\r\n\r\n options = options || {};\r\n\r\n if (!_.isPlainObject(conditions)) conditions = {\r\n _id: conditions\r\n };\r\n\r\n _.defaults(options, {\r\n w: 'majority',\r\n multi: true\r\n });\r\n\r\n return Bluebird.resolve().then(() => {\r\n conditions = this._helpers.convertToDB(conditions);\r\n\r\n return new Bluebird((resolve, reject) => {\r\n this.collection.updateMany(conditions, changes, options,(err, response) => {\r\n if (err) return reject(err);\r\n\r\n // New MongoDB 2.6+ response type\r\n if (response.result && response.result.nModified !== undefined) return resolve(response.result.nModified);\r\n\r\n // Legacy response type\r\n return resolve(response.result.n);\r\n });\r\n })\r\n }).nodeify(callback);\r\n }\r\n\r\n /**\r\n * Counts the number of documents in the collection\r\n * @param {function(Error, Number)} callback A callback which is triggered when the operation completes\r\n * @returns {Promise}\r\n */\r\n count(callback?: General.Callback): Bluebird;\r\n /**\r\n * Counts the number of documents in the collection which match the conditions provided\r\n * @param {Object} conditions The conditions which determine whether an object is counted or not\r\n * @param {function(Error, Number)} callback A callback which is triggered when the operation completes\r\n * @returns {Promise}\r\n */\r\n count(conditions: { _id?: any, [key: string]: any } | any, callback?: General.Callback): Bluebird;\r\n count(conds?: any, callback?: General.Callback): Bluebird {\r\n var conditions: { _id?: any, [key: string]: any } = <{ _id?: any, [key: string]: any }>conds;\r\n if (typeof conds == 'function') {\r\n callback = >conds;\r\n conditions = {};\r\n }\r\n\r\n conditions = conditions || {};\r\n\r\n if (!_.isPlainObject(conditions)) conditions = {\r\n _id: conditions\r\n };\r\n\r\n return Bluebird.resolve().then(() => {\r\n conditions = this._helpers.convertToDB(conditions);\r\n\r\n return new Bluebird((resolve, reject) => {\r\n this.collection.count(conditions,(err, results) => {\r\n if (err) return reject(err);\r\n return resolve(results);\r\n });\r\n });\r\n }).nodeify(callback);\r\n }\r\n\r\n /**\r\n * Removes all documents from the collection\r\n * @param {function(Error, Number)} callback A callback which is triggered when the operation completes\r\n * @returns {Promise}\r\n */\r\n remove(callback?: General.Callback): Bluebird;\r\n /**\r\n * Removes all documents from the collection which match the conditions\r\n * @param {Object} conditions The conditions determining whether an object is removed or not\r\n * @param {function(Error, Number)} callback A callback which is triggered when the operation completes\r\n * @returns {Promise}\r\n */\r\n remove(conditions: { _id?: any, [key: string]: any } | any, callback?: General.Callback): Bluebird;\r\n /**\r\n * Removes all documents from the collection which match the conditions\r\n * @param {Object} conditions The conditions determining whether an object is removed or not\r\n * @param {Object} options The options controlling the way in which the function behaves\r\n * @param {function(Error, Number)} callback A callback which is triggered when the operation completes\r\n * @returns {Promise}\r\n */\r\n remove(conditions: { _id?: any, [key: string]: any }, options: ModelOptions.RemoveOptions, callback?: General.Callback): Bluebird;\r\n remove(conds?: any, options?: ModelOptions.RemoveOptions, callback?: General.Callback): Bluebird {\r\n var conditions: { _id?: any, [key: string]: any } = <{ _id?: any, [key: string]: any }>conds;\r\n\r\n if (typeof options === 'function') {\r\n callback = >options;\r\n options = {};\r\n }\r\n\r\n if (typeof conds == 'function') {\r\n callback = >conds;\r\n options = {};\r\n conditions = {};\r\n }\r\n\r\n conditions = conditions || {};\r\n options = options || {};\r\n\r\n _.defaults(options, {\r\n w: 'majority'\r\n });\r\n\r\n if (!_.isPlainObject(conditions)) conditions = {\r\n _id: conditions\r\n };\r\n\r\n return Bluebird.resolve().then(() => {\r\n conditions = this._helpers.convertToDB(conditions);\r\n\r\n return new Bluebird((resolve, reject) => {\r\n this.collection.remove(conditions, options,(err, response) => {\r\n if (err) return reject(err);\r\n return resolve(response.result.n);\r\n });\r\n });\r\n }).then((count) => {\r\n if (count === 1) this._cache.clear(conditions);\r\n return Bluebird.resolve(count);\r\n }).nodeify(callback);\r\n }\r\n\r\n aggregate(pipeline: AggregationPipeline.Stage[]): Bluebird {\r\n return new Bluebird((resolve, reject) => {\r\n this.collection.aggregate(pipeline, (err, results) => {\r\n if(err) return reject(err);\r\n return resolve(results);\r\n });\r\n });\r\n }\r\n\r\n /**\r\n * Ensures that the given index is created for the collection\r\n * @param {Object} specification The index specification object used by MongoDB\r\n * @param {function(Error, String)} callback A callback which is triggered when the operation completes\r\n * @returns {Promise} The name of the index\r\n */\r\n ensureIndex(specification: Index.IndexSpecification, callback?: General.Callback): Bluebird;\r\n /**\r\n * Ensures that the given index is created for the collection\r\n * @param {Object} specification The index specification object used by MongoDB\r\n * @param {MongoDB.IndexOptions} options The options dictating how the index is created and behaves\r\n * @param {function(Error, String)} callback A callback which is triggered when the operation completes\r\n * @returns {Promise} The name of the index\r\n */\r\n ensureIndex(specification: Index.IndexSpecification, options: MongoDB.IndexOptions, callback?: General.Callback): Bluebird;\r\n ensureIndex(specification: Index.IndexSpecification, options?: MongoDB.IndexOptions, callback?: General.Callback): Bluebird {\r\n if (typeof options == 'function') {\r\n callback = >options;\r\n options = {};\r\n }\r\n\r\n return new Bluebird((resolve, reject) => {\r\n this.collection.ensureIndex(specification, options,(err, name: any) => {\r\n if (err) return reject(err);\r\n return resolve(name);\r\n });\r\n }).nodeify(callback);\r\n }\r\n\r\n /**\r\n * Ensures that all indexes defined in the model's options are created\r\n * @param {function(Error, String[])} callback A callback which is triggered when the operation completes\r\n * @returns {Promise} The names of the indexes\r\n */\r\n ensureIndexes(callback?: General.Callback): Bluebird {\r\n return Bluebird.resolve(this._indexes).map((index: Index.Index | Index.IndexSpecification) => {\r\n return this.ensureIndex((index).spec || index,(index).options || {});\r\n }).nodeify(callback);\r\n }\r\n\r\n /**\r\n * Drops the index with the specified name if it exists in the collection\r\n * @param {String} name The name of the index to remove\r\n * @param {function(Error, Boolean)} callback A callback which is triggered when the operation completes\r\n * @returns {Promise} Whether the index was dropped\r\n */\r\n dropIndex(name: string, callback?: General.Callback): Bluebird;\r\n /**\r\n * Drops the index if it exists in the collection\r\n * @param {IndexSpecification} index The index to remove\r\n * @param {function(Error, Boolean)} callback A callback which is triggered when the operation completes\r\n * @returns {Promise} Whether the index was dropped\r\n */\r\n dropIndex(index: Index.IndexSpecification, callback?: General.Callback): Bluebird;\r\n dropIndex(specification: string | Index.IndexSpecification, callback?: General.Callback): Bluebird {\r\n var index: string;\r\n\r\n if (typeof (specification) === 'string') index = specification;\r\n else {\r\n index = _(specification).map((direction, key) => key + '_' + direction).reduce((x, y) => x + '_' + y);\r\n }\r\n\r\n return new Bluebird((resolve, reject) => {\r\n this.collection.dropIndex(index,(err, result: { ok: number }) => {\r\n if (err) return reject(err);\r\n return resolve(!!result.ok);\r\n });\r\n }).nodeify(callback);\r\n }\r\n\r\n /**\r\n * Removes all indexes (except for _id) from the collection\r\n * @param {function(Error, Boolean)} callback A callback which is triggered when the operation completes\r\n * @returns {Promise} Whether the indexes were dropped\r\n */\r\n dropIndexes(callback?: General.Callback): Bluebird {\r\n return new Bluebird((resolve, reject) => {\r\n this.collection.dropAllIndexes((err, count) => {\r\n if (err) return reject(err);\r\n return resolve(count);\r\n });\r\n }).nodeify(callback);\r\n }\r\n}\r\n"],"sourceRoot":"/source/"} \ No newline at end of file diff --git a/dist/lib/ModelCache.js b/dist/lib/ModelCache.js index 3f69829..dcdac0b 100644 --- a/dist/lib/ModelCache.js +++ b/dist/lib/ModelCache.js @@ -1,4 +1,9 @@ var Bluebird = require('bluebird'); +/** + * A centralized class which ties the cache and cache directors together in a cohesive way + * for use by Iridium. + * @internal + */ var ModelCache = (function () { function ModelCache(model) { this.model = model; @@ -20,6 +25,6 @@ var ModelCache = (function () { }; return ModelCache; })(); -exports.default = ModelCache; +exports.ModelCache = ModelCache; //# sourceMappingURL=../lib/ModelCache.js.map \ No newline at end of file diff --git a/dist/lib/ModelCache.js.map b/dist/lib/ModelCache.js.map index d549311..50e57fa 100644 --- a/dist/lib/ModelCache.js.map +++ b/dist/lib/ModelCache.js.map @@ -1 +1 @@ -{"version":3,"sources":["lib/ModelCache.ts"],"names":["ModelCache","ModelCache.constructor","ModelCache.set","ModelCache.get","ModelCache.clear"],"mappings":"AAEA,IAAO,QAAQ,WAAW,UAAU,CAAC,CAAC;AAEtC;IACIA,oBAAmBA,KAAqBA;QAArBC,UAAKA,GAALA,KAAKA,CAAgBA;IAExCA,CAACA;IAEDD,wBAAGA,GAAHA,UAAOA,KAAQA;QACXE,EAAEA,CAACA,CAACA,CAACA,IAAIA,CAACA,KAAKA,CAACA,aAAaA,IAAIA,CAACA,IAAIA,CAACA,KAAKA,CAACA,aAAaA,CAACA,KAAKA,CAACA,KAAKA,CAACA,CAACA;YAACA,MAAMA,CAACA;QAChFA,IAAIA,CAACA,KAAKA,CAACA,IAAIA,CAACA,KAAKA,CAACA,GAAGA,CAACA,IAAIA,CAACA,KAAKA,CAACA,aAAaA,CAACA,QAAQA,CAACA,KAAKA,CAACA,EAAEA,KAAKA,CAACA,CAACA;IAC/EA,CAACA;IAEDF,wBAAGA,GAAHA,UAAOA,UAAeA;QAClBG,EAAEA,CAACA,CAACA,CAACA,IAAIA,CAACA,KAAKA,CAACA,aAAaA,IAAIA,CAACA,IAAIA,CAACA,KAAKA,CAACA,aAAaA,CAACA,UAAUA,CAACA,UAAUA,CAACA,CAACA;YAACA,MAAMA,CAACA,QAAQA,CAACA,OAAOA,CAAIA,IAAIA,CAACA,CAACA;QACpHA,MAAMA,CAACA,IAAIA,CAACA,KAAKA,CAACA,IAAIA,CAACA,KAAKA,CAACA,GAAGA,CAAIA,IAAIA,CAACA,KAAKA,CAACA,aAAaA,CAACA,aAAaA,CAACA,UAAUA,CAACA,CAACA,CAACA;IAC5FA,CAACA;IAEDH,0BAAKA,GAALA,UAAMA,UAAeA;QACjBI,EAAEA,CAACA,CAACA,CAACA,IAAIA,CAACA,KAAKA,CAACA,aAAaA,IAAIA,CAACA,IAAIA,CAACA,KAAKA,CAACA,aAAaA,CAACA,UAAUA,CAACA,UAAUA,CAACA,CAACA;YAACA,MAAMA,CAACA;QAC1FA,IAAIA,CAACA,KAAKA,CAACA,IAAIA,CAACA,KAAKA,CAACA,KAAKA,CAACA,IAAIA,CAACA,KAAKA,CAACA,aAAaA,CAACA,aAAaA,CAACA,UAAUA,CAACA,CAACA,CAACA;IACpFA,CAACA;IACLJ,iBAACA;AAADA,CAnBA,AAmBCA,IAAA;AAnBD,4BAmBC,CAAA","file":"lib/ModelCache.js","sourcesContent":["/// \r\nimport Model from './Model';\r\nimport Bluebird = require('bluebird');\r\n\r\nexport default class ModelCache {\r\n constructor(public model: Model) {\r\n\r\n }\r\n\r\n set(value: T): void {\r\n if (!this.model.cacheDirector || !this.model.cacheDirector.valid(value)) return;\r\n this.model.core.cache.set(this.model.cacheDirector.buildKey(value), value);\r\n }\r\n\r\n get(conditions: any): Bluebird {\r\n if (!this.model.cacheDirector || !this.model.cacheDirector.validQuery(conditions)) return Bluebird.resolve(null);\r\n return this.model.core.cache.get(this.model.cacheDirector.buildQueryKey(conditions));\r\n }\r\n\r\n clear(conditions: any): void {\r\n if (!this.model.cacheDirector || !this.model.cacheDirector.validQuery(conditions)) return;\r\n this.model.core.cache.clear(this.model.cacheDirector.buildQueryKey(conditions));\r\n }\r\n}\r\n"],"sourceRoot":"/source/"} \ No newline at end of file +{"version":3,"sources":["lib/ModelCache.ts"],"names":["ModelCache","ModelCache.constructor","ModelCache.set","ModelCache.get","ModelCache.clear"],"mappings":"AAEA,IAAO,QAAQ,WAAW,UAAU,CAAC,CAAC;AAEtC;;;;GAIG;AACH;IACIA,oBAAmBA,KAAqBA;QAArBC,UAAKA,GAALA,KAAKA,CAAgBA;IAExCA,CAACA;IAEDD,wBAAGA,GAAHA,UAAOA,KAAQA;QACXE,EAAEA,CAACA,CAACA,CAACA,IAAIA,CAACA,KAAKA,CAACA,aAAaA,IAAIA,CAACA,IAAIA,CAACA,KAAKA,CAACA,aAAaA,CAACA,KAAKA,CAACA,KAAKA,CAACA,CAACA;YAACA,MAAMA,CAACA;QAChFA,IAAIA,CAACA,KAAKA,CAACA,IAAIA,CAACA,KAAKA,CAACA,GAAGA,CAACA,IAAIA,CAACA,KAAKA,CAACA,aAAaA,CAACA,QAAQA,CAACA,KAAKA,CAACA,EAAEA,KAAKA,CAACA,CAACA;IAC/EA,CAACA;IAEDF,wBAAGA,GAAHA,UAAOA,UAAeA;QAClBG,EAAEA,CAACA,CAACA,CAACA,IAAIA,CAACA,KAAKA,CAACA,aAAaA,IAAIA,CAACA,IAAIA,CAACA,KAAKA,CAACA,aAAaA,CAACA,UAAUA,CAACA,UAAUA,CAACA,CAACA;YAACA,MAAMA,CAACA,QAAQA,CAACA,OAAOA,CAAIA,IAAIA,CAACA,CAACA;QACpHA,MAAMA,CAACA,IAAIA,CAACA,KAAKA,CAACA,IAAIA,CAACA,KAAKA,CAACA,GAAGA,CAAIA,IAAIA,CAACA,KAAKA,CAACA,aAAaA,CAACA,aAAaA,CAACA,UAAUA,CAACA,CAACA,CAACA;IAC5FA,CAACA;IAEDH,0BAAKA,GAALA,UAAMA,UAAeA;QACjBI,EAAEA,CAACA,CAACA,CAACA,IAAIA,CAACA,KAAKA,CAACA,aAAaA,IAAIA,CAACA,IAAIA,CAACA,KAAKA,CAACA,aAAaA,CAACA,UAAUA,CAACA,UAAUA,CAACA,CAACA;YAACA,MAAMA,CAACA;QAC1FA,IAAIA,CAACA,KAAKA,CAACA,IAAIA,CAACA,KAAKA,CAACA,KAAKA,CAACA,IAAIA,CAACA,KAAKA,CAACA,aAAaA,CAACA,aAAaA,CAACA,UAAUA,CAACA,CAACA,CAACA;IACpFA,CAACA;IACLJ,iBAACA;AAADA,CAnBA,AAmBCA,IAAA;AAnBY,kBAAU,aAmBtB,CAAA","file":"lib/ModelCache.js","sourcesContent":["/// \r\nimport {Model} from './Model';\r\nimport Bluebird = require('bluebird');\r\n\r\n/**\r\n * A centralized class which ties the cache and cache directors together in a cohesive way\r\n * for use by Iridium.\r\n * @internal\r\n */\r\nexport class ModelCache {\r\n constructor(public model: Model) {\r\n\r\n }\r\n\r\n set(value: T): void {\r\n if (!this.model.cacheDirector || !this.model.cacheDirector.valid(value)) return;\r\n this.model.core.cache.set(this.model.cacheDirector.buildKey(value), value);\r\n }\r\n\r\n get(conditions: any): Bluebird {\r\n if (!this.model.cacheDirector || !this.model.cacheDirector.validQuery(conditions)) return Bluebird.resolve(null);\r\n return this.model.core.cache.get(this.model.cacheDirector.buildQueryKey(conditions));\r\n }\r\n\r\n clear(conditions: any): void {\r\n if (!this.model.cacheDirector || !this.model.cacheDirector.validQuery(conditions)) return;\r\n this.model.core.cache.clear(this.model.cacheDirector.buildQueryKey(conditions));\r\n }\r\n}\r\n"],"sourceRoot":"/source/"} \ No newline at end of file diff --git a/dist/lib/ModelHandlers.js b/dist/lib/ModelHandlers.js index 0ab058d..caeca40 100644 --- a/dist/lib/ModelHandlers.js +++ b/dist/lib/ModelHandlers.js @@ -1,5 +1,13 @@ var _ = require('lodash'); var Bluebird = require('bluebird'); +/** + * Provides a number of methods which are used to handle events that occur within + * the Iridium workflow - such as what happens when a document is received from + * the database, or how to handle the creation of new documents and saving of instances. + * + * Mostly this is for cache support, wrapping and hook triggering. + * @internal + */ var ModelHandlers = (function () { function ModelHandlers(model) { this.model = model; @@ -52,6 +60,6 @@ var ModelHandlers = (function () { }; return ModelHandlers; })(); -exports.default = ModelHandlers; +exports.ModelHandlers = ModelHandlers; //# sourceMappingURL=../lib/ModelHandlers.js.map \ No newline at end of file diff --git a/dist/lib/ModelHandlers.js.map b/dist/lib/ModelHandlers.js.map index fded2bf..bd8b075 100644 --- a/dist/lib/ModelHandlers.js.map +++ b/dist/lib/ModelHandlers.js.map @@ -1 +1 @@ -{"version":3,"sources":["lib/ModelHandlers.ts"],"names":["ModelHandlers","ModelHandlers.constructor","ModelHandlers.documentReceived","ModelHandlers.creatingDocuments","ModelHandlers.savingDocument"],"mappings":"AAOA,IAAO,CAAC,WAAW,QAAQ,CAAC,CAAC;AAE7B,IAAO,QAAQ,WAAW,UAAU,CAAC,CAAC;AAEtC;IACIA,uBAAmBA,KAAkCA;QAAlCC,UAAKA,GAALA,KAAKA,CAA6BA;IAErDA,CAACA;IAEDD,wCAAgBA,GAAhBA,UAA0BA,UAAeA,EACrCA,MAAiBA,EACjBA,OAA+EA,EAC/EA,OAAuCA;QAH3CE,iBA2BCA;QAxBGA,uBAAuCA,GAAvCA,YAAuCA;QACvCA,CAACA,CAACA,QAAQA,CAACA,OAAOA,EAAEA;YAChBA,KAAKA,EAAEA,IAAIA;YACXA,OAAOA,EAAEA,KAAKA;SACjBA,CAACA,CAACA;QAEHA,MAAMA,CAACA,QAAQA,CAACA,OAAOA,CAACA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AACA,IAAIA,CAACA;gBAC3BA,EAAEA,CAACA,CAACA,KAAIA,CAACA,KAAKA,CAACA,KAAKA,CAACA,UAAUA,CAACA;oBAACA,KAAIA,CAACA,KAAKA,CAACA,KAAKA,CAACA,UAAUA,CAACA,QAAQA,CAACA,CAACA;gBACvEA,QAAQA,GAAGA,KAAIA,CAACA,KAAKA,CAACA,OAAOA,CAACA,WAAWA,CAACA,QAAQA,CAACA,CAACA;gBACpDA,IAAIA,UAAUA,GAAkBA,KAAIA,CAACA,KAAKA,CAACA,OAAOA,CAACA,QAAQA,CAACA,QAAQA,CAACA,CAACA;gBACtEA,EAAEA,CAACA,CAACA,UAAUA,CAACA,MAAMA,CAACA;oBAACA,MAAMA,CAACA,QAAQA,CAACA,MAAMA,CAACA,UAAUA,CAACA,KAAKA,CAACA,CAACA;gBAEhEA,MAAMA,CAACA,QAAQA,CAACA;YACpBA,CAACA,CAACA,CAACA;QACPA,CAACA,CAACA,CAACA,CAACA;IACRA,CAACA;IAEDH,sCAAcA,GAAdA,UAAeA,QAAmBA,EAAEA,OAAYA;QAAhDI,iBAKCA;QAJGA,MAAMA,CAACA,QAAQA,CAACA,OAAOA,EAAEA,CAACA,IAAIA,CAACA;YAC3BA,EAAEA,CAACA,CAACA,KAAIA,CAACA,KAAKA,CAACA,KAAKA,CAACA,QAAQA,CAACA;gBAACA,KAAIA,CAACA,KAAKA,CAACA,KAAKA,CAACA,QAAQA,CAACA,QAAQA,EAAEA,OAAOA,CAACA,CAACA;YAC5EA,MAAMA,CAACA,QAAQA,CAACA;QACpBA,CAACA,CAACA,CAACA;IACPA,CAACA;IACLJ,oBAACA;AAADA,CArDA,AAqDCA,IAAA;AArDD,+BAqDC,CAAA","file":"lib/ModelHandlers.js","sourcesContent":["/// \r\nimport Core from './Core';\r\nimport {Schema} from './Schema';\r\nimport Model from './Model';\r\nimport ModelCache from './ModelCache';\r\nimport * as ModelOptions from './ModelOptions';\r\n\r\nimport _ = require('lodash');\r\nimport MongoDB = require('mongodb');\r\nimport Bluebird = require('bluebird');\r\n\r\nexport default class ModelHandlers {\r\n constructor(public model: Model) {\r\n\r\n }\r\n\r\n documentReceived(conditions: any,\r\n result: TDocument,\r\n wrapper: (document: TDocument, isNew?: boolean, isPartial?: boolean) => TResult,\r\n options: ModelOptions.QueryOptions = {}): Bluebird {\r\n _.defaults(options, {\r\n cache: true,\r\n partial: false\r\n });\r\n\r\n return Bluebird.resolve(result).then((target: any) => {\r\n return >Bluebird.resolve().then(() => {\r\n\r\n // Cache the document if caching is enabled\r\n if (this.model.core.cache && options.cache && !options.fields) {\r\n this.model.cache.set(target); // Does not block execution pipeline - fire and forget\r\n }\r\n \r\n // Trigger the received hook\r\n if (this.model.hooks.onRetrieved) this.model.hooks.onRetrieved(target);\r\n\r\n // Wrap the document and trigger the ready hook\r\n let wrapped: TResult = wrapper(target, false, !!options.fields);\r\n\r\n if (this.model.hooks.onReady && wrapped instanceof this.model.Instance) this.model.hooks.onReady(wrapped);\r\n return wrapped;\r\n });\r\n });\r\n }\r\n\r\n creatingDocuments(documents: TDocument[]): Bluebird {\r\n return Bluebird.all(documents.map((document: any) => {\r\n return Bluebird.resolve().then(() => {\r\n if (this.model.hooks.onCreating) this.model.hooks.onCreating(document);\r\n document = this.model.helpers.convertToDB(document);\r\n let validation: Skmatc.Result = this.model.helpers.validate(document);\r\n if (validation.failed) return Bluebird.reject(validation.error);\r\n \r\n return document;\r\n });\r\n }));\r\n }\r\n\r\n savingDocument(instance: TInstance, changes: any): Bluebird {\r\n return Bluebird.resolve().then(() => {\r\n if (this.model.hooks.onSaving) this.model.hooks.onSaving(instance, changes);\r\n return instance;\r\n });\r\n }\r\n}\r\n"],"sourceRoot":"/source/"} \ No newline at end of file +{"version":3,"sources":["lib/ModelHandlers.ts"],"names":["ModelHandlers","ModelHandlers.constructor","ModelHandlers.documentReceived","ModelHandlers.creatingDocuments","ModelHandlers.savingDocument"],"mappings":"AAOA,IAAO,CAAC,WAAW,QAAQ,CAAC,CAA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AACA,KAAIA,CAACA,KAAKA,CAACA,KAAKA,CAACA,QAAQA,CAACA;gBAACA,KAAIA,CAACA,KAAKA,CAACA,KAAKA,CAACA,QAAQA,CAACA,QAAQA,EAAEA,OAAOA,CAACA,CAACA;YAC5EA,MAAMA,CAACA,QAAQA,CAACA;QACpBA,CAACA,CAACA,CAACA;IACPA,CAACA;IACLJ,oBAACA;AAADA,CArDA,AAqDCA,IAAA;AArDY,qBAAa,gBAqDzB,CAAA","file":"lib/ModelHandlers.js","sourcesContent":["/// \r\nimport {Core} from './Core';\r\nimport {Schema} from './Schema';\r\nimport {Model} from './Model';\r\nimport {ModelCache} from './ModelCache';\r\nimport * as ModelOptions from './ModelOptions';\r\n\r\nimport _ = require('lodash');\r\nimport MongoDB = require('mongodb');\r\nimport Bluebird = require('bluebird');\r\n\r\n/**\r\n * Provides a number of methods which are used to handle events that occur within\r\n * the Iridium workflow - such as what happens when a document is received from\r\n * the database, or how to handle the creation of new documents and saving of instances.\r\n * \r\n * Mostly this is for cache support, wrapping and hook triggering.\r\n * @internal\r\n */\r\nexport class ModelHandlers {\r\n constructor(public model: Model) {\r\n\r\n }\r\n\r\n documentReceived(conditions: any,\r\n result: TDocument,\r\n wrapper: (document: TDocument, isNew?: boolean, isPartial?: boolean) => TResult,\r\n options: ModelOptions.QueryOptions = {}): Bluebird {\r\n _.defaults(options, {\r\n cache: true,\r\n partial: false\r\n });\r\n\r\n return Bluebird.resolve(result).then((target: any) => {\r\n return >Bluebird.resolve().then(() => {\r\n\r\n // Cache the document if caching is enabled\r\n if (this.model.core.cache && options.cache && !options.fields) {\r\n this.model.cache.set(target); // Does not block execution pipeline - fire and forget\r\n }\r\n \r\n // Trigger the received hook\r\n if (this.model.hooks.onRetrieved) this.model.hooks.onRetrieved(target);\r\n\r\n // Wrap the document and trigger the ready hook\r\n let wrapped: TResult = wrapper(target, false, !!options.fields);\r\n\r\n if (this.model.hooks.onReady && wrapped instanceof this.model.Instance) this.model.hooks.onReady(wrapped);\r\n return wrapped;\r\n });\r\n });\r\n }\r\n\r\n creatingDocuments(documents: TDocument[]): Bluebird {\r\n return Bluebird.all(documents.map((document: any) => {\r\n return Bluebird.resolve().then(() => {\r\n if (this.model.hooks.onCreating) this.model.hooks.onCreating(document);\r\n document = this.model.helpers.convertToDB(document);\r\n let validation: Skmatc.Result = this.model.helpers.validate(document);\r\n if (validation.failed) return Bluebird.reject(validation.error);\r\n \r\n return document;\r\n });\r\n }));\r\n }\r\n\r\n savingDocument(instance: TInstance, changes: any): Bluebird {\r\n return Bluebird.resolve().then(() => {\r\n if (this.model.hooks.onSaving) this.model.hooks.onSaving(instance, changes);\r\n return instance;\r\n });\r\n }\r\n}\r\n"],"sourceRoot":"/source/"} \ No newline at end of file diff --git a/dist/lib/ModelHelpers.js b/dist/lib/ModelHelpers.js index a8d4e9c..a5b77b8 100644 --- a/dist/lib/ModelHelpers.js +++ b/dist/lib/ModelHelpers.js @@ -1,6 +1,12 @@ var skmatc = require('skmatc'); var Omnom_1 = require('./utils/Omnom'); var _ = require('lodash'); +/** + * A number of helper methods used commonly within Iridium, they provide a means to transform, + * validate, wrap and diff instances and documents. By keeping these methods in one place we + * help to improve testability and reduce code duplication (mouse abuse) throughout the codebase. + * @internal + */ var ModelHelpers = (function () { function ModelHelpers(model) { var _this = this; @@ -54,12 +60,12 @@ var ModelHelpers = (function () { * @param {any} modified The document after changes were made */ ModelHelpers.prototype.diff = function (original, modified) { - var omnom = new Omnom_1.default(); + var omnom = new Omnom_1.Omnom(); omnom.diff(original, modified); return omnom.changes; }; return ModelHelpers; })(); -exports.default = ModelHelpers; +exports.ModelHelpers = ModelHelpers; //# sourceMappingURL=../lib/ModelHelpers.js.map \ No newline at end of file diff --git a/dist/lib/ModelHelpers.js.map b/dist/lib/ModelHelpers.js.map index 051c1b1..9c971f9 100644 --- a/dist/lib/ModelHelpers.js.map +++ b/dist/lib/ModelHelpers.js.map @@ -1 +1 @@ -{"version":3,"sources":["lib/ModelHelpers.ts"],"names":["ModelHelpers","ModelHelpers.constructor","ModelHelpers.validate","ModelHelpers.wrapDocument","ModelHelpers.transformToDB","ModelHelpers.convertToDB","ModelHelpers.diff"],"mappings":"AAGA,IAAO,MAAM,WAAW,QAAQ,CAAC,CAAC;AAClC,sBAAkB,eAAe,CAAC,CAAA;AAClC,IAAO,CAAC,WAAW,QAAQ,CAAC,CAAC;AAG7B;IACIA,sBAAmBA,KAAkCA;QADzDC,iBA8DCA;QA7DsBA,UAAKA,GAALA,KAAKA,CAA6BA;QACjDA,IAAIA,CAACA,UAAUA,GAAGA,IAAIA,MAAMA,CAACA,KAAKA,CAACA,MAAMA,CAACA,CAACA;QAC3CA,KAAKA,CAACA,UAAUA,CAACA,OAAOA,CAACA,UAAAA,SAASA,IAAIA,OAAAA,KAAIA,CAACA,UAAUA,CAACA,QAAQA,CAACA,SAASA,CAACA,EAAnCA,CAAmCA,CAACA,CAACA;IAC/EA,CAACA;IAIDD;;;;OAIGA;IACHA,+BAAQA,GAARA,UAASA,QAAmBA;QACxBE,MAAMA,CAACA,IAAIA,CAACA,UAAUA,CAACA,QAAQA,CAACA,QAAQA,CAACA,CAACA;IAC9CA,CAACA;IAEDF;;;;;;OAMGA;IACHA,mCAAYA,GAAZA,UAAaA,QAAmBA,EAAEA,KAAeA,EAAEA,SAAmBA;QAClEG,MAAMA,CAACA,IAAIA,IAAIA,CAACA,KAAKA,CAACA,QAAQA,CAACA,QAAQA,EAAEA,KAAKA,EAAEA,SAASA,CAACA,CAACA;IAC/DA,CAACA;IAEDH;;;;;OAKGA;IACHA,oCAAaA,GAAbA,UAAiBA,QAAWA;QACxBI,GAAGA,CAACA,CAACA,GAAGA,CAACA,QAAQA,IAAIA,IAAIA,CAACA,KAAKA,CAACA,UAAUA,CAACA;YACvCA,EAAEA,CAAAA,CAACA,QAAQA,CAACA,cAAcA,CAACA,QAAQA,CAACA,CAACA;gBACjCA,QAAQA,CAACA,QAAQA,CAACA,GAAGA,IAAIA,CAACA,KAAKA,CAACA,UAAUA,CAACA,QAAQA,CAACA,CAACA,IAAIA,CAACA,QAAQA,CAACA,QAAQA,CAACA,CAACA,CAACA;QACtFA,MAAMA,CAACA,QAAQA,CAACA;IACpBA,CAACA;IAEDJ;;;;;OAKGA;IACHA,kCAAWA,GAAXA,UAAeA,QAAWA;QACtBK,IAAIA,GAAGA,GAAMA,CAACA,CAACA,SAASA,CAACA,QAAQA,CAACA,CAACA;QACnCA,MAAMA,CAACA,IAAIA,CAACA,aAAaA,CAACA,GAAGA,CAACA,CAACA;IACnCA,CAACA;IAEDL;;;;OAIGA;IACHA,2BAAIA,GAAJA,UAAKA,QAAmBA,EAAEA,QAAmBA;QACzCM,IAAIA,KAAKA,GAAGA,IAAIA,eAAKA,EAAEA,CAACA;QACxBA,KAAKA,CAACA,IAAIA,CAACA,QAAQA,EAAEA,QAAQA,CAACA,CAACA;QAC/BA,MAAMA,CAACA,KAAKA,CAACA,OAAOA,CAACA;IACzBA,CAACA;IACLN,mBAACA;AAADA,CA9DA,AA8DCA,IAAA;AA9DD,8BA8DC,CAAA","file":"lib/ModelHelpers.js","sourcesContent":["/// \r\nimport MongoDB = require('mongodb');\r\nimport Model from './Model';\r\nimport skmatc = require('skmatc');\r\nimport Omnom from './utils/Omnom';\r\nimport _ = require('lodash');\r\nimport Bluebird = require('bluebird');\r\n\r\nexport default class ModelHelpers {\r\n constructor(public model: Model) {\r\n this._validator = new skmatc(model.schema);\r\n model.validators.forEach(validator => this._validator.register(validator));\r\n }\r\n\r\n private _validator: Skmatc.Skmatc;\r\n\r\n /**\r\n * Validates a document to ensure that it matches the model's ISchema requirements\r\n * @param {any} document The document to validate against the ISchema\r\n * @returns {SkmatcCore.IResult} The result of the validation\r\n */\r\n validate(document: TDocument): Skmatc.Result {\r\n return this._validator.validate(document);\r\n }\r\n\r\n /**\r\n * Wraps the given document in an instance wrapper for use throughout the application\r\n * @param {any} document The document to be wrapped as an instance\r\n * @param {Boolean} isNew Whether the instance originated from the database or was created by the application\r\n * @param {Boolean} isPartial Whether the document supplied contains all information present in the database\r\n * @returns {any} An instance which wraps this document\r\n */\r\n wrapDocument(document: TDocument, isNew?: boolean, isPartial?: boolean): TInstance {\r\n return new this.model.Instance(document, isNew, isPartial);\r\n }\r\n \r\n /**\r\n * Converts the given document to its database form into a form\r\n * using the transforms defined on the model.\r\n * @param {any} document The document to be converted\r\n * @returns {any} A new document cloned from the original and transformed\r\n */\r\n transformToDB(document: T): T {\r\n for (var property in this.model.transforms)\r\n if(document.hasOwnProperty(property))\r\n document[property] = this.model.transforms[property].toDB(document[property]);\r\n return document;\r\n }\r\n \r\n /**\r\n * Converts the given document to its database form into a form\r\n * using the transforms defined on the model.\r\n * @param {any} document The document to be converted\r\n * @returns {any} A new document cloned from the original and transformed\r\n */\r\n convertToDB(document: T): T {\r\n var doc: T = _.cloneDeep(document);\r\n return this.transformToDB(doc);\r\n }\r\n\r\n /**\r\n * Performs a diff operation between two documents and creates a MongoDB changes object to represent the differences\r\n * @param {any} original The original document prior to changes being made\r\n * @param {any} modified The document after changes were made\r\n */\r\n diff(original: TDocument, modified: TDocument): any {\r\n var omnom = new Omnom();\r\n omnom.diff(original, modified);\r\n return omnom.changes;\r\n }\r\n}\r\n"],"sourceRoot":"/source/"} \ No newline at end of file +{"version":3,"sources":["lib/ModelHelpers.ts"],"names":["ModelHelpers","ModelHelpers.constructor","ModelHelpers.validate","ModelHelpers.wrapDocument","ModelHelpers.transformToDB","ModelHelpers.convertToDB","ModelHelpers.diff"],"mappings":"AAGA,IAAO,MAAM,WAAW,QAAQ,CAAC,CAAC;AAClC,sBAAoB,eAAe,CAAC,CAAA;AACpC,IAAO,CAAC,WAAW,QAAQ,CAAC,CAAC;AAG7B;;;;;GAKG;AACH;IACIA,sBAAmBA,KAAkCA;QADzDC,iBA8DCA;QA7DsBA,UAAKA,GAALA,KAAKA,CAA6BA;QACjDA,IAAIA,CAACA,UAAUA,GAAGA,IAAIA,MAAMA,CAACA,KAAKA,CAACA,MAAMA,CAACA,C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,QAAmBA;QACzCM,IAAIA,KAAKA,GAAGA,IAAIA,aAAKA,EAAEA,CAACA;QACxBA,KAAKA,CAACA,IAAIA,CAACA,QAAQA,EAAEA,QAAQA,CAACA,CAACA;QAC/BA,MAAMA,CAACA,KAAKA,CAACA,OAAOA,CAACA;IACzBA,CAACA;IACLN,mBAACA;AAADA,CA9DA,AA8DCA,IAAA;AA9DY,oBAAY,eA8DxB,CAAA","file":"lib/ModelHelpers.js","sourcesContent":["/// \r\nimport MongoDB = require('mongodb');\r\nimport {Model} from './Model';\r\nimport skmatc = require('skmatc');\r\nimport {Omnom} from './utils/Omnom';\r\nimport _ = require('lodash');\r\nimport Bluebird = require('bluebird');\r\n\r\n/**\r\n * A number of helper methods used commonly within Iridium, they provide a means to transform,\r\n * validate, wrap and diff instances and documents. By keeping these methods in one place we\r\n * help to improve testability and reduce code duplication (mouse abuse) throughout the codebase.\r\n * @internal\r\n */\r\nexport class ModelHelpers {\r\n constructor(public model: Model) {\r\n this._validator = new skmatc(model.schema);\r\n model.validators.forEach(validator => this._validator.register(validator));\r\n }\r\n\r\n private _validator: Skmatc.Skmatc;\r\n\r\n /**\r\n * Validates a document to ensure that it matches the model's ISchema requirements\r\n * @param {any} document The document to validate against the ISchema\r\n * @returns {SkmatcCore.IResult} The result of the validation\r\n */\r\n validate(document: TDocument): Skmatc.Result {\r\n return this._validator.validate(document);\r\n }\r\n\r\n /**\r\n * Wraps the given document in an instance wrapper for use throughout the application\r\n * @param {any} document The document to be wrapped as an instance\r\n * @param {Boolean} isNew Whether the instance originated from the database or was created by the application\r\n * @param {Boolean} isPartial Whether the document supplied contains all information present in the database\r\n * @returns {any} An instance which wraps this document\r\n */\r\n wrapDocument(document: TDocument, isNew?: boolean, isPartial?: boolean): TInstance {\r\n return new this.model.Instance(document, isNew, isPartial);\r\n }\r\n \r\n /**\r\n * Converts the given document to its database form into a form\r\n * using the transforms defined on the model.\r\n * @param {any} document The document to be converted\r\n * @returns {any} A new document cloned from the original and transformed\r\n */\r\n transformToDB(document: T): T {\r\n for (var property in this.model.transforms)\r\n if(document.hasOwnProperty(property))\r\n document[property] = this.model.transforms[property].toDB(document[property]);\r\n return document;\r\n }\r\n \r\n /**\r\n * Converts the given document to its database form into a form\r\n * using the transforms defined on the model.\r\n * @param {any} document The document to be converted\r\n * @returns {any} A new document cloned from the original and transformed\r\n */\r\n convertToDB(document: T): T {\r\n var doc: T = _.cloneDeep(document);\r\n return this.transformToDB(doc);\r\n }\r\n\r\n /**\r\n * Performs a diff operation between two documents and creates a MongoDB changes object to represent the differences\r\n * @param {any} original The original document prior to changes being made\r\n * @param {any} modified The document after changes were made\r\n */\r\n diff(original: TDocument, modified: TDocument): any {\r\n var omnom = new Omnom();\r\n omnom.diff(original, modified);\r\n return omnom.changes;\r\n }\r\n}\r\n"],"sourceRoot":"/source/"} \ No newline at end of file diff --git a/dist/lib/ModelInterfaces.js.map b/dist/lib/ModelInterfaces.js.map index f6543fd..7e85f28 100644 --- a/dist/lib/ModelInterfaces.js.map +++ b/dist/lib/ModelInterfaces.js.map @@ -1 +1 @@ -{"version":3,"sources":["lib/ModelInterfaces.ts"],"names":[],"mappings":"AAAA,AACA,4CAD4C;AAG3C","file":"lib/ModelInterfaces.js","sourcesContent":["/// \r\nexport interface ModelSpecificInstanceConstructor {\r\n new (doc: TDocument, isNew?: boolean, isPartial?: boolean): TInstance;\r\n}"],"sourceRoot":"/source/"} \ No newline at end of file +{"version":3,"sources":["lib/ModelInterfaces.ts"],"names":[],"mappings":"AAAA,AAaA,4CAb4C;AAe3C","file":"lib/ModelInterfaces.js","sourcesContent":["/// \r\n/**\r\n * The interface to which a prepared instance constructor should conform. When called with a document\r\n * object, it should instantiate a new instance of type TInstance which is associated with its parent\r\n * model.\r\n * \r\n * This is primarily used internally for prepared model instance constructors.\r\n * \r\n * @param TDocument The interface used to describe the structure of the documents found in the database collection.\r\n * @param TInstance The interface or class used to wrap the documents returned from the database.\r\n * \r\n * @internal\r\n */\r\nexport interface ModelSpecificInstanceConstructor {\r\n new (doc: TDocument, isNew?: boolean, isPartial?: boolean): TInstance;\r\n}"],"sourceRoot":"/source/"} \ No newline at end of file diff --git a/dist/lib/ModelOptions.js.map b/dist/lib/ModelOptions.js.map index dd4b25b..49c1d99 100644 --- a/dist/lib/ModelOptions.js.map +++ b/dist/lib/ModelOptions.js.map @@ -1 +1 @@ -{"version":3,"sources":["lib/ModelOptions.ts"],"names":[],"mappings":"AAyCC","file":"lib/ModelOptions.js","sourcesContent":["/// \r\nimport MongoDB = require('mongodb');\r\nimport Index = require('./Index');\r\nimport Hooks = require('./Hooks');\r\nimport {CacheDirector} from './CacheDirector';\r\nimport * as General from './General';\r\n\r\nexport interface QueryOptions {\r\n cache?: boolean;\r\n fields?: { [name: string]: number };\r\n limit?: number;\r\n skip?: number;\r\n sort?: Index.IndexSpecification;\r\n}\r\n\r\nexport interface CreateOptions {\r\n w?: any;\r\n wtimeout?: number;\r\n j?: number;\r\n serializeFunctions?: boolean;\r\n forceServerObjectId?: boolean;\r\n upsert?: boolean;\r\n cache?: boolean;\r\n}\r\n\r\nexport interface UpdateOptions {\r\n w?: any;\r\n wtimeout?: number;\r\n j?: boolean;\r\n upsert?: boolean;\r\n}\r\n\r\nexport interface RemoveOptions {\r\n w?: any;\r\n wtimeout?: number;\r\n j?: boolean;\r\n single?: boolean;\r\n}\r\n\r\nexport interface Transforms {\r\n [property: string]: { fromDB: (value: any) => any; toDB: (value: any) => any; };\r\n}"],"sourceRoot":"/source/"} \ No newline at end of file +{"version":3,"sources":["lib/ModelOptions.ts"],"names":[],"mappings":"AAqIC","file":"lib/ModelOptions.js","sourcesContent":["/// \r\nimport MongoDB = require('mongodb');\r\nimport * as Index from './Index';\r\nimport {Hooks} from './Hooks';\r\nimport {CacheDirector} from './CacheDirector';\r\nimport * as General from './General';\r\n\r\n/**\r\n * Options which can be used to control the way in which a query is executed\r\n * against the MongoDB database.\r\n */\r\nexport interface QueryOptions {\r\n cache?: boolean;\r\n fields?: { [name: string]: number };\r\n limit?: number;\r\n skip?: number;\r\n sort?: Index.IndexSpecification;\r\n}\r\n\r\n/**\r\n * Options which can be used to control the way in which a document is created\r\n * on the MongoDB server.\r\n */\r\nexport interface CreateOptions {\r\n /**\r\n * The write concern, can either be a number from 0 to the number of nodes within\r\n * the cluster, or 'majority' if you would like to wait for the majority of nodes\r\n * within the cluster to confirm the write before returning.\r\n * \r\n * It is recommended that you set this to 'majority', however in all situations\r\n * where you mind if data is lost, you should set it to at least 1.\r\n */\r\n w?: string | number;\r\n \r\n /**\r\n * The timeout in milliseconds before the write will be aborted by the MongoDB server\r\n * and an error response (if the write concern is non-zero) is returned to the client.\r\n */\r\n wtimeout?: number;\r\n \r\n /**\r\n * Whether to wait for the write to be commited to the server's journal (flushed to disk)\r\n * or not. By specifying 1 here, you imply w:1 - howver this can be combined with w:'majority'\r\n * to give excellent write reliability within a cluster, even across failures.\r\n */\r\n j?: number;\r\n \r\n /**\r\n * Whether or not to serialize JavaScript functions which are provided as values. For security\r\n * reasons it is probably best to set this to false, however it may come in handy under certain\r\n * circumstances.\r\n */\r\n serializeFunctions?: boolean;\r\n \r\n /**\r\n * Whether to generate document ObjectIDs within the client library or on the server, it is recommended\r\n * that you leave this to default (false) unless you are making thousands of inserts per second from\r\n * a single node and experiencing _id collisions.\r\n */\r\n forceServerObjectId?: boolean;\r\n \r\n /**\r\n * Whether to perform an upsert operation if the document already exists.\r\n */\r\n upsert?: boolean;\r\n \r\n /**\r\n * Whether to store the resulting document in the Iridium document cache to boost later retrieval times.\r\n */\r\n cache?: boolean;\r\n}\r\n\r\nexport interface UpdateOptions {\r\n /**\r\n * The write concern, can either be a number from 0 to the number of nodes within\r\n * the cluster, or 'majority' if you would like to wait for the majority of nodes\r\n * within the cluster to confirm the write before returning.\r\n * \r\n * It is recommended that you set this to 'majority', however in all situations\r\n * where you mind if data is lost, you should set it to at least 1.\r\n */\r\n w?: string | number;\r\n \r\n /**\r\n * The timeout in milliseconds before the write will be aborted by the MongoDB server\r\n * and an error response (if the write concern is non-zero) is returned to the client.\r\n */\r\n wtimeout?: number;\r\n \r\n /**\r\n * Whether to wait for the write to be commited to the server's journal (flushed to disk)\r\n * or not. By specifying 1 here, you imply w:1 - howver this can be combined with w:'majority'\r\n * to give excellent write reliability within a cluster, even across failures.\r\n */\r\n j?: boolean;\r\n \r\n /**\r\n * Whether to perform an upsert operation if the document already exists. This can be combined\r\n * with $setOnInsert to automatically create documents which do not exist in the database prior\r\n * to making changes - and can be very handy for high-throughput systems.\r\n */\r\n upsert?: boolean;\r\n}\r\n\r\nexport interface RemoveOptions {\r\n /**\r\n * The write concern, can either be a number from 0 to the number of nodes within\r\n * the cluster, or 'majority' if you would like to wait for the majority of nodes\r\n * within the cluster to confirm the write before returning.\r\n * \r\n * It is recommended that you set this to 'majority', however in all situations\r\n * where you mind if data is lost, you should set it to at least 1.\r\n */\r\n w?: string | number;\r\n \r\n /**\r\n * The timeout in milliseconds before the write will be aborted by the MongoDB server\r\n * and an error response (if the write concern is non-zero) is returned to the client.\r\n */\r\n wtimeout?: number;\r\n \r\n /**\r\n * Whether to wait for the write to be commited to the server's journal (flushed to disk)\r\n * or not. By specifying 1 here, you imply w:1 - howver this can be combined with w:'majority'\r\n * to give excellent write reliability within a cluster, even across failures.\r\n */\r\n j?: number;\r\n \r\n /**\r\n * Whether to only remove the first document in the collection or not, by default this is false\r\n * and any document matching the conditions will be removed.\r\n */\r\n single?: boolean;\r\n}"],"sourceRoot":"/source/"} \ No newline at end of file diff --git a/dist/lib/ModelSpecificInstance.js b/dist/lib/ModelSpecificInstance.js index bd49ec3..8e83a01 100644 --- a/dist/lib/ModelSpecificInstance.js +++ b/dist/lib/ModelSpecificInstance.js @@ -1,5 +1,17 @@ var util = require('util'); var _ = require('lodash'); +/** + * Creates a new subclass of the given instanceType which correctly performs property transforms + * and associates the instance with the correct model when instantiated. + * + * @param TDocument The interface representing the structure of the documents found in the database. + * @param TInstance The interface or class representing the documents after they have been wrapped in an instance. + * + * @param model The model which instances should be associated with when the resulting constructor is used. + * @param instanceType The constructor used to create new instances of type TInstance. + * + * @internal + */ function ModelSpecificInstance(model, instanceType) { var constructor = function (doc, isNew, isPartial) { instanceType.call(this, model, doc, isNew, isPartial); @@ -30,6 +42,6 @@ function ModelSpecificInstance(model, instanceType) { }); return constructor; } -exports.default = ModelSpecificInstance; +exports.ModelSpecificInstance = ModelSpecificInstance; //# sourceMappingURL=../lib/ModelSpecificInstance.js.map \ No newline at end of file diff --git a/dist/lib/ModelSpecificInstance.js.map b/dist/lib/ModelSpecificInstance.js.map index 855af48..d8be31c 100644 --- a/dist/lib/ModelSpecificInstance.js.map +++ b/dist/lib/ModelSpecificInstance.js.map @@ -1 +1 @@ -{"version":3,"sources":["lib/ModelSpecificInstance.ts"],"names":["ModelSpecificInstance"],"mappings":"AAGA,IAAO,IAAI,WAAW,MAAM,CAAC,CAAC;AAC9B,IAAO,CAAC,WAAW,QAAQ,CAAC,CAAC;AAE7B,+BAA0F,KAAkC,EAAE,YAA0D;IACpLA,IAAIA,WAAWA,GAAGA,UAAUA,GAAcA,EAAEA,KAAeA,EAAEA,SAAmBA;QAC5E,YAAY,CAAC,IAAI,CAAC,IAAI,EAAE,KAAK,EAAE,GAAG,EAAE,KAAK,EAAE,SAAS,CAAC,CAAC;IAC1D,CAAC,CAACA;IAEFA,IAAIA,CAACA,QAAQA,CAACA,WAAWA,EAAEA,YAAYA,CAACA,CAACA;IAEzCA,CAACA,CAACA,IAAIA,CAACA,MAAMA,CAACA,IAAIA,CAACA,KAAKA,CAACA,MAAMA,CAACA,EAACA,UAACA,QAAQA;QACtCA,EAAEA,CAACA,CAACA,KAAKA,CAACA,UAAUA,CAACA,cAAcA,CAACA,QAAQA,CAACA,CAACA,CAACA,CAACA;YAC5CA,MAAMA,CAACA,MAAMA,CAACA,cAAcA,CAACA,WAAWA,CAACA,SAASA,EAAEA,QAAQA,EAAEA;gBAC1DA,GAAGA,EAAEA;oBACD,MAAM,CAAC,KAAK,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAC,CAAC;gBACvE,CAAC;gBACDA,GAAGA,EAAEA,UAAUA,KAAKA;oBAChB,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,GAAG,KAAK,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;gBACtE,CAAC;gBACDA,UAAUA,EAAEA,IAAIA;gBAChBA,YAAYA,EAAEA,IAAIA;aACrBA,CAACA,CAACA;QACPA,CAACA;QAEDA,MAAMA,CAACA,cAAcA,CAACA,WAAWA,CAACA,SAASA,EAAEA,QAAQA,EAAEA;YACnDA,GAAGA,EAAEA;gBACD,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAC;YACpC,CAAC;YACDA,GAAGA,EAAEA,UAAUA,KAAKA;gBAChB,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,GAAG,KAAK,CAAC;YACrC,CAAC;YACDA,UAAUA,EAAEA,IAAIA;SACnBA,CAACA,CAACA;IACPA,CAACA,CAACA,CAACA;IAEHA,MAAMA,CAAMA,WAAWA,CAACA;AAC5BA,CAACA;AAjCD,uCAiCC,CAAA","file":"lib/ModelSpecificInstance.js","sourcesContent":["/// \r\nimport Model from './Model';\r\nimport InstanceImplementation from './InstanceInterface';\r\nimport util = require('util');\r\nimport _ = require('lodash');\r\n\r\nexport default function ModelSpecificInstance(model: Model, instanceType: InstanceImplementation): new (doc: TDocument, isNew?: boolean, isPartial?: boolean) => TInstance {\r\n var constructor = function (doc: TDocument, isNew?: boolean, isPartial?: boolean) {\r\n instanceType.call(this, model, doc, isNew, isPartial);\r\n };\r\n\r\n util.inherits(constructor, instanceType);\r\n\r\n _.each(Object.keys(model.schema),(property) => {\r\n if (model.transforms.hasOwnProperty(property)) {\r\n return Object.defineProperty(constructor.prototype, property, {\r\n get: function () {\r\n return model.transforms[property].fromDB(this._modified[property]);\r\n },\r\n set: function (value) {\r\n this._modified[property] = model.transforms[property].toDB(value);\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n }\r\n\r\n Object.defineProperty(constructor.prototype, property, {\r\n get: function () {\r\n return this._modified[property];\r\n },\r\n set: function (value) {\r\n this._modified[property] = value;\r\n },\r\n enumerable: true\r\n });\r\n });\r\n\r\n return constructor;\r\n}\r\n"],"sourceRoot":"/source/"} \ No newline at end of file +{"version":3,"sources":["lib/ModelSpecificInstance.ts"],"names":["ModelSpecificInstance"],"mappings":"AAIA,IAAO,IAAI,WAAW,MAAM,CAAC,CAAC;AAC9B,IAAO,CAAC,WAAW,QAAQ,CAAC,CAAC;AAE7B;;;;;;;;;;;GAWG;AACH,+BAAkF,KAAkC,EAAE,YAA0D;IAC5KA,IAAIA,WAAWA,GAAGA,UAAUA,GAAcA,EAAEA,KAAeA,EAAEA,SAAmBA;QAC5E,YAAY,CAAC,IAAI,CAAC,IAAI,EAAE,KAAK,EAAE,GAAG,EAAE,KAAK,EAAE,SAAS,CAAC,CAAC;IAC1D,CAAC,CAACA;IAEFA,IAAIA,CAACA,QAAQA,CAACA,WAAWA,EAAEA,YAAYA,CAACA,CAACA;IAEzCA,CAACA,CAACA,IAAIA,CAACA,MAAMA,CAACA,IAAIA,CAACA,KAAKA,CAACA,MAAMA,CAACA,EAACA,UAACA,QAAQA;QACtCA,EAAEA,CAACA,CAACA,KAAKA,CAACA,UAAUA,CAACA,cAAcA,CAACA,QAAQA,CAACA,CAACA,CAACA,CAACA;YAC5CA,MAAMA,CAACA,MAAMA,CAACA,cAAcA,CAACA,WAAWA,CAACA,SAASA,EAAEA,QAAQA,EAAEA;gBAC1DA,GAAGA,EAAEA;oBACD,MAAM,CAAC,KAAK,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAC,CAAC;gBACvE,CAAC;gBACDA,GAAGA,EAAEA,UAAUA,KAAKA;oBAChB,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,GAAG,KAAK,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;gBACtE,CAAC;gBACDA,UAAUA,EAAEA,IAAIA;gBAChBA,YAAYA,EAAEA,IAAIA;aACrBA,CAACA,CAACA;QACPA,CAACA;QAEDA,MAAMA,CAACA,cAAcA,CAACA,WAAWA,CAACA,SAASA,EAAEA,QAAQA,EAAEA;YACnDA,GAAGA,EAAEA;gBACD,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAC;YACpC,CAAC;YACDA,GAAGA,EAAEA,UAAUA,KAAKA;gBAChB,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,GAAG,KAAK,CAAC;YACrC,CAAC;YACDA,UAAUA,EAAEA,IAAIA;SACnBA,CAACA,CAACA;IACPA,CAACA,CAACA,CAACA;IAEHA,MAAMA,CAAMA,WAAWA,CAACA;AAC5BA,CAACA;AAjCe,6BAAqB,wBAiCpC,CAAA","file":"lib/ModelSpecificInstance.js","sourcesContent":["/// \r\nimport {Model} from './Model';\r\nimport {InstanceImplementation} from './InstanceInterface';\r\nimport {ModelSpecificInstanceConstructor} from './ModelInterfaces';\r\nimport util = require('util');\r\nimport _ = require('lodash');\r\n\r\n/**\r\n * Creates a new subclass of the given instanceType which correctly performs property transforms\r\n * and associates the instance with the correct model when instantiated.\r\n * \r\n * @param TDocument The interface representing the structure of the documents found in the database.\r\n * @param TInstance The interface or class representing the documents after they have been wrapped in an instance.\r\n * \r\n * @param model The model which instances should be associated with when the resulting constructor is used.\r\n * @param instanceType The constructor used to create new instances of type TInstance.\r\n * \r\n * @internal\r\n */\r\nexport function ModelSpecificInstance(model: Model, instanceType: InstanceImplementation): ModelSpecificInstanceConstructor {\r\n var constructor = function (doc: TDocument, isNew?: boolean, isPartial?: boolean) {\r\n instanceType.call(this, model, doc, isNew, isPartial);\r\n };\r\n\r\n util.inherits(constructor, instanceType);\r\n\r\n _.each(Object.keys(model.schema),(property) => {\r\n if (model.transforms.hasOwnProperty(property)) {\r\n return Object.defineProperty(constructor.prototype, property, {\r\n get: function () {\r\n return model.transforms[property].fromDB(this._modified[property]);\r\n },\r\n set: function (value) {\r\n this._modified[property] = model.transforms[property].toDB(value);\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n }\r\n\r\n Object.defineProperty(constructor.prototype, property, {\r\n get: function () {\r\n return this._modified[property];\r\n },\r\n set: function (value) {\r\n this._modified[property] = value;\r\n },\r\n enumerable: true\r\n });\r\n });\r\n\r\n return constructor;\r\n}\r\n"],"sourceRoot":"/source/"} \ No newline at end of file diff --git a/dist/lib/Plugins.js.map b/dist/lib/Plugins.js.map index fa9051a..5e44a21 100644 --- a/dist/lib/Plugins.js.map +++ b/dist/lib/Plugins.js.map @@ -1 +1 @@ -{"version":3,"sources":["lib/Plugins.ts"],"names":[],"mappings":"AAQC","file":"lib/Plugins.js","sourcesContent":["/// \r\nimport core = require('./Core');\r\nimport Model from './Model';\r\n\r\nexport interface Plugin {\r\n newModel? (model: Model);\r\n newInstance? (instance: any, model: Model);\r\n validate?: Skmatc.Validator | Skmatc.Validator[];\r\n}"],"sourceRoot":"/source/"} \ No newline at end of file +{"version":3,"sources":["lib/Plugins.ts"],"names":[],"mappings":"AAQC","file":"lib/Plugins.js","sourcesContent":["/// \r\nimport {Core} from './Core';\r\nimport {Model} from './Model';\r\n\r\nexport interface Plugin {\r\n newModel? (model: Model);\r\n newInstance? (instance: any, model: Model);\r\n validate?: Skmatc.Validator | Skmatc.Validator[];\r\n}"],"sourceRoot":"/source/"} \ No newline at end of file diff --git a/dist/lib/Transforms.js b/dist/lib/Transforms.js new file mode 100644 index 0000000..9e05865 --- /dev/null +++ b/dist/lib/Transforms.js @@ -0,0 +1,3 @@ +/// + +//# sourceMappingURL=../lib/Transforms.js.map \ No newline at end of file diff --git a/dist/lib/Transforms.js.map b/dist/lib/Transforms.js.map new file mode 100644 index 0000000..cffb1b1 --- /dev/null +++ b/dist/lib/Transforms.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["lib/Transforms.ts"],"names":[],"mappings":"AAAA,AACA,4CAD4C;AAwB3C","file":"lib/Transforms.js","sourcesContent":["/// \r\nexport interface Transforms {\r\n\t[property:string]: PropertyTransform;\r\n}\r\n\r\n/**\r\n * Converts the value of a property to and from its database representation.\r\n */\r\nexport interface PropertyTransform {\r\n\t/**\r\n\t * Converts a property's value from its database representation into one\r\n\t * suitable for the application.\r\n\t * @param value The value stored in the MongoDB database document.\r\n\t * @returns A derived value which is more useful to the application.\r\n\t */\r\n\tfromDB(value: any): any;\r\n\t\r\n\t/**\r\n\t * Converts a property's value into a representation more suitable for\r\n\t * the database.\r\n\t * @param value The value used by the application.\r\n\t * @returns The database optimized representation of the value.\r\n\t */\r\n\ttoDB(value: any): any;\r\n}"],"sourceRoot":"/source/"} \ No newline at end of file diff --git a/dist/lib/cacheControllers/IDDirector.js b/dist/lib/cacheControllers/IDDirector.js index ce59a8a..2894fd5 100644 --- a/dist/lib/cacheControllers/IDDirector.js +++ b/dist/lib/cacheControllers/IDDirector.js @@ -1,25 +1,31 @@ var MongoDB = require('mongodb'); -var IDCacheDirector = (function () { - function IDCacheDirector() { +/** + * Caches documents using their _id field as the unique cache key. This + * is useful if you primarily query your documents using their _id field, + * however can be suboptimal (or even a complete waste) if you use different + * types of queries. + */ +var CacheOnID = (function () { + function CacheOnID() { } - IDCacheDirector.prototype.valid = function (object) { + CacheOnID.prototype.valid = function (object) { return !!object._id; }; - IDCacheDirector.prototype.buildKey = function (object) { + CacheOnID.prototype.buildKey = function (object) { if (object._id._bsontype == 'ObjectID') return new MongoDB.ObjectID(object._id.id).toHexString(); return object._id; }; - IDCacheDirector.prototype.validQuery = function (conditions) { + CacheOnID.prototype.validQuery = function (conditions) { return !!conditions._id; }; - IDCacheDirector.prototype.buildQueryKey = function (conditions) { + CacheOnID.prototype.buildQueryKey = function (conditions) { if (conditions._id._bsontype == 'ObjectID') return new MongoDB.ObjectID(conditions._id.id).toHexString(); return conditions._id; }; - return IDCacheDirector; + return CacheOnID; })(); -exports.default = IDCacheDirector; +exports.CacheOnID = CacheOnID; //# sourceMappingURL=../../lib/cacheControllers/IDDirector.js.map \ No newline at end of file diff --git a/dist/lib/cacheControllers/IDDirector.js.map b/dist/lib/cacheControllers/IDDirector.js.map index ceaafbb..86a1552 100644 --- a/dist/lib/cacheControllers/IDDirector.js.map +++ b/dist/lib/cacheControllers/IDDirector.js.map @@ -1 +1 @@ -{"version":3,"sources":["lib/cacheControllers/IDDirector.ts"],"names":["IDCacheDirector","IDCacheDirector.constructor","IDCacheDirector.valid","IDCacheDirector.buildKey","IDCacheDirector.validQuery","IDCacheDirector.buildQueryKey"],"mappings":"AAEA,IAAO,OAAO,WAAW,SAAS,CAAC,CAAC;AAEpC;IAAAA;IAoBAC,CAACA;IAnBGD,+BAAKA,GAALA,UAAMA,MAAoBA;QACtBE,MAAMA,CAACA,CAACA,CAACA,MAAMA,CAACA,GAAGA,CAACA;IACxBA,CAACA;IAEDF,kCAAQA,GAARA,UAASA,MAAoBA;QACzBG,EAAEA,CAACA,CAACA,MAAMA,CAACA,GAAGA,CAACA,SAASA,IAAIA,UAAUA,CAACA;YACnCA,MAAMA,CAACA,IAAIA,OAAOA,CAACA,QAAQA,CAACA,MAAMA,CAACA,GAAGA,CAACA,EAAEA,CAACA,CAACA,WAAWA,EAAEA,CAACA;QAC7DA,MAAMA,CAACA,MAAMA,CAACA,GAAGA,CAACA;IACtBA,CAACA;IAEDH,oCAAUA,GAAVA,UAAWA,UAAUA;QACjBI,MAAMA,CAACA,CAACA,CAACA,UAAUA,CAACA,GAAGA,CAACA;IAC5BA,CAACA;IAEDJ,uCAAaA,GAAbA,UAAcA,UAAUA;QACpBK,EAAEA,CAACA,CAACA,UAAUA,CAACA,GAAGA,CAACA,SAASA,IAAIA,UAAUA,CAACA;YACvCA,MAAMA,CAACA,IAAIA,OAAOA,CAACA,QAAQA,CAACA,UAAUA,CAACA,GAAGA,CAACA,EAAEA,CAACA,CAACA,WAAWA,EAAEA,CAACA;QACjEA,MAAMA,CAACA,UAAUA,CAACA,GAAGA,CAACA;IAC1BA,CAACA;IACLL,sBAACA;AAADA,CApBA,AAoBCA,IAAA;AApBD,iCAoBC,CAAA","file":"lib/cacheControllers/IDDirector.js","sourcesContent":["/// \r\nimport {CacheDirector} from '../CacheDirector';\r\nimport MongoDB = require('mongodb');\r\n\r\nexport default class IDCacheDirector implements CacheDirector{\r\n valid(object: { _id: any }) {\r\n return !!object._id;\r\n }\r\n\r\n buildKey(object: { _id: any }) {\r\n if (object._id._bsontype == 'ObjectID')\r\n return new MongoDB.ObjectID(object._id.id).toHexString();\r\n return object._id;\r\n }\r\n\r\n validQuery(conditions) {\r\n return !!conditions._id;\r\n }\r\n\r\n buildQueryKey(conditions) {\r\n if (conditions._id._bsontype == 'ObjectID')\r\n return new MongoDB.ObjectID(conditions._id.id).toHexString();\r\n return conditions._id;\r\n }\r\n}"],"sourceRoot":"/source/"} \ No newline at end of file +{"version":3,"sources":["lib/cacheControllers/IDDirector.ts"],"names":["CacheOnID","CacheOnID.constructor","CacheOnID.valid","CacheOnID.buildKey","CacheOnID.validQuery","CacheOnID.buildQueryKey"],"mappings":"AAEA,IAAO,OAAO,WAAW,SAAS,CAAC,CAAC;AAEpC;;;;;GAKG;AACH;IAAAA;IAoBAC,CAACA;IAnBGD,yBAAKA,GAALA,UAAMA,MAAoBA;QACtBE,MAAMA,CAACA,CAACA,CAACA,MAAMA,CAACA,GAAGA,CAACA;IACxBA,CAACA;IAEDF,4BAAQA,GAARA,UAASA,MAAoBA;QACzBG,EAAEA,CAACA,CAACA,MAAMA,CAACA,GAAGA,CAACA,SAASA,IAAIA,UAAUA,CAACA;YACnCA,MAAMA,CAACA,IAAIA,OAAOA,CAACA,QAAQA,CAACA,MAAMA,CAACA,GAAGA,CAACA,EAAEA,CAACA,CAACA,WAAWA,EAAEA,CAACA;QAC7DA,MAAMA,CAACA,MAAMA,CAACA,GAAGA,CAACA;IACtBA,CAACA;IAEDH,8BAAUA,GAAVA,UAAWA,UAAUA;QACjBI,MAAMA,CAACA,CAACA,CAACA,UAAUA,CAACA,GAAGA,CAACA;IAC5BA,CAACA;IAEDJ,iCAAaA,GAAbA,UAAcA,UAAUA;QACpBK,EAAEA,CAACA,CAACA,UAAUA,CAACA,GAAGA,CAACA,SAASA,IAAIA,UAAUA,CAACA;YACvCA,MAAMA,CAACA,IAAIA,OAAOA,CAACA,QAAQA,CAACA,UAAUA,CAACA,GAAGA,CAACA,EAAEA,CAACA,CAACA,WAAWA,EAAEA,CAACA;QACjEA,MAAMA,CAACA,UAAUA,CAACA,GAAGA,CAACA;IAC1BA,CAACA;IACLL,gBAACA;AAADA,CApBA,AAoBCA,IAAA;AApBY,iBAAS,YAoBrB,CAAA","file":"lib/cacheControllers/IDDirector.js","sourcesContent":["/// \r\nimport {CacheDirector} from '../CacheDirector';\r\nimport MongoDB = require('mongodb');\r\n\r\n/**\r\n * Caches documents using their _id field as the unique cache key. This\r\n * is useful if you primarily query your documents using their _id field,\r\n * however can be suboptimal (or even a complete waste) if you use different\r\n * types of queries.\r\n */\r\nexport class CacheOnID implements CacheDirector{\r\n valid(object: { _id: any }) {\r\n return !!object._id;\r\n }\r\n\r\n buildKey(object: { _id: any }) {\r\n if (object._id._bsontype == 'ObjectID')\r\n return new MongoDB.ObjectID(object._id.id).toHexString();\r\n return object._id;\r\n }\r\n\r\n validQuery(conditions) {\r\n return !!conditions._id;\r\n }\r\n\r\n buildQueryKey(conditions) {\r\n if (conditions._id._bsontype == 'ObjectID')\r\n return new MongoDB.ObjectID(conditions._id.id).toHexString();\r\n return conditions._id;\r\n }\r\n}"],"sourceRoot":"/source/"} \ No newline at end of file diff --git a/dist/lib/caches/MemoryCache.js b/dist/lib/caches/MemoryCache.js index eb3fc28..bd30806 100644 --- a/dist/lib/caches/MemoryCache.js +++ b/dist/lib/caches/MemoryCache.js @@ -1,5 +1,11 @@ /// var Bluebird = require('bluebird'); +/** + * A cache implementation which stores documents in an in-memory cache. + * + * Be aware that this is an incredibly simplistic implementation which doesn't manage + * memory usage at all and is very likely NOT suitable for production use. + */ var MemoryCache = (function () { function MemoryCache() { this.cache = {}; @@ -19,6 +25,6 @@ var MemoryCache = (function () { }; return MemoryCache; })(); -exports.default = MemoryCache; +exports.MemoryCache = MemoryCache; //# sourceMappingURL=../../lib/caches/MemoryCache.js.map \ No newline at end of file diff --git a/dist/lib/caches/MemoryCache.js.map b/dist/lib/caches/MemoryCache.js.map index 5b4ed7e..1114fbf 100644 --- a/dist/lib/caches/MemoryCache.js.map +++ b/dist/lib/caches/MemoryCache.js.map @@ -1 +1 @@ -{"version":3,"sources":["lib/caches/MemoryCache.ts"],"names":["MemoryCache","MemoryCache.constructor","MemoryCache.set","MemoryCache.get","MemoryCache.clear"],"mappings":"AAAA,AACA,+CAD+C;AAC/C,IAAO,QAAQ,WAAW,UAAU,CAAC,CAAC;AAGtC;IAAAA;QACYC,UAAKA,GAAQA,EAAEA,CAACA;IAgB5BA,CAACA;IAdGD,yBAAGA,GAAHA,UAAOA,GAAWA,EAAEA,KAAQA;QACxBE,IAAIA,CAACA,KAAKA,CAACA,GAAGA,CAACA,GAAGA,KAAKA,CAACA;QACxBA,MAAMA,CAACA,QAAQA,CAACA,OAAOA,CAACA,KAAKA,CAACA,CAACA;IACnCA,CAACA;IAEDF,yBAAGA,GAAHA,UAAOA,GAAWA;QACdG,MAAMA,CAACA,QAAQA,CAACA,OAAOA,CAACA,IAAIA,CAACA,KAAKA,CAACA,GAAGA,CAACA,CAACA,CAACA;IAC7CA,CAACA;IAEDH,2BAAKA,GAALA,UAAMA,GAAWA;QACbI,IAAIA,GAAGA,GAAGA,IAAIA,CAACA,KAAKA,CAACA,cAAcA,CAACA,GAAGA,CAACA,CAACA;QACzCA,EAAEA,CAAAA,CAACA,GAAGA,CAACA;YAACA,OAAOA,IAAIA,CAACA,KAAKA,CAACA,GAAGA,CAACA,CAACA;QAC/BA,MAAMA,CAACA,QAAQA,CAACA,OAAOA,CAACA,GAAGA,CAACA,CAACA;IACjCA,CAACA;IACLJ,kBAACA;AAADA,CAjBA,AAiBCA,IAAA;AAjBD,6BAiBC,CAAA","file":"lib/caches/MemoryCache.js","sourcesContent":["/// \r\nimport Bluebird = require('bluebird');\r\nimport {Cache} from '../Cache';\r\n\r\nexport default class MemoryCache implements Cache {\r\n private cache: any = {};\r\n\r\n set(key: string, value: T): Bluebird {\r\n this.cache[key] = value;\r\n return Bluebird.resolve(value);\r\n }\r\n\r\n get(key: string): Bluebird {\r\n return Bluebird.resolve(this.cache[key]);\r\n }\r\n\r\n clear(key: string) : Bluebird {\r\n var has = this.cache.hasOwnProperty(key);\r\n if(has) delete this.cache[key];\r\n return Bluebird.resolve(has);\r\n }\r\n}"],"sourceRoot":"/source/"} \ No newline at end of file +{"version":3,"sources":["lib/caches/MemoryCache.ts"],"names":["MemoryCache","MemoryCache.constructor","MemoryCache.set","MemoryCache.get","MemoryCache.clear"],"mappings":"AAAA,AACA,+CAD+C;AAC/C,IAAO,QAAQ,WAAW,UAAU,CAAC,CAAC;AAGtC;;;;;GAKG;AACH;IAAAA;QACYC,UAAKA,GAAQA,EAAEA,CAACA;IAgB5BA,CAACA;IAdGD,yBAAGA,GAAHA,UAAOA,GAAWA,EAAEA,KAAQA;QACxBE,IAAIA,CAACA,KAAKA,CAACA,GAAGA,CAACA,GAAGA,KAAKA,CAACA;QACxBA,MAAMA,CAACA,QAAQA,CAACA,OAAOA,CAACA,KAAKA,CAACA,CAACA;IACnCA,CAACA;IAEDF,yBAAGA,GAAHA,UAAOA,GAAWA;QACdG,MAAMA,CAACA,QAAQA,CAACA,OAAOA,CAACA,IAAIA,CAACA,KAAKA,CAACA,GAAGA,CAACA,CAACA,CAACA;IAC7CA,CAACA;IAEDH,2BAAKA,GAALA,UAAMA,GAAWA;QACbI,IAAIA,GAAGA,GAAGA,IAAIA,CAACA,KAAKA,CAACA,cAAcA,CAACA,GAAGA,CAACA,CAACA;QACzCA,EAAEA,CAAAA,CAACA,GAAGA,CAACA;YAACA,OAAOA,IAAIA,CAACA,KAAKA,CAACA,GAAGA,CAACA,CAACA;QAC/BA,MAAMA,CAACA,QAAQA,CAACA,OAAOA,CAACA,GAAGA,CAACA,CAACA;IACjCA,CAACA;IACLJ,kBAACA;AAADA,CAjBA,AAiBCA,IAAA;AAjBY,mBAAW,cAiBvB,CAAA","file":"lib/caches/MemoryCache.js","sourcesContent":["/// \r\nimport Bluebird = require('bluebird');\r\nimport {Cache} from '../Cache';\r\n\r\n/**\r\n * A cache implementation which stores documents in an in-memory cache.\r\n * \r\n * Be aware that this is an incredibly simplistic implementation which doesn't manage\r\n * memory usage at all and is very likely NOT suitable for production use.\r\n */\r\nexport class MemoryCache implements Cache {\r\n private cache: any = {};\r\n\r\n set(key: string, value: T): Bluebird {\r\n this.cache[key] = value;\r\n return Bluebird.resolve(value);\r\n }\r\n\r\n get(key: string): Bluebird {\r\n return Bluebird.resolve(this.cache[key]);\r\n }\r\n\r\n clear(key: string) : Bluebird {\r\n var has = this.cache.hasOwnProperty(key);\r\n if(has) delete this.cache[key];\r\n return Bluebird.resolve(has);\r\n }\r\n}"],"sourceRoot":"/source/"} \ No newline at end of file diff --git a/dist/lib/caches/NoOpCache.js b/dist/lib/caches/NoOpCache.js index f9c4789..f645260 100644 --- a/dist/lib/caches/NoOpCache.js +++ b/dist/lib/caches/NoOpCache.js @@ -1,4 +1,11 @@ var Bluebird = require('bluebird'); +/** + * A cache implementation which does not cache any received documents + * and returns nothing when requested - mimicking an empty cache. + * + * This is the default cache used if one is not supplied and should + * not impose any significant performance overhead. + */ var NoOpCache = (function () { function NoOpCache() { } @@ -13,6 +20,6 @@ var NoOpCache = (function () { }; return NoOpCache; })(); -exports.default = NoOpCache; +exports.NoOpCache = NoOpCache; //# sourceMappingURL=../../lib/caches/NoOpCache.js.map \ No newline at end of file diff --git a/dist/lib/caches/NoOpCache.js.map b/dist/lib/caches/NoOpCache.js.map index 2faf674..de56a0c 100644 --- a/dist/lib/caches/NoOpCache.js.map +++ b/dist/lib/caches/NoOpCache.js.map @@ -1 +1 @@ -{"version":3,"sources":["lib/caches/NoOpCache.ts"],"names":["NoOpCache","NoOpCache.constructor","NoOpCache.set","NoOpCache.get","NoOpCache.clear"],"mappings":"AAEA,IAAO,QAAQ,WAAW,UAAU,CAAC,CAAC;AAEtC;IAAAA;IAYAC,CAACA;IAXGD,uBAAGA,GAAHA,UAAOA,GAAWA,EAAEA,MAASA;QACzBE,MAAMA,CAACA,QAAQA,CAACA,OAAOA,CAACA,MAAMA,CAACA,CAACA;IACpCA,CAACA;IAEDF,uBAAGA,GAAHA,UAAOA,GAAWA;QACdG,MAAMA,CAACA,QAAQA,CAACA,OAAOA,EAAEA,CAACA;IAC9BA,CAACA;IAEDH,yBAAKA,GAALA,UAAMA,GAAWA;QACbI,MAAMA,CAACA,QAAQA,CAACA,OAAOA,CAACA,KAAKA,CAACA,CAACA;IACnCA,CAACA;IACLJ,gBAACA;AAADA,CAZA,AAYCA,IAAA;AAZD,2BAYC,CAAA","file":"lib/caches/NoOpCache.js","sourcesContent":["/// \r\nimport {Cache} from '../Cache';\r\nimport Bluebird = require('bluebird');\r\n\r\nexport default class NoOpCache implements Cache {\r\n set(key: string, object: T): Bluebird {\r\n return Bluebird.resolve(object);\r\n }\r\n\r\n get(key: string): Bluebird {\r\n return Bluebird.resolve();\r\n }\r\n\r\n clear(key: string): Bluebird {\r\n return Bluebird.resolve(false);\r\n }\r\n}"],"sourceRoot":"/source/"} \ No newline at end of file +{"version":3,"sources":["lib/caches/NoOpCache.ts"],"names":["NoOpCache","NoOpCache.constructor","NoOpCache.set","NoOpCache.get","NoOpCache.clear"],"mappings":"AAEA,IAAO,QAAQ,WAAW,UAAU,CAAC,CAAC;AAEtC;;;;;;GAMG;AACH;IAAAA;IAYAC,CAACA;IAXGD,uBAAGA,GAAHA,UAAOA,GAAWA,EAAEA,MAASA;QACzBE,MAAMA,CAACA,QAAQA,CAACA,OAAOA,CAACA,MAAMA,CAACA,CAACA;IACpCA,CAACA;IAEDF,uBAAGA,GAAHA,UAAOA,GAAWA;QACdG,MAAMA,CAACA,QAAQA,CAACA,OAAOA,EAAEA,CAACA;IAC9BA,CAACA;IAEDH,yBAAKA,GAALA,UAAMA,GAAWA;QACbI,MAAMA,CAACA,QAAQA,CAACA,OAAOA,CAACA,KAAKA,CAACA,CAACA;IACnCA,CAACA;IACLJ,gBAACA;AAADA,CAZA,AAYCA,IAAA;AAZY,iBAAS,YAYrB,CAAA","file":"lib/caches/NoOpCache.js","sourcesContent":["/// \r\nimport {Cache} from '../Cache';\r\nimport Bluebird = require('bluebird');\r\n\r\n/**\r\n * A cache implementation which does not cache any received documents\r\n * and returns nothing when requested - mimicking an empty cache.\r\n * \r\n * This is the default cache used if one is not supplied and should\r\n * not impose any significant performance overhead.\r\n */\r\nexport class NoOpCache implements Cache {\r\n set(key: string, object: T): Bluebird {\r\n return Bluebird.resolve(object);\r\n }\r\n\r\n get(key: string): Bluebird {\r\n return Bluebird.resolve();\r\n }\r\n\r\n clear(key: string): Bluebird {\r\n return Bluebird.resolve(false);\r\n }\r\n}"],"sourceRoot":"/source/"} \ No newline at end of file diff --git a/dist/lib/middleware/Express.js b/dist/lib/middleware/Express.js index 5404bb0..cc3e8d9 100644 --- a/dist/lib/middleware/Express.js +++ b/dist/lib/middleware/Express.js @@ -1,3 +1,10 @@ +/** + * A factory method which creates Express/Connect compatible middleware functions to inject + * a 'db' field on your request objects as well as ensuring that the Iridium Core is connected + * to a MongoDB database before handling any requests. + * + * @internal + */ function ExpressMiddlewareFactory(core) { return function (req, res, next) { core.connect().then(function () { @@ -8,6 +15,6 @@ function ExpressMiddlewareFactory(core) { }).catch(next); }; } -exports.default = ExpressMiddlewareFactory; +exports.ExpressMiddlewareFactory = ExpressMiddlewareFactory; //# sourceMappingURL=../../lib/middleware/Express.js.map \ No newline at end of file diff --git a/dist/lib/middleware/Express.js.map b/dist/lib/middleware/Express.js.map index 6096e2e..53f2d64 100644 --- a/dist/lib/middleware/Express.js.map +++ b/dist/lib/middleware/Express.js.map @@ -1 +1 @@ -{"version":3,"sources":["lib/middleware/Express.ts"],"names":["ExpressMiddlewareFactory"],"mappings":"AAKA,kCAAiD,IAAU;IACvDA,MAAMA,CAACA,UAAUA,GAAuBA,EAAEA,GAAwBA,EAAEA,IAA0CA;QAC1G,IAAI,CAAC,OAAO,EAAE,CAAC,IAAI,CAAC;YAChB,MAAM,CAAC,cAAc,CAAC,GAAG,EAAE,IAAI,EAAE;gBAC7B,GAAG,EAAE,cAAa,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC;aACnC,CAAC,CAAC;YACH,IAAI,EAAE,CAAC;QACX,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IACnB,CAAC,CAACA;AACNA,CAACA;AATD,0CASC,CAAA;AAIA","file":"lib/middleware/Express.js","sourcesContent":["/// \r\nimport http = require('http');\r\nimport {MiddlewareFactory} from '../Middleware';\r\nimport Core from '../Core';\r\n\r\nexport default function ExpressMiddlewareFactory(core: Core): ExpressMiddleware {\r\n return function (req: http.ServerRequest, res: http.ServerResponse, next:(err?: Error, route?: String) => void) {\r\n core.connect().then(function() {\r\n Object.defineProperty(req, 'db', {\r\n get: function() { return core; }\r\n });\r\n next();\r\n }).catch(next);\r\n };\r\n}\r\n\r\nexport interface ExpressMiddleware {\r\n (req: http.ServerRequest, res: http.ServerResponse, next:(err?: Error, route?: String) => void);\r\n}"],"sourceRoot":"/source/"} \ No newline at end of file +{"version":3,"sources":["lib/middleware/Express.ts"],"names":["ExpressMiddlewareFactory"],"mappings":"AAKA;;;;;;GAMG;AACH,kCAAyC,IAAU;IAC/CA,MAAMA,CAACA,UAAUA,GAAuBA,EAAEA,GAAwBA,EAAEA,IAA0CA;QAC1G,IAAI,CAAC,OAAO,EAAE,CAAC,IAAI,CAAC;YAChB,MAAM,CAAC,cAAc,CAAC,GAAG,EAAE,IAAI,EAAE;gBAC7B,GAAG,EAAE,cAAa,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC;aACnC,CAAC,CAAC;YACH,IAAI,EAAE,CAAC;QACX,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IACnB,CAAC,CAACA;AACNA,CAACA;AATe,gCAAwB,2BASvC,CAAA;AAQA","file":"lib/middleware/Express.js","sourcesContent":["/// \r\nimport http = require('http');\r\nimport {MiddlewareFactory} from '../Middleware';\r\nimport {Core} from '../Core';\r\n\r\n/**\r\n * A factory method which creates Express/Connect compatible middleware functions to inject\r\n * a 'db' field on your request objects as well as ensuring that the Iridium Core is connected\r\n * to a MongoDB database before handling any requests.\r\n * \r\n * @internal\r\n */\r\nexport function ExpressMiddlewareFactory(core: Core): ExpressMiddleware {\r\n return function (req: http.ServerRequest, res: http.ServerResponse, next:(err?: Error, route?: String) => void) {\r\n core.connect().then(function() {\r\n Object.defineProperty(req, 'db', {\r\n get: function() { return core; }\r\n });\r\n next();\r\n }).catch(next);\r\n };\r\n}\r\n\r\n/**\r\n * An Express/Connect compatible middleware function which injects req.db and ensures that the Iridium Core\r\n * has an active database connection before continuing the request handling process.\r\n */\r\nexport interface ExpressMiddleware {\r\n (req: http.ServerRequest, res: http.ServerResponse, next:(err?: Error, route?: String) => void);\r\n}"],"sourceRoot":"/source/"} \ No newline at end of file diff --git a/dist/lib/utils/ObjectID.js b/dist/lib/utils/ObjectID.js index e12f2ae..ad808ee 100644 --- a/dist/lib/utils/ObjectID.js +++ b/dist/lib/utils/ObjectID.js @@ -1,5 +1,18 @@ /// var MongoDB = require('mongodb'); +/** + * Converts a string to an ObjectID instance - a shortcut for require('mongodb').ObjectID.createFromHexString + * + * @param value The string representation of the ObjectID you wish to create. + * @returns A MongoDB ObjectID instance equivalent to the string you provided. + * + * You should be aware that this method performs no validation on the received string, MongoDB's ObjectID requires + * that it either be a 12 byte UTF8 string, or a 24 byte hexadecimal string in order to be converted correctly. + * + * This method removes the need for your application to directly depend on MongoDB's Node.js client library, + * which helps clean up your code a bit and reduces the headache of maintaining two different versions of the + * library (since Iridium also has one). + */ function toObjectID(value) { return MongoDB.ObjectID.createFromHexString(value); } diff --git a/dist/lib/utils/ObjectID.js.map b/dist/lib/utils/ObjectID.js.map index 3a29101..a25711e 100644 --- a/dist/lib/utils/ObjectID.js.map +++ b/dist/lib/utils/ObjectID.js.map @@ -1 +1 @@ -{"version":3,"sources":["lib/utils/ObjectID.ts"],"names":["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 +{"version":3,"sources":["lib/utils/ObjectID.ts"],"names":["toObjectID"],"mappings":"AAAA,AACA,+CAD+C;AAC/C,IAAO,OAAO,WAAW,SAAS,CAAC,CAAC;AAEpC;;;;;;;;;;;;GAYG;AACH,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\n/**\r\n * Converts a string to an ObjectID instance - a shortcut for require('mongodb').ObjectID.createFromHexString\r\n * \r\n * @param value The string representation of the ObjectID you wish to create.\r\n * @returns A MongoDB ObjectID instance equivalent to the string you provided.\r\n * \r\n * You should be aware that this method performs no validation on the received string, MongoDB's ObjectID requires\r\n * that it either be a 12 byte UTF8 string, or a 24 byte hexadecimal string in order to be converted correctly.\r\n * \r\n * This method removes the need for your application to directly depend on MongoDB's Node.js client library,\r\n * which helps clean up your code a bit and reduces the headache of maintaining two different versions of the\r\n * library (since Iridium also has one).\r\n */\r\nexport function toObjectID(value: string): MongoDB.ObjectID {\r\n\treturn MongoDB.ObjectID.createFromHexString(value);\r\n}"],"sourceRoot":"/source/"} \ No newline at end of file diff --git a/dist/lib/utils/Omnom.js b/dist/lib/utils/Omnom.js index aa3fb36..ac39e74 100644 --- a/dist/lib/utils/Omnom.js +++ b/dist/lib/utils/Omnom.js @@ -182,6 +182,6 @@ var Omnom = (function () { }; return Omnom; })(); -exports.default = Omnom; +exports.Omnom = Omnom; //# sourceMappingURL=../../lib/utils/Omnom.js.map \ No newline at end of file diff --git a/dist/lib/utils/Omnom.js.map b/dist/lib/utils/Omnom.js.map index 0d18585..8de9ae2 100644 --- a/dist/lib/utils/Omnom.js.map +++ b/dist/lib/utils/Omnom.js.map @@ -1 +1 @@ -{"version":3,"sources":["lib/utils/Omnom.ts"],"names":["Omnom","Omnom.constructor","Omnom.changes","Omnom.diff","Omnom.onObject","Omnom.onArray","Omnom.set","Omnom.unset","Omnom.inc","Omnom.push","Omnom.pull","Omnom.pullAll","Omnom.resolve","Omnom.almostEqual"],"mappings":"AAAA,AACA,+CAD+C;AAC/C,IAAO,CAAC,WAAW,QAAQ,CAAC,CAAC;AAC7B,IAAO,OAAO,WAAW,SAAS,CAAC,CAAC;AAEpC;IACIA,eAAmBA,OAEbA;QAFMC,uBAENA,GAFMA,YAENA;QAFaA,YAAOA,GAAPA,OAAOA,CAEpBA;QACFA,IAAIA,CAACA,QAAQA,GAAGA,EAAEA,CAACA;IACvBA,CAACA;IAUDD,sBAAIA,0BAAOA;aAAXA;YAQIE,MAAMA,CAACA,IAAIA,CAACA,QAAQA,CAACA;QACzBA,CAACA;;;OAAAF;IAMDA,oBAAIA,GAAJA,UA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hPA,AAgPCA,IAAA;AAhPD,uBAgPC,CAAA","file":"lib/utils/Omnom.js","sourcesContent":["/// \r\nimport _ = require('lodash');\r\nimport MongoDB = require('mongodb');\r\n\r\nexport default class Omnom {\r\n constructor(public options: {\r\n atomicNumbers?: boolean;\r\n } = {}) {\r\n this._changes = {};\r\n }\r\n\r\n private _changes: {\r\n $set?: any;\r\n $unset?: any;\r\n $inc?: any;\r\n $push?: any;\r\n $pull?: any;\r\n $pullAll?: any;\r\n };\r\n get changes(): {\r\n $set?: any;\r\n $unset?: any;\r\n $inc?: any;\r\n $push?: any;\r\n $pull?: any;\r\n $pullAll?: any;\r\n } {\r\n return this._changes;\r\n }\r\n\r\n diff(original: number, modified: number): Omnom;\r\n diff(original: [any], modified: any[]): Omnom;\r\n diff(original: MongoDB.ObjectID, modified: MongoDB.ObjectID): Omnom;\r\n diff(original: Object, modified: Object): Omnom;\r\n diff(original: any, modified: any): Omnom {\r\n this.onObject(original, modified);\r\n return this;\r\n }\r\n\r\n static diff(original: number, modified: number, options?: {\r\n atomicNumbers?: boolean;\r\n });\r\n static diff(original: [any], modified: any[], options?: {\r\n atomicNumbers?: boolean;\r\n });\r\n static diff(original: MongoDB.ObjectID, modified: MongoDB.ObjectID, options?: {\r\n atomicNumbers?: boolean;\r\n });\r\n static diff(original: Object, modified: Object, options?: {\r\n atomicNumbers?: boolean;\r\n });\r\n static diff(original: any, modified: any, options?: {\r\n atomicNumbers?: boolean;\r\n }) {\r\n return new Omnom(options).diff(original, modified).changes;\r\n }\r\n\r\n private onObject(original: number, modified: number, changePath?: string);\r\n private onObject(original: [any], modified: any[], changePath?: string);\r\n private onObject(original: MongoDB.ObjectID, modified: MongoDB.ObjectID, changePath?: string);\r\n private onObject(original: Object, modified: Object, changePath?: string);\r\n private onObject(original: any, modified: any, changePath?: string) {\r\n if (original === undefined || original === null)\r\n return (original !== modified) && this.set(changePath, modified);\r\n\r\n if (typeof original == 'number' && typeof modified == 'number' && original !== modified) {\r\n if (this.options.atomicNumbers) return this.inc(changePath, modified - original);\r\n return this.set(changePath, modified);\r\n }\r\n\r\n if (Array.isArray(original) && Array.isArray(modified))\r\n return this.onArray(original, modified, changePath);\r\n\r\n if (original instanceof MongoDB.ObjectID && modified instanceof MongoDB.ObjectID)\r\n return !original.equals(modified) && this.set(changePath, modified);\r\n\r\n if (!_.isPlainObject(original) || !_.isPlainObject(modified))\r\n return !_.isEqual(original, modified) && this.set(changePath, modified);\r\n\r\n _.each(modified, function (value, key) {\r\n // Handle array diffs in their own special way\r\n if (Array.isArray(value) && Array.isArray(original[key])) this.onArray(original[key], value, this.resolve(changePath, key));\r\n\r\n // Otherwise, just keep going\r\n else this.onObject(original[key], value, this.resolve(changePath, key));\r\n }, this);\r\n\r\n // Unset removed properties\r\n _.each(original, function (value, key) {\r\n if (modified[key] === undefined) return this.unset(this.resolve(changePath, key));\r\n }, this);\r\n }\r\n\r\n private onArray(original: [any], modified: [any], changePath: string) {\r\n var i, j;\r\n\r\n // Check if we can get from original => modified using just pulls\r\n if (original.length > modified.length) {\r\n var pulls = [];\r\n for (i = 0, j = 0; i < original.length && j < modified.length; i++) {\r\n if (this.almostEqual(original[i], modified[j])) j++;\r\n else pulls.push(original[i]);\r\n }\r\n\r\n for (; i < original.length; i++)\r\n pulls.push(original[i]);\r\n\r\n if (j === modified.length) {\r\n if (pulls.length === 1) return this.pull(changePath, pulls[0]);\r\n // We can complete using just pulls\r\n return pulls.forEach((pull) => this.pull(changePath, pull));\r\n }\r\n\r\n // If we have a smaller target array than our source, we will need to re-create it\r\n // regardless (if we want to do so in a single operation anyway)\r\n else return this.set(changePath, modified);\r\n }\r\n\r\n // Check if we can get from original => modified using just pushes\r\n if (original.length < modified.length) {\r\n var canPush = true;\r\n for (i = 0; i < original.length; i++)\r\n if (this.almostEqual(original[i], modified[i]) < 1) {\r\n canPush = false;\r\n break;\r\n }\r\n\r\n if (canPush) {\r\n for (i = original.length; i < modified.length; i++)\r\n this.push(changePath, modified[i]);\r\n return;\r\n }\r\n }\r\n\r\n // Otherwise, we need to use $set to generate the new array\r\n\r\n // Check how many manipulations would need to be performed, if it's more than half the array size\r\n // then rather re-create the array\r\n\r\n var sets = [];\r\n var partials = [];\r\n for (i = 0; i < modified.length; i++) {\r\n var equality = this.almostEqual(original[i], modified[i]);\r\n if (equality === 0) sets.push(i);\r\n else if (equality < 1) partials.push(i);\r\n }\r\n\r\n if (sets.length > modified.length / 2)\r\n return this.set(changePath, modified);\r\n\r\n for (i = 0; i < sets.length; i++)\r\n this.set(this.resolve(changePath, sets[i].toString()), modified[sets[i]]);\r\n\r\n for (i = 0; i < partials.length; i++)\r\n this.onObject(original[partials[i]], modified[partials[i]], this.resolve(changePath, partials[i].toString()));\r\n }\r\n\r\n private set(path: string, value: any) {\r\n if (!this.changes.$set)\r\n this.changes.$set = {};\r\n\r\n this.changes.$set[path] = value;\r\n }\r\n\r\n private unset(path: string) {\r\n if (!this.changes.$unset)\r\n this.changes.$unset = {};\r\n\r\n this.changes.$unset[path] = 1;\r\n }\r\n\r\n private inc(path: string, value: number) {\r\n if (!this.changes.$inc)\r\n this.changes.$inc = {};\r\n\r\n this.changes.$inc[path] = value;\r\n }\r\n\r\n private push(path: string, value: any) {\r\n if (!this.changes.$push)\r\n this.changes.$push = {};\r\n\r\n if (this.changes.$push[path]) {\r\n if (this.changes.$push[path].$each)\r\n this.changes.$push[path].$each.push(value);\r\n else\r\n this.changes.$push[path] = { $each: [this.changes.$push[path], value] };\r\n } else this.changes.$push[path] = value;\r\n }\r\n\r\n private pull(path: string, value: any) {\r\n if (!this.changes.$pull)\r\n this.changes.$pull = {};\r\n\r\n if (this.changes.$pullAll && this.changes.$pullAll[path]) {\r\n return this.changes.$pullAll[path].push(value);\r\n }\r\n\r\n if (this.changes.$pull[path]) {\r\n this.pullAll(path, [this.changes.$pull[path], value]);\r\n delete this.changes.$pull[path];\r\n if (_.keys(this.changes.$pull).length === 0)\r\n delete this.changes.$pull;\r\n return;\r\n }\r\n\r\n this.changes.$pull[path] = value;\r\n }\r\n\r\n private pullAll(path: string, values: any[]) {\r\n if (!this.changes.$pullAll)\r\n this.changes.$pullAll = {};\r\n\r\n this.changes.$pullAll[path] = values;\r\n }\r\n\r\n private resolve(...args) {\r\n var validArguments = [];\r\n args.forEach(function (arg) {\r\n if (arg) validArguments.push(arg);\r\n });\r\n return validArguments.join('.');\r\n }\r\n\r\n private almostEqual(o1: Object, o2: Object);\r\n private almostEqual(o1: any, o2: any) {\r\n if (!_.isPlainObject(o1) || !_.isPlainObject(o2)) return o1 == o2 ? 1 : 0;\r\n\r\n var o1i, o1k = Object.keys(o1);\r\n var o2k = Object.keys(o2);\r\n\r\n var commonKeys = [];\r\n for (o1i = 0; o1i < o1k.length; o1i++)\r\n if (~o2k.indexOf(o1k[o1i])) commonKeys.push(o1k[o1i]);\r\n\r\n var totalKeys = o1k.length + o2k.length - commonKeys.length;\r\n var keysDifference = totalKeys - commonKeys.length;\r\n\r\n var requiredChanges = 0;\r\n for (var i = 0; i < commonKeys.length; i++)\r\n if (this.almostEqual(o1[commonKeys[i]], o2[commonKeys[i]]) < 1) requiredChanges++;\r\n\r\n return 1 - (keysDifference / totalKeys) - (requiredChanges / commonKeys.length);\r\n }\r\n}"],"sourceRoot":"/source/"} \ No newline at end of file +{"version":3,"sources":["lib/utils/Omnom.ts"],"names":["Omnom","Omnom.constructor","Omnom.changes","Omnom.diff","Omnom.onObject","Omnom.onArray","Omnom.set","Omnom.unset","Omnom.inc","Omnom.push","Omnom.pull","Omnom.pullAll","Omnom.resolve","Omnom.almostEqual"],"mappings":"AAAA,AACA,+CAD+C;AAC/C,IAAO,CAAC,WAAW,QAAQ,CAAC,CAAC;AAC7B,IAAO,OAAO,WAAW,SAAS,CAAC,CAAC;AAEpC;IACIA,eAAmBA,OAEbA;QAFMC,uBAENA,GAFMA,YAENA;QAFaA,YAAOA,GAAPA,OAAOA,CAEpBA;QACFA,IAAIA,CAACA,QAAQA,GAAGA,EAAEA,CAACA;IACvBA,C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AGA,CAACA,cAAcA,GAAGA,SAASA,CAACA,GAAGA,CAACA,eAAeA,GAAGA,UAAUA,CAACA,MAAMA,CAACA,CAACA;IACpFA,CAACA;IACLb,YAACA;AAADA,CAhPA,AAgPCA,IAAA;AAhPY,aAAK,QAgPjB,CAAA","file":"lib/utils/Omnom.js","sourcesContent":["/// \r\nimport _ = require('lodash');\r\nimport MongoDB = require('mongodb');\r\n\r\nexport class Omnom {\r\n constructor(public options: {\r\n atomicNumbers?: boolean;\r\n } = {}) {\r\n this._changes = {};\r\n }\r\n\r\n private _changes: {\r\n $set?: any;\r\n $unset?: any;\r\n $inc?: any;\r\n $push?: any;\r\n $pull?: any;\r\n $pullAll?: any;\r\n };\r\n get changes(): {\r\n $set?: any;\r\n $unset?: any;\r\n $inc?: any;\r\n $push?: any;\r\n $pull?: any;\r\n $pullAll?: any;\r\n } {\r\n return this._changes;\r\n }\r\n\r\n diff(original: number, modified: number): Omnom;\r\n diff(original: [any], modified: any[]): Omnom;\r\n diff(original: MongoDB.ObjectID, modified: MongoDB.ObjectID): Omnom;\r\n diff(original: Object, modified: Object): Omnom;\r\n diff(original: any, modified: any): Omnom {\r\n this.onObject(original, modified);\r\n return this;\r\n }\r\n\r\n static diff(original: number, modified: number, options?: {\r\n atomicNumbers?: boolean;\r\n });\r\n static diff(original: [any], modified: any[], options?: {\r\n atomicNumbers?: boolean;\r\n });\r\n static diff(original: MongoDB.ObjectID, modified: MongoDB.ObjectID, options?: {\r\n atomicNumbers?: boolean;\r\n });\r\n static diff(original: Object, modified: Object, options?: {\r\n atomicNumbers?: boolean;\r\n });\r\n static diff(original: any, modified: any, options?: {\r\n atomicNumbers?: boolean;\r\n }) {\r\n return new Omnom(options).diff(original, modified).changes;\r\n }\r\n\r\n private onObject(original: number, modified: number, changePath?: string);\r\n private onObject(original: [any], modified: any[], changePath?: string);\r\n private onObject(original: MongoDB.ObjectID, modified: MongoDB.ObjectID, changePath?: string);\r\n private onObject(original: Object, modified: Object, changePath?: string);\r\n private onObject(original: any, modified: any, changePath?: string) {\r\n if (original === undefined || original === null)\r\n return (original !== modified) && this.set(changePath, modified);\r\n\r\n if (typeof original == 'number' && typeof modified == 'number' && original !== modified) {\r\n if (this.options.atomicNumbers) return this.inc(changePath, modified - original);\r\n return this.set(changePath, modified);\r\n }\r\n\r\n if (Array.isArray(original) && Array.isArray(modified))\r\n return this.onArray(original, modified, changePath);\r\n\r\n if (original instanceof MongoDB.ObjectID && modified instanceof MongoDB.ObjectID)\r\n return !original.equals(modified) && this.set(changePath, modified);\r\n\r\n if (!_.isPlainObject(original) || !_.isPlainObject(modified))\r\n return !_.isEqual(original, modified) && this.set(changePath, modified);\r\n\r\n _.each(modified, function (value, key) {\r\n // Handle array diffs in their own special way\r\n if (Array.isArray(value) && Array.isArray(original[key])) this.onArray(original[key], value, this.resolve(changePath, key));\r\n\r\n // Otherwise, just keep going\r\n else this.onObject(original[key], value, this.resolve(changePath, key));\r\n }, this);\r\n\r\n // Unset removed properties\r\n _.each(original, function (value, key) {\r\n if (modified[key] === undefined) return this.unset(this.resolve(changePath, key));\r\n }, this);\r\n }\r\n\r\n private onArray(original: [any], modified: [any], changePath: string) {\r\n var i, j;\r\n\r\n // Check if we can get from original => modified using just pulls\r\n if (original.length > modified.length) {\r\n var pulls = [];\r\n for (i = 0, j = 0; i < original.length && j < modified.length; i++) {\r\n if (this.almostEqual(original[i], modified[j])) j++;\r\n else pulls.push(original[i]);\r\n }\r\n\r\n for (; i < original.length; i++)\r\n pulls.push(original[i]);\r\n\r\n if (j === modified.length) {\r\n if (pulls.length === 1) return this.pull(changePath, pulls[0]);\r\n // We can complete using just pulls\r\n return pulls.forEach((pull) => this.pull(changePath, pull));\r\n }\r\n\r\n // If we have a smaller target array than our source, we will need to re-create it\r\n // regardless (if we want to do so in a single operation anyway)\r\n else return this.set(changePath, modified);\r\n }\r\n\r\n // Check if we can get from original => modified using just pushes\r\n if (original.length < modified.length) {\r\n var canPush = true;\r\n for (i = 0; i < original.length; i++)\r\n if (this.almostEqual(original[i], modified[i]) < 1) {\r\n canPush = false;\r\n break;\r\n }\r\n\r\n if (canPush) {\r\n for (i = original.length; i < modified.length; i++)\r\n this.push(changePath, modified[i]);\r\n return;\r\n }\r\n }\r\n\r\n // Otherwise, we need to use $set to generate the new array\r\n\r\n // Check how many manipulations would need to be performed, if it's more than half the array size\r\n // then rather re-create the array\r\n\r\n var sets = [];\r\n var partials = [];\r\n for (i = 0; i < modified.length; i++) {\r\n var equality = this.almostEqual(original[i], modified[i]);\r\n if (equality === 0) sets.push(i);\r\n else if (equality < 1) partials.push(i);\r\n }\r\n\r\n if (sets.length > modified.length / 2)\r\n return this.set(changePath, modified);\r\n\r\n for (i = 0; i < sets.length; i++)\r\n this.set(this.resolve(changePath, sets[i].toString()), modified[sets[i]]);\r\n\r\n for (i = 0; i < partials.length; i++)\r\n this.onObject(original[partials[i]], modified[partials[i]], this.resolve(changePath, partials[i].toString()));\r\n }\r\n\r\n private set(path: string, value: any) {\r\n if (!this.changes.$set)\r\n this.changes.$set = {};\r\n\r\n this.changes.$set[path] = value;\r\n }\r\n\r\n private unset(path: string) {\r\n if (!this.changes.$unset)\r\n this.changes.$unset = {};\r\n\r\n this.changes.$unset[path] = 1;\r\n }\r\n\r\n private inc(path: string, value: number) {\r\n if (!this.changes.$inc)\r\n this.changes.$inc = {};\r\n\r\n this.changes.$inc[path] = value;\r\n }\r\n\r\n private push(path: string, value: any) {\r\n if (!this.changes.$push)\r\n this.changes.$push = {};\r\n\r\n if (this.changes.$push[path]) {\r\n if (this.changes.$push[path].$each)\r\n this.changes.$push[path].$each.push(value);\r\n else\r\n this.changes.$push[path] = { $each: [this.changes.$push[path], value] };\r\n } else this.changes.$push[path] = value;\r\n }\r\n\r\n private pull(path: string, value: any) {\r\n if (!this.changes.$pull)\r\n this.changes.$pull = {};\r\n\r\n if (this.changes.$pullAll && this.changes.$pullAll[path]) {\r\n return this.changes.$pullAll[path].push(value);\r\n }\r\n\r\n if (this.changes.$pull[path]) {\r\n this.pullAll(path, [this.changes.$pull[path], value]);\r\n delete this.changes.$pull[path];\r\n if (_.keys(this.changes.$pull).length === 0)\r\n delete this.changes.$pull;\r\n return;\r\n }\r\n\r\n this.changes.$pull[path] = value;\r\n }\r\n\r\n private pullAll(path: string, values: any[]) {\r\n if (!this.changes.$pullAll)\r\n this.changes.$pullAll = {};\r\n\r\n this.changes.$pullAll[path] = values;\r\n }\r\n\r\n private resolve(...args) {\r\n var validArguments = [];\r\n args.forEach(function (arg) {\r\n if (arg) validArguments.push(arg);\r\n });\r\n return validArguments.join('.');\r\n }\r\n\r\n private almostEqual(o1: Object, o2: Object);\r\n private almostEqual(o1: any, o2: any) {\r\n if (!_.isPlainObject(o1) || !_.isPlainObject(o2)) return o1 == o2 ? 1 : 0;\r\n\r\n var o1i, o1k = Object.keys(o1);\r\n var o2k = Object.keys(o2);\r\n\r\n var commonKeys = [];\r\n for (o1i = 0; o1i < o1k.length; o1i++)\r\n if (~o2k.indexOf(o1k[o1i])) commonKeys.push(o1k[o1i]);\r\n\r\n var totalKeys = o1k.length + o2k.length - commonKeys.length;\r\n var keysDifference = totalKeys - commonKeys.length;\r\n\r\n var requiredChanges = 0;\r\n for (var i = 0; i < commonKeys.length; i++)\r\n if (this.almostEqual(o1[commonKeys[i]], o2[commonKeys[i]]) < 1) requiredChanges++;\r\n\r\n return 1 - (keysDifference / totalKeys) - (requiredChanges / commonKeys.length);\r\n }\r\n}"],"sourceRoot":"/source/"} \ No newline at end of file diff --git a/index.ts b/index.ts index a93db85..5893e96 100644 --- a/index.ts +++ b/index.ts @@ -1,7 +1,6 @@ -import {Core} from './lib/Core'; -import {Model} from './lib/Model'; -import {Instance} from './lib/Instance'; -export {Core, Model, Instance}; +export * from './lib/Core'; +export * from './lib/Model'; +export * from './lib/Instance'; export * from './lib/Decorators'; @@ -12,13 +11,11 @@ export * from './lib/CacheDirector'; export * from './lib/ModelOptions'; export * from './lib/Configuration'; export * from './lib/Hooks'; +export * from './lib/Transforms'; -import {MemoryCache} from './lib/caches/MemoryCache'; -import {NoOpCache} from './lib/caches/NoOpCache'; -export {MemoryCache, NoOpCache}; +export * from './lib/caches/MemoryCache'; +export * from './lib/caches/NoOpCache'; -import {IDDirector} from './lib/cacheControllers/IDDirector'; -export {IDDirector as CacheOnID}; +export * from './lib/cacheControllers/IDDirector'; -import {toObjectID} from './lib/utils/ObjectID'; -export {toObjectID}; +export * from './lib/utils/ObjectID'; diff --git a/test/Aggregate.ts b/test/Aggregate.ts index 889ba4d..a88d403 100644 --- a/test/Aggregate.ts +++ b/test/Aggregate.ts @@ -1,7 +1,7 @@ /// import * as Iridium from '../index'; import MongoDB = require('mongodb'); -import Cursor from '../lib/Cursor'; +import {Cursor} from '../lib/Cursor'; import Promise = require('bluebird'); import _ = require('lodash'); diff --git a/test/Model.ts b/test/Model.ts index 086b173..f20f6fd 100644 --- a/test/Model.ts +++ b/test/Model.ts @@ -1,7 +1,7 @@ /// import * as Iridium from '../index'; import MongoDB = require('mongodb'); -import Cursor from '../lib/Cursor'; +import {Cursor} from '../lib/Cursor'; import Promise = require('bluebird'); import _ = require('lodash'); @@ -831,7 +831,6 @@ describe("Model",() => { }); it("should configure all indexes defined in the model's options", () => { - console.log(model.indexes); return chai.expect(model.ensureIndexes()).to.eventually.exist.and.have.length(1); }); }); diff --git a/test/Omnom.ts b/test/Omnom.ts index 7995ce8..00d4804 100644 --- a/test/Omnom.ts +++ b/test/Omnom.ts @@ -1,5 +1,5 @@ /// -import Omnom from '../lib/utils/Omnom'; +import {Omnom} from '../lib/utils/Omnom'; import MongoDB = require('mongodb'); describe("Omnom",() => { From 9ece18ae140feec3b946021b294733a0719461fc Mon Sep 17 00:00:00 2001 From: Benjamin Pannell Date: Sun, 30 Aug 2015 22:36:47 +0200 Subject: [PATCH 19/22] Updated docs --- doc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc b/doc index 3afe2b2..3a19fcd 160000 --- a/doc +++ b/doc @@ -1 +1 @@ -Subproject commit 3afe2b260ef0dc8bca7ba9bafbb28a5b246f8c24 +Subproject commit 3a19fcd05825c0fd4f21523fdfc01195ff3d9c10 From ad989060fe4a5535a569fd9d6d410c90b943b5c1 Mon Sep 17 00:00:00 2001 From: Benjamin Pannell Date: Sun, 30 Aug 2015 22:40:18 +0200 Subject: [PATCH 20/22] Version 5.10.1 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 59053e3..13d7dd5 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "iridium", - "version": "5.10.0", + "version": "5.10.1", "author": "Benjamin Pannell ", "description": "A custom lightweight ORM for MongoDB designed for power-users", "license": "MIT", From 016263c5a76c0d0cbde59d8faf7e964b134f2cfa Mon Sep 17 00:00:00 2001 From: Benjamin Pannell Date: Sun, 30 Aug 2015 22:40:22 +0200 Subject: [PATCH 21/22] Updated CHANGELOG --- CHANGELOG.md | 35 ++++++++++++++++++++++++++++++----- 1 file changed, 30 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 491557b..6944000 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,7 +1,32 @@ +## [v5.10.1](https://github.com/sierrasoftworks/iridium/tree/v5.10.1) +- [ad98906](https://github.com/sierrasoftworks/iridium/commit/ad98906) Version 5.10.1 +- [b18beb5](https://github.com/sierrasoftworks/iridium/commit/b18beb5) (origin/master) Merge pull request [#17](https://github.com/sierrasoftworks/iridium/issues/17) from SierraSoftworks/feature/nicedocs +- [9ece18a](https://github.com/sierrasoftworks/iridium/commit/9ece18a) (origin/feature/nicedocs, feature/nicedocs) Updated docs +- [39524f7](https://github.com/sierrasoftworks/iridium/commit/39524f7) Fixed a number of broken test fixtures +- [89725a4](https://github.com/sierrasoftworks/iridium/commit/89725a4) Fix a little issue with CI tests +- [7b29f33](https://github.com/sierrasoftworks/iridium/commit/7b29f33) Changed the submodule URL for docs +- [7c9cf0d](https://github.com/sierrasoftworks/iridium/commit/7c9cf0d) Updated documentation +- [f02e177](https://github.com/sierrasoftworks/iridium/commit/f02e177) Updated documentation +- [db7c92c](https://github.com/sierrasoftworks/iridium/commit/db7c92c) Refactored doc gulp script +- [d37c855](https://github.com/sierrasoftworks/iridium/commit/d37c855) Updated documentation +- [47213a9](https://github.com/sierrasoftworks/iridium/commit/47213a9) Updated doc script to push changes to gh-pages branch +- [3dcd9c8](https://github.com/sierrasoftworks/iridium/commit/3dcd9c8) Updated script to only commit doc changes if there are changes to be committed +- [711c490](https://github.com/sierrasoftworks/iridium/commit/711c490) Added gulp script to automatically update documentation +- [006da28](https://github.com/sierrasoftworks/iridium/commit/006da28) Made the doc directory a git submodule for the gh-pages branch +- [c60b030](https://github.com/sierrasoftworks/iridium/commit/c60b030) Exclude documentation website from NPM module +- [5d05863](https://github.com/sierrasoftworks/iridium/commit/5d05863) Restructuring and a massive amount of extra documentation for TypeDoc +- [d92fce4](https://github.com/sierrasoftworks/iridium/commit/d92fce4) Ensure that documentation is generated correctly +- [d339af9](https://github.com/sierrasoftworks/iridium/commit/d339af9) Merge remote-tracking branch 'origin/master' into feature/nicedocs +- [138e448](https://github.com/sierrasoftworks/iridium/commit/138e448) Removed legacy documentation +- [ea6d099](https://github.com/sierrasoftworks/iridium/commit/ea6d099) Added TypeDoc documentation compilation step +- [54ad856](https://github.com/sierrasoftworks/iridium/commit/54ad856) Updated a variety of files to better support TypeDoc +- [c559581](https://github.com/sierrasoftworks/iridium/commit/c559581) Added TypeDoc dependency +- [99cc6cd](https://github.com/sierrasoftworks/iridium/commit/99cc6cd) Updated CHANGELOG + ## [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)) +- [09bfb53](https://github.com/sierrasoftworks/iridium/commit/09bfb53) Make use of arrow functions in Core (Closes #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 @@ -12,7 +37,7 @@ - [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) (infrastructure/travisci-containers) Updated travis config to use MongoDB precise (3.x) +- [cefc0f4](https://github.com/sierrasoftworks/iridium/commit/cefc0f4) 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 @@ -317,7 +342,7 @@ - [40fab25](https://github.com/sierrasoftworks/iridium/commit/40fab25) Log all the things for Travis - [50523ce](https://github.com/sierrasoftworks/iridium/commit/50523ce) Come on Travis, we believe in you - [858b766](https://github.com/sierrasoftworks/iridium/commit/858b766) Return nModified from update() on MongoDB 2.4 -- [caf864a](https://github.com/sierrasoftworks/iridium/commit/caf864a) (sierrasoftworks/master) Make some test failures output more useful informatio +- [caf864a](https://github.com/sierrasoftworks/iridium/commit/caf864a) Make some test failures output more useful informatio - [86b494f](https://github.com/sierrasoftworks/iridium/commit/86b494f) Travis is still broken, more logging and possible fixes - [2448a4f](https://github.com/sierrasoftworks/iridium/commit/2448a4f) Support MongoDB 2.4 responses in update() - [81144a2](https://github.com/sierrasoftworks/iridium/commit/81144a2) Added some logging to find out why Travis is failing tes @@ -337,7 +362,7 @@ - [0147aea](https://github.com/sierrasoftworks/iridium/commit/0147aea) Updated project file - [f9e57cb](https://github.com/sierrasoftworks/iridium/commit/f9e57cb) Show badges for the master branch - [fdb0746](https://github.com/sierrasoftworks/iridium/commit/fdb0746) Merge pull request #7 from SierraSoftworks/typescript -- [cab9a81](https://github.com/sierrasoftworks/iridium/commit/cab9a81) Renamed Promise to Bluebird to avoid confusion and possible conflicts +- [cab9a81](https://github.com/sierrasoftworks/iridium/commit/cab9a81) (sierrasoftworks/typescript) Renamed Promise to Bluebird to avoid confusion and possible conflicts - [a029c1e](https://github.com/sierrasoftworks/iridium/commit/a029c1e) Removed unused variable in Omnom - [b4fb151](https://github.com/sierrasoftworks/iridium/commit/b4fb151) Removed unnecessary semicolons in module index - [45ec39d](https://github.com/sierrasoftworks/iridium/commit/45ec39d) Updated .jshintrc file @@ -347,7 +372,7 @@ - [aad75e8](https://github.com/sierrasoftworks/iridium/commit/aad75e8) Separated Model into a number of smaller files to make it more manageable - [fb6f69a](https://github.com/sierrasoftworks/iridium/commit/fb6f69a) Added some fringe case tests for Omnom - [2e48949](https://github.com/sierrasoftworks/iridium/commit/2e48949) Fixed Travis code climate configuration -- [c91116d](https://github.com/sierrasoftworks/iridium/commit/c91116d) (sierrasoftworks/typescript) Added more badges to the README +- [c91116d](https://github.com/sierrasoftworks/iridium/commit/c91116d) Added more badges to the README - [65ffea9](https://github.com/sierrasoftworks/iridium/commit/65ffea9) Updated code coverage submissions for CodeClimate - [8949641](https://github.com/sierrasoftworks/iridium/commit/8949641) Added coveralls coverage badge to README - [5e229b9](https://github.com/sierrasoftworks/iridium/commit/5e229b9) Updated the project file From 4b5213663bf40672ae00e4a8fffa01b0b3465794 Mon Sep 17 00:00:00 2001 From: Benjamin Pannell Date: Sun, 30 Aug 2015 22:41:25 +0200 Subject: [PATCH 22/22] Updated documentation --- doc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc b/doc index 3a19fcd..4c33078 160000 --- a/doc +++ b/doc @@ -1 +1 @@ -Subproject commit 3a19fcd05825c0fd4f21523fdfc01195ff3d9c10 +Subproject commit 4c33078a5459b11490223ea759c0c7f94e386f34