diff --git a/.settings/launch.json b/.vscode/launch.json similarity index 100% rename from .settings/launch.json rename to .vscode/launch.json diff --git a/.settings/tasks.json b/.vscode/tasks.json similarity index 100% rename from .settings/tasks.json rename to .vscode/tasks.json diff --git a/CHANGELOG.md b/CHANGELOG.md index 1be3d2c..629f72c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,10 +1,46 @@ +## [v6.0.0](https://github.com/sierrasoftworks/iridium/tree/v6.0.0) +- [656c73d](https://github.com/sierrasoftworks/iridium/commit/656c73d) Version 6.0.0 +- [7e4c31f](https://github.com/sierrasoftworks/iridium/commit/7e4c31f) (origin/master, origin/HEAD) Updated CHANGELOG +- [8fe5933](https://github.com/sierrasoftworks/iridium/commit/8fe5933) Updated documentation + +## [v6.0.0-alpha.2](https://github.com/sierrasoftworks/iridium/tree/v6.0.0-alpha.2) +- [30c17cb](https://github.com/sierrasoftworks/iridium/commit/30c17cb) Version 6.0.0-alpha.2 +- [56bb772](https://github.com/sierrasoftworks/iridium/commit/56bb772) fix: Undefined reference to Skmatc in ModelHandlers +- [44fc771](https://github.com/sierrasoftworks/iridium/commit/44fc771) test: Fix compilation of tests +- [cfb92a9](https://github.com/sierrasoftworks/iridium/commit/cfb92a9) tweak: Updated typescript definition pointer in package.json +- [92ae221](https://github.com/sierrasoftworks/iridium/commit/92ae221) refactor: Remove _references.d.ts file +- [9d4f52b](https://github.com/sierrasoftworks/iridium/commit/9d4f52b) refactor: Update all skmatc references to use new dependency structure +- [a020ffe](https://github.com/sierrasoftworks/iridium/commit/a020ffe) dep: Update skmatc to 1.1.4 +- [9370b18](https://github.com/sierrasoftworks/iridium/commit/9370b18) dep: Update skmatc to 1.1.3 +- [f35342b](https://github.com/sierrasoftworks/iridium/commit/f35342b) Updated documentation +- [a19768c](https://github.com/sierrasoftworks/iridium/commit/a19768c) Updated CHANGELOG + +## [v6.0.0-alpha.1](https://github.com/sierrasoftworks/iridium/tree/v6.0.0-alpha.1) +- [a8f4c01](https://github.com/sierrasoftworks/iridium/commit/a8f4c01) Version 6.0.0-alpha.1 +- [f7886b3](https://github.com/sierrasoftworks/iridium/commit/f7886b3) Version 6.0.0-alpha.1 +- [8ba693c](https://github.com/sierrasoftworks/iridium/commit/8ba693c) tweak: Gulp CI command includes build step +- [bd728e1](https://github.com/sierrasoftworks/iridium/commit/bd728e1) tweak: Added multi option to update options +- [3fe9ebc](https://github.com/sierrasoftworks/iridium/commit/3fe9ebc) build: Fix CI test command +- [6b73bbe](https://github.com/sierrasoftworks/iridium/commit/6b73bbe) dist: Build latest version of Iridium +- [14cc15e](https://github.com/sierrasoftworks/iridium/commit/14cc15e) fix: Remove hacky approach to dependency resolution +- [6032286](https://github.com/sierrasoftworks/iridium/commit/6032286) feat: Add index.d.ts file for TypeScript 1.6 +- [aabb131](https://github.com/sierrasoftworks/iridium/commit/aabb131) refactor: Remove references file from all files +- [ba6c01c](https://github.com/sierrasoftworks/iridium/commit/ba6c01c) dep: Updated dependencies to latest versions +- [12b201b](https://github.com/sierrasoftworks/iridium/commit/12b201b) refactor: Fix definitelytyped reference for mongodb remove function +- [b869541](https://github.com/sierrasoftworks/iridium/commit/b869541) test: Fix reference to _id for a number of instance tests +- [aa34363](https://github.com/sierrasoftworks/iridium/commit/aa34363) build: Switch to tsconfig for all build tasks +- [351deb3](https://github.com/sierrasoftworks/iridium/commit/351deb3) build: Set experimental decorators flag when building TS files +- [78f5339](https://github.com/sierrasoftworks/iridium/commit/78f5339) env: Update to VSCode 0.8.0 +- [6d1278d](https://github.com/sierrasoftworks/iridium/commit/6d1278d) Updated documentation +- [0ea880a](https://github.com/sierrasoftworks/iridium/commit/0ea880a) Updated CHANGELOG + ## [v5.11.0](https://github.com/sierrasoftworks/iridium/tree/v5.11.0) - [bd475da](https://github.com/sierrasoftworks/iridium/commit/bd475da) Version 5.11.0 - [ea2a7c8](https://github.com/sierrasoftworks/iridium/commit/ea2a7c8) Listed docs in README (Closes [#9](https://github.com/sierrasoftworks/iridium/issues/9)) - [d806e89](https://github.com/sierrasoftworks/iridium/commit/d806e89) Updated documentation - [971a2b8](https://github.com/sierrasoftworks/iridium/commit/971a2b8) Added implementation and tests for core level connection hooks -- [4b52136](https://github.com/sierrasoftworks/iridium/commit/4b52136) (origin/master, origin/HEAD) Updated documentation +- [4b52136](https://github.com/sierrasoftworks/iridium/commit/4b52136) Updated documentation - [016263c](https://github.com/sierrasoftworks/iridium/commit/016263c) Updated CHANGELOG ## [v5.10.1](https://github.com/sierrasoftworks/iridium/tree/v5.10.1) diff --git a/_references.d.ts b/_references.d.ts deleted file mode 100644 index 4995816..0000000 --- a/_references.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -/// -/// diff --git a/build/build.js b/build/build.js index 6fa1421..a4ca760 100644 --- a/build/build.js +++ b/build/build.js @@ -1,31 +1,33 @@ var gulp = require('gulp'), typescript = require('gulp-typescript'), sourcemaps = require('gulp-sourcemaps'); - + var paths = require('./paths'); - -var tsProject = { - module: 'commonjs', - target: 'es5', + +var tsProjectLib = typescript.createProject('tsconfig.json', { typescript: require('typescript') -}; +}); + +var tsProjectTest = typescript.createProject('test/tsconfig.json', { + typescript: require('typescript') +}); gulp.task('build', ['build-lib', 'build-tests']); -function build(files) { +function build(files, project) { var tsResult = gulp.src(files, { base: paths.projectRoot }) .pipe(sourcemaps.init()) - .pipe(typescript(tsProject)); - + .pipe(typescript(project)); + return tsResult.js .pipe(sourcemaps.write('.')) .pipe(gulp.dest(paths.distFolder)); } gulp.task('build-lib', function () { - return build(paths.buildFiles); + return build(paths.buildFiles, tsProjectLib); }); gulp.task('build-tests', function () { - return build(paths.testFiles); + return build(paths.testFiles, tsProjectTest); }); \ No newline at end of file diff --git a/build/ci.js b/build/ci.js index ce54436..e70b436 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('postpublish','build', 'ci-test'); + return runSequence('build', 'ci-test'); }); gulp.task('ci-test', function () { diff --git a/build/paths.js b/build/paths.js index 1163216..492c61f 100644 --- a/build/paths.js +++ b/build/paths.js @@ -3,22 +3,23 @@ module.exports = { distFolder: path.resolve(__dirname, '../dist'), projectRoot: path.dirname(__dirname), coverageFolder: path.resolve(__dirname, '../coverage'), - - buildFiles: ["lib/**/*.ts", "index.ts"], - testFiles: ["test/**/*.ts"], + + buildFiles: ["typings/DefinitelyTyped/tsd.d.ts", "lib/**/*.ts", "index.ts"], + testFiles: ["typings/DefinitelyTyped/tsd.d.ts", "test/**/*.ts"], cleanFiles: ["coverage", "dist"], - + builtTestFiles: 'dist/test/*.js', builtFiles: ["dist/lib/**/*.js", "dist/index.js"], testSupportFiles: ['dist/test/support/chai'], - + docSourceFiles: [ + "typings/DefinitelyTyped/tsd.d.ts", "lib/Core.ts", "lib/Model.ts", "lib/Instance.ts", - + "lib/Decorators.ts", - + "lib/Plugins.ts", "lib/Schema.ts", "lib/Cache.ts", @@ -27,12 +28,12 @@ module.exports = { "lib/Configuration.ts", "lib/Hooks.ts", "lib/Transforms.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/build/publish.js b/build/publish.js deleted file mode 100644 index 5f3ee71..0000000 --- a/build/publish.js +++ /dev/null @@ -1,14 +0,0 @@ -var gulp = require('gulp'), - replace = require('gulp-replace'); - -gulp.task('prepublish', function () { - return gulp.src(['_references.d.ts']) - .pipe(replace(/^(\/{3}\s*<[^>]*tsd\.d\.ts[^>]*\/>)/g, '//$1')) - .pipe(gulp.dest('.')); -}); - -gulp.task('postpublish', function () { - return gulp.src('_references.d.ts') - .pipe(replace(/^\/{2}(\/{3}\s*<[^>]*tsd\.d\.ts[^>]*\/>)/ig, '$1')) - .pipe(gulp.dest('.')); -}); \ No newline at end of file diff --git a/build/version.js b/build/version.js index 1347c11..fc7fefd 100644 --- a/build/version.js +++ b/build/version.js @@ -45,7 +45,6 @@ gulp.task('version-push-tags', function (cb) { gulp.task('version', function (callback) { runSequence( - 'postpublish', 'doc', 'version-bump', 'version-commit', diff --git a/dist/index.js b/dist/index.js index db3a407..959232e 100644 --- a/dist/index.js +++ b/dist/index.js @@ -18,4 +18,4 @@ __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 +//# sourceMappingURL=index.js.map diff --git a/dist/lib/Aggregate.js b/dist/lib/Aggregate.js index 1bf79e7..570eb84 100644 --- a/dist/lib/Aggregate.js +++ b/dist/lib/Aggregate.js @@ -1,3 +1,3 @@ -/// -//# sourceMappingURL=../lib/Aggregate.js.map \ No newline at end of file + +//# sourceMappingURL=Aggregate.js.map diff --git a/dist/lib/Aggregate.js.map b/dist/lib/Aggregate.js.map index 043d6c5..438741a 100644 --- a/dist/lib/Aggregate.js.map +++ b/dist/lib/Aggregate.js.map @@ -1 +1 @@ -{"version":3,"sources":["lib/Aggregate.ts"],"names":[],"mappings":"AAAA,4CAA4C;AAI3C","file":"lib/Aggregate.js","sourcesContent":["/// \r\n\r\nexport interface Stage {\r\n\r\n}"],"sourceRoot":"/source/"} \ No newline at end of file +{"version":3,"sources":[],"names":[],"mappings":"","file":"lib/Aggregate.js","sourcesContent":[],"sourceRoot":"/source/"} \ No newline at end of file diff --git a/dist/lib/Cache.js b/dist/lib/Cache.js index d1bbc7d..d9710bc 100644 --- a/dist/lib/Cache.js +++ b/dist/lib/Cache.js @@ -1,3 +1,3 @@ -//# sourceMappingURL=../lib/Cache.js.map \ No newline at end of file +//# sourceMappingURL=Cache.js.map diff --git a/dist/lib/Cache.js.map b/dist/lib/Cache.js.map index 8fe1036..cb6eacc 100644 --- a/dist/lib/Cache.js.map +++ b/dist/lib/Cache.js.map @@ -1 +1 @@ -{"version":3,"sources":["lib/Cache.ts"],"names":[],"mappings":"AAOC","file":"lib/Cache.js","sourcesContent":["/// \r\nimport Bluebird = require('bluebird');\r\n\r\nexport interface Cache {\r\n set(key: string, value: T): void;\r\n get(key: string): Bluebird;\r\n clear(key: string): void\r\n}"],"sourceRoot":"/source/"} \ No newline at end of file +{"version":3,"sources":[],"names":[],"mappings":"","file":"lib/Cache.js","sourcesContent":[],"sourceRoot":"/source/"} \ No newline at end of file diff --git a/dist/lib/CacheDirector.js b/dist/lib/CacheDirector.js index fa0218f..0ae8228 100644 --- a/dist/lib/CacheDirector.js +++ b/dist/lib/CacheDirector.js @@ -1,3 +1,3 @@ -/// -//# sourceMappingURL=../lib/CacheDirector.js.map \ No newline at end of file + +//# sourceMappingURL=CacheDirector.js.map diff --git a/dist/lib/CacheDirector.js.map b/dist/lib/CacheDirector.js.map index a6557ff..c8cb4bf 100644 --- a/dist/lib/CacheDirector.js.map +++ b/dist/lib/CacheDirector.js.map @@ -1 +1 @@ -{"version":3,"sources":["lib/CacheDirector.ts"],"names":[],"mappings":"AAAA,AACA,4CAD4C;AAO3C","file":"lib/CacheDirector.js","sourcesContent":["/// \r\nexport interface CacheDirector {\r\n valid(object: T): boolean;\r\n buildKey(object: T): string;\r\n\r\n validQuery(conditions: any): boolean;\r\n buildQueryKey(conditions: any): string;\r\n}"],"sourceRoot":"/source/"} \ No newline at end of file +{"version":3,"sources":[],"names":[],"mappings":"","file":"lib/CacheDirector.js","sourcesContent":[],"sourceRoot":"/source/"} \ No newline at end of file diff --git a/dist/lib/Configuration.js b/dist/lib/Configuration.js index 01a23ff..a177dbe 100644 --- a/dist/lib/Configuration.js +++ b/dist/lib/Configuration.js @@ -1,3 +1,3 @@ -/// -//# sourceMappingURL=../lib/Configuration.js.map \ No newline at end of file + +//# sourceMappingURL=Configuration.js.map diff --git a/dist/lib/Configuration.js.map b/dist/lib/Configuration.js.map index f15a39c..37929ab 100644 --- a/dist/lib/Configuration.js.map +++ b/dist/lib/Configuration.js.map @@ -1 +1 @@ -{"version":3,"sources":["lib/Configuration.ts"],"names":[],"mappings":"AAAA,AACA,4CAD4C;AAS3C","file":"lib/Configuration.js","sourcesContent":["/// \r\nexport interface Configuration {\r\n host?: string;\r\n port?: number;\r\n hosts?: { address: string; port?: number }[];\r\n database?: string;\r\n username?: string;\r\n password?: string;\r\n [key:string]: any;\r\n}"],"sourceRoot":"/source/"} \ No newline at end of file +{"version":3,"sources":[],"names":[],"mappings":"","file":"lib/Configuration.js","sourcesContent":[],"sourceRoot":"/source/"} \ No newline at end of file diff --git a/dist/lib/Core.js b/dist/lib/Core.js index 0bc49be..0ffcfac 100644 --- a/dist/lib/Core.js +++ b/dist/lib/Core.js @@ -1,4 +1,3 @@ -/// var Bluebird = require('bluebird'); var MongoDB = require('mongodb'); var _ = require('lodash'); @@ -210,4 +209,4 @@ var Core = (function () { })(); exports.Core = Core; -//# sourceMappingURL=../lib/Core.js.map \ No newline at end of file +//# sourceMappingURL=Core.js.map diff --git a/dist/lib/Core.js.map b/dist/lib/Core.js.map index bd55bc9..55d342f 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","Core.onConnecting","Core.onConnected"],"mappings":"AAAA,AACA,4CAD4C;AAC5C,IAAO,QAAQ,WAAW,U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,KAAIA,CAACA,WAAWA,GAAGA,IAAIA,CAACA;YACxBA,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;IAEDV;;;;;;;;;;OAUGA;IACOA,2BAAYA,GAAtBA,UAAuBA,UAAsBA;QACzCW,MAAMA,CAACA,QAAQA,CAACA,OAAOA,CAACA,UAAUA,CAACA,CAACA;IACxCA,CAACA;IAEDX;;;;;;OAMGA;IACOA,0BAAWA,GAArBA;QACIY,MAAMA,CAACA,QAAQA,CAACA,OAAOA,EAAEA,CAACA;IAC9BA,CAACA;IACLZ,WAACA;AAADA,CAhNA,AAgNCA,IAAA;AAhNY,YAAI,OAgNhB,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 return this.onConnecting(db);\r\n }).then(db => {\r\n this._connection = db;\r\n this._connectPromise = null;\r\n return this.onConnected();\r\n }).then(() => {\r\n return this;\r\n }, (err) => {\r\n if (this._connection) this._connection.close();\r\n this._connection = null;\r\n this._connectPromise = null;\r\n return Bluebird.reject(err);\r\n }).nodeify(callback);\r\n }\r\n\r\n /**\r\n * Closes the active database connection\r\n * @type {Promise}\r\n */\r\n close(): Bluebird {\r\n return Bluebird.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 /**\r\n * A method which is called whenever a new connection is made to the database.\r\n *\r\n * @param connection The underlying MongoDB connection which was created, you can modify or replace this if you wish.\r\n * @returns A promise for the connection, allowing you to perform any asynchronous initialization required by your application.\r\n *\r\n * In subclassed Iridium Cores this method can be overridden to manipulate the properties\r\n * of the underlying MongoDB connection object, such as authenticating. Until this method\r\n * resolves a connection object, Iridium will be unable to execute any queries. If you wish\r\n * to run Iridium queries then look at the onConnected method.\r\n */\r\n protected onConnecting(connection: MongoDB.Db): Bluebird {\r\n return Bluebird.resolve(connection);\r\n }\r\n\r\n /**\r\n * A method which is called once a database connection has been established and accepted by Iridium\r\n *\r\n * In subclassed Iridium cores this method can be overridden to perform tasks whenever a\r\n * connection to the database has been established - such as setting up indexes for your\r\n * collections or seeding the database.\r\n */\r\n protected onConnected(): Bluebird {\r\n return Bluebird.resolve();\r\n }\r\n}\r\n"],"sourceRoot":"/source/"} \ No newline at end of file +{"version":3,"sources":["lib/Core.ts"],"names":["Core","Core.constructor","Core.plugins","Core.settings","Core.connection","Core.url","Core.cache","Core.register","Core.connect","Core.close","Core.express","Core.onConnecting","Core.onConnected"],"mappings":"AAAA,IAAO,QAAQ,WAAW,UAAU,CAAC,CAAC;AACtC,IAAO,OAAO,WAAW,SAAS,CAAC,CAAC;AACpC,IAAO,CAAC,WAAW,QAAQ,CAAC,CAAC;AAW7B,wBAAuC,sBAAsB,CAAC,CAAA;AAG9D,0BAAwB,oBAAoB,CAAC,CAAA;AAG7C;;;;;;GAMG;AACH;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,OAAOA,IAAIA,CAACA,CAACA,CAACA,IAAIA,QAAQA,CAACA;gBAChCA,MAAMA,GAAGA,IAAIA,CAACA,CAACA,CAACA,CAACA;QAC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A,EAAEA,CAACA;IAC9BA,CAACA;IACLZ,WAACA;AAADA,CAhNA,AAgNCA,IAAA;AAhNY,YAAI,OAgNhB,CAAA","file":"lib/Core.js","sourcesContent":["import Bluebird = require('bluebird');\r\nimport MongoDB = require('mongodb');\r\nimport _ = require('lodash');\r\nimport http = require('http');\r\nimport events = require('events');\r\n\r\nimport {Configuration} from './Configuration';\r\nimport {Plugin} from './Plugins';\r\nimport {Model} from './Model';\r\nimport {Instance} from './Instance';\r\n\r\nimport {MiddlewareFactory} from './Middleware';\r\nimport * as ExpressMiddleware from './middleware/Express';\r\nimport {ExpressMiddlewareFactory} from './middleware/Express';\r\n\r\nimport {Cache} from './Cache';\r\nimport {NoOpCache} from './caches/NoOpCache';\r\nimport {MemoryCache} from './caches/MemoryCache';\r\n\r\n/**\r\n * The Iridium Core, responsible for managing the connection to the database as well\r\n * as any plugins you are making use of.\r\n *\r\n * Generally you will subclass this to provide your own custom core with the models you\r\n * make use of within your application.\r\n */\r\nexport class Core {\r\n /**\r\n * Creates a new Iridium Core instance connected to the specified MongoDB instance\r\n * @param {Iridium.IridiumConfiguration} config The config object defining the database to connect to\r\n * @constructs Core\r\n */\r\n constructor(config: Configuration);\r\n /**\r\n * Creates a new Iridium Core instance connected to the specified MongoDB instance\r\n * @param {String} url The URL of the MongoDB instance to connect to\r\n * @param {Iridium.IridiumConfiguration} config The config object made available as settings\r\n * @constructs Core\r\n */\r\n constructor(uri: string, config?: Configuration);\r\n constructor(uri: string | Configuration, config?: Configuration) {\r\n\r\n 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 return this.onConnecting(db);\r\n }).then(db => {\r\n this._connection = db;\r\n this._connectPromise = null;\r\n return this.onConnected();\r\n }).then(() => {\r\n return this;\r\n }, (err) => {\r\n if (this._connection) this._connection.close();\r\n this._connection = null;\r\n this._connectPromise = null;\r\n return Bluebird.reject(err);\r\n }).nodeify(callback);\r\n }\r\n\r\n /**\r\n * Closes the active database connection\r\n * @type {Promise}\r\n */\r\n close(): Bluebird {\r\n return Bluebird.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 /**\r\n * A method which is called whenever a new connection is made to the database.\r\n *\r\n * @param connection The underlying MongoDB connection which was created, you can modify or replace this if you wish.\r\n * @returns A promise for the connection, allowing you to perform any asynchronous initialization required by your application.\r\n *\r\n * In subclassed Iridium Cores this method can be overridden to manipulate the properties\r\n * of the underlying MongoDB connection object, such as authenticating. Until this method\r\n * resolves a connection object, Iridium will be unable to execute any queries. If you wish\r\n * to run Iridium queries then look at the onConnected method.\r\n */\r\n protected onConnecting(connection: MongoDB.Db): Bluebird {\r\n return Bluebird.resolve(connection);\r\n }\r\n\r\n /**\r\n * A method which is called once a database connection has been established and accepted by Iridium\r\n *\r\n * In subclassed Iridium cores this method can be overridden to perform tasks whenever a\r\n * connection to the database has been established - such as setting up indexes for your\r\n * collections or seeding the database.\r\n */\r\n protected onConnected(): Bluebird {\r\n return Bluebird.resolve();\r\n }\r\n}\r\n"],"sourceRoot":"/source/"} \ No newline at end of file diff --git a/dist/lib/Cursor.js b/dist/lib/Cursor.js index 9418db3..c1dff17 100644 --- a/dist/lib/Cursor.js +++ b/dist/lib/Cursor.js @@ -148,4 +148,4 @@ var Cursor = (function () { })(); exports.Cursor = Cursor; -//# sourceMappingURL=../lib/Cursor.js.map \ No newline at end of file +//# sourceMappingURL=Cursor.js.map diff --git a/dist/lib/Cursor.js.map b/dist/lib/Cursor.js.map index a7e3c05..51eb0b9 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;;;;;;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,EA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AACA,OAAOA,CAACA,QAAQA,CAACA,CAACA;IACzBA,CAACA;IAEDN;;;OAGGA;IACHA,uBAAMA,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 +{"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":"AAGA,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,MAAMA,CAACA,MAAMA,CAACA,GAAGA,CAACA,CAACA;gBAC5BA,MAAMA,CAACA,OAAOA,CAAMA,KAAKA,CAACA,CAACA;YAC/BA,CAACA,CA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AIGA;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":["import {Model} from './Model';\r\nimport General = require('./General');\r\nimport MongoDB = require('mongodb');\r\nimport Bluebird = require('bluebird');\r\nimport * as Index from './Index';\r\n\r\n/**\r\n * An Iridium collection cursor which allows the itteration through documents\r\n * in the collection, automatically wrapping them in the correct instance type.\r\n *\r\n * @param TDocument The interface representing the collection's documents\r\n * @param TInstance The interface or class used to represent the wrapped documents.\r\n */\r\nexport class Cursor {\r\n /**\r\n * Creates a new Iridium cursor which wraps a MongoDB cursor object\r\n * @param {Model} model The Iridium model that this cursor belongs to\r\n * @param {Object} conditions The conditions that resulte in this cursor being created\r\n * @param {MongoDB.Cursor} cursor The MongoDB native cursor object to be wrapped\r\n * @constructor\r\n */\r\n constructor(private model: Model, private conditions: any, public cursor: MongoDB.Cursor) {\r\n\r\n }\r\n\r\n /**\r\n * Counts the number of documents which are matched by this cursor\r\n * @param {function(Error, Number)} callback A callback which is triggered when the result is available\r\n * @return {Promise} A promise which will resolve with the number of documents matched by this cursor\r\n */\r\n count(callback?: General.Callback): Bluebird {\r\n return new Bluebird((resolve, reject) => {\r\n this.cursor.count(true,(err, count) => {\r\n if (err) return reject(err);\r\n return resolve(count);\r\n });\r\n }).nodeify(callback);\r\n }\r\n\r\n /**\r\n * Runs the specified handler over each instance in the query results\r\n * @param {function(Instance)} handler The handler which is triggered for each element in the query\r\n * @param {function(Error)} callback A callback which is triggered when all operations have been dispatched\r\n * @return {Promise} A promise which is resolved when all operations have been dispatched\r\n */\r\n forEach(handler: (instance: TInstance) => void, callback?: General.Callback): Bluebird {\r\n var helpers = this.model.helpers;\r\n return new Bluebird((resolve, reject) => {\r\n this.cursor.forEach((item: TDocument) => {\r\n this.model.handlers.documentReceived(this.conditions, item, function () { return helpers.wrapDocument.apply(helpers, arguments); }).then(handler);\r\n },(err) => {\r\n if (err) return reject(err);\r\n return resolve(null);\r\n });\r\n }).nodeify(callback);\r\n }\r\n\r\n /**\r\n * Runs the specified transform over each instance in the query results and returns the resulting transformed objects\r\n * @param {function(Instance): TResult} transform A handler which is used to transform the result objects\r\n * @param {function(Error, TResult[])} callback A callback which is triggered when the transformations are completed\r\n * @return {Promise} A promise which is fulfilled with the results of the transformations\r\n */\r\n map(transform: (instance: TInstance) => TResult | Bluebird, callback?: General.Callback): Bluebird {\r\n var helpers = this.model.helpers;\r\n return new Bluebird((resolve, reject) => {\r\n var promises: Bluebird[] = [];\r\n this.cursor.forEach((item: TDocument) => {\r\n promises.push(this.model.handlers.documentReceived(this.conditions, item, function () { return helpers.wrapDocument.apply(helpers, arguments); })\r\n .then(<(instance) => TResult>transform));\r\n },(err) => {\r\n if (err) return reject(err);\r\n return resolve(Bluebird.all(promises));\r\n });\r\n }).nodeify(callback);\r\n }\r\n\r\n /**\r\n * Retrieves all matching instances and returns them in an array\r\n * @param {function(Error, TInstance[])} callback A callback which is triggered with the resulting instances\r\n * @return {Promise} A promise which resolves with the instances returned by the query\r\n */\r\n toArray(callback?: General.Callback): Bluebird {\r\n var helpers = this.model.helpers;\r\n return new Bluebird((resolve, reject) => {\r\n this.cursor.toArray((err, results: any[]) => {\r\n if (err) return reject(err);\r\n return resolve(results);\r\n });\r\n }).map((document) => {\r\n return this.model.handlers.documentReceived(this.conditions, document, function () { return helpers.wrapDocument.apply(helpers, arguments); });\r\n }).nodeify(callback);\r\n }\r\n\r\n /**\r\n * Retrieves the next item in the results list\r\n * @param {function(Error, TInstance)} callback A callback which is triggered when the next item becomes available\r\n * @return {Promise} A promise which is resolved with the next item\r\n */\r\n next(callback?: General.Callback): Bluebird {\r\n return new Bluebird((resolve, reject) => {\r\n this.cursor.next((err, result: any) => {\r\n if (err) return reject(err);\r\n return resolve(result);\r\n });\r\n }).then((document) => {\r\n if (!document) return Bluebird.resolve(null);\r\n return this.model.handlers.documentReceived(this.conditions, document,(document, isNew?, isPartial?) => this.model.helpers.wrapDocument(document, isNew, isPartial));\r\n }).nodeify(callback);\r\n }\r\n\r\n /**\r\n * 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 47a0345..31ced78 100644 --- a/dist/lib/Decorators.js +++ b/dist/lib/Decorators.js @@ -1,7 +1,6 @@ -/// var MongoDB = require('mongodb'); var _ = require('lodash'); -var skmatc = require('skmatc'); +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. @@ -44,7 +43,7 @@ exports.Index = Index; */ function Validate(forType, validate) { return function (target) { - target.validators = (target.validators || []).concat(skmatc.create(function (schema) { return schema === forType; }, validate)); + target.validators = (target.validators || []).concat(Skmatc.create(function (schema) { return schema === forType; }, validate)); }; } exports.Validate = Validate; @@ -57,18 +56,19 @@ function Property() { if (args.length > 1 && typeof args[args.length - 1] === 'boolean') required = args.pop(); return function (target, property) { + var staticTarget = target; if (!property) name = args.shift(); else { name = property; - target = target.constructor; + staticTarget = target.constructor; } asType = args.pop() || false; - target.schema = _.clone(target.schema || {}); + staticTarget.schema = _.clone(staticTarget.schema || { _id: false }); if (!required && typeof asType !== 'boolean') - target.schema[name] = { $required: required, $type: asType }; + staticTarget.schema[name] = { $required: required, $type: asType }; else - target.schema[name] = asType; + staticTarget.schema[name] = asType; }; } exports.Property = Property; @@ -85,8 +85,9 @@ exports.Property = Property; */ function Transform(fromDB, toDB) { return function (target, property) { - target.constructor.transforms = _.clone(target.constructor.transforms || {}); - target.constructor.transforms[property] = { + var staticTarget = (target.constructor || target); + staticTarget.transforms = _.clone(staticTarget.transforms || {}); + staticTarget.transforms[property] = { fromDB: fromDB, toDB: toDB }; @@ -106,4 +107,4 @@ function ObjectID(target, name) { } exports.ObjectID = ObjectID; -//# sourceMappingURL=../lib/Decorators.js.map \ No newline at end of file +//# sourceMappingURL=Decorators.js.map diff --git a/dist/lib/Decorators.js.map b/dist/lib/Decorators.js.map index a93fa2a..8d2b1bc 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;;;;;;;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,CAAA;AAED;;;;;;;;;GASG;AACH,kBAAyB,OAAY,EAAE,QAAiE;IACvGC,MAAMA,CAACA,UAASA,MAAuCA;QACtD,MAAM,CAAC,UAAU,GAAG,CAAC,MAAM,CAAC,UAAU,IAAI,EAAE,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,UAAA,MAAM,IAAI,OAAA,MAAM,KAAK,OAAO,EAAlB,CAAkB,EAAE,QAAQ,CAAC,CAAC,CAAC;IAC7G,CAAC,CAAAA;AACFA,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WA,EAAEA,QAAgBA;QAC5C,MAAM,CAAC,WAAW,CAAC,UAAU,GAAG,CAAC,CAAC,KAAK,CAAC,MAAM,CAAC,WAAW,CAAC,UAAU,IAAI,EAAE,CAAC,CAAA;QAC5E,MAAM,CAAC,WAAW,CAAC,UAAU,CAAC,QAAQ,CAAC,GAAG;YACzC,MAAM,EAAE,MAAM;YACd,IAAI,EAAE,IAAI;SACV,CAAC;IACH,CAAC,CAACA;AACHA,CAACA;AARe,iBAAS,YAQxB,CAAA;AAGD;;;;;;GAMG;AACH,kBAAyB,MAAwC,EAAE,IAAY;IAC9EC,QAAQA,CAACA,OAAOA,CAACA,QAAQA,CAACA,CAACA,MAAMA,EAAEA,IAAIA,CAACA,CAACA;IACzCA,SAASA,CACRA,UAAAA,KAAKA,IAAIA,OAAAA,KAAKA,IAAIA,KAAKA,CAACA,SAASA,IAAIA,UAAUA,GAAGA,IAAIA,OAAOA,CAACA,QAAQA,CAACA,KAAKA,CAACA,EAAEA,CAACA,CAACA,WAAWA,EAAEA,GAAGA,KAAKA,EAA7FA,CAA6FA,EACtGA,UAAAA,KAAKA,IAAIA,OAAAA,KAAKA,IAAIA,OAAOA,KAAKA,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\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 +{"version":3,"sources":["lib/Decorators.ts"],"names":["Collection","Index","Validate","Property","Transform","ObjectID"],"mappings":"AAAA,IAAO,OAAO,WAAW,SAAS,CAAC,CAAC;AACpC,IAAO,CAAC,WAAW,QAAQ,CAAC,CAAC;AAC7B,IAAO,MAAM,WAAW,QAAQ,CAAC,CAAC;AAOlC;;;;;;;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,CAAA;AAED;;;;;;;;;GASG;AACH,kBAAyB,OAAY,EAAE,QAAiE;IACvGC,MAAMA,CAACA,UAASA,MAAuCA;QACtD,MAAM,CAAC,UAAU,GAAG,CAAC,MAAM,CAAC,UAAU,IAAI,EAAE,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,UAAA,MAAM,IAAI,OAAA,MAAM,KAAK,OAAO,EAAlB,CAAkB,EAAE,QAAQ,CAAC,CAAC,CAAC;IAC7G,CAAC,CAAAA;AACFA,CAACA;AAJe,gBAAQ,WA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IAAyB;IAC/EC,MAAMA,CAACA,UAASA,MAA0BA,EAAEA,QAAgBA;QAC3D,IAAI,YAAY,GAAuE,CAAC,MAAM,CAAC,WAAW,IAAI,MAAM,CAAC,CAAC;QAEtH,YAAY,CAAC,UAAU,GAAG,CAAC,CAAC,KAAK,CAAC,YAAY,CAAC,UAAU,IAAgB,EAAE,CAAC,CAAA;QAC5E,YAAY,CAAC,UAAU,CAAC,QAAQ,CAAC,GAAG;YACnC,MAAM,EAAE,MAAM;YACd,IAAI,EAAE,IAAI;SACV,CAAC;IACH,CAAC,CAACA;AACHA,CAACA;AAVe,iBAAS,YAUxB,CAAA;AAGD;;;;;;GAMG;AACH,kBAAyB,MAA0B,EAAE,IAAY;IAChEC,QAAQA,CAACA,OAAOA,CAACA,QAAQA,CAACA,CAACA,MAAMA,EAAEA,IAAIA,CAACA,CAACA;IACzCA,SAASA,CACRA,UAAAA,KAAKA,IAAIA,OAAAA,KAAKA,IAAIA,KAAKA,CAACA,SAASA,IAAIA,UAAUA,GAAGA,IAAIA,OAAOA,CAACA,QAAQA,CAACA,KAAKA,CAACA,EAAEA,CAACA,CAACA,WAAWA,EAAEA,GAAGA,KAAKA,EAA7FA,CAA6FA,EACtGA,UAAAA,KAAKA,IAAIA,OAAAA,KAAKA,IAAIA,OAAOA,KAAKA,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":["import 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\nimport {Transforms} from './Transforms';\r\n\r\n/**\r\n * Specifies the name of the collection to which this instance's documents should be sent.\r\n * @param name The name of the MongoDB collection to store the documents in.\r\n *\r\n * This decorator replaces the use of the static collection property on instance implementation\r\n * classes. If your transpiler does not support decorators then you are free to make use of the\r\n * property instead.\r\n */\r\nexport function Collection(name: string) {\r\n\treturn function(target: InstanceImplementation) {\r\n\t\ttarget.collection = name;\r\n\t};\r\n}\r\n\r\n/**\r\n * Specifies a MongoDB collection level index to be managed by Iridium for this instance type.\r\n * More than one instance of this decorator may be used if you wish to specify multiple indexes.\r\n * @param spec The formal index specification which defines the properties and ordering used in the index.\r\n * @param options The options dictating the way in which the index behaves.\r\n *\r\n * This decorator replaces the use of the static indexes property on instance implementation\r\n * classes. If your transpiler does not support decorators then you are free to make use of the\r\n * property instead.\r\n */\r\nexport function Index(spec: IndexSpecification, options?: MongoDB.IndexOptions) {\r\n\treturn function(target: InstanceImplementation) {\r\n\t\ttarget.indexes = (target.indexes || []).concat({ spec: spec, options: options || {} });\r\n\t}\r\n}\r\n\r\n/**\r\n * Specifies a custom validator to be made available for this collection's schema.\r\n * More than one instance of this decorator may be used if you wish to specify multiple validators.\r\n * @param forType The value in the schema which will be delegated to this function for validation.\r\n * @param validate A function which calls this.assert(condition) to determine whether a schema node is valid or not.\r\n *\r\n * This decorator replaces the use of the static validators property on instance implementation\r\n * classes. If your transpiler does not support decorators then you are free to make use of the\r\n * property instead.\r\n */\r\nexport function Validate(forType: any, validate: (schema: any, data: any, path: string) => Skmatc.Result) {\r\n\treturn function(target: InstanceImplementation) {\r\n\t\ttarget.validators = (target.validators || []).concat(Skmatc.create(schema => schema === forType, validate));\r\n\t}\r\n}\r\n\r\n/**\r\n * Specifies the schema type for the property this decorator is applied to. This can be used to replace the\r\n * static schema property on your instance. Multiple instances of this decorator can be applied, but no more\r\n * than one per property.\r\n *\r\n * @param asType The schema validation type to make use of for this property\r\n * @param required Whether this property is required to have a value or not, defaults to true.\r\n */\r\nexport function Property(asType: any, required?: boolean): (target: Instance, name: string) => void;\r\n/**\r\n * Specifies the schema type for a property with the given name on the class this decorator is applied to. This\r\n * can either compliment or replace the static schema property on your instance class.\r\n *\r\n * @param name The name of the property that is being targetted\r\n * @param asType The schema validation type to make use of for this property\r\n * @param required Whether this property is required to have a value or not, defaults to true.\r\n */\r\nexport function Property(name: string, asType: any, required?: boolean): (target: InstanceImplementation) => void;\r\nexport function Property(...args: any[]): (target: Instance | InstanceImplementation, name?: string) => void {\r\n\tlet name = null,\r\n\t\tasType = false,\r\n\t\trequired = true;\r\n\r\n\tif (args.length > 1 && typeof args[args.length - 1] === 'boolean')\r\n\t\trequired = args.pop();\r\n\r\n\treturn function(target: InstanceImplementation, property?: string) {\r\n\t\tlet staticTarget: InstanceImplementation = target;\r\n\t\tif (!property) name = args.shift();\r\n\t\telse {\r\n\t\t\tname = property;\r\n\t\t\tstaticTarget = >target.constructor;\r\n\t\t}\r\n\t\tasType = args.pop() || false;\r\n\r\n\t\tstaticTarget.schema = _.clone(staticTarget.schema || { _id: false });\r\n\t\tif(!required && typeof asType !== 'boolean') staticTarget.schema[name] = { $required: required, $type: asType };\r\n\t\telse staticTarget.schema[name] = asType;\r\n\t}\r\n}\r\n\r\n/**\r\n * Specifies a custom transform to be applied to the property this decorator is applied to.\r\n *\r\n * @param fromDB The function used to convert values from the database for the application.\r\n * @param toDB The function used to convert values from the application to the form used in the database.\r\n *\r\n * This decorator can either compliment or replace the static transforms property on your instance\r\n * class, however only one transform can be applied to any property at a time.\r\n * If your transpiler does not support decorators then you are free to make use of the\r\n * property instead.\r\n */\r\nexport function Transform(fromDB: (value: any) => any, toDB: (value: any) => any) {\r\n\treturn function(target: Instance, property: string) {\r\n\t\tlet staticTarget: InstanceImplementation = >(target.constructor || target);\r\n\r\n\t\tstaticTarget.transforms = _.clone(staticTarget.transforms || {})\r\n\t\tstaticTarget.transforms[property] = {\r\n\t\t\tfromDB: fromDB,\r\n\t\t\ttoDB: toDB\r\n\t\t};\r\n\t};\r\n}\r\n\r\n\r\n/**\r\n * Specifies that this property should be treated as an ObjectID, with the requisite validator and transforms.\r\n *\r\n * This decorator applies an ObjectID validator to the property, which ensures that values sent to the database\r\n * are instances of the MongoDB ObjectID type, as well as applying a transform operation which converts ObjectIDs\r\n * to strings for your application, and then converts strings back to ObjectIDs for the database.\r\n */\r\nexport function ObjectID(target: Instance, name: string) {\r\n\tProperty(MongoDB.ObjectID)(target, name);\r\n\tTransform(\r\n\t\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 b/dist/lib/General.js index f88be71..8fd2e3c 100644 --- a/dist/lib/General.js +++ b/dist/lib/General.js @@ -1,3 +1,3 @@ -/// -//# sourceMappingURL=../lib/General.js.map \ No newline at end of file + +//# sourceMappingURL=General.js.map diff --git a/dist/lib/General.js.map b/dist/lib/General.js.map index ce272e2..e883d6d 100644 --- a/dist/lib/General.js.map +++ b/dist/lib/General.js.map @@ -1 +1 @@ -{"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 +{"version":3,"sources":[],"names":[],"mappings":"","file":"lib/General.js","sourcesContent":[],"sourceRoot":"/source/"} \ No newline at end of file diff --git a/dist/lib/Hooks.js b/dist/lib/Hooks.js index 117b52f..d85dcbf 100644 --- a/dist/lib/Hooks.js +++ b/dist/lib/Hooks.js @@ -1,3 +1,3 @@ -//# sourceMappingURL=../lib/Hooks.js.map \ No newline at end of file +//# sourceMappingURL=Hooks.js.map diff --git a/dist/lib/Hooks.js.map b/dist/lib/Hooks.js.map index 91cecf9..ac61dd3 100644 --- a/dist/lib/Hooks.js.map +++ b/dist/lib/Hooks.js.map @@ -1 +1 @@ -{"version":3,"sources":["lib/Hooks.ts"],"names":[],"mappings":"AAQC","file":"lib/Hooks.js","sourcesContent":["/// \r\nimport instance = require('./Instance');\r\n\r\nexport interface Hooks {\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}"],"sourceRoot":"/source/"} \ No newline at end of file +{"version":3,"sources":[],"names":[],"mappings":"","file":"lib/Hooks.js","sourcesContent":[],"sourceRoot":"/source/"} \ No newline at end of file diff --git a/dist/lib/Index.js b/dist/lib/Index.js index f99f4da..632e5c0 100644 --- a/dist/lib/Index.js +++ b/dist/lib/Index.js @@ -1,3 +1,3 @@ -//# sourceMappingURL=../lib/Index.js.map \ No newline at end of file +//# sourceMappingURL=Index.js.map diff --git a/dist/lib/Index.js.map b/dist/lib/Index.js.map index 713707c..0b0f8cb 100644 --- a/dist/lib/Index.js.map +++ b/dist/lib/Index.js.map @@ -1 +1 @@ -{"version":3,"sources":["lib/Index.ts"],"names":[],"mappings":"AAUC","file":"lib/Index.js","sourcesContent":["/// \r\nimport MongoDB = require('mongodb');\r\n\r\nexport interface Index {\r\n spec: IndexSpecification;\r\n options?: MongoDB.IndexOptions;\r\n}\r\n\r\nexport interface IndexSpecification {\r\n [key: string]: number | string;\r\n}"],"sourceRoot":"/source/"} \ No newline at end of file +{"version":3,"sources":[],"names":[],"mappings":"","file":"lib/Index.js","sourcesContent":[],"sourceRoot":"/source/"} \ No newline at end of file diff --git a/dist/lib/Instance.js b/dist/lib/Instance.js index 1817ffe..4d0dc37 100644 --- a/dist/lib/Instance.js +++ b/dist/lib/Instance.js @@ -1,7 +1,7 @@ var _ = require('lodash'); var MongoDB = require('mongodb'); var Bluebird = require('bluebird'); -var skmatc = require('skmatc'); +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 @@ -264,7 +264,7 @@ var Instance = (function () { * 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) { + 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' }) ]; @@ -280,4 +280,4 @@ var Instance = (function () { })(); exports.Instance = Instance; -//# sourceMappingURL=../lib/Instance.js.map \ No newline at end of file +//# sourceMappingURL=Instance.js.map diff --git a/dist/lib/Instance.js.map b/dist/lib/Instance.js.map index 316587f..d77cc6b 100644 --- a/dist/lib/Instance.js.map +++ b/dist/lib/Instance.js.map @@ -1 +1 @@ -{"version":3,"sources":["lib/Instance.ts"],"names":["Instance","Instance.constructor","Instance.document","Instance.save","Instance.update","Instance.refresh","Instance.delete","Instance.remove","Instance.first","Instance.select","Instance.toJSON","Instance.toString"],"mappings":"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,IAAI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AEA,qBAAqBA,EAAEA,CAACA;KACtCA,CAACA;IAEFA;;OAEGA;IACIA,mBAAUA,GAAeA,EAE/BA,CAACA;IAOFA;;OAEGA;IACIA,gBAAOA,GAA+CA,EAAEA,CAACA;IAiQpEA,eAACA;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 +{"version":3,"sources":["lib/Instance.ts"],"names":["Instance","Instance.constructor","Instance.document","Instance.save","Instance.update","Instance.refresh","Instance.delete","Instance.remove","Instance.first","Instance.select","Instance.toJSON","Instance.toString"],"mappings":"AAUA,IAAO,CAAC,WAAW,QAAQ,CAAC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A;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,KAAIA,CAACA,SAASA,CAACA;YAEpC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,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;IA/RDX;;OAEGA;IACIA,eAAMA,GAAWA;QACpBA,GAAGA,EAAEA,KAAKA;KACbA,CAACA;IAEFA;;OAEGA;IACIA,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;IAEFA;;OAEGA;IACIA,mBAAUA,GAAeA,EAE/BA,CAACA;IAOFA;;OAEGA;IACIA,gBAAOA,GAA+CA,EAAEA,CAACA;IAiQpEA,eAACA;AAADA,CAtWA,AAsWCA,IAAA;AAtWY,gBAAQ,WAsWpB,CAAA","file":"lib/Instance.js","sourcesContent":["import {Core} from './Core';\r\nimport {Model} from './Model';\r\nimport {Plugin} from './Plugins';\r\nimport {CacheDirector} from './CacheDirector';\r\nimport * as General from './General';\r\nimport * as ModelInterfaces from './ModelInterfaces';\r\nimport * as Index from './Index';\r\nimport {Schema} from './Schema';\r\nimport {Transforms} from './Transforms';\r\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 b/dist/lib/InstanceInterface.js index 430cbbd..760d882 100644 --- a/dist/lib/InstanceInterface.js +++ b/dist/lib/InstanceInterface.js @@ -1,3 +1,3 @@ -//# sourceMappingURL=../lib/InstanceInterface.js.map \ No newline at end of file +//# sourceMappingURL=InstanceInterface.js.map diff --git a/dist/lib/InstanceInterface.js.map b/dist/lib/InstanceInterface.js.map index 5926ff6..50a9833 100644 --- a/dist/lib/InstanceInterface.js.map +++ b/dist/lib/InstanceInterface.js.map @@ -1 +1 @@ -{"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 +{"version":3,"sources":[],"names":[],"mappings":"","file":"lib/InstanceInterface.js","sourcesContent":[],"sourceRoot":"/source/"} \ No newline at end of file diff --git a/dist/lib/Middleware.js b/dist/lib/Middleware.js index 33be524..bcd68e8 100644 --- a/dist/lib/Middleware.js +++ b/dist/lib/Middleware.js @@ -1,3 +1,3 @@ -//# sourceMappingURL=../lib/Middleware.js.map \ No newline at end of file +//# sourceMappingURL=Middleware.js.map diff --git a/dist/lib/Middleware.js.map b/dist/lib/Middleware.js.map index 05be03c..e305d11 100644 --- a/dist/lib/Middleware.js.map +++ b/dist/lib/Middleware.js.map @@ -1 +1 @@ -{"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 +{"version":3,"sources":[],"names":[],"mappings":"","file":"lib/Middleware.js","sourcesContent":[],"sourceRoot":"/source/"} \ No newline at end of file diff --git a/dist/lib/Model.js b/dist/lib/Model.js index 618c5f3..84ef40e 100644 --- a/dist/lib/Model.js +++ b/dist/lib/Model.js @@ -1,4 +1,3 @@ -/// var MongoDB = require('mongodb'); var Bluebird = require('bluebird'); var _ = require('lodash'); @@ -538,4 +537,4 @@ var Model = (function () { })(); exports.Model = Model; -//# sourceMappingURL=../lib/Model.js.map \ No newline at end of file +//# sourceMappingURL=Model.js.map diff --git a/dist/lib/Model.js.map b/dist/lib/Model.js.map index dd70524..06d2102 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,qBAA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A,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 +{"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,IAAO,OAAO,WAAW,SAAS,CAAC,CAAC;AACpC,IAAO,QAAQ,WAAW,UAAU,CAAC,CAAC;AAEtC,IAAO,CAAC,WAAW,QAAQ,CAAC,CAAC;AAG7B,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,8DAA8DA,CAACA,CAACA;QAC5JA,EAAEA,CAACA,CAACA,CAACA,CAACA,CAACA,aAAaA,CAACA,YAAYA,CAACA,MAAMA,CAACA,IAAIA,YAAYA,CAACA,MAAMA,CAACA,GAAGA,KAAKA,SAASA,CAACA;YAACA,MAA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AEA,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":["import MongoDB = require('mongodb');\r\nimport Bluebird = require('bluebird');\r\nimport util = require('util');\r\nimport _ = require('lodash');\r\nimport Skmatc = require('skmatc');\r\n\r\nimport {Core} from './Core';\r\nimport {Instance} from './Instance';\r\nimport {Schema} from './Schema';\r\nimport {Hooks} from './Hooks';\r\nimport {Plugin} from './Plugins';\r\nimport {Cache} from './Cache';\r\nimport {CacheDirector} from './CacheDirector';\r\nimport * as General from './General';\r\nimport {Cursor} from './Cursor';\r\nimport * as Index from './Index';\r\nimport * as ModelOptions from './ModelOptions';\r\n\r\nimport {Omnom} from './utils/Omnom';\r\nimport {ModelCache} from './ModelCache';\r\nimport {ModelHelpers} from './ModelHelpers';\r\nimport {ModelHandlers} from './ModelHandlers';\r\nimport * as ModelInterfaces from './ModelInterfaces';\r\nimport {ModelSpecificInstance} from './ModelSpecificInstance';\r\nimport {InstanceImplementation} from './InstanceInterface';\r\nimport {Transforms} 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 dcdac0b..acaf70a 100644 --- a/dist/lib/ModelCache.js +++ b/dist/lib/ModelCache.js @@ -27,4 +27,4 @@ var ModelCache = (function () { })(); exports.ModelCache = ModelCache; -//# sourceMappingURL=../lib/ModelCache.js.map \ No newline at end of file +//# sourceMappingURL=ModelCache.js.map diff --git a/dist/lib/ModelCache.js.map b/dist/lib/ModelCache.js.map index 50e57fa..f57a039 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;;;;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 +{"version":3,"sources":["lib/ModelCache.ts"],"names":["ModelCache","ModelCache.constructor","ModelCache.set","ModelCache.get","ModelCache.clear"],"mappings":"AACA,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":["import {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 caeca40..ff325e4 100644 --- a/dist/lib/ModelHandlers.js +++ b/dist/lib/ModelHandlers.js @@ -62,4 +62,4 @@ var ModelHandlers = (function () { })(); exports.ModelHandlers = ModelHandlers; -//# sourceMappingURL=../lib/ModelHandlers.js.map \ No newline at end of file +//# sourceMappingURL=ModelHandlers.js.map diff --git a/dist/lib/ModelHandlers.js.map b/dist/lib/ModelHandlers.js.map index bd8b075..2300699 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;;;;;;;GAOG;AACH;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,MAAMA,CAACA,CAACA,IAAIA,CAACA,UAACA,MAAWA;YAC7CA,MAAMA,CAAoBA,QAAQA,CAACA,OAAOA,EAAEA,CAACA,IAAIA,CAACA;gBAE9CA,2CAA2CA;gBAC3CA,EAAEA,CAACA,CAACA,KAAIA,CAACA,KAAKA,CAACA,IAAIA,CAACA,KAAKA,IAAIA,OAAOA,CAACA,KAAKA,IAAIA,CAACA,OAAOA,CAACA,MAAMA,CAACA,CAACA,CAACA;oBAC5DA,KAAIA,CAACA,KAAKA,CAACA,KAAKA,CAACA,GAAGA,CAACA,MAAMA,CAACA,CAACA,CAACA,sDAAsDA;gBACxF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ACA,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;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 +{"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;;;;;;;GAOG;AACH;IACIA,uBAAmBA,KAAkCA;QAAlCC,UAAKA,GAALA,KAAKA,CAA6BA;IAErDA,CAACA;IAEDD,wCAAgBA,GAAhBA,UAA0BA,UAAeA,EACrCA,MAAiBA,EACjBA,OAA+EA,EAC/EA,O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,oBAACA;AAADA,CArDA,AAqDCA,IAAA;AArDY,qBAAa,gBAqDzB,CAAA","file":"lib/ModelHandlers.js","sourcesContent":["import {Core} from './Core';\r\nimport {Schema} from './Schema';\r\nimport {Model} from './Model';\r\nimport {ModelCache} from './ModelCache';\r\nimport * as ModelOptions from './ModelOptions';\r\n\r\nimport Skmatc = require('skmatc');\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 a5b77b8..19303ca 100644 --- a/dist/lib/ModelHelpers.js +++ b/dist/lib/ModelHelpers.js @@ -1,4 +1,4 @@ -var skmatc = require('skmatc'); +var Skmatc = require('skmatc'); var Omnom_1 = require('./utils/Omnom'); var _ = require('lodash'); /** @@ -11,7 +11,7 @@ var ModelHelpers = (function () { function ModelHelpers(model) { var _this = this; this.model = model; - this._validator = new skmatc(model.schema); + this._validator = Skmatc.scope(model.schema); model.validators.forEach(function (validator) { return _this._validator.register(validator); }); } /** @@ -68,4 +68,4 @@ var ModelHelpers = (function () { })(); exports.ModelHelpers = ModelHelpers; -//# sourceMappingURL=../lib/ModelHelpers.js.map \ No newline at end of file +//# sourceMappingURL=ModelHelpers.js.map diff --git a/dist/lib/ModelHelpers.js.map b/dist/lib/ModelHelpers.js.map index 9c971f9..d09d61b 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,sBAAoB,eAAe,CAAC,CAAA;AACpC,IAAO,CAAC,WAAW,QAAQ,CAAC,CAAC;AAG7B;;;;;GAKG;AACH;IACIA,sBAAmBA,KAAkCA;QADzDC,iBA8DCA;QA7DsBA,UAAKA,GAALA,KAAKA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AAGA,CAACA,CAACA;IACnCA,CAACA;IAEDL;;;;OAIGA;IACHA,2BAAIA,GAAJA,UAAKA,QAAmBA,EAAEA,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 +{"version":3,"sources":["lib/ModelHelpers.ts"],"names":["ModelHelpers","ModelHelpers.constructor","ModelHelpers.validate","ModelHelpers.wrapDocument","ModelHelpers.transformToDB","ModelHelpers.convertToDB","ModelHelpers.diff"],"mappings":"AAEA,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,MAAMA,CAACA,KAAKA,CAACA,KAAKA,CAACA,MAAMA,CAACA,CAACA;QAC7CA,KAAKA,CAACA,UAAUA,CAACA,OAAOA,CAACA,UAAAA,SAASA,IAAIA,OAAAA,KAAIA,CAACA,UAAUA,CAACA,QAAQA,CAACA,SAASA,CAACA,EAAnCA,CAAmCA,CA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ACA,KAAKA,CAACA,OAAOA,CAACA;IACzBA,CAACA;IACLN,mBAACA;AAADA,CA9DA,AA8DCA,IAAA;AA9DY,oBAAY,eA8DxB,CAAA","file":"lib/ModelHelpers.js","sourcesContent":["import MongoDB = require('mongodb');\r\nimport {Model} from './Model';\r\nimport Skmatc = require('skmatc');\r\nimport {Omnom} from './utils/Omnom';\r\nimport _ = require('lodash');\r\nimport Bluebird = require('bluebird');\r\n\r\n/**\r\n * A number of helper methods used commonly within Iridium, they provide a means to transform,\r\n * validate, wrap and diff instances and documents. By keeping these methods in one place we\r\n * help to improve testability and reduce code duplication (mouse abuse) throughout the codebase.\r\n * @internal\r\n */\r\nexport class ModelHelpers {\r\n constructor(public model: Model) {\r\n this._validator = Skmatc.scope(model.schema);\r\n model.validators.forEach(validator => this._validator.register(validator));\r\n }\r\n\r\n private _validator: Skmatc.Skmatc;\r\n\r\n /**\r\n * Validates a document to ensure that it matches the model's ISchema requirements\r\n * @param {any} document The document to validate against the ISchema\r\n * @returns {SkmatcCore.IResult} The result of the validation\r\n */\r\n validate(document: TDocument): Skmatc.Result {\r\n return this._validator.validate(document);\r\n }\r\n\r\n /**\r\n * Wraps the given document in an instance wrapper for use throughout the application\r\n * @param {any} document The document to be wrapped as an instance\r\n * @param {Boolean} isNew Whether the instance originated from the database or was created by the application\r\n * @param {Boolean} isPartial Whether the document supplied contains all information present in the database\r\n * @returns {any} An instance which wraps this document\r\n */\r\n wrapDocument(document: TDocument, isNew?: boolean, isPartial?: boolean): TInstance {\r\n return new this.model.Instance(document, isNew, isPartial);\r\n }\r\n\r\n /**\r\n * Converts the given document to its database form into a form\r\n * using the transforms defined on the model.\r\n * @param {any} document The document to be converted\r\n * @returns {any} 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 b/dist/lib/ModelInterfaces.js index f833bad..57c9a5a 100644 --- a/dist/lib/ModelInterfaces.js +++ b/dist/lib/ModelInterfaces.js @@ -1,3 +1,3 @@ -/// -//# sourceMappingURL=../lib/ModelInterfaces.js.map \ No newline at end of file + +//# sourceMappingURL=ModelInterfaces.js.map diff --git a/dist/lib/ModelInterfaces.js.map b/dist/lib/ModelInterfaces.js.map index 7e85f28..99b7d1e 100644 --- a/dist/lib/ModelInterfaces.js.map +++ b/dist/lib/ModelInterfaces.js.map @@ -1 +1 @@ -{"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 +{"version":3,"sources":[],"names":[],"mappings":"","file":"lib/ModelInterfaces.js","sourcesContent":[],"sourceRoot":"/source/"} \ No newline at end of file diff --git a/dist/lib/ModelOptions.js b/dist/lib/ModelOptions.js index d024eab..57b2e73 100644 --- a/dist/lib/ModelOptions.js +++ b/dist/lib/ModelOptions.js @@ -1,3 +1,3 @@ -//# sourceMappingURL=../lib/ModelOptions.js.map \ No newline at end of file +//# sourceMappingURL=ModelOptions.js.map diff --git a/dist/lib/ModelOptions.js.map b/dist/lib/ModelOptions.js.map index 49c1d99..5133c5d 100644 --- a/dist/lib/ModelOptions.js.map +++ b/dist/lib/ModelOptions.js.map @@ -1 +1 @@ -{"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 +{"version":3,"sources":[],"names":[],"mappings":"","file":"lib/ModelOptions.js","sourcesContent":[],"sourceRoot":"/source/"} \ No newline at end of file diff --git a/dist/lib/ModelSpecificInstance.js b/dist/lib/ModelSpecificInstance.js index 8e83a01..a9e08e8 100644 --- a/dist/lib/ModelSpecificInstance.js +++ b/dist/lib/ModelSpecificInstance.js @@ -44,4 +44,4 @@ function ModelSpecificInstance(model, instanceType) { } exports.ModelSpecificInstance = ModelSpecificInstance; -//# sourceMappingURL=../lib/ModelSpecificInstance.js.map \ No newline at end of file +//# sourceMappingURL=ModelSpecificInstance.js.map diff --git a/dist/lib/ModelSpecificInstance.js.map b/dist/lib/ModelSpecificInstance.js.map index d8be31c..365d531 100644 --- a/dist/lib/ModelSpecificInstance.js.map +++ b/dist/lib/ModelSpecificInstance.js.map @@ -1 +1 @@ -{"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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BAiCpC,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 +{"version":3,"sources":["lib/ModelSpecificInstance.ts"],"names":["ModelSpecificInstance"],"mappings":"AAGA,IAAO,IAAI,WAAW,MAAM,CAAC,CAAC;AAC9B,IAAO,CAAC,WAAW,QAAQ,CAAC,CAAC;AAE7B;;;;;;;;;;;GAWG;AACH,+BAAkF,KAAkC,EAAE,YAA0D;IAC5KA,IAAI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C,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":["import {Model} from './Model';\r\nimport {InstanceImplementation} from './InstanceInterface';\r\nimport {ModelSpecificInstanceConstructor} from './ModelInterfaces';\r\nimport util = require('util');\r\nimport _ = require('lodash');\r\n\r\n/**\r\n * Creates a new subclass of the given instanceType which correctly performs property transforms\r\n * and associates the instance with the correct model when instantiated.\r\n *\r\n * @param TDocument The interface representing the structure of the documents found in the database.\r\n * @param TInstance The interface or class representing the documents after they have been wrapped in an instance.\r\n *\r\n * @param model The model which instances should be associated with when the resulting constructor is used.\r\n * @param instanceType The constructor used to create new instances of type TInstance.\r\n *\r\n * @internal\r\n */\r\nexport function ModelSpecificInstance(model: Model, instanceType: InstanceImplementation): ModelSpecificInstanceConstructor {\r\n var constructor = function (doc: TDocument, isNew?: boolean, isPartial?: boolean) {\r\n instanceType.call(this, model, doc, isNew, isPartial);\r\n };\r\n\r\n util.inherits(constructor, instanceType);\r\n\r\n _.each(Object.keys(model.schema),(property) => {\r\n if (model.transforms.hasOwnProperty(property)) {\r\n return Object.defineProperty(constructor.prototype, property, {\r\n get: function () {\r\n return model.transforms[property].fromDB(this._modified[property]);\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 b/dist/lib/Plugins.js index e1ca0cd..940f1ac 100644 --- a/dist/lib/Plugins.js +++ b/dist/lib/Plugins.js @@ -1,3 +1,3 @@ -//# sourceMappingURL=../lib/Plugins.js.map \ No newline at end of file +//# sourceMappingURL=Plugins.js.map diff --git a/dist/lib/Plugins.js.map b/dist/lib/Plugins.js.map index 5e44a21..9379c1b 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} 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 +{"version":3,"sources":[],"names":[],"mappings":"","file":"lib/Plugins.js","sourcesContent":[],"sourceRoot":"/source/"} \ No newline at end of file diff --git a/dist/lib/Schema.js b/dist/lib/Schema.js index cdd60f9..014a6ce 100644 --- a/dist/lib/Schema.js +++ b/dist/lib/Schema.js @@ -1,3 +1,3 @@ -/// -//# sourceMappingURL=../lib/Schema.js.map \ No newline at end of file + +//# sourceMappingURL=Schema.js.map diff --git a/dist/lib/Schema.js.map b/dist/lib/Schema.js.map index 7b02e00..afca0cc 100644 --- a/dist/lib/Schema.js.map +++ b/dist/lib/Schema.js.map @@ -1 +1 @@ -{"version":3,"sources":["lib/Schema.ts"],"names":[],"mappings":"AAAA,AACA,4CAD4C;AAI3C","file":"lib/Schema.js","sourcesContent":["/// \r\nexport interface Schema {\r\n _id: boolean | any;\r\n [key:string]: any;\r\n}"],"sourceRoot":"/source/"} \ No newline at end of file +{"version":3,"sources":[],"names":[],"mappings":"","file":"lib/Schema.js","sourcesContent":[],"sourceRoot":"/source/"} \ No newline at end of file diff --git a/dist/lib/Transforms.js b/dist/lib/Transforms.js index 9e05865..d36a8a8 100644 --- a/dist/lib/Transforms.js +++ b/dist/lib/Transforms.js @@ -1,3 +1,3 @@ -/// -//# sourceMappingURL=../lib/Transforms.js.map \ No newline at end of file + +//# sourceMappingURL=Transforms.js.map diff --git a/dist/lib/Transforms.js.map b/dist/lib/Transforms.js.map index cffb1b1..78490fb 100644 --- a/dist/lib/Transforms.js.map +++ b/dist/lib/Transforms.js.map @@ -1 +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 +{"version":3,"sources":[],"names":[],"mappings":"","file":"lib/Transforms.js","sourcesContent":[],"sourceRoot":"/source/"} \ No newline at end of file diff --git a/dist/lib/cacheControllers/IDDirector.js b/dist/lib/cacheControllers/IDDirector.js index 2894fd5..8b554c9 100644 --- a/dist/lib/cacheControllers/IDDirector.js +++ b/dist/lib/cacheControllers/IDDirector.js @@ -28,4 +28,4 @@ var CacheOnID = (function () { })(); exports.CacheOnID = CacheOnID; -//# sourceMappingURL=../../lib/cacheControllers/IDDirector.js.map \ No newline at end of file +//# sourceMappingURL=IDDirector.js.map diff --git a/dist/lib/cacheControllers/IDDirector.js.map b/dist/lib/cacheControllers/IDDirector.js.map index 86a1552..70b7ee2 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":["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 +{"version":3,"sources":["lib/cacheControllers/IDDirector.ts"],"names":["CacheOnID","CacheOnID.constructor","CacheOnID.valid","CacheOnID.buildKey","CacheOnID.validQuery","CacheOnID.buildQueryKey"],"mappings":"AACA,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":["import {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 bd30806..59cd048 100644 --- a/dist/lib/caches/MemoryCache.js +++ b/dist/lib/caches/MemoryCache.js @@ -1,4 +1,3 @@ -/// var Bluebird = require('bluebird'); /** * A cache implementation which stores documents in an in-memory cache. @@ -27,4 +26,4 @@ var MemoryCache = (function () { })(); exports.MemoryCache = MemoryCache; -//# sourceMappingURL=../../lib/caches/MemoryCache.js.map \ No newline at end of file +//# sourceMappingURL=MemoryCache.js.map diff --git a/dist/lib/caches/MemoryCache.js.map b/dist/lib/caches/MemoryCache.js.map index 1114fbf..2a24043 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;;;;;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 +{"version":3,"sources":["lib/caches/MemoryCache.ts"],"names":["MemoryCache","MemoryCache.constructor","MemoryCache.set","MemoryCache.get","MemoryCache.clear"],"mappings":"AAAA,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":["import Bluebird = require('bluebird');\r\nimport {Cache} from '../Cache';\r\n\r\n/**\r\n * A cache implementation which stores documents in an in-memory cache.\r\n *\r\n * Be aware that this is an incredibly simplistic implementation which doesn't manage\r\n * memory usage at all and is very likely NOT suitable for production use.\r\n */\r\nexport class MemoryCache implements Cache {\r\n private cache: any = {};\r\n\r\n set(key: string, value: T): Bluebird {\r\n this.cache[key] = value;\r\n return Bluebird.resolve(value);\r\n }\r\n\r\n get(key: string): Bluebird {\r\n return Bluebird.resolve(this.cache[key]);\r\n }\r\n\r\n clear(key: string) : Bluebird {\r\n var has = this.cache.hasOwnProperty(key);\r\n if(has) delete this.cache[key];\r\n return Bluebird.resolve(has);\r\n }\r\n}"],"sourceRoot":"/source/"} \ No newline at end of file diff --git a/dist/lib/caches/NoOpCache.js b/dist/lib/caches/NoOpCache.js index f645260..a01259d 100644 --- a/dist/lib/caches/NoOpCache.js +++ b/dist/lib/caches/NoOpCache.js @@ -22,4 +22,4 @@ var NoOpCache = (function () { })(); exports.NoOpCache = NoOpCache; -//# sourceMappingURL=../../lib/caches/NoOpCache.js.map \ No newline at end of file +//# sourceMappingURL=NoOpCache.js.map diff --git a/dist/lib/caches/NoOpCache.js.map b/dist/lib/caches/NoOpCache.js.map index de56a0c..83ed2d5 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;;;;;;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 +{"version":3,"sources":["lib/caches/NoOpCache.ts"],"names":["NoOpCache","NoOpCache.constructor","NoOpCache.set","NoOpCache.get","NoOpCache.clear"],"mappings":"AACA,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":["import {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 cc3e8d9..8e94404 100644 --- a/dist/lib/middleware/Express.js +++ b/dist/lib/middleware/Express.js @@ -17,4 +17,4 @@ function ExpressMiddlewareFactory(core) { } exports.ExpressMiddlewareFactory = ExpressMiddlewareFactory; -//# sourceMappingURL=../../lib/middleware/Express.js.map \ No newline at end of file +//# sourceMappingURL=Express.js.map diff --git a/dist/lib/middleware/Express.js.map b/dist/lib/middleware/Express.js.map index 53f2d64..e529520 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;;;;;;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 +{"version":3,"sources":["lib/middleware/Express.ts"],"names":["ExpressMiddlewareFactory"],"mappings":"AAIA;;;;;;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","file":"lib/middleware/Express.js","sourcesContent":["import 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 ad808ee..8ccea59 100644 --- a/dist/lib/utils/ObjectID.js +++ b/dist/lib/utils/ObjectID.js @@ -1,4 +1,3 @@ -/// var MongoDB = require('mongodb'); /** * Converts a string to an ObjectID instance - a shortcut for require('mongodb').ObjectID.createFromHexString @@ -18,4 +17,4 @@ function toObjectID(value) { } exports.toObjectID = toObjectID; -//# sourceMappingURL=../../lib/utils/ObjectID.js.map \ No newline at end of file +//# sourceMappingURL=ObjectID.js.map diff --git a/dist/lib/utils/ObjectID.js.map b/dist/lib/utils/ObjectID.js.map index a25711e..dc04a37 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;;;;;;;;;;;;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 +{"version":3,"sources":["lib/utils/ObjectID.ts"],"names":["toObjectID"],"mappings":"AAAA,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":["import 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 ac39e74..1be96fb 100644 --- a/dist/lib/utils/Omnom.js +++ b/dist/lib/utils/Omnom.js @@ -1,4 +1,3 @@ -/// var _ = require('lodash'); var MongoDB = require('mongodb'); var Omnom = (function () { @@ -184,4 +183,4 @@ var Omnom = (function () { })(); exports.Omnom = Omnom; -//# sourceMappingURL=../../lib/utils/Omnom.js.map \ No newline at end of file +//# sourceMappingURL=Omnom.js.map diff --git a/dist/lib/utils/Omnom.js.map b/dist/lib/utils/Omnom.js.map index 8de9ae2..e4a9747 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,UAAKA,QAAaA,EAAEA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;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 +{"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,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;aAAX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ACA,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":["import _ = 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/doc b/doc index d94d715..a9d2021 160000 --- a/doc +++ b/doc @@ -1 +1 @@ -Subproject commit d94d715f58e3409068fce5449a3394e34c0907d3 +Subproject commit a9d2021ce49818adddb2edb9b6c7696c9581173d diff --git a/index.d.ts b/index.d.ts new file mode 100644 index 0000000..12dbaf5 --- /dev/null +++ b/index.d.ts @@ -0,0 +1 @@ +export * from './index'; \ No newline at end of file diff --git a/lib/Aggregate.ts b/lib/Aggregate.ts index a91bf6a..5efa97c 100644 --- a/lib/Aggregate.ts +++ b/lib/Aggregate.ts @@ -1,5 +1,3 @@ -/// - export interface Stage { } \ No newline at end of file diff --git a/lib/Cache.ts b/lib/Cache.ts index 6208825..7368bd1 100644 --- a/lib/Cache.ts +++ b/lib/Cache.ts @@ -1,4 +1,3 @@ -/// import Bluebird = require('bluebird'); export interface Cache { diff --git a/lib/CacheDirector.ts b/lib/CacheDirector.ts index 6173380..57bc318 100644 --- a/lib/CacheDirector.ts +++ b/lib/CacheDirector.ts @@ -1,4 +1,3 @@ -/// export interface CacheDirector { valid(object: T): boolean; buildKey(object: T): string; diff --git a/lib/Configuration.ts b/lib/Configuration.ts index 443d0ab..8aa1e48 100644 --- a/lib/Configuration.ts +++ b/lib/Configuration.ts @@ -1,4 +1,3 @@ -/// export interface Configuration { host?: string; port?: number; diff --git a/lib/Core.ts b/lib/Core.ts index a7a0028..4ecead8 100644 --- a/lib/Core.ts +++ b/lib/Core.ts @@ -1,4 +1,3 @@ -/// import Bluebird = require('bluebird'); import MongoDB = require('mongodb'); import _ = require('lodash'); diff --git a/lib/Cursor.ts b/lib/Cursor.ts index dedf099..99f23d9 100644 --- a/lib/Cursor.ts +++ b/lib/Cursor.ts @@ -1,5 +1,4 @@ -/// -import {Model} from './Model'; +import {Model} from './Model'; import General = require('./General'); import MongoDB = require('mongodb'); import Bluebird = require('bluebird'); @@ -8,7 +7,7 @@ import * as Index from './Index'; /** * An Iridium collection cursor which allows the itteration through documents * in the collection, automatically wrapping them in the correct instance type. - * + * * @param TDocument The interface representing the collection's documents * @param TInstance The interface or class used to represent the wrapped documents. */ diff --git a/lib/Decorators.ts b/lib/Decorators.ts index da97fb6..77845bd 100644 --- a/lib/Decorators.ts +++ b/lib/Decorators.ts @@ -1,16 +1,16 @@ -/// import MongoDB = require('mongodb'); import _ = require('lodash'); -import skmatc = require('skmatc'); +import Skmatc = require('skmatc'); import {Instance} from './Instance'; import {Index, IndexSpecification} from './Index'; import {Schema} from './Schema'; import {InstanceImplementation} from './InstanceInterface'; +import {Transforms} from './Transforms'; /** * Specifies the name of the collection to which this instance's documents should be sent. * @param name The name of the MongoDB collection to store the documents in. - * + * * 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. @@ -26,7 +26,7 @@ export function Collection(name: string) { * 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. @@ -42,14 +42,14 @@ export function Index(spec: IndexSpecification, options?: MongoDB.IndexOptions) * 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)); + target.validators = (target.validators || []).concat(Skmatc.create(schema => schema === forType, validate)); } } @@ -57,57 +57,60 @@ export function Validate(forType: any, validate: (schema: any, data: any, path: * 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. + * @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; +export function Property(asType: any, required?: boolean): (target: Instance, 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. + * @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 { +export function Property(name: string, asType: any, required?: boolean): (target: InstanceImplementation) => void; +export function Property(...args: any[]): (target: Instance | InstanceImplementation, name?: string) => void { let name = null, asType = false, required = true; - + if (args.length > 1 && typeof args[args.length - 1] === 'boolean') required = args.pop(); - - return function(target: any, property?: string) { + + return function(target: InstanceImplementation, property?: string) { + let staticTarget: InstanceImplementation = target; if (!property) name = args.shift(); else { name = property; - target = target.constructor; + staticTarget = >target.constructor; } asType = args.pop() || false; - - target.schema = _.clone(target.schema || {}); - if(!required && typeof asType !== 'boolean') target.schema[name] = { $required: required, $type: asType }; - else target.schema[name] = asType; + + staticTarget.schema = _.clone(staticTarget.schema || { _id: false }); + if(!required && typeof asType !== 'boolean') staticTarget.schema[name] = { $required: required, $type: asType }; + else staticTarget.schema[name] = asType; } } /** * 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 || {}) - target.constructor.transforms[property] = { + return function(target: Instance, property: string) { + let staticTarget: InstanceImplementation = >(target.constructor || target); + + staticTarget.transforms = _.clone(staticTarget.transforms || {}) + staticTarget.transforms[property] = { fromDB: fromDB, toDB: toDB }; @@ -117,12 +120,12 @@ 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) { +export function ObjectID(target: Instance, name: string) { Property(MongoDB.ObjectID)(target, name); Transform( value => value && value._bsontype == 'ObjectID' ? new MongoDB.ObjectID(value.id).toHexString() : value, diff --git a/lib/General.ts b/lib/General.ts index d8a6728..173f630 100644 --- a/lib/General.ts +++ b/lib/General.ts @@ -1,5 +1,3 @@ -/// - /** * A method which is called once an asynchronous operation has completed, an alternative * to using Promises. diff --git a/lib/Hooks.ts b/lib/Hooks.ts index dbe3bb6..b0a247a 100644 --- a/lib/Hooks.ts +++ b/lib/Hooks.ts @@ -1,4 +1,3 @@ -/// import instance = require('./Instance'); export interface Hooks { diff --git a/lib/Index.ts b/lib/Index.ts index b296b7e..04746ec 100644 --- a/lib/Index.ts +++ b/lib/Index.ts @@ -1,5 +1,4 @@ -/// -import MongoDB = require('mongodb'); +import MongoDB = require('mongodb'); export interface Index { spec: IndexSpecification; diff --git a/lib/Instance.ts b/lib/Instance.ts index 643e49a..f2c0f13 100644 --- a/lib/Instance.ts +++ b/lib/Instance.ts @@ -1,5 +1,4 @@ -/// -import {Core} from './Core'; +import {Core} from './Core'; import {Model} from './Model'; import {Plugin} from './Plugins'; import {CacheDirector} from './CacheDirector'; @@ -12,17 +11,17 @@ import {Transforms} from './Transforms'; import _ = require('lodash'); import MongoDB = require('mongodb'); import Bluebird = require('bluebird'); -import skmatc = require('skmatc'); +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 @@ -70,24 +69,24 @@ export class Instance { * @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. */ @@ -109,7 +108,7 @@ export class Instance { * 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) { + 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' }) ]; @@ -125,12 +124,12 @@ export class Instance { * 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)[] = []; - + /** * 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 diff --git a/lib/InstanceInterface.ts b/lib/InstanceInterface.ts index a49a7c1..f52e76c 100644 --- a/lib/InstanceInterface.ts +++ b/lib/InstanceInterface.ts @@ -1,4 +1,4 @@ -/// +import Skmatc = require('skmatc'); import {Schema} from './Schema'; import {Model} from './Model'; import * as Index from './Index'; @@ -8,10 +8,10 @@ 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 @@ -26,7 +26,7 @@ export interface InstanceImplementation, doc: TDocument, isNew?: boolean, isPartial?: boolean): TInstance; - + /** * The name of the database collection from which documents are retrieved, and to which they are stored. */ @@ -41,32 +41,32 @@ export interface InstanceImplementation import {Core} from './Core'; /** diff --git a/lib/Model.ts b/lib/Model.ts index cdb5a08..bce3c65 100644 --- a/lib/Model.ts +++ b/lib/Model.ts @@ -1,8 +1,8 @@ -/// -import MongoDB = require('mongodb'); +import MongoDB = require('mongodb'); import Bluebird = require('bluebird'); import util = require('util'); import _ = require('lodash'); +import Skmatc = require('skmatc'); import {Core} from './Core'; import {Instance} from './Instance'; @@ -30,10 +30,10 @@ import * as AggregationPipeline from './Aggregate'; * An Iridium Model which represents a structured MongoDB collection. * Models expose the methods you will generally use to query those collections, and ensure that * the results of those queries are returned as {TInstance} instances. - * + * * @param TDocument The interface used to determine the schema of documents in the collection. * @param TInstance The interface or class used to represent collection documents in the JS world. - * + * * @class */ export class Model { diff --git a/lib/ModelCache.ts b/lib/ModelCache.ts index cc335b0..eab93a5 100644 --- a/lib/ModelCache.ts +++ b/lib/ModelCache.ts @@ -1,5 +1,4 @@ -/// -import {Model} from './Model'; +import {Model} from './Model'; import Bluebird = require('bluebird'); /** diff --git a/lib/ModelHandlers.ts b/lib/ModelHandlers.ts index 79b7ad0..21cebaa 100644 --- a/lib/ModelHandlers.ts +++ b/lib/ModelHandlers.ts @@ -1,10 +1,10 @@ -/// -import {Core} from './Core'; +import {Core} from './Core'; import {Schema} from './Schema'; import {Model} from './Model'; import {ModelCache} from './ModelCache'; import * as ModelOptions from './ModelOptions'; +import Skmatc = require('skmatc'); import _ = require('lodash'); import MongoDB = require('mongodb'); import Bluebird = require('bluebird'); @@ -13,7 +13,7 @@ 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 */ @@ -38,7 +38,7 @@ export class ModelHandlers { if (this.model.core.cache && options.cache && !options.fields) { this.model.cache.set(target); // Does not block execution pipeline - fire and forget } - + // Trigger the received hook if (this.model.hooks.onRetrieved) this.model.hooks.onRetrieved(target); @@ -58,7 +58,7 @@ export class ModelHandlers { document = this.model.helpers.convertToDB(document); let validation: Skmatc.Result = this.model.helpers.validate(document); if (validation.failed) return Bluebird.reject(validation.error); - + return document; }); })); diff --git a/lib/ModelHelpers.ts b/lib/ModelHelpers.ts index ad04677..fd0181c 100644 --- a/lib/ModelHelpers.ts +++ b/lib/ModelHelpers.ts @@ -1,7 +1,6 @@ -/// -import MongoDB = require('mongodb'); +import MongoDB = require('mongodb'); import {Model} from './Model'; -import skmatc = require('skmatc'); +import Skmatc = require('skmatc'); import {Omnom} from './utils/Omnom'; import _ = require('lodash'); import Bluebird = require('bluebird'); @@ -14,7 +13,7 @@ import Bluebird = require('bluebird'); */ export class ModelHelpers { constructor(public model: Model) { - this._validator = new skmatc(model.schema); + this._validator = Skmatc.scope(model.schema); model.validators.forEach(validator => this._validator.register(validator)); } @@ -39,7 +38,7 @@ export class ModelHelpers { wrapDocument(document: TDocument, isNew?: boolean, isPartial?: boolean): TInstance { return new this.model.Instance(document, isNew, isPartial); } - + /** * Converts the given document to its database form into a form * using the transforms defined on the model. @@ -52,7 +51,7 @@ export class ModelHelpers { document[property] = this.model.transforms[property].toDB(document[property]); return document; } - + /** * Converts the given document to its database form into a form * using the transforms defined on the model. diff --git a/lib/ModelInterfaces.ts b/lib/ModelInterfaces.ts index 0ead466..01fe5d9 100644 --- a/lib/ModelInterfaces.ts +++ b/lib/ModelInterfaces.ts @@ -1,14 +1,13 @@ -/// -/** +/** * 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 { diff --git a/lib/ModelOptions.ts b/lib/ModelOptions.ts index bc2cbd1..86e618a 100644 --- a/lib/ModelOptions.ts +++ b/lib/ModelOptions.ts @@ -1,5 +1,4 @@ -/// -import MongoDB = require('mongodb'); +import MongoDB = require('mongodb'); import * as Index from './Index'; import {Hooks} from './Hooks'; import {CacheDirector} from './CacheDirector'; @@ -26,44 +25,44 @@ export interface CreateOptions { * 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. */ @@ -75,31 +74,37 @@ export interface UpdateOptions { * 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; + + /** + * Whether to update multiple documents at once, defaults to false unless run using a method + * which explcitly sets it to true. + */ + multi?: boolean; } export interface RemoveOptions { @@ -107,25 +112,25 @@ export interface RemoveOptions { * 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 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. diff --git a/lib/ModelSpecificInstance.ts b/lib/ModelSpecificInstance.ts index 21306e9..4b14bcc 100644 --- a/lib/ModelSpecificInstance.ts +++ b/lib/ModelSpecificInstance.ts @@ -1,5 +1,4 @@ -/// -import {Model} from './Model'; +import {Model} from './Model'; import {InstanceImplementation} from './InstanceInterface'; import {ModelSpecificInstanceConstructor} from './ModelInterfaces'; import util = require('util'); @@ -8,13 +7,13 @@ import _ = 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 */ export function ModelSpecificInstance(model: Model, instanceType: InstanceImplementation): ModelSpecificInstanceConstructor { diff --git a/lib/Plugins.ts b/lib/Plugins.ts index 3697502..d0f3e5e 100644 --- a/lib/Plugins.ts +++ b/lib/Plugins.ts @@ -1,6 +1,6 @@ -/// import {Core} from './Core'; import {Model} from './Model'; +import Skmatc = require('skmatc'); export interface Plugin { newModel? (model: Model); diff --git a/lib/Schema.ts b/lib/Schema.ts index d96924f..84f8c31 100644 --- a/lib/Schema.ts +++ b/lib/Schema.ts @@ -1,4 +1,3 @@ -/// export interface Schema { _id: boolean | any; [key:string]: any; diff --git a/lib/Transforms.ts b/lib/Transforms.ts index 514cd1c..42ad555 100644 --- a/lib/Transforms.ts +++ b/lib/Transforms.ts @@ -1,4 +1,3 @@ -/// export interface Transforms { [property:string]: PropertyTransform; } @@ -14,7 +13,7 @@ export interface PropertyTransform { * @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. diff --git a/lib/cacheControllers/IDDirector.ts b/lib/cacheControllers/IDDirector.ts index eab3166..7c1ddfb 100644 --- a/lib/cacheControllers/IDDirector.ts +++ b/lib/cacheControllers/IDDirector.ts @@ -1,4 +1,3 @@ -/// import {CacheDirector} from '../CacheDirector'; import MongoDB = require('mongodb'); diff --git a/lib/caches/MemoryCache.ts b/lib/caches/MemoryCache.ts index bda0c4c..de158d5 100644 --- a/lib/caches/MemoryCache.ts +++ b/lib/caches/MemoryCache.ts @@ -1,10 +1,9 @@ -/// 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. */ diff --git a/lib/caches/NoOpCache.ts b/lib/caches/NoOpCache.ts index a898871..86607c4 100644 --- a/lib/caches/NoOpCache.ts +++ b/lib/caches/NoOpCache.ts @@ -1,11 +1,10 @@ -/// 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. */ diff --git a/lib/middleware/Express.ts b/lib/middleware/Express.ts index 8e4f8e3..e496db4 100644 --- a/lib/middleware/Express.ts +++ b/lib/middleware/Express.ts @@ -1,4 +1,3 @@ -/// import http = require('http'); import {MiddlewareFactory} from '../Middleware'; import {Core} from '../Core'; @@ -7,7 +6,7 @@ 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 { diff --git a/lib/utils/ObjectID.ts b/lib/utils/ObjectID.ts index cd6e8d3..203abee 100644 --- a/lib/utils/ObjectID.ts +++ b/lib/utils/ObjectID.ts @@ -1,15 +1,14 @@ -/// 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). diff --git a/lib/utils/Omnom.ts b/lib/utils/Omnom.ts index 6ec13ab..1646bff 100644 --- a/lib/utils/Omnom.ts +++ b/lib/utils/Omnom.ts @@ -1,4 +1,3 @@ -/// import _ = require('lodash'); import MongoDB = require('mongodb'); diff --git a/package.json b/package.json index 27ed261..c7a15a3 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "iridium", - "version": "5.11.0", + "version": "6.0.0", "author": "Benjamin Pannell ", "description": "A custom lightweight ORM for MongoDB designed for power-users", "license": "MIT", @@ -18,54 +18,50 @@ "licence": "MIT", "main": "./dist/index.js", "scripts": { - "prepublish": "gulp prepublish", - "postpublish": "gulp postpublish", - "test": "gulp build && gulp ci", + "test": "gulp ci", "coverage": "gulp coverage", "lint": "jshint lib/", "benchmark": "node ./benchmarks/mongodb.js", "build": "gulp build" }, - "typescript": { - "definition": "iridium.d.ts" - }, + "typings": "index.d.ts", "engines": { "node": ">= 0.10" }, "dependencies": { - "bluebird": "^2.9.25", - "lodash": "^3.7.0", - "mongodb": "^2.0.28", - "skmatc": "^1.1.2" + "bluebird": "^2.10.1", + "lodash": "^3.10.1", + "mongodb": "^2.0.44", + "skmatc": "^1.1.4" }, "devDependencies": { "chai": "^2.2.0", - "chai-as-promised": "^5.0.0", - "chai-fuzzy": "^1.5.0", + "chai-as-promised": "^5.1.0", + "chai-fuzzy": "^1.6.0", "codeclimate-test-reporter": "~0.0.4", - "coveralls": "^2.11.2", - "del": "^1.2.0", + "coveralls": "^2.11.4", + "del": "^1.2.1", "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-git": "^1.4.0", + "gulp-istanbul": "^0.10.1", + "gulp-mocha": "^2.1.3", "gulp-plumber": "^1.0.1", - "gulp-replace": "~0.5.3", - "gulp-sourcemaps": "^1.5.2", + "gulp-replace": "^0.5.4", + "gulp-sourcemaps": "^1.6.0", "gulp-typedoc": "^1.2.1", - "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", + "gulp-typescript": "^2.9.0", + "gulp-util": "^3.0.6", + "istanbul": "^0.3.21", + "jshint": "^2.8.0", + "minimist": "^1.2.0", + "mocha": "^2.3.3", "require-dir": "~0.3.0", - "run-sequence": "^1.1.0", + "run-sequence": "^1.1.4", "semver": "^4.3.6", "tick": "~0.1.1", - "typedoc": "^0.3.8", - "typescript": "^1.5.0-beta", + "typedoc": "^0.3.11", + "typescript": "^1.6.2", "underscore": "^1.8.3" }, "keywords": [ diff --git a/test/Aggregate.ts b/test/Aggregate.ts index a88d403..d634432 100644 --- a/test/Aggregate.ts +++ b/test/Aggregate.ts @@ -1,4 +1,4 @@ -/// +/// import * as Iridium from '../index'; import MongoDB = require('mongodb'); import {Cursor} from '../lib/Cursor'; @@ -29,7 +29,6 @@ describe("Model", () => { before(() => core.connect()); - describe("aggregate()", () => { let model = new Iridium.Model(core, Test); diff --git a/test/Cache.ts b/test/Cache.ts index 762e510..5dce461 100644 --- a/test/Cache.ts +++ b/test/Cache.ts @@ -1,4 +1,4 @@ -/// +/// import * as Iridium from '../index'; interface Document { @@ -9,7 +9,7 @@ class Instance extends Iridium.Instance { static collection = 'test'; static schema: Iridium.Schema = { _id: false }; static cache = new Iridium.CacheOnID(); - + _id: string; } diff --git a/test/Core.ts b/test/Core.ts index f7b9181..3cfeaa3 100644 --- a/test/Core.ts +++ b/test/Core.ts @@ -1,4 +1,4 @@ -/// +/// import * as Iridium from '../index'; import events = require('events'); import Bluebird = require('bluebird'); diff --git a/test/Decorators.ts b/test/Decorators.ts index 89180a9..3846d2f 100644 --- a/test/Decorators.ts +++ b/test/Decorators.ts @@ -1,4 +1,4 @@ -/// +/// import * as Iridium from '../index'; import skmatc = require('skmatc'); import MongoDB = require('mongodb'); @@ -17,24 +17,24 @@ function VersionValidator(schema, data) { @Iridium.Index({ name: 1 }) @Iridium.Index({ email: 1 }, { background: true }) @Iridium.Validate('version', VersionValidator) -@Iridium.Property('version', 'version') -@Iridium.Property('optional2', Boolean, false) +@Iridium.Property('version', 'version') +@Iridium.Property('optional2', Boolean, false) class Test extends Iridium.Instance implements TestDocument { static transforms: Iridium.Transforms = {}; static indexes = []; - + @Iridium.ObjectID _id: string; - + @Iridium.Property(String) name: string; - + @Iridium.Property(/^.+@.+$/) @Iridium.Transform(email => email.toLowerCase().trim(), email => email.toLowerCase().trim()) email: string; - + version: string; - + @Iridium.Property(Boolean, false) optional1: boolean; optional2: boolean; @@ -45,114 +45,114 @@ describe("Decorators", () => { it("should populate the collection static field", () => { chai.expect(Test.collection).to.equal('test'); }); - + it("should not pollute the parent's collection property", () => { chai.expect(Iridium.Instance.collection).to.not.exist; }); }); - + describe("Index", () => { it("should populate the constructor's indexes property with index objects", () => { chai.expect(Test.indexes).to.exist.and.have.length(2); }); - + it("should support just spec indexes", () => { chai.expect(Test.indexes).to.containOneLike({ spec: { name: 1 }, options: {} }); }); - + it("should support indexes with both a spec and options", () => { chai.expect(Test.indexes).to.containOneLike({ spec: { email: 1 }, options: { background: true }}); }); - + it("should not pollute the parent's index object", () => { chai.expect(Iridium.Instance.indexes).to.exist.and.have.length(0); }); }); - + describe("Validate", () => { it("should populate the constructor's valdiators property", () => { chai.expect(Test.validators).to.exist.and.have.length(Iridium.Instance.validators.length + 1); }); - + it("should create a valid Skmatc validator instance", () => { - let s = new skmatc(Test.schema); - + let s = skmatc.scope(Test.schema); + for (let i = 0; i < Test.validators.length; i++) { chai.expect(Test.validators[i]).to.be.a('function'); s.register(Test.validators[i]); } - + chai.expect(s.validate({ name: 'Test', email: 'test@test.com', version: '1.0.0' })).to.exist.and.have.property('failures').eql([]); }); - + it("should correctly include the validations", () => { - let s = new skmatc(Test.schema); - + let s = skmatc.scope(Test.schema); + for (let i = 0; i < Test.validators.length; i++) { chai.expect(Test.validators[i]).to.be.a('function'); s.register(Test.validators[i]); } - + chai.expect(s.validate({ name: 'Test', email: 'test@test.com', version: 'a1.0.0' })).to.exist.and.have.property('failures').not.eql([]); }); - + it("should not pollute the parent's validators object", () => { chai.expect(Iridium.Instance.validators).to.exist.and.have.length(1); }); }); - + describe("ObjectID", () => { it("should populate the constructor's schema object", () => { chai.expect(Test.schema).to.exist.and.have.property('_id').and.eql(MongoDB.ObjectID); }); - + it("should populate the constructor's transforms object", () => { chai.expect(Test.transforms).to.exist.and.have.property('_id').with.property('fromDB').which.is.a('function'); chai.expect(Test.transforms).to.exist.and.have.property('_id').with.property('toDB').which.is.a('function'); }); - + describe("the ObjectID transform", () => { it("should convert an ObjectID to a string", () => { chai.expect(Test.transforms['_id'].fromDB({ _bsontype: 'ObjectID', id: 'aaaaaaaaaaaaaaaaaaaaaaaa' })).to.eql('aaaaaaaaaaaaaaaaaaaaaaaa'); }); - + it("should convert a string to an ObjectID", () => { chai.expect(Test.transforms['_id'].toDB('aaaaaaaaaaaaaaaaaaaaaaaa')).to.be.instanceOf(MongoDB.ObjectID); }); - + it("should handle undefined values correctly", () => { chai.expect(Test.transforms['_id'].toDB(undefined)).to.not.exist; chai.expect(Test.transforms['_id'].fromDB(undefined)).to.not.exist; }); }); }); - + describe("Property", () => { it("should populate the constructor's schema object when applied to properties", () => { chai.expect(Test.schema).to.exist.and.have.property('name', String); chai.expect(Test.schema).to.exist.and.have.property('email').and.eql(/^.+@.+$/); }); - + it("should populate the constructor's schema object when to the constructor", () => { chai.expect(Test.schema).to.exist.and.have.property('version', 'version'); }); - + it("should correctly handle optional properties defined on instance fields", () => { chai.expect(Test.schema).to.exist.and.have.property('optional1').eql({ $required: false, $type: Boolean }); }); - + it("should correctly handle optional properties defined on the constructor", () => { chai.expect(Test.schema).to.exist.and.have.property('optional2').eql({ $required: false, $type: Boolean }); }); - + it("should not pollute the parent's schema object", () => { chai.expect(Iridium.Instance.schema).to.exist.and.not.have.property('name'); chai.expect(Iridium.Instance.schema).to.exist.and.not.have.property('email'); @@ -161,18 +161,18 @@ describe("Decorators", () => { chai.expect(Iridium.Instance.schema).to.exist.and.not.have.property('optional2'); }); }); - + describe("Transform", () => { it("should not remove existing entries in the transforms object", () => { chai.expect(Test.transforms).to.exist.and.have.property('_id').with.property('fromDB').which.is.a('function'); chai.expect(Test.transforms).to.exist.and.have.property('_id').with.property('toDB').which.is.a('function'); }); - + it("should populate the constructor's transforms object", () => { chai.expect(Test.transforms).to.exist.and.have.property('email').with.property('fromDB').which.is.a('function'); chai.expect(Test.transforms).to.exist.and.have.property('email').with.property('toDB').which.is.a('function'); }); - + it("should not pollute the parent's transforms object", () => { chai.expect(Iridium.Instance.transforms).to.exist.and.not.have.property('email'); }); diff --git a/test/Hooks.ts b/test/Hooks.ts index 6d0a7d4..88874fd 100644 --- a/test/Hooks.ts +++ b/test/Hooks.ts @@ -1,4 +1,4 @@ -/// +/// import * as Iridium from '../index'; import Events = require('events'); import Promise = require('bluebird'); @@ -16,22 +16,22 @@ class Test extends Iridium.Instance { _id: false, answer: Number }; - + id: string; answer: number; - + static onCreating(document: TestDocument) { hookEmitter.emit('creating', document); } - + static onReady(instance: Test) { hookEmitter.emit('ready', instance); } - + static onRetrieved(document: TestDocument) { hookEmitter.emit('retrieved', document); } - + static onSaving(instance: Test, changes: any) { hookEmitter.emit('saving', instance, changes); } diff --git a/test/Instance.ts b/test/Instance.ts index 854306d..dc714f6 100644 --- a/test/Instance.ts +++ b/test/Instance.ts @@ -1,4 +1,4 @@ -/// +/// import * as Iridium from '../index'; import MongoDB = require('mongodb'); import Bluebird = require('bluebird'); @@ -18,7 +18,7 @@ class Test extends Iridium.Instance implements TestDocument lots: { $required: false, $type: [Number] }, less: { $required: false, $propertyType: Number } }; - + _id: string; answer: number; lots: number[]; @@ -78,43 +78,43 @@ describe("Instance",() => { describe("methods",() => { it("should expose save()",() => { - chai.expect(core.Test.helpers.wrapDocument({ id: '1', answer: 2 }).save).to.exist.and.be.a('function'); + chai.expect(core.Test.helpers.wrapDocument({ _id: '1', answer: 2 }).save).to.exist.and.be.a('function'); }); it("should expose update()",() => { - chai.expect(core.Test.helpers.wrapDocument({ id: '1', answer: 2 }).update).to.exist.and.be.a('function'); + chai.expect(core.Test.helpers.wrapDocument({ _id: '1', answer: 2 }).update).to.exist.and.be.a('function'); }); it("should expose refresh()",() => { - chai.expect(core.Test.helpers.wrapDocument({ id: '1', answer: 2 }).refresh).to.exist.and.be.a('function'); + chai.expect(core.Test.helpers.wrapDocument({ _id: '1', answer: 2 }).refresh).to.exist.and.be.a('function'); }); it("should expose delete()",() => { - chai.expect(core.Test.helpers.wrapDocument({ id: '1', answer: 2 }).delete).to.exist.and.be.a('function'); + chai.expect(core.Test.helpers.wrapDocument({ _id: '1', answer: 2 }).delete).to.exist.and.be.a('function'); }); it("should expose remove()",() => { - chai.expect(core.Test.helpers.wrapDocument({ id: '1', answer: 2 }).remove).to.exist.and.be.a('function'); + chai.expect(core.Test.helpers.wrapDocument({ _id: '1', answer: 2 }).remove).to.exist.and.be.a('function'); }); it("should override toJSON()",() => { - chai.expect(core.Test.helpers.wrapDocument({ id: '1', answer: 2 }).toJSON()).to.eql({ id: '1', answer: 2 }); + chai.expect(core.Test.helpers.wrapDocument({ _id: '1', answer: 2 }).toJSON()).to.eql({ _id: '1', answer: 2 }); }); it("should override toString()",() => { - chai.expect(core.Test.helpers.wrapDocument({ id: '1', answer: 2 }).toString()).to.eql(JSON.stringify({ id: '1', answer: 2 }, null, 2)); + chai.expect(core.Test.helpers.wrapDocument({ _id: '1', answer: 2 }).toString()).to.eql(JSON.stringify({ _id: '1', answer: 2 }, null, 2)); }); }); describe("properties",() => { it("should expose document",() => { - chai.expect(core.Test.helpers.wrapDocument({ id: '1', answer: 2 }).document).to.eql({ id: '1', answer: 2 }); + chai.expect(core.Test.helpers.wrapDocument({ _id: '1', answer: 2 }).document).to.eql({ _id: '1', answer: 2 }); }); }); it("should expose additional getters and setters",() => { let instance = core.Test.helpers.wrapDocument({ - id: 'aaaaaa', + _id: 'aaaaaa', answer: 2 }); @@ -124,7 +124,7 @@ describe("Instance",() => { it("should expose additional methods",() => { let instance = core.Test.helpers.wrapDocument({ - id: 'aaaaaa', + _id: 'aaaaaa', answer: 2 }); @@ -420,10 +420,10 @@ describe("Instance",() => { return chai.expect(core.Test.get().then(instance => instance.select(instance.less, lot => lot > 100))).to.eventually.be.eql({}); }); }); - + describe("modifications", () => { beforeEach(() => core.Test.remove().then(() => core.Test.insert({ answer: 1, lots: [1, 2, 3, 4], less: { 'a': 1, 'b': 2 } }))); - + it("should correctly diff simple property changes", () => { return core.Test.get().then(instance => { instance.answer = 2; @@ -432,7 +432,7 @@ describe("Instance",() => { chai.expect(instance).to.have.property('answer', 2); }); }); - + it("should correctly diff deep property changes", () => { return core.Test.get().then(instance => { instance.less['a'] = 2; @@ -441,7 +441,7 @@ describe("Instance",() => { chai.expect(instance).to.have.property('less').eql({ a: 2, b: 2 }); }); }); - + it("should correctly diff array operations", () => { return core.Test.get().then(instance => { instance.lots.push(5); @@ -451,19 +451,19 @@ describe("Instance",() => { }); }); }); - + describe("after a save", () => { var instance: Test; - + before(() => core.Test.remove().then(() => core.Test.insert({ answer: 1, lots: [1, 2, 3, 4], less: { 'a': 1, 'b': 2 } })).then(i => { i.answer = 3; return i.save(); }).then(i => instance = i)); - + it("should return the instance", () => { chai.expect(instance).to.exist; }); - + it("should correctly diff simple property changes", () => { return Bluebird.resolve(instance).then(i => { i.answer = 2; @@ -473,7 +473,7 @@ describe("Instance",() => { chai.expect(i).to.have.property('answer', 2); }); }); - + it("should correctly diff deep property changes", () => { return Bluebird.resolve(instance).then(i => { i.less['a'] = 2; @@ -483,7 +483,7 @@ describe("Instance",() => { chai.expect(i).to.have.property('less').eql({ a: 2, b: 2 }); }); }); - + it("should correctly diff array operations", () => { return Bluebird.resolve(instance).then(i => { i.lots.push(5); @@ -493,6 +493,6 @@ describe("Instance",() => { chai.expect(i).to.have.property('lots').eql([1,2,3,4,5]); }); }); - + }); }); \ No newline at end of file diff --git a/test/Iridium.ts b/test/Iridium.ts index 96443d2..987f0a4 100644 --- a/test/Iridium.ts +++ b/test/Iridium.ts @@ -1,4 +1,4 @@ -/// +/// import * as Iridium from '../index'; describe("Iridium",() => { diff --git a/test/Middleware.ts b/test/Middleware.ts index 04689c2..a892a02 100644 --- a/test/Middleware.ts +++ b/test/Middleware.ts @@ -1,4 +1,4 @@ -/// +/// import * as Iridium from '../index'; describe("Middleware",() => { diff --git a/test/Model.ts b/test/Model.ts index f20f6fd..6af1995 100644 --- a/test/Model.ts +++ b/test/Model.ts @@ -1,4 +1,4 @@ -/// +/// import * as Iridium from '../index'; import MongoDB = require('mongodb'); import {Cursor} from '../lib/Cursor'; @@ -16,7 +16,7 @@ class Test extends Iridium.Instance implements TestDocument _id: MongoDB.ObjectID, answer: Number }; - + _id: string; answer: number; } @@ -41,7 +41,7 @@ describe("Model",() => { _.merge(fn, properties); return fn; } - + it("should throw an error if you don't provide a valid core",() => { chai.expect(() => { new Iridium.Model(null, createInstanceImplementation({ @@ -210,7 +210,7 @@ describe("Model",() => { it("should allow you to provide options to control the creation",() => { return chai.expect(model.create({ answer: 14 }, { upsert: true })).to.eventually.exist; }); - + it("should return an error if you don't meet the schema validation requirements",() => { return chai.expect(model.create({ answer: 'wrong' })).to.eventually.be.rejected; }); @@ -258,7 +258,7 @@ describe("Model",() => { it("should allow you to provide options to control the creation",() => { return chai.expect(model.insert({ answer: 14 }, { upsert: true })).to.eventually.exist; }); - + it("should return an error if you don't meet the schema validation requirements",() => { return chai.expect(model.insert({ answer: 'wrong' })).to.eventually.be.rejected; }); @@ -380,7 +380,7 @@ describe("Model",() => { sort: { answer: -1 } })).to.eventually.exist.and.have.property('answer', 14); }); - + it("should allow you to limit the returned fields",() => { return chai.expect(model.findOne({}, { fields: { answer: 0 } @@ -502,7 +502,7 @@ describe("Model",() => { count++; }).then(() => chai.expect(count).to.not.equal(5)).then(() => Promise.delay(10)).then(() => count)).to.eventually.equal(5); }); - + it("should be capable of functioning correctly with empty result sets",() => { return chai.expect(model.find({ nothing: true }).forEach((instance) => { chai.assert.fail(); @@ -542,7 +542,7 @@ describe("Model",() => { return count++; }).then(() => count)).to.eventually.equal(5); }); - + it("should be capable of functioning correctly with empty result sets",() => { return chai.expect(model.find({ nothing: true }).map((instance) => { chai.assert.fail(); @@ -563,7 +563,7 @@ describe("Model",() => { it("should return all documents",() => { return chai.expect(model.find().toArray()).to.eventually.exist.and.have.length(5); }); - + it("should be capable of functioning correctly with empty result sets",() => { return chai.expect(model.find({ nothing: true }).toArray()).to.eventually.eql([]); }); @@ -585,7 +585,7 @@ describe("Model",() => { it("which should resolve to the next instance in the query",() => { return chai.expect(model.find().next()).to.eventually.be.an.instanceof(model.Instance); }); - + it("should be capable of functioning correctly with empty result sets",() => { return chai.expect(model.find({ nothing: true }).next()).to.eventually.not.exist; }); @@ -902,26 +902,26 @@ describe("Model",() => { return chai.expect(model.dropIndexes()).to.eventually.be.true; }); }); - + describe("identifier transforms", () => { it("should have a default converter", () => { let model = new Iridium.Model(core, Test); chai.expect(model.transforms).to.exist.and.have.property('_id').with.property('fromDB').which.is.a('function'); chai.expect(model.transforms).to.exist.and.have.property('_id').with.property('toDB').which.is.a('function'); }); - + it("should have a default ObjectID to String converter", () => { let model = new Iridium.Model(core, Test); chai.expect(model.transforms['_id'].fromDB(MongoDB.ObjectID.createFromHexString('aaaaaaaaaaaaaaaaaaaaaaaa'))).to.eql('aaaaaaaaaaaaaaaaaaaaaaaa'); chai.expect(model.transforms['_id'].toDB('aaaaaaaaaaaaaaaaaaaaaaaa')).to.eql(MongoDB.ObjectID.createFromHexString('aaaaaaaaaaaaaaaaaaaaaaaa')); }); - + it("should allow you to specify a custom converter by providing a property on the class", () => { let model = new Iridium.Model(core, TestWithCustomID); - + chai.expect(model.transforms['_id']).to.exist.and.have.property('fromDB').which.is.a('function'); chai.expect(model.transforms['_id']).to.exist.and.have.property('toDB').which.is.a('function'); - + chai.expect(model.transforms['_id'].fromDB(12)).to.eql(120); chai.expect(model.transforms['_id'].toDB(120)).to.eql(12); }); diff --git a/test/Omnom.ts b/test/Omnom.ts index 00d4804..0e442d9 100644 --- a/test/Omnom.ts +++ b/test/Omnom.ts @@ -1,4 +1,4 @@ -/// +/// import {Omnom} from '../lib/utils/Omnom'; import MongoDB = require('mongodb'); diff --git a/test/Plugins.ts b/test/Plugins.ts index 7128b8f..54d0f80 100644 --- a/test/Plugins.ts +++ b/test/Plugins.ts @@ -1,4 +1,4 @@ -/// +/// import * as Iridium from '../index'; import Skmatc = require('skmatc'); @@ -7,7 +7,7 @@ class Test extends Iridium.Instance { static schema: Iridium.Schema = { _id: false }; - + _id: string; } @@ -102,7 +102,7 @@ describe("Plugins",() => { instanceImplementation.schema = { _id: false }; - + let model = new Iridium.Model(core, instanceImplementation); let instance = new model.Instance({}); chai.expect(wasCalled).to.be.false; diff --git a/test/Transforms.ts b/test/Transforms.ts index 7fa4bc3..8a1320c 100644 --- a/test/Transforms.ts +++ b/test/Transforms.ts @@ -1,4 +1,4 @@ -/// +/// import * as Iridium from '../index'; import MongoDB = require('mongodb'); import Events = require('events'); @@ -18,30 +18,30 @@ class Person extends Iridium.Instance { name: String, email: String }; - + static transforms: Iridium.Transforms = { email: { fromDB: x => x.toUpperCase(), toDB: x => x.toLowerCase().trim() } }; - + _id: string; name: string; email: string; - + static onCreating(document: Document) { hookEmitter.emit('creating', document); } - + static onReady(instance: Person) { hookEmitter.emit('ready', instance); } - + static onRetrieved(document: Document) { hookEmitter.emit('retrieved', document); } - + static onSaving(instance: Person, changes: any) { hookEmitter.emit('saving', instance, changes); } @@ -57,19 +57,19 @@ class TestDB extends Iridium.Core { describe("Transforms", () => { var db = new TestDB(); - + before(() => db.connect()); beforeEach(() => db.Person.remove()); after(() => db.close()); - + it("should include a sensible default for the _id field schema", () => { chai.expect(db.Person).to.have.property('schema').with.property('_id', MongoDB.ObjectID); }); - + it("should include a sensible default for the _id field transform", () => { chai.expect(db.Person).to.have.property('transforms').with.property('_id'); }); - + describe("during creation", () => { it("should be applied", () => { return db.Person.insert({ @@ -79,14 +79,14 @@ describe("Transforms", () => { chai.expect(user).to.exist.and.have.property('email', 'TEST@EMAIL.COM'); }); }); - + it("should only be applied after onCreating", () => { let onCreatingCalled = false; hookEmitter.once('creating', (doc) => { onCreatingCalled = true; chai.expect(doc.email).to.eql('Test@email.com'); }); - + return db.Person.insert({ name: 'Test User', email: 'Test@email.com' @@ -94,7 +94,7 @@ describe("Transforms", () => { chai.expect(onCreatingCalled).to.be.true; }); }); - + it("should be applied before validation", () => { db.Person.schema['email'] = /^test@email.com$/; return db.Person.insert({ @@ -103,20 +103,20 @@ describe("Transforms", () => { }); }); }); - + describe("with an instance", () => { beforeEach(() => db.Person.insert({ name: 'Test User', email: 'test@email.com' })); - + it("should apply the transform on property reads", () => { return db.Person.get().then(person => { chai.expect(person.email).to.eql('TEST@EMAIL.COM'); chai.expect(person.document.email).to.eql('test@email.com'); }); }); - + it("should apply the transform on property writes", () => { return db.Person.get().then(person => { person.email = 'Test@email.com'; @@ -124,27 +124,27 @@ describe("Transforms", () => { chai.expect(person.document.email).to.eql('test@email.com'); }); }); - + it("should diff the transformed property", () => { let changesChecked = false; hookEmitter.once('saving', (instance, changes) => { chai.expect(changes).to.eql({ $set: { name: 'Testy User' }}); changesChecked = true; }); - + return db.Person.get().then(person => { person.name = 'Testy User'; person.email = 'Test@email.com'; chai.expect(person.email).to.eql('TEST@EMAIL.COM'); chai.expect(person.document.email).to.eql('test@email.com'); - + return person.save(); }).then(person => { - chai.expect(person).to.have.property('email', 'TEST@EMAIL.COM'); + chai.expect(person).to.have.property('email', 'TEST@EMAIL.COM'); chai.expect(changesChecked).to.be.true; }); }); - + describe("the default ObjectID transform", () => { it("should return a string", () => { return db.Person.get().then(person => { @@ -152,7 +152,7 @@ describe("Transforms", () => { chai.expect(person.document._id).to.be.a('object'); }); }); - + it("should convert a string to an ObjectID", () => { return db.Person.get().then(person => { person._id = 'aaaaaaaaaaaaaaaaaaaaaaaa'; diff --git a/test/Utilities.ts b/test/Utilities.ts index f9f1424..b5645c8 100644 --- a/test/Utilities.ts +++ b/test/Utilities.ts @@ -1,4 +1,4 @@ -/// +/// import * as Iridium from '../index'; import MongoDB = require('mongodb'); diff --git a/test/Validation.ts b/test/Validation.ts index 31f155f..bc3500a 100644 --- a/test/Validation.ts +++ b/test/Validation.ts @@ -1,4 +1,4 @@ -/// +/// import * as Iridium from '../index'; import skmatc = require('skmatc'); import MongoDB = require('mongodb'); @@ -28,7 +28,7 @@ class Person extends Iridium.Instance { ageDifference: Number }] }; - + name: string; dateOfBirth: Date; siblings: { @@ -47,7 +47,7 @@ describe("Validation", () => { after(() => model.remove().then(() => core.close())); beforeEach(() => model.remove()); - + describe("custom validators", () => { it("should successfully validate documents which are valid", () => { return chai.expect(model.insert({ @@ -60,7 +60,7 @@ describe("Validation", () => { }] })).to.eventually.be.ok; }); - + it("should fail to validate documents which are invalid", () => { return chai.expect(model.insert({ name: 'John', diff --git a/test/support/chai.ts b/test/support/chai.ts index 7a1bb08..de14511 100644 --- a/test/support/chai.ts +++ b/test/support/chai.ts @@ -1,4 +1,4 @@ -/// +/// import chai = require('chai'); import chaiAsPromised = require('chai-as-promised'); import Bluebird = require('bluebird'); diff --git a/test/tsconfig.json b/test/tsconfig.json new file mode 100644 index 0000000..2f98762 --- /dev/null +++ b/test/tsconfig.json @@ -0,0 +1,11 @@ +{ + "compilerOptions": { + "version": true, + "target": "ES5", + "module": "commonjs", + "outDir": "../dist/test/", + "sourceMap": true, + "declaration": false, + "experimentalDecorators": true + } +} \ No newline at end of file diff --git a/tsconfig.json b/tsconfig.json index e19341e..92cc065 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -4,6 +4,12 @@ "module": "commonjs", "target": "es5", "sourceMap": true, - "declaration": false - } + "declaration": false, + "experimentalDecorators": true, + "outDir": "./dist/" + }, + "files": [ + "typings/DefinitelyTyped/tsd.d.ts", + "index.ts" + ] } \ No newline at end of file diff --git a/typings/DefinitelyTyped/mongodb/mongodb.d.ts b/typings/DefinitelyTyped/mongodb/mongodb.d.ts index c11f497..91e741e 100644 --- a/typings/DefinitelyTyped/mongodb/mongodb.d.ts +++ b/typings/DefinitelyTyped/mongodb/mongodb.d.ts @@ -305,7 +305,7 @@ declare module "mongodb" { insertMany(docs: any[], options: { w?: any; wtimeout?: number; j?: boolean; serializeFunctions?: boolean; forceServerObjectId?: boolean }, callback: (err: Error, result: any) => void): void; remove(selector: Object, callback?: (err: Error, result: any) => void): void; - remove(selector: Object, options: { safe?: any; single?: boolean; }, callback?: (err: Error, result: any) => void): void; + remove(selector: Object, options: { safe?: any; single?: boolean; w?: string | number; }, callback?: (err: Error, result: any) => void): void; rename(newName: String, callback?: (err: Error, result: any) => void): void; diff --git a/typings/skmatc/skmatc.d.ts b/typings/skmatc/skmatc.d.ts deleted file mode 100644 index 390e0df..0000000 --- a/typings/skmatc/skmatc.d.ts +++ /dev/null @@ -1,65 +0,0 @@ -declare module "skmatc" { - export = Skmatc.Skmatc; -} - -declare module Skmatc { - export class Skmatc { - constructor(schema: any); - - static validators: Validator[]; - static Validator: typeof Validator; - static Result: typeof Result; - static Failure: typeof Failure; - static create(handles: (schema: any) => boolean, validate: (schema: any, data: any, path: string) => Result, options?: { name?: string }): Validator; - static validate(validators: Validator[], schema: any, data: any, path?: string): Result; - static register(validator: Validator); - - schema: any; - validators: Validator[]; - validate(data: any, path?: string): Result; - register(validator: Validator); - } - - export class Validator { - constructor(skmatc: Skmatc, options?: any); - static create(handles: (schema: any) => boolean, validate: (schema: any, data: any, path: string) => Result, options?: { name?: string }): Validator; - static module(handles: (schema: any) => boolean, validate: (schema: any, data: any, path: string) => Result, options?: { name?: string }): Validator; - - name: string; - skmatc: Skmatc; - handles(schema: any): boolean; - validate(schema: any, data: any, path: string): Result; - assert(schema: any, data: any, path: string, test: boolean, message?: string): Result; - fail(schema: any, data: any, path: string, message?: string): Result; - } - - export class Result { - constructor(failures: Failure[]); - static compound(results: Result[]): Result; - - failures: Failure[]; - success: boolean; - failed: boolean; - message: string; - messages: string[]; - error: Error; - } - - export class Failure { - constructor(validator: Validator, schema: any, data: any, path: string, message?: string); - validator: Validator; - schema: any; - data: any; - path: string; - message: string; - } - - export interface IValidationHandler { - (thisArg: { - validator: IValidationHandler; - skmatc: Skmatc; - fail(message?: string); - assert(test: boolean, message?: string); - }, schema: any, data: any, path: string): Result; - } -} \ No newline at end of file