dictionary.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. var fs = require('fs');
  2. var path = require('path');
  3. var utils = require('../util/utils');
  4. var Loader = require('pomelo-loader');
  5. var pathUtil = require('../util/pathUtil');
  6. var crypto = require('crypto');
  7. module.exports = function(app, opts) {
  8. return new Component(app, opts);
  9. };
  10. var Component = function(app, opts) {
  11. this.app = app;
  12. this.dict = {};
  13. this.abbrs = {};
  14. this.userDicPath = null;
  15. this.version = "";
  16. //Set userstate dictionary
  17. var p = path.join(app.getBase(), '/config/dictionary.json');
  18. if(!!opts && !!opts.dict) {
  19. p = opts.dict;
  20. }
  21. if(fs.existsSync(p)) {
  22. this.userDicPath = p;
  23. }
  24. };
  25. var pro = Component.prototype;
  26. pro.name = '__dictionary__';
  27. pro.start = function(cb) {
  28. var servers = this.app.get('servers');
  29. var routes = [];
  30. //Load all the handler files
  31. for(var serverType in servers) {
  32. var p = pathUtil.getHandlerPath(this.app.getBase(), serverType);
  33. if(!p) {
  34. continue;
  35. }
  36. var handlers = Loader.load(p, this.app);
  37. for(var name in handlers) {
  38. var handler = handlers[name];
  39. for(var key in handler) {
  40. if(typeof(handler[key]) === 'function') {
  41. routes.push(serverType + '.' + name + '.' + key);
  42. }
  43. }
  44. }
  45. }
  46. //Sort the route to make sure all the routers abbr are the same in all the servers
  47. routes.sort();
  48. var abbr;
  49. var i;
  50. for(i = 0; i < routes.length; i++) {
  51. abbr = i + 1;
  52. this.abbrs[abbr] = routes[i];
  53. this.dict[routes[i]] = abbr;
  54. }
  55. //Load userstate dictionary
  56. if(!!this.userDicPath) {
  57. var userDic = require(this.userDicPath);
  58. abbr = routes.length + 1;
  59. for(i = 0; i < userDic.length; i++) {
  60. var route = userDic[i];
  61. this.abbrs[abbr] = route;
  62. this.dict[route] = abbr;
  63. abbr++;
  64. }
  65. }
  66. this.version = crypto.createHash('md5').update(JSON.stringify(this.dict)).digest('base64');
  67. utils.invokeCallback(cb);
  68. };
  69. pro.getDict = function() {
  70. return this.dict;
  71. };
  72. pro.getAbbrs = function() {
  73. return this.abbrs;
  74. };
  75. pro.getVersion = function() {
  76. return this.version;
  77. };