console.js 1.3 KB

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