1 | import fetch from 'node-fetch'
|
2 | import { marked } from 'marked'
|
3 |
|
4 | const regExp = /^(-{3}(?:\n|\r)([\w\W]+?)(?:\n|\r)-{3})?([\w\W]*)*/
|
5 |
|
6 | function convertMarkdownResponse (response) {
|
7 | const contentType = response.headers.get('Content-Type')
|
8 | if (contentType.includes('text')) return response.text()
|
9 | }
|
10 |
|
11 | function getMarkdownFrontMatter (metas) {
|
12 | return metas.split('\n').reduce((acc, meta) => {
|
13 | const [key, value] = meta.trim().split(': ', 2)
|
14 | const schema = { [key]: value.slice(1, -1) }
|
15 | return { ...acc, ...schema }
|
16 | }, {})
|
17 | }
|
18 |
|
19 | function formatMarkdownResponseToHtml (data) {
|
20 | if (!data) return null
|
21 |
|
22 | const { 2: metas, 3: body } = regExp.exec(data)
|
23 | const content = body ? marked(body) : null
|
24 | const head = metas ? getMarkdownFrontMatter(metas) : null
|
25 |
|
26 | return { head, content }
|
27 | }
|
28 |
|
29 | export default function markdownService (url) {
|
30 | if (!url) return null
|
31 |
|
32 | return fetch(url)
|
33 | .then(convertMarkdownResponse)
|
34 | .then(formatMarkdownResponseToHtml)
|
35 | .catch(() => null)
|
36 | }
|