Skip to content

Commit

Permalink
Update index.js
Browse files Browse the repository at this point in the history
Signed-off-by: SkandaBT <9980056379Skanda@gmail.com>
  • Loading branch information
skanda890 authored Nov 23, 2024
1 parent dea8415 commit 7b9a30a
Showing 1 changed file with 17 additions and 3 deletions.
20 changes: 17 additions & 3 deletions dictionary-app/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ const path = require('path');
const app = express();
const port = 5000;

const API_URL = 'https://api.dictionaryapi.dev/api/v2/entries/en/';
const DICTIONARY_API_URL = 'https://api.dictionaryapi.dev/api/v2/entries/en/';
const TRANSLATE_API_URL = 'https://libretranslate.com/translate';

app.use(express.json());
app.use(express.static(path.join(__dirname, 'public')));
Expand All @@ -14,9 +15,22 @@ app.get('/', (req, res) => {
});

app.post('/define', async (req, res) => {
const { word } = req.body;
const { word, lang } = req.body;
try {
const response = await axios.get(`${API_URL}${word}`);
// Translate the word to English if it's not already in English
let translatedWord = word;
if (lang !== 'en') {
const translateResponse = await axios.post(TRANSLATE_API_URL, {
q: word,
source: lang,
target: 'en',
format: 'text'
});
translatedWord = translateResponse.data.translatedText;
}

// Fetch the definition of the translated word
const response = await axios.get(`${DICTIONARY_API_URL}${translatedWord}`);
res.json(response.data);
} catch (error) {
console.error('Error fetching definition:', error.message);
Expand Down

0 comments on commit 7b9a30a

Please sign in to comment.