Skip to content

Commit

Permalink
merge: 优化和修复异常处理 (#32)
Browse files Browse the repository at this point in the history
  • Loading branch information
guobao2333 authored Jan 15, 2025
2 parents 3d9e9c0 + 0cac624 commit 58d5fc2
Show file tree
Hide file tree
Showing 5 changed files with 53 additions and 157 deletions.
6 changes: 5 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# DeepLX Serverless

<p align="center">
<a href="https://github.com/guobao2333/MT-syntax-highlight"><img alt="Repository" src="https://img.shields.io/badge/Github-%230A0A0A.svg?&style=flat-square&logo=Github&logoColor=white"/></a>
</p>

***本项目3.0版本开始完全基于[OwO-Network/DeepLX](https://github.com/OwO-Network/DeepLX)和DeepL网页端API进行重写。***
**2.0及之前版本在[LegendLeo/deeplx-serverless](https://github.com/LegendLeo/deeplx-serverless)的基础上进行重构。**

Expand Down Expand Up @@ -69,7 +73,7 @@ curl -X POST 'http://localhost:6119/translate' -H 'Content-Type: application/jso

简单的示例:
```javascript
import { translate } from './translate.js';
import { translate } from './src/translate.js';
translate('how are you?', 'en', 'zh', '', false, false)
.then(result => {
console.log(result)
Expand Down
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"version": "3.0.1",
"description": "DeepL free API for Serverless",
"type": "module",
"main": "server.js",
"main": "src/server.js",
"keywords": [
"deeplxs",
"deeplx",
Expand All @@ -19,7 +19,7 @@
"scripts": {
"start": "node src/server.js",
"test": "node test.js",
"start:sl": "node src/index.js",
"start:sl": "node api/index.js",
"test:post": "node test_post.js"
},
"dependencies": {
Expand Down
25 changes: 16 additions & 9 deletions src/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,6 @@ async function post(req, res) {
code: 405,
message: "Alternative Translate Not Allowed"
});
// alt_count = 0;
}

try {
Expand All @@ -83,10 +82,19 @@ async function post(req, res) {
return decompressedData;
});*/

const duration = Date.now() - startTime; // 计算处理时间
let duration = Date.now() - startTime;
if(result.code === 429) {
console.error(`[WARN] ${new Date().toISOString()} | POST "translate" | 429 | ${result.message} | ${duration}ms`);
res.status(429).json({
code: 429,
message: result.message
});
}

duration = Date.now() - startTime;
// console.log(result);
if(result == "") {
console.error(`[ERROR] ${new Date().toISOString()} | POST "translate" | 500 | ${error.message} | ${duration}ms`);
if(result == "" || result.data == "") {
console.error(`[ERROR] ${new Date().toISOString()} | POST "translate" | 500 | ${result.message} | ${duration}ms`);
res.status(500).json({
code: 500,
message: "Translation failed",
Expand All @@ -96,7 +104,7 @@ async function post(req, res) {
console.log(`[LOG] ${new Date().toISOString()} | POST "translate" | 200 | ${duration}ms`);

const responseData = {
code: 200,
code: result.code,
id: result.id,
data: result.data, // 取第一个翻译结果
method: "Free",
Expand All @@ -116,16 +124,15 @@ async function post(req, res) {

} catch (err) {
console.error(err, err.stack);
return res.status(500).json({
res.status(500).json({
code: 500,
message: "Translation failed",
error: err.message
message: err.message
});
}
};

async function get(req, res) {
res.json({
res.status(200).json({
code: 200,
message: "Welcome to the DeepL Free API. Please POST to '/translate'. Visit 'https://github.com/guobao2333/DeepLX-Serverless' for more information."
});
Expand Down
45 changes: 30 additions & 15 deletions src/translate.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,24 +35,33 @@ async function sendRequest(postData, urlMethod, dlSession, printResult) {
...(dlSession && {'Cookie': `dl_session=${dlSession}`})
};
postData = formatPostString(postData);
// console.log(postData);
// console.warn(postData);

try {
const response = await axios.post(urlFull, postData, {
headers: headers
});
// console.log(response.data);


if (response.headers['content-encoding'] === 'br') {
const decompressed = brotliDecompress(response.data, (err, data) => {
if (err) console.error(err);
return data;
const decompressed = await new Promise((resolve, reject) => {
brotliDecompress(response.data, (err, data) => {
if (err) reject(err);
else resolve(data);
});
});
return JSON.parse(decompressed.toString());
}
return response.data;
} catch (err) {
console.error(err);
if (err.response.status === 429) {
return {
code: err.response.status,
message: 'Too Many Requests'
};
} else {
console.error(`[ERROR] sendRequest: ${err.message}`);
throw err;
}
}
}

Expand All @@ -69,7 +78,12 @@ async function splitText(text, tagHandling, dlSession, printResult) {
}
};

return await sendRequest(postData, 'LMT_split_text', dlSession, printResult);
try {
return await sendRequest(postData, 'LMT_split_text', dlSession, printResult);
} catch (err) {
console.error("[ERROR] splitText:", err);
throw new Error(`splitText failed: ${err.message || err}`);
}
}

// 执行翻译任务
Expand All @@ -81,12 +95,12 @@ async function translate(text, sourceLang, targetLang, dlSession, tagHandling, p

// 分割文本
const splitResult = await splitText(text, tagHandling === 'html' || tagHandling === 'xml', dlSession, printResult);
// console.log(splitResult);
// console.warn(splitResult);

if (splitResult.code == 429) {
throw {
if (splitResult.code === 429) {
return {
code: splitResult.code,
message: splitResult.data.error
message: splitResult.message
}
}

Expand Down Expand Up @@ -157,7 +171,7 @@ async function translate(text, sourceLang, targetLang, dlSession, tagHandling, p
}

const ret = {
code: 200,
code: postData.status,
id: postData.id,
method: "Free",
data: translatedText,
Expand All @@ -167,8 +181,9 @@ async function translate(text, sourceLang, targetLang, dlSession, tagHandling, p
}
if(printResult) console.log(ret);
return ret;
} catch(err) {
return err;
} catch (err) {
console.error("[ERROR] translate:", err);
throw new Error(err.message || err);
}
}

Expand Down
130 changes: 0 additions & 130 deletions src/translate_old.js

This file was deleted.

0 comments on commit 58d5fc2

Please sign in to comment.