UNPKG

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