-
Notifications
You must be signed in to change notification settings - Fork 145
/
server.js
153 lines (132 loc) · 4.46 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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
import express from 'express';
import cors from 'cors';
import bodyParser from 'body-parser';
import yargs from 'yargs/yargs';
import { hideBin } from 'yargs/helpers';
import { brotliCompress, brotliDecompress } from 'zlib';
import { translate } from './translate.js';
import'dotenv/config';
// 解析参数
const argv = yargs(hideBin(process.argv))
.option('port', {
alias: 'p',
describe: 'Service port number',
coerce: check_port,
default: Number(process.env.PORT) || 6119
})
.option('alt', {
alias: 'a',
describe: 'Allow request alternatives translation',
type: 'boolean',
default: Boolean(process.env.ALTERNATIVE) || true
})
.option('cors', {
alias: 'c',
describe: 'Origin that allow cross-domain access',
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
};
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();
let { text, source_lang, target_lang, alt_count } = req.body;
source_lang = source_lang.toUpperCase();
target_lang = target_lang.toUpperCase();
// 检查请求体
if (!req.body || !text || !target_lang || (alt_count !== undefined && typeof alt_count !== 'number')) {
const duration = Date.now() - startTime;
console.log(`[WARN] ${new Date().toISOString()} | POST "translate" | 400 | Bad Request | ${duration}ms`);
return res.status(400).json({
"code": 400,
"message": "Bad Request"
});
}
// 是否允许备选翻译
if (!allowAlternative && alt_count !== undefined) {
const duration = Date.now() - startTime;
console.log(`[LOG] ${new Date().toISOString()} | POST "translate" | 405 | Alternative 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);
/*result = brotliDecompress(result, (err, decompressedData) => {
if (err) console.error(err);
return decompressedData;
});*/
const duration = Date.now() - startTime; // 计算处理时间
console.log(result)
if(result == "") {
console.error(`[ERROR] ${new Date().toISOString()} | POST "translate" | 500 | ${error.message} | ${duration}ms`);
res.status(500).json({
code: 500,
message: "Translation failed",
error: error.message
});
}
console.log(`[LOG] ${new Date().toISOString()} | POST "translate" | 200 | ${duration}ms`);
const responseData = {
code: 200,
id: result.id,
data: result.data, // 取第一个翻译结果
method: "Free",
source_lang: result.source_lang,
target_lang,
alternatives: result.alternatives
};
/*brotliCompress(responseData, (err, compressedData) => {
if (err) {
console.error('压缩错误: '+err);
res.json(responseData);
} else res.json(compressedData);
});*/
res.json(responseData);
} catch (err) {
console.error(err, err.stack);
return 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'. 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}/translate`);
});
export { post, get };