Skip to content

Commit

Permalink
Trying to fix translate API
Browse files Browse the repository at this point in the history
  • Loading branch information
philliparaujo committed Nov 14, 2024
1 parent fd76ce1 commit 5805aca
Showing 1 changed file with 25 additions and 3 deletions.
28 changes: 25 additions & 3 deletions src/translate/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,29 @@ const translatorApi = module.exports;

translatorApi.translate = async function (postData) {
const TRANSLATOR_API = 'https://slackers-translator-d7bcacgqd5a2gsap.canadacentral-01.azurewebsites.net/';
const response = await fetch(`${TRANSLATOR_API}/?content=${postData.content}`);
const data = await response.json();
return [data.is_english, data.translated_content];

try {
const response = await fetch(`${TRANSLATOR_API}/?content=${encodeURIComponent(postData.content)}`);
if (!response.ok) {
throw new Error(`Failed to fetch translation: ${response.status} ${response.statusText}`);
}

// Attempt to parse response as JSON
let data;
try {
data = await response.json();
} catch (err) {
throw new Error('Unexpected response format: Expected JSON but received non-JSON data');
}

// Check if the necessary fields are present in the data
if (!data || typeof data.is_english !== 'boolean' || typeof data.translated_content !== 'string') {
throw new Error('Incomplete data: Missing expected fields in response');
}

return [data.is_english, data.translated_content];
} catch (error) {
console.error('Translation API error:', error.message);
return [null, 'Error in translation service'];
}
};

0 comments on commit 5805aca

Please sign in to comment.