@mixxtor/adonisjs-translader
v1.0.2
Published
AdonisJS integration for TransladerJS - Multi-provider translation service
Downloads
7
Maintainers
Readme
Translader AdonisJS
AdonisJS integration for Translader.js - Multi-provider translation service with Google Translate, DeepL, and more.
✨ Features
- 🚀 AdonisJS Integration - Seamless integration with AdonisJS v6 framework
- 🌐 Multi-Provider - Google Translate (Free & Paid), with future support for DeepL, OpenAI, and more
- 💉 Dependency Injection - Registered as AdonisJS service for easy injection
- 🎯 Type Safety - Full TypeScript support with intelligent type inference
- 🔄 Provider Switching - Switch between providers at runtime with auto-complete
- 📦 Easy Setup - Simple configuration and installation via
node ace configure - 🔧 Extensible - Easy to add custom translation providers
- 💡 IntelliSense - Auto-completion for configured providers using type augmentation
📦 Installation
npm install @mixxtor/adonisjs-translader @mixxtor/translader🚀 Setup
1. Configure the package
node ace configure @mixxtor/adonisjs-transladerThis will:
- Create
config/translation.tsconfiguration file - Register the service provider in
adonisrc.ts
2. Configure environment variables
Add to your .env file:
# Default translation provider
TRANSLATION_PROVIDER=google-free
# Google Cloud Translation API (for paid provider)
GOOGLE_TRANSLATE_API_KEY=your_api_key_here
# OR use service account credentials
# GOOGLE_CLOUD_PROJECT_ID=your_project_id
# GOOGLE_CLOUD_PRIVATE_KEY=your_private_key
# GOOGLE_CLOUD_CLIENT_EMAIL=your_service_account_email3. Configure providers
Edit config/translation.ts:
import env from '#start/env'
import { defineConfig } from '@mixxtor/adonisjs-translader'
import type { InferProviders } from '@mixxtor/adonisjs-translader'
import { GoogleTranslateFreeProvider, GoogleTranslatePaidProvider } from '@mixxtor/translader'
const translationConfig = defineConfig({
/*
|--------------------------------------------------------------------------
| Default Provider
|--------------------------------------------------------------------------
*/
default: env.get('TRANSLATION_PROVIDER', 'google-free') as 'google-free' | 'google-paid',
/*
|--------------------------------------------------------------------------
| Provider Configurations
|--------------------------------------------------------------------------
*/
providers: {
/*
| Google Translate Free - No API key required
*/
'google-free': new GoogleTranslateFreeProvider(),
/*
| Google Cloud Translation API - Requires API key or credentials
*/
'google-paid': new GoogleTranslatePaidProvider({
apiKey: env.get('GOOGLE_TRANSLATE_API_KEY'),
// OR use service account:
// credentials: {
// projectId: env.get('GOOGLE_CLOUD_PROJECT_ID'),
// privateKey: env.get('GOOGLE_CLOUD_PRIVATE_KEY'),
// clientEmail: env.get('GOOGLE_CLOUD_CLIENT_EMAIL'),
// }
}),
},
})
export default translationConfig
/*
|--------------------------------------------------------------------------
| Type Augmentation
|--------------------------------------------------------------------------
|
| Augment the module types to enable IntelliSense for configured providers.
| This allows auto-completion when using translation.use('provider-name')
|
*/
declare module '@mixxtor/adonisjs-translader/types' {
interface TranslationProviders extends InferProviders<typeof translationConfig> {}
}💡 Usage
Basic Translation in Controllers
// app/controllers/translation_controller.ts
import { inject } from '@adonisjs/core'
import type { HttpContext } from '@adonisjs/core/http'
import translation from '@mixxtor/adonisjs-translader/services/main'
@inject()
export default class TranslationController {
constructor(private translation: typeof translation) {}
async translate({ request, response }: HttpContext) {
const { text, from, to } = request.only(['text', 'from', 'to'])
const result = await this.translation.translate({
text,
from,
to,
})
if (result.success) {
return response.json({
success: true,
data: {
original: text,
translated: result.text,
from: result.from,
to: result.to,
provider: result.provider,
},
})
}
return response.status(400).json({
success: false,
error: result.error,
})
}
async batchTranslate({ request, response }: HttpContext) {
const { texts, from, to } = request.only(['texts', 'from', 'to'])
const result = await this.translation.translateBatch({
texts,
from,
to,
})
if (result.success) {
return response.json({
success: true,
data: result.translations,
})
}
return response.status(400).json({
success: false,
error: result.error,
})
}
async detectLanguage({ request, response }: HttpContext) {
const { text } = request.only(['text'])
const result = await this.translation.detectLanguage({ text })
if (result.success) {
return response.json({
success: true,
language: result.language,
confidence: result.confidence,
})
}
return response.status(400).json({
success: false,
error: result.error,
})
}
async getSupportedLanguages({ response }: HttpContext) {
const result = await this.translation.getSupportedLanguages()
if (result.success) {
return response.json({
success: true,
languages: result.languages,
})
}
return response.status(400).json({
success: false,
error: result.error,
})
}
}Provider Switching
// Switch to different provider at runtime
const googleFree = this.translation.use('google-free')
const freeResult = await googleFree.translate({
text: 'Hello, world!',
from: 'en',
to: 'es',
})
const googlePaid = this.translation.use('google-paid')
const paidResult = await googlePaid.translate({
text: 'Hello, world!',
from: 'en',
to: 'es',
})Using in Services
// app/services/content_translation_service.ts
import { inject } from '@adonisjs/core'
import translation from '@mixxtor/adonisjs-translader/services/main'
@inject()
export default class ContentTranslationService {
constructor(private translation: typeof translation) {}
async translateContent(content: string, targetLanguage: string) {
// Auto-detect source language
const detection = await this.translation.detectLanguage({ text: content })
if (!detection.success) {
throw new Error('Failed to detect language')
}
// Translate to target language
const result = await this.translation.translate({
text: content,
from: detection.language,
to: targetLanguage,
})
if (!result.success) {
throw new Error('Translation failed')
}
return {
original: content,
translated: result.text,
sourceLanguage: detection.language,
targetLanguage,
}
}
}📚 API Reference
The AdonisJS integration provides the same API as the core Translader.js package:
Core Methods
translate(params: TranslateParams): Promise<TranslationResult>
Translate text from one language to another.
const result = await translation.translate({
text: 'Hello, world!',
from: 'en',
to: 'es',
})translateBatch(params: BatchTranslateParams): Promise<BatchTranslationResult>
Translate multiple texts at once.
const result = await translation.translateBatch({
texts: ['Hello', 'Goodbye', 'Thank you'],
from: 'en',
to: 'es',
})detectLanguage(params: DetectLanguageParams): Promise<DetectionResult>
Detect the language of a text.
const result = await translation.detectLanguage({
text: 'Bonjour le monde',
})
// result.language === 'fr'getSupportedLanguages(params?: GetSupportedLanguagesParams): Promise<SupportedLanguagesResult>
Get list of supported languages.
const result = await translation.getSupportedLanguages()
// result.languages: [{ code: 'en', name: 'English' }, ...]Provider Management
use(provider: string): TranslationService
Switch to a different provider.
const googlePaid = translation.use('google-paid')
const result = await googlePaid.translate({ text: 'Hello', from: 'en', to: 'es' })⚙️ Configuration
Environment Variables
# Default provider
TRANSLATION_PROVIDER=google-free
# Google Cloud Translation API
GOOGLE_TRANSLATE_API_KEY=your_api_key_here
# OR Service Account (recommended for production)
GOOGLE_CLOUD_PROJECT_ID=your_project_id
GOOGLE_CLOUD_PRIVATE_KEY="-----BEGIN PRIVATE KEY-----\n..."
GOOGLE_CLOUD_CLIENT_EMAIL=your-service-account@project.iam.gserviceaccount.comProvider Configuration
Google Translate Free
'google-free': new GoogleTranslateFreeProvider()- No API key required
- Rate limited
- Unofficial API (may break)
Google Translate Paid (Cloud Translation API)
'google-paid': new GoogleTranslatePaidProvider({
apiKey: 'your-api-key',
// OR
credentials: {
projectId: 'your-project-id',
privateKey: '-----BEGIN PRIVATE KEY-----...',
clientEmail: '[email protected]',
}
})- Requires Google Cloud project
- Higher rate limits
- Official API with SLA
- Better quality translations
For detailed Google Cloud setup instructions, see: GOOGLE-CLOUD-SETUP.md
🛡️ Error Handling
All methods return result objects with success indicators:
const result = await translation.translate({
text: 'Hello',
from: 'en',
to: 'es',
})
if (result.success) {
// Handle success
console.log(`Translated: ${result.text}`)
console.log(`Provider: ${result.provider}`)
} else {
// Handle error
console.error(`Error: ${result.error}`)
}🧪 Testing
The package includes comprehensive tests. Run them with:
npm testFor development testing:
npm run quick:test📋 Requirements
- Node.js >= 18.0.0
- AdonisJS >= 6.19.0
- @mixxtor/translader >= 1.0.0-beta.0
🤝 Contributing
Contributions are welcome! Please read the contributing guidelines before submitting PRs.
📄 License
MIT License - see LICENSE.txt file for details.
📦 Related Packages
- @mixxtor/translader - Core translation library
Made with ❤️ by Mixxtor
