Skip to content

Commit

Permalink
update refactor
Browse files Browse the repository at this point in the history
Signed-off-by: Sankarsan Kampa <[email protected]>
  • Loading branch information
iamtraction committed May 7, 2020
1 parent 9b829ef commit 15a1a53
Show file tree
Hide file tree
Showing 3 changed files with 316 additions and 322 deletions.
258 changes: 129 additions & 129 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
const languages = require('./languages');
const tokenGenerator = require('./tokenGenerator');
const querystring = require('querystring');
const got = require('got');
const languages = require("./languages");
const tokenGenerator = require("./tokenGenerator");
const querystring = require("querystring");
const got = require("got");

/**
* @function translate
Expand All @@ -10,144 +10,144 @@ const got = require('got');
* @returns {Object} The result containing the translation.
*/
async function translate(text, options) {
try {
if (typeof options !== 'object') options = {};
text = String(text);

// Check if a lanugage is in supported; if not, throw an error object.
let error;
[ options.from, options.to ].forEach((lang) => {
if (lang && !languages.isSupported(lang)) {
error = new Error();
error.code = 400;
error.message = `The language '${lang}' is not supported.`;
}
});
if (error) throw error;

// If options object doesn't have 'from' language, set it to 'auto'.
if (!options.hasOwnProperty('from')) options.from = 'auto';
// If options object doesn't have 'to' language, set it to 'en'.
if (!options.hasOwnProperty('to')) options.to = 'en';
// If options object has a 'raw' property evaluating to true, set it to true.
options.raw = Boolean(options.raw);

// Get ISO 639-1 codes for the languages.
options.from = languages.getISOCode(options.from);
options.to = languages.getISOCode(options.to);

// Generate Google Translate token for the text to be translated.
let token = await tokenGenerator.generate(text);

// URL & query string required by Google Translate.
let baseUrl = 'https://translate.google.com/translate_a/single';
let data = {
client: 'gtx',
sl: options.from,
tl: options.to,
hl: options.to,
dt: [ 'at', 'bd', 'ex', 'ld', 'md', 'qca', 'rw', 'rm', 'ss', 't' ],
ie: 'UTF-8',
oe: 'UTF-8',
otf: 1,
ssel: 0,
tsel: 0,
kc: 7,
q: text,
[token.name]: token.value
};

// Append query string to the request URL.
let url = `${baseUrl}?${querystring.stringify(data)}`;

let requestOptions;
// If request URL is greater than 2048 characters, use POST method.
if (url.length > 2048) {
delete data.q;
requestOptions = [
`${baseUrl}?${querystring.stringify(data)}`,
{
method: 'POST',
form: true,
body: {
q: text
}
try {
if (typeof options !== "object") options = {};
text = String(text);

// Check if a lanugage is in supported; if not, throw an error object.
let error;
[ options.from, options.to ].forEach((lang) => {
if (lang && !languages.isSupported(lang)) {
error = new Error();
error.code = 400;
error.message = `The language '${lang}' is not supported.`;
}
});
if (error) throw error;

// If options object doesn"t have "from" language, set it to "auto".
if (!Object.prototype.hasOwnProperty.call(options, "from")) options.from = "auto";
// If options object doesn"t have "to" language, set it to "en".
if (!Object.prototype.hasOwnProperty.call(options, "to")) options.to = "en";
// If options object has a "raw" property evaluating to true, set it to true.
options.raw = Boolean(options.raw);

// Get ISO 639-1 codes for the languages.
options.from = languages.getISOCode(options.from);
options.to = languages.getISOCode(options.to);

// Generate Google Translate token for the text to be translated.
let token = await tokenGenerator.generate(text);

// URL & query string required by Google Translate.
let baseUrl = "https://translate.google.com/translate_a/single";
let data = {
client: "gtx",
sl: options.from,
tl: options.to,
hl: options.to,
dt: [ "at", "bd", "ex", "ld", "md", "qca", "rw", "rm", "ss", "t" ],
ie: "UTF-8",
oe: "UTF-8",
otf: 1,
ssel: 0,
tsel: 0,
kc: 7,
q: text,
[token.name]: token.value
};

// Append query string to the request URL.
let url = `${baseUrl}?${querystring.stringify(data)}`;

let requestOptions;
// If request URL is greater than 2048 characters, use POST method.
if (url.length > 2048) {
delete data.q;
requestOptions = [
`${baseUrl}?${querystring.stringify(data)}`,
{
method: "POST",
form: true,
body: {
q: text
}
}
];
}
else {
requestOptions = [ url ];
}
];
}
else {
requestOptions = [ url ];
}

// Request translation from Google Translate.
let response = await got(...requestOptions);

let result = {
text: '',
from: {
language: {
didYouMean: false,
iso: ''
},
text: {
autoCorrected: false,
value: '',
didYouMean: false
// Request translation from Google Translate.
let response = await got(...requestOptions);

let result = {
text: "",
from: {
language: {
didYouMean: false,
iso: ""
},
text: {
autoCorrected: false,
value: "",
didYouMean: false
}
},
raw: ""
};

// If user requested a raw output, add the raw response to the result
if (options.raw) {
result.raw = response.body;
}
},
raw: ''
};

// If user requested a raw output, add the raw response to the result
if (options.raw) {
result.raw = response.body;
}
// Parse string body to JSON and add it to result object.

// Parse string body to JSON and add it to result object.
let body = JSON.parse(response.body);
body[0].forEach((obj) => {
if (obj[0]) {
result.text += obj[0];
}
});

let body = JSON.parse(response.body);
body[0].forEach((obj) => {
if (obj[0]) {
result.text += obj[0];
}
});
if (body[2] === body[8][0][0]) {
result.from.language.iso = body[2];
}
else {
result.from.language.didYouMean = true;
result.from.language.iso = body[8][0][0];
}

if (body[2] === body[8][0][0]) {
result.from.language.iso = body[2];
}
else {
result.from.language.didYouMean = true;
result.from.language.iso = body[8][0][0];
}
if (body[7] && body[7][0]) {
let str = body[7][0];

if (body[7] && body[7][0]) {
let str = body[7][0];
str = str.replace(/<b><i>/g, "[");
str = str.replace(/<\/i><\/b>/g, "]");

str = str.replace(/<b><i>/g, '[');
str = str.replace(/<\/i><\/b>/g, ']');
result.from.text.value = str;

result.from.text.value = str;
if (body[7][5] === true) {
result.from.text.autoCorrected = true;
}
else {
result.from.text.didYouMean = true;
}
}

if (body[7][5] === true) {
result.from.text.autoCorrected = true;
}
else {
result.from.text.didYouMean = true;
}
return result;
}

return result;
}
catch (e) {
if (e.name === 'HTTPError') {
let error = new Error();
error.name = e.name;
error.statusCode = e.statusCode;
error.statusMessage = e.statusMessage;
throw error;
catch (e) {
if (e.name === "HTTPError") {
let error = new Error();
error.name = e.name;
error.statusCode = e.statusCode;
error.statusMessage = e.statusMessage;
throw error;
}
throw e;
}
throw e;
}
}

module.exports = translate;
Expand Down
Loading

0 comments on commit 15a1a53

Please sign in to comment.