Create Translator class

This commit is contained in:
Cédric FAMIBELLE-PRONZOLA
2022-03-27 02:08:37 +04:00
parent a5f6e3334a
commit ea5a1e8e80
+39
View File
@@ -0,0 +1,39 @@
const qs = require('qs')
const axios = require('axios')
class Translator {
constructor() {
this.deeplApi = process.env.DEEPL_URL || 'api-free.deepl.com'
this.deeplKey = process.env.DEEPL_KEY
this.urlRequest = `https://${this.deeplApi}/v2/translate`
}
async get(origin, target, text) {
try {
const data = {
auth_key: this.deeplKey,
source_lang: origin,
target_lang: target,
text
}
const result = await axios.post(this.urlRequest, qs.stringify(data), {
headers: {
'content-type': 'application/x-www-form-urlencoded'
}
})
return result.data
} catch (error) {
console.log('error', error)
}
}
}
const translator = new Translator()
async function translate(origin, target, text) {
const data = await translator.get(origin, target, text)
return data.translations[0].text
}
module.exports = {translate}