diff --git a/lib/persistence/index.js b/lib/persistence/index.js index bed5e89..99fb3db 100644 --- a/lib/persistence/index.js +++ b/lib/persistence/index.js @@ -33,3 +33,12 @@ module.exports.Memory = require("./memory"); module.exports.LevelUp = require("./levelup"); module.exports.Redis = require("./redis"); module.exports.Mongo = require("./mongo"); + +var factories = {}; +Object.keys(module.exports).forEach(function(type) { + factories[type.toLowerCase()] = module.exports[type]; +}); + +module.exports.getFactory = function(name) { + return factories[name.toLowerCase()]; +}; diff --git a/lib/server.js b/lib/server.js index cb5b7d0..7aae2ed 100644 --- a/lib/server.js +++ b/lib/server.js @@ -39,6 +39,7 @@ var Stats = require("./stats"); var uuid = require("node-uuid"); var st = require("st"); var url = require("url"); +var persistence = require('./persistence'); var defaults = { port: 1883, host: null, @@ -120,12 +121,21 @@ function Server(opts, callback) { this.opts = extend(true, {}, defaults, opts); - if (this.opts.persistence && this.opts.persistence.factory) { - this.opts.persistence.factory(this.opts.persistence).wire(this); - } - callback = callback || function() {}; + var persistenceFactory = this.opts.persistence && this.opts.persistence.factory; + if (persistenceFactory) { + if (typeof persistenceFactory === 'string') { + var factoryName = persistenceFactory; + persistenceFactory = persistence.getFactory(factoryName); + if (!persistenceFactory) { + return callback(new Error('No persistence factory found for ' + factoryName )); + } + } + + persistenceFactory(this.opts.persistence).wire(this); + } + this._dedupId = 0; this.clients = {}; this.closed = false; diff --git a/test/server.js b/test/server.js index 080916d..8c84388 100644 --- a/test/server.js +++ b/test/server.js @@ -736,4 +736,53 @@ describe("mosca.Server - MQTT backend", function() { } ], done); }); + + it("should build the correct persistence with string", function(done) { + var newSettings = moscaSettings(); + + newSettings.persistence = { + factory: 'redis', + port: 6379, + host: 'localhost' + }; + + var server = new mosca.Server(newSettings); + + async.series([ + + function(cb) { + server.on("ready", cb); + }, + + function(cb) { + expect(server.persistence.constructor).to.match(/RedisPersistence/); + cb(); + }, + + function(cb) { + server.close(cb); + } + ], done); + }); + + it("should fail if persistence string is not correct", function(done) { + var newSettings = moscaSettings(); + + newSettings.persistence = { + factory: 'no_such_persistence', + port: 6379, + host: 'localhost' + }; + + var server = new mosca.Server(newSettings, function(err) { + if(err instanceof Error) { + done(); + } else { + expect().fail('new mosca.Server should fail'); + } + }); + + }); + + });