i18-fe-automator
Version:
前端代码提取中文并替换成$t函数
87 lines (86 loc) • 3.05 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.baiduTranslate = void 0;
const md5_1 = __importDefault(require("md5"));
const qs_1 = __importDefault(require("qs"));
const got = require('got');
const log_1 = __importDefault(require("../../utils/log"));
const MAX_COUNT = 500;
const DELAY_TIME = 2000;
async function baiduTranslate(word, originLang, targetLang, option) {
const key = option.key;
const secret = option.secret;
const salt = Math.random();
const sign = (0, md5_1.default)(key + word + salt + secret);
const baseUrl = 'https://fanyi-api.baidu.com/api/trans/vip/translate';
const params = {
from: originLang,
to: targetLang.split('-')[0],
appid: key,
salt,
sign,
q: word,
};
const url = `${baseUrl}?${qs_1.default.stringify(params)}`;
return new Promise((resolve, reject) => {
got
.get(url)
.then(({ body }) => {
const res = JSON.parse(body);
if (!res.error_code) {
resolve(res.trans_result);
}
else {
reject(body);
}
})
.catch((e) => {
reject(e);
});
});
// log.success(`本批次${word.length}个中文待翻译`)
// log.info('q' + word)
// const requestLimitLen = Math.ceil(word.length / MAX_COUNT)
// const paramsList: any = []
// const urlList: string[] = []
// for (let i = 0; i < requestLimitLen; i++) {
// const currText = word.slice(i * MAX_COUNT, MAX_COUNT * (i + 1))
// log.success(`第${i + 1}小队${currText.length}个中文`)
// paramsList.push({
// ...params,
// q: currText,
// })
// urlList.push(`${baseUrl}?${qs.stringify(params)}`)
// }
// const list = await callApiMultipleTimes(urlList, paramsList)
// return new Promise((resolve) => resolve(list.flat(Infinity)))
}
exports.baiduTranslate = baiduTranslate;
function callApiMultipleTimes(urlList, paramsList) {
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const promises = paramsList.map((params, index) => {
return delay(DELAY_TIME * index)
.then(() => {
log_1.default.success(`开始执行翻译本批次第${index + 1}次请求`);
// 调用接口,并返回 Promise 对象
return got.get(urlList[index]);
})
.then(({ body }) => {
const res = JSON.parse(body);
if (!res.error_code) {
return res.trans_result;
}
else {
throw body;
}
})
.catch((error) => {
console.error(`Error calling API for params: ${JSON.stringify(params)}`, error);
throw error;
});
});
return Promise.all(promises);
}