renderer.js 1.4 KB

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