Files
api.pawol.nu/src/api/parole/services/parole.js
T
2022-06-04 01:15:42 +04:00

70 lines
2.1 KiB
JavaScript

'use strict';
const qs = require('qs')
const axios = require('axios')
const { createCoreService } = require('@strapi/strapi').factories;
const { ValidationError } = require("@strapi/utils").errors
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)
}
}
}
module.exports = createCoreService('api::parole.parole', ({strapi}) => ({
async translate(origin, target, text) {
const translator = new Translator()
const data = await translator.get(origin, target, text)
return data.translations[0].text
},
async translateLyrics(parolesFR) {
const anglais = await this.translate('FR', 'EN', parolesFR)
const espagnol = await this.translate('FR', 'ES', parolesFR)
const allemand = await this.translate('FR', 'DE', parolesFR)
const italien = await this.translate('FR', 'IT', parolesFR)
return {
francais: parolesFR,
anglais: anglais + '\n\n (Translated by DeepL)',
espagnol: espagnol + '\n\n (Traducido por DeepL)',
allemand: allemand + '\n\n (Übersetzt von DeepL)',
italien: italien + '\n\n (Tradotto da DeepL)'
}
},
validateParoles(titre, transcription) {
if (!titre || titre.trim().length === 0) {
throw new ValidationError('Champ obligatoire. Veuillez choisir un titre.');
}
if (!transcription || transcription.trim().length === 0) {
throw new ValidationError('Champ obligatoire. Veuillez renseigner la transcription.')
}
if (transcription.trim().length < 10) {
throw new ValidationError('La transcription doit contenir au moins 10 caractères.')
}
}
}));