console.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. 'use strict';
  2. const Promise = require('bluebird');
  3. const abbrev = require('abbrev');
  4. function Console() {
  5. this.store = {};
  6. this.alias = {};
  7. }
  8. Console.prototype.get = function(name) {
  9. name = name.toLowerCase();
  10. return this.store[this.alias[name]];
  11. };
  12. Console.prototype.list = function() {
  13. return this.store;
  14. };
  15. Console.prototype.register = function(name, desc, options, fn) {
  16. if (!name) throw new TypeError('name is required');
  17. if (!fn) {
  18. if (options) {
  19. if (typeof options === 'function') {
  20. fn = options;
  21. if (typeof desc === 'object') { // name, options, fn
  22. options = desc;
  23. desc = '';
  24. } else { // name, desc, fn
  25. options = {};
  26. }
  27. } else {
  28. throw new TypeError('fn must be a function');
  29. }
  30. } else {
  31. // name, fn
  32. if (typeof desc === 'function') {
  33. fn = desc;
  34. options = {};
  35. desc = '';
  36. } else {
  37. throw new TypeError('fn must be a function');
  38. }
  39. }
  40. }
  41. if (fn.length > 1) {
  42. fn = Promise.promisify(fn);
  43. } else {
  44. fn = Promise.method(fn);
  45. }
  46. const c = this.store[name.toLowerCase()] = fn;
  47. c.options = options;
  48. c.desc = desc;
  49. this.alias = abbrev(Object.keys(this.store));
  50. };
  51. module.exports = Console;