-
Notifications
You must be signed in to change notification settings - Fork 38
/
search.js
114 lines (106 loc) · 2.67 KB
/
search.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
109
110
111
112
113
114
'use strict'
const yaml = require('js-yaml')
const glob = require('glob')
const fs = require('fs')
const path = require('path')
const htmlToText = require('html-to-text')
const mm = require('marky-mark')
const crypto = require('crypto')
const co = require('co')
const fetch = require('node-fetch')
const config = yaml.safeLoad(fs.readFileSync('./_config.yml', 'utf8'))
let clean = function* () {
let sdk = config.sdk.replace('-sdk', '')
let res = yield fetchJson(getUrl('clean'), {
sdk: sdk
})
if (res.ok) {
console.log(`CLEAN ${sdk} DOC DONE`)
} else {
console.log(res.status, res.statusText)
}
}
let upload = function* () {
let posts = getAllPosts()
let resArr = yield posts.map(function (post) {
return fetchJson(getUrl('documents'), {
document: post
})
})
console.log('UPLOAD DONE (', resArr.length, 'Posts )')
}
let rebuild = function* () {
let res = yield fetchJson(getUrl('rebuild'))
if (res.ok) {
console.log(`REBUILD DONE`)
} else {
console.log(res.status, res.statusText)
}
}
// helpers
function getUrl (key) {
const host = 'http:' + process.env.API_HOST + '/api/docsearch'
switch (key) {
case 'clean':
return host + '/clean'
case 'rebuild':
return host + '/rebuild'
case 'documents':
return host + '/documents'
default:
return host
}
}
function getAllPosts () {
let sourceDir = path.join(__dirname, 'source')
let langs = config['language']
let sdk = config['sdk'].replace('-sdk', '')
let files = glob.sync(path.join(sourceDir, '**/*.md'))
let posts = []
files.map(function (file) {
let lang = 'en'
langs.map(function (_lang) {
if (file.match(path.join(sourceDir, _lang))) {
lang = _lang
}
})
let post = mm.parseFileSync(file)
post.locale = lang
post.url = path.join('/', path.relative(sourceDir, file).replace(/\.md$/, '.html'))
post.meta.sdk = sdk
post.content = htmlToText.fromString(post.content)
delete post.yaml
delete post.markdown
delete post.filenameExtension
delete post.filename
posts.push(post)
})
return posts
}
function genKey (time) {
let key = process.env.API_KEY
return crypto.createHash('md5').update(time + key).digest('hex')
}
function fetchJson (url, data) {
let time = new Date().getTime().toString()
let signature = genKey(time)
let json = {
time: time,
signature: signature
}
for (let k in data) {
json[k] = data[k]
}
return fetch(url, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(json)
})
}
// run
co(clean)
.then(() => co(upload))
.then(() => co(rebuild))