diff --git a/api/translator/services/translator.js b/api/translator/services/translator.js new file mode 100644 index 0000000..7f0de12 --- /dev/null +++ b/api/translator/services/translator.js @@ -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}