const express = require('express'); const bodyParser = require('body-parser'); const { translate } = require('./translate'); const cors = require('cors'); const fs = require('fs'); const app = express(); const PORT = 7860; app.use(cors({ origin: '*' })); app.use(bodyParser.json()); let delay = 1500; const delayIncrement = 100; const maxDelay = 5000; let currentTranslations = 0; function delayFileTermination(delay) { if (fs.existsSync('delay.txt')) { delay = parseInt(fs.readFileSync('delay.txt', 'utf8')); } else { fs.writeFile('delay.txt', `delay:${delay}`, function (err) { if (err === null) { console.log('success'); } else { console.log('fail'); } }); } } console.log('File system loaded'); app.post('/translate', async (req, res) => { console.log('Translate start'); currentTranslations++; const { text, source_lang, target_lang } = req.body; try { await new Promise((resolve) => setTimeout(resolve, delay)); const result = await translate(text, source_lang, target_lang); const responseData = { alternatives: result.alternatives, code: 200, data: result.text, id: Math.floor(Math.random() * 10000000000), method: 'Free', source_lang, target_lang, }; res.json(responseData); } catch (error) { console.error(`Translation failed: ${error}`); res.status(500).json({ error: 'Translation failed' }); delay += delayIncrement; if (delay > maxDelay) { delay = maxDelay; } delayFileTermination(delay); console.log(`현재 Delay 타임: ${delay}ms`); } finally { currentTranslations--; } }); app.get('/', (req, res) => { const delayMessage = fs.existsSync('delay.txt') ? fs.readFileSync('delay.txt', 'utf8') : '0'; const statusMessage = `서버가 구동되었습니다. 현재 딜레이 시간은 ${delay}ms이며, 현재 처리 중인 번역 요청 수는 ${currentTranslations}건입니다.`; res.send(statusMessage); }); app.listen(PORT, () => { console.log(`Server is running on http://localhost:${PORT}`); });