-
Notifications
You must be signed in to change notification settings - Fork 82
/
index.js
108 lines (92 loc) · 2.32 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
'use strict';
const moment = require('moment');
const lodash = require('lodash');
const out = require('../lib/out');
const formatMarkdown = (() => {
let prettier;
try {
prettier = require('prettier');
return body => prettier.format(body, { parser: 'markdown' });
} catch (error) {
out.warn('Node 8 doesn\'t support prettier@latest (see: https://github.com/prettier/eslint-config-prettier/issues/140), the markdown will not be formated.');
return body => body;
}
})();
/**
* 格式化 markdown 中的 tags
*
* @param {Array} tags tags
* @return {String} body
*/
function formatTags(tags) {
tags = Array.isArray(tags) ? tags : [];
return `[${tags.join(',')}]`;
}
exports.formatTags = formatTags;
/**
* 格式化 front matter 中的可嵌套数组
*
* @param {Array} list list
* @return {String} body
*/
function formatList(list = []) {
const result = [];
for (const item of list) {
if (Array.isArray(item)) {
result.push(formatList(item));
} else {
result.push(item);
}
}
return `[${result.join(',')}]`;
}
exports.formatList = formatList;
/**
* 格式化 markdown 内容
*
* @param {String} body md 文档
* @return {String} body
*/
function formatRaw(body) {
const multiBr = /(<br>[\s\n]){2}/gi;
const multiBrEnd = /(<br \/>[\n]?){2}/gi;
const brBug = /<br \/>/g;
const hiddenContent = /<div style="display:none">[\s\S]*?<\/div>/gi;
// 删除语雀特有的锚点
const emptyAnchor = /<a name=\".*?\"><\/a>/g;
body = body
.replace(hiddenContent, '')
.replace(multiBr, '<br>')
.replace(multiBrEnd, '<br />\n')
.replace(brBug, '\n')
.replace(emptyAnchor, '');
return formatMarkdown(body);
}
exports.formatRaw = formatRaw;
/**
* 判断是否为 post
*
* @param {*} post 文章
* @return {Boolean} isPost
*/
function isPost(post) {
return lodash.isObject(post) && post.body && post.title;
}
exports.isPost = isPost;
function doubleDigit(num) {
return num < 10 ? '0' + num : num;
}
exports.doubleDigit = doubleDigit;
function formatDate(date) {
return moment(new Date(date).toISOString()).format('YYYY-MM-DD HH:mm:ss ZZ');
}
exports.formatDate = formatDate;
function transformRes(res) {
try {
if (lodash.isString(res)) return res;
return JSON.stringify(res);
} catch (e) {
return res;
}
}
exports.transformRes = transformRes;