-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
63 lines (50 loc) · 1.44 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
'use strict'
const debug = require('./lib/debug')
const fetch = require('./lib/fetch')
const parser = require('./lib/parser')
const assign = require('lodash.assign')
const defaultConfigs = require('./defaultConfig')
const pkg = require('./package.json')
const { EDOutput, CODES } = require('eazydict-standard-output')
// 入口
function main (words, userConfigs) {
debug('run with arguments %O', {
words,
userConfigs
})
const configs = assign({}, defaultConfigs, userConfigs)
debug('use configs %O', configs)
if (!words) {
return Promise.reject(new Error('请输入要查询的文字'))
}
// 编码
const keywords = encodeURIComponent(words)
const url = `http://cn.bing.com/dict/search?q=${keywords}`
debug(`fetch url ${url}`)
return fetch(url, configs)
.then((body) => parser(body))
.catch((error) => {
if (error.name === 'FetchError') {
return new EDOutput(CODES.NETWORK_ERROR)
}
return new EDOutput(CODES.OTHER)
})
.then((output) => {
// 添加插件信息
output.pluginName = 'Bing'
output.packageName = pkg.name
output.words = words
output.url = url
debug('output: %O', output)
return output
})
}
if (require.main === module) {
// istanbul ignore next
const word = process.argv.slice(2).join(' ')
main(word).then((result) => {
console.log(result) // eslint-disable-line no-console
})
} else {
module.exports = main
}