-
Notifications
You must be signed in to change notification settings - Fork 7
/
query.ts
100 lines (90 loc) · 2.6 KB
/
query.ts
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
import {
RequestParams,
RawResponseParams,
ResponseParams,
Config,
} from './types';
import { API_URL, REQUEST_ALTERNATIVES } from './const';
function buildRequestParams(sourceLang = 'auto', targetLang = 'en') {
return {
jsonrpc: '2.0',
method: 'LMT_handle_texts',
id: Math.floor(Math.random() * 100000 + 100000) * 1000,
params: {
texts: [{ text: '', requestAlternatives: REQUEST_ALTERNATIVES }],
timestamp: 0,
splitting: 'newlines',
lang: {
source_lang_user_selected: sourceLang?.toUpperCase(),
target_lang: targetLang?.toUpperCase(),
},
},
};
}
function countLetterI(translateText: string) {
return (translateText || '').split('i').length - 1;
}
function getTimestamp(letterCount: number) {
const timestamp = new Date().getTime();
return letterCount !== 0
? timestamp - (timestamp % (letterCount + 1)) + (letterCount + 1)
: timestamp;
}
function buildRequestBody(data: RequestParams) {
const requestData = buildRequestParams(data.source_lang, data.target_lang);
requestData.params.texts = [
{ text: data.text, requestAlternatives: REQUEST_ALTERNATIVES },
];
requestData.params.timestamp = getTimestamp(countLetterI(data.text));
let requestString = JSON.stringify(requestData);
if (
[0, 3].includes((requestData['id'] + 5) % 29) ||
(requestData['id'] + 3) % 13 === 0
) {
requestString = requestString.replace('"method":"', '"method" : "');
} else {
requestString = requestString.replace('"method":"', '"method": "');
}
return requestString;
}
async function query(
params: RequestParams,
config?: Config
): Promise<ResponseParams> {
if (!params?.text) {
return {
code: 404,
message: 'No Translate Text Found',
data: null,
};
}
const response = await fetch(config?.proxyEndpoint ?? API_URL, {
headers: {
'Content-Type': 'application/json; charset=utf-8',
...config?.customHeader,
},
method: 'POST',
body: buildRequestBody(params),
});
if (response.ok) {
const { result } = (await response.json()) as RawResponseParams;
return {
code: 200,
message: 'success',
data: result?.texts?.[0]?.text,
source_lang: params?.source_lang || result?.lang || 'auto',
target_lang: params?.target_lang || 'en',
alternatives: result.texts?.[0]?.alternatives?.map?.(item => item.text),
};
} else {
return {
code: response.status,
data: null,
message:
response.status === 429
? 'Too many requests, please try again later.'
: 'Unknown error.',
};
}
}
export { query };