Skip to content

Commit

Permalink
added new validations to the code
Browse files Browse the repository at this point in the history
  • Loading branch information
heliomar-pena committed Nov 11, 2023
1 parent d535786 commit 2241527
Show file tree
Hide file tree
Showing 6 changed files with 71 additions and 19 deletions.
3 changes: 1 addition & 2 deletions cli.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

const { Command, Argument } = require('commander');
const program = new Command();
const supportedLanguages = require('./SUPPORTED-LANGUAGE.json');
const { configPath } = require('./utils/getConfigPath');
const { translateController } = require('./controllers/translateController');

Expand All @@ -14,7 +13,7 @@ program
program.command('translate')
.description('Translate a text and put the result on the files in the output directory')
.argument('<text>', 'Text to translate')
.addArgument(new Argument('<source-language>', 'Source language of the string').choices(supportedLanguages))
.argument('<source-language>', 'Source language of the string')
.argument('<name-of-translation>', 'Name of your translation')
.option('-e, --engine <string>', "Engine to use for the translation. In case you don't define it will be use by default all the translation engines that are free and doesn't requires API Key.")
.option('-s, --settings-file <string>', 'Path to the settings file', configPath)
Expand Down
10 changes: 5 additions & 5 deletions controllers/translateController.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,17 @@ const { validateSettingsFile } = require('../utils/validateSettingsFile');
const { dset: setDeepValue } = require('dset');
const { validateAndPromptUserJSONFiles } = require('../utils/validateAndPromptUserJSONFiles');
const { setTranslateWithFallbackEngines, isEngineValid } = require('../services/translateService');
const { validateLanguageRequested } = require('../utils/validateLanguageRequested');

const translateController = async (text, sourceLanguage, nameOfTranslation, options) => {
const settingsFilePath = parsePath(options.settingsFile);
const isValidSettingsFile = validateSettingsFile(settingsFilePath);

if (!isValidSettingsFile) throw new Error('Invalid settings file');
validateSettingsFile(settingsFilePath);
validateLanguageRequested(sourceLanguage, options.engine);

if (!text) throw new Error('No text to translate provided');
if (!sourceLanguage) throw new Error('No source language provided');
if (!nameOfTranslation) throw new Error('No name of translation provided');

const { languages, basePath, translationEngines: settingsTranslationEngines } = require(settingsFilePath);
const { languages, basePath, translationEngines: settingsTranslationEngines } = require(settingsFilePath);

if (options.engine && !isEngineValid(options.engine)) throw new Error(`You've provided an invalid engine as arg on your CLI Command. Try with one of these: ${validEngines.join(', ')}`);

Expand Down
34 changes: 22 additions & 12 deletions services/translateService.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ const { translate: libreTranslate } = require("./libreTranslate");
const {
getTranslationEnginesToUse,
} = require("../utils/getTranslationEnginePreferences");
const { validateLanguageIsSupportedByEngine } = require("../utils/validateLanguageIsSupportedByEngine");

const translateEngines = {
google: googleTranslate,
Expand Down Expand Up @@ -76,18 +77,27 @@ const setTranslateWithFallbackEngines = ({
);

for await (const engine of enginesFiltered) {
await translate(text, from, to, engine)
.then(({ text }) => {
result = text;
})
.catch(() => {
console.log(
`Error translating with ${engine} engine. Trying next engine...`
);
enginesFailed.push(engine);
});

if (result) break;
try {
// Validate that the language is supported by the engine to avoid unnecessary network requests
validateLanguageIsSupportedByEngine(from, engine);
validateLanguageIsSupportedByEngine(to, engine);

await translate(text, from, to, engine)
.then(({ text }) => {
result = text;
console.log(`Translated successfully with ${engine} engine. Result: ${text}`)
})
.catch(() => {
console.log(
`Error translating with ${engine} engine. Trying next engine...`
);
enginesFailed.push(engine);
});

if (result) break;
} catch (error) {
console.log(error.message);
}
}

if (!result) {
Expand Down
9 changes: 9 additions & 0 deletions utils/formatSupportedLanguages.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
const getSupportedLanguagesWithNames = (supportedLanguages) => {
return Object.entries(supportedLanguages).map(([language, data]) => {
return `${language} -> ${data.name}`
})
}

module.exports = {
getSupportedLanguagesWithNames
}
11 changes: 11 additions & 0 deletions utils/validateLanguageIsSupportedByEngine.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
const supportedLanguages = require('../SUPPORTED-LANGUAGES.json');

const validateLanguageIsSupportedByEngine = (requestedLanguage, engine) => {
const isLanguageSupportedByEngine = Object.keys(supportedLanguages[requestedLanguage]).includes(engine);

if (!isLanguageSupportedByEngine) throw new Error(`Language ${requestedLanguage} is not supported by this ${engine}.`);

return true;
}

module.exports = { validateLanguageIsSupportedByEngine }
23 changes: 23 additions & 0 deletions utils/validateLanguageRequested.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
const supportedLanguages = require('../SUPPORTED-LANGUAGES.json');
const { validEngines } = require('../services/translateService');
const { getSupportedLanguagesWithNames } = require('./formatSupportedLanguages');

const validateLanguageRequested = (requestedLanguage) => {
try {
if (!requestedLanguage) throw new Error('No language provided.');

const isLanguageSupported = supportedLanguages[requestedLanguage] !== undefined;

if (!isLanguageSupported) throw new Error(`Language ${requestedLanguage} is not supported.`);

const isLanguageSupportedByAlmostOneEngine = Object.keys(supportedLanguages[requestedLanguage]).some(value => validEngines.includes(value));

if (!isLanguageSupportedByAlmostOneEngine) throw new Error(`Language ${requestedLanguage} is not supported by any engine.`);

return true;
} catch (error) {
throw new Error(`${error.message}. \n\nPlease use one of these:\n\n${getSupportedLanguagesWithNames(supportedLanguages).join('\n')}`)
}
}

module.exports = { validateLanguageRequested }

0 comments on commit 2241527

Please sign in to comment.