-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtranslate.js
More file actions
58 lines (47 loc) · 1.12 KB
/
translate.js
File metadata and controls
58 lines (47 loc) · 1.12 KB
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
import crypto from 'crypto';
import { Redis } from 'ioredis';
import 'dotenv/config.js';
import * as tencent from './providers/tencent.js';
const ttl = 60 * 60 * 10; // 10 hours
const providers = [
{
name: 'tencent',
translate: tencent.translate,
},
];
const redis = new Redis(process.env.REDIS_URL_CACHE, {
keyPrefix: 'fanyi:',
});
/**
* @param {string} text
*/
export async function translate(text) {
text = text.trim();
const chars = text.length;
if (!chars) {
return { text };
}
const textHash = crypto.createHash('md5').update(text).digest('hex');
const cacheKey = `cache:${textHash}`;
const cacheValue = await redis.get(cacheKey);
if (cacheValue !== null) {
return {
...JSON.parse(cacheValue),
cache: true,
};
}
const provider = providers[0];
if (!provider) {
throw new Error('没有可用的翻译服务');
}
const tResult = await provider.translate(text);
const result = {
provider: provider.name,
from: tResult.from,
text: tResult.text,
};
await redis.set(cacheKey, JSON.stringify(result), 'EX', ttl);
return {
...result,
};
}