UNPKG

pomelo-components

Version:

pomelo components, like protobuf, dictionary

94 lines (76 loc) 2.39 kB
var logger = require('pomelo-logger').getLogger("pomelo", "DictionaryComponent"); var Constant = require('../util/constant'); var FileUtil = require('../util/fileUtil'); var Loader = require('pomelo-loader'); var Utils = require('../util/utils'); var DictionaryComponent = function(app, opts) { this.app = app; this.version = 0; this.dict = {}; this.abbrs = {}; this.version = ""; this.opts = opts || {}; this.base = app.getBase(); this.env = app.get('env'); this.userDicPath = opts.dict || '/config/' + this.env + '/dictionary.json'; }; DictionaryComponent.prototype.name = '__bearcat__dictionary__'; DictionaryComponent.prototype.start = function(cb) { var servers = this.app.get('servers'); var routes = []; var base = this.base; this.userDicPath = FileUtil.pathJoin(base, this.userDicPath); //Load all the handler files for (var serverType in servers) { var p = FileUtil.getHandlerPath(base, serverType); if (!p) { continue; } var handlers = Loader.load(p, this.app); for (var name in handlers) { var handler = handlers[name]; for (var key in handler) { if (key[0] != Constant.FUNCTION_PRIVATE && typeof(handler[key]) === 'function') { routes.push(serverType + '.' + name + '.' + key); } } } } //Sort the route to make sure all the routers abbr are the same in all the servers routes.sort(); var abbr; var i; for (i = 0; i < routes.length; i++) { abbr = i + 1; this.abbrs[abbr] = routes[i]; this.dict[routes[i]] = abbr; } //Load user dictionary if (this.userDicPath && FileUtil.existsSync(this.userDicPath)) { var userDic = require(this.userDicPath); abbr = routes.length + 1; for (i = 0; i < userDic.length; i++) { var route = userDic[i]; this.abbrs[abbr] = route; this.dict[route] = abbr; abbr++; } } this.version = Utils.md5(JSON.stringify(this.dict)); process.nextTick(cb); }; DictionaryComponent.prototype.stop = function(force, cb) { process.nextTick(cb); }; DictionaryComponent.prototype.getDict = function() { return this.dict; }; DictionaryComponent.prototype.getAbbrs = function() { return this.abbrs; }; DictionaryComponent.prototype.getVersion = function() { return this.version; }; module.exports = function(app, opts) { return new DictionaryComponent(app, opts); };