-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
74 lines (65 loc) · 1.83 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
'use strict'
const jstransformer = require('jstransformer')
const transformers = require('list-of-jstransformers')
/**
* Extract the callback, options, and locals from the provided arguments.
*
* @param [options] The options to be passed to the transformer.
* @param [fn] There function callback, should there be one.
*/
function extractArgs(options, fn) {
if (typeof options === 'function') {
fn = options
options = {}
}
return {
fn,
options,
locals: options ? (options.locals || options) : options
}
}
transformers.forEach(name => {
/**
* The file renderer.
*/
module.exports[name] = (file, options, fn) => {
const transformer = jstransformer(require('jstransformer-' + name))
const args = extractArgs(options, fn)
if (args.fn) {
return transformer.renderFileAsync(file, args.options, args.locals, (err, result) => {
args.fn(err, result.body ? result.body : null)
})
}
return new Promise((resolve, reject) => {
transformer.renderFileAsync(file, args.options, args.locals, (err, result) => {
if (err) {
reject(err)
} else {
resolve(result.body)
}
})
})
}
/**
* The string renderer.
*/
module.exports[name].render = function (str, options, fn) {
const former = require('jstransformer-' + name)
const transformer = jstransformer(former)
const args = extractArgs(options, fn)
if (args.fn) {
return transformer.renderAsync(str, args.options, args.locals, (err, result) => {
args.fn(err, result.body ? result.body : null)
})
}
return new Promise((resolve, reject) => {
transformer.renderAsync(str, args.options, args.locals, (err, result) => {
if (err) {
reject(err)
} else {
resolve(result.body)
}
})
})
}
})