1+ import { URLSearchParams } from 'url' ;
2+ import { v4 as uuidv4 } from 'uuid' ;
3+ import md5 from 'blueimp-md5' ;
4+ import axios from 'axios' ;
5+
6+ export interface BaiduResponse
7+ {
8+ from : string ;
9+ to : string ;
10+ trans_result : Array < { src : string ; dst : string } > ;
11+ error_code ?: number ;
12+ }
13+
14+ /**
15+ * this module is used to get baidu translation resource
16+ * including sentence translation and the dictionary resource
17+ *
18+ * @param {string } query - 查询字符串
19+ * @param {boolean } [isChinese] - 查询字符串是否为中文
20+ * @return {* } string - 请求链接
21+ */
22+ export const getBaiduSource = ( query : string , isChinese ?: boolean ) : string =>
23+ {
24+ const q = query . toLocaleLowerCase ( ) ;
25+ const appid = '20191014000341469' ;
26+ const key = '4GEOkedoeuLlSiwypAoD' ;
27+ const baidu = 'http://api.fanyi.baidu.com/api/trans/vip/translate' ;
28+ const from = 'auto' ;
29+ const to = isChinese ? 'en' : 'zh' ; // to can't be auto
30+ const salt = uuidv4 ( ) ; // UUID
31+ const str = appid + q + salt + key ;
32+ const dict = '1'
33+
34+ // 获取 md5 加密后的 sign
35+ const sign = md5 ( str ) ;
36+
37+ // 构建参数
38+ // 这里也会做 URL encode 操作
39+ const search = new URLSearchParams ( {
40+ q,
41+ from,
42+ to,
43+ appid,
44+ salt,
45+ sign,
46+ dict,
47+ } ) . toString ( ) ;
48+
49+ const source = `${ baidu } ?${ search } ` ;
50+
51+ return source ;
52+ } ;
53+
54+
55+ /**
56+ * 翻译中文文本,错误将会被抛出
57+ *
58+ * @param {string } query - 将要翻译的中文文本
59+ * @return {* } {Promise<string[]>} - 翻译结果数组
60+ */
61+ export const getZhTranslation = async ( query : string ) : Promise < string [ ] > =>
62+ {
63+ if ( ! query ) return [ ]
64+
65+ const source = getBaiduSource ( query , true )
66+
67+ const result = await axios . get < BaiduResponse > ( source )
68+
69+ const {
70+ trans_result,
71+ error_code,
72+ } = result . data
73+
74+ if ( result . data . error_code ) throw new Error ( '翻译错误码' + error_code )
75+
76+ console . log ( 'translationResult' , result )
77+
78+ return trans_result . map ( r => r . dst )
79+ }
0 commit comments