-
Notifications
You must be signed in to change notification settings - Fork 133
/
server.js
134 lines (117 loc) · 3.96 KB
/
server.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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
import express from 'express';
import 'dotenv/config';
import cors from 'cors';
import bodyParser from 'body-parser';
import yargs from 'yargs/yargs';
import { hideBin } from 'yargs/helpers';
import { translate } from './translate.js';
// 解析参数
const argv = yargs(hideBin(process.argv))
.option('port', {
alias: 'p',
describe: '端口号',
coerce: check_port,
default: Number(process.env.PORT) || 6119
})
.option('alt', {
alias: 'a',
describe: '请求备选翻译',
type: 'boolean',
default: Boolean(process.env.ALTERNATIVE) || true
})
.option('cors', {
alias: 'c',
describe: '允许跨域访问的源(origin)',
coerce: check_cors,
default: process.env.CORS_ORIGIN || false
})
.help().alias('help', 'h')
.argv;
// 定义配置
const app = express(),
PORT = argv.port,
allowAlternative = argv.alt,
CORS = {
origin: argv.cors,
methods: 'GET,POST',
allowedHeaders: ['Content-Type', 'Authorization'],
preflightContinue: false
};
// 其他平台支持配置CORS,我就不兼容了
app.use(cors(CORS));
app.use(bodyParser.json());
// 为了方便兼容多平台才这样写
app.post('/translate', async (req, res) => await post(req, res));
app.get('/', async (req, res) => await get(req, res));
async function post(req, res) {
const startTime = Date.now(); // 记录开始时间
// 检查请求体
if (!req.body || Object.keys(req.body).length === 0) {
const duration = Date.now() - startTime;
console.log(`[LOG] ${new Date().toISOString()} | POST "translate" | 400 | Request body does not exist | ${duration}ms`);
return res.status(400).json({
"code": 400,
"message": "Bad Request"
});
}
const { text, source_lang, target_lang, alt_count } = req.body;
// 是否允许备选翻译
if (!allowAlternative && alt_count !== undefined) {
const duration = Date.now() - startTime;
console.log(`[LOG] ${new Date().toISOString()} | POST "translate" | 405 | Alt Not Allowed | ${duration}ms`);
return res.status(405).json({
"code": 405,
"message": "Alternative Translate Not Allowed"
});
alt_count = 0;
}
try {
const result = await translate(text, source_lang, target_lang, alt_count);
const duration = Date.now() - startTime; // 计算处理时间
console.log(`[LOG] ${new Date().toISOString()} | POST "translate" | 200 | ${duration}ms`);
const responseData = {
code: 200,
data: result.text, // 取第一个翻译结果
id: Math.floor(Math.random() * 10000000000), // 生成一个随机 ID
method: 'Free',
source_lang,
target_lang,
alternatives: result.alternatives
};
res.json(responseData);
} catch (error) {
const duration = Date.now() - startTime;
console.error(`[ERR] ${new Date().toISOString()} | POST "translate" | 500 | ${error.message} | ${duration}ms`);
res.status(500).json({
code: 500,
message: 'Translation failed',
error: error.message
});
}
};
async function get(req, res) {
res.json({
code: 200,
message: "Welcome to the DeepL Free API. Please POST to '/translate'. This program is published in accordance with the terms of GNU/AGPLv3. Visit 'https://github.com/guobao2333/DeepLX-Serverless' for more information."
});
};
function check_cors(arg) {
if (arg === undefined) return;
if (typeof arg === 'string' || typeof arg === 'boolean') {
return arg;
}
console.error("ParamTypeError: \x1b[33m'"+arg+"'\x1b[31m, origin should be Boolean or String.\n\x1b[0meg: \x1b[32m'*' or true or RegExp");
process.exit(1);
}
function check_port(arg) {
if (typeof arg === 'number' && !isNaN(arg) && Number.isInteger(arg) && arg >= 0 && arg <= 65535) {
return arg;
}
console.warn("WARNING:\x1b[0m port should be >= 0 and < 65536.\nUsed default value instead: 6119\n");
return 6119;
}
// 启动本地服务器
app.listen(PORT, () => {
console.log(`Server is running and listening on http://localhost:${PORT}`);
});
export { post, get };