renderer.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. 'use strict';
  2. const pathFn = require('path');
  3. const Promise = require('bluebird');
  4. function getExtname(str) {
  5. if (typeof str !== 'string') return '';
  6. const extname = pathFn.extname(str) || str;
  7. return extname[0] === '.' ? extname.slice(1) : extname;
  8. }
  9. function Renderer() {
  10. this.store = {};
  11. this.storeSync = {};
  12. }
  13. Renderer.prototype.list = function(sync) {
  14. return sync ? this.storeSync : this.store;
  15. };
  16. Renderer.prototype.get = function(name, sync) {
  17. const store = this[sync ? 'storeSync' : 'store'];
  18. return store[getExtname(name)] || store[name];
  19. };
  20. Renderer.prototype.isRenderable = function(path) {
  21. return Boolean(this.get(path));
  22. };
  23. Renderer.prototype.isRenderableSync = function(path) {
  24. return Boolean(this.get(path, true));
  25. };
  26. Renderer.prototype.getOutput = function(path) {
  27. const renderer = this.get(path);
  28. return renderer ? renderer.output : '';
  29. };
  30. Renderer.prototype.register = function(name, output, fn, sync) {
  31. if (!name) throw new TypeError('name is required');
  32. if (!output) throw new TypeError('output is required');
  33. if (typeof fn !== 'function') throw new TypeError('fn must be a function');
  34. name = getExtname(name);
  35. output = getExtname(output);
  36. if (sync) {
  37. this.storeSync[name] = fn;
  38. this.storeSync[name].output = output;
  39. this.store[name] = Promise.method(fn);
  40. } else {
  41. if (fn.length > 2) fn = Promise.promisify(fn);
  42. this.store[name] = fn;
  43. }
  44. this.store[name].output = output;
  45. this.store[name].compile = fn.compile;
  46. };
  47. module.exports = Renderer;