-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.js
59 lines (47 loc) · 1.35 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
'use strict'
const fs = require('fs')
const util = require('util')
const marked = require('marked')
const fp = require('fastify-plugin')
function fastifyMarkdown (fastify, opts, done) {
if (typeof opts === 'function') {
done = opts
opts = undefined
}
const markedOptions = opts.markedOptions || {}
function none (obj) {
if (obj === undefined) return true
if (obj && Object.getOwnPropertyNames(obj).length === 0) return true
return false
}
function have (obj) {
return !!obj
}
function isString (str) {
return typeof str === 'string'
}
function asyncFileMarked (src, option) {
const read = util.promisify(fs.readFile)
return read(src, 'utf8').then(data => marked(data, option), err => err)
}
fastify.decorateReply('markdown', function (md) {
if (none(opts) && none(md)) return marked
if (none(opts) && have(md)) opts = {data: md}
if (opts.data) {
if (none(md) && isString(opts.data)) md = opts.data
return marked(md, markedOptions)
} else if (opts.src) {
if (none(md) && isString(opts.src)) md = opts.src
return asyncFileMarked(md, markedOptions)
} else if (opts.markedOptions) {
return marked.setOptions(markedOptions)
} else {
return marked
}
})
done()
}
module.exports = fp(fastifyMarkdown, {
fastify: '>=1.4.0',
name: 'fastify-markdown'
})