@plyaz/translations
v1.4.7
Published
Shared translation utilities for Plyaz apps and backend services.
Keywords
Readme
@plyaz/translations
Overview
The @plyaz/translations package provides a centralized internationalization (i18n) solution for the Plyaz platform. It offers a consistent way to manage and access translations across both frontend and backend applications, ensuring a unified multilingual experience.
Purpose
This package aims to:
- Centralize translation strings for all applications
- Support multiple languages across the platform
- Provide type-safe access to translation keys
- Enable dynamic language switching
- Support string interpolation for dynamic content
- Integrate seamlessly with both frontend and backend frameworks
Core Features
✅ Translation Management
Organized by language and namespace, for example:
// en/errors.ts
export const errors = {
'auth.unauthorized': 'You are not authorized to access this resource',
'auth.forbidden': 'You do not have permission to perform this action',
'validation.required_field': '{field} is required',
'resource.not_found': '{entity} not found',
'blockchain.transaction_failed': 'Blockchain transaction failed: {reason}',
// ...
};⚙️ Translation Function
The translate function supports key lookup and parameter interpolation:
export function translate(
key: string,
lang: string = 'en',
params?: Record<string, string | number>
): string {
const locale = getLocale(lang);
const [namespace, ...keyParts] = key.split('.');
const actualKey = keyParts.join('.');
let message = locale[namespace]?.[actualKey] || key;
if (params) {
Object.entries(params).forEach(([param, value]) => {
message = message.replace(new RegExp(`{${param}}`, 'g'), String(value));
});
}
return message;
}🛡️ Type-Safe Translation Keys
export type ErrorKeys =
| 'auth.unauthorized'
| 'auth.forbidden'
| 'validation.required_field'
| 'resource.not_found';
// ...
export type TranslationKey = ErrorKeys | CommonKeys | /* other keys */;Frontend Integration (React)
🧠 React Hook
export function useTranslation() {
const { language } = React.useContext(TranslationContext);
const t = React.useCallback(
(key: TranslationKey, params?: Record<string, string | number>) => {
return translate(key, language, params);
},
[language]
);
return { t, language };
}📦 Provider
export const TranslationProvider: React.FC<{
initialLanguage?: LanguageCode;
}> = ({ initialLanguage = DEFAULT_LANGUAGE, children }) => {
const [language, setLanguage] = useState(initialLanguage);
useEffect(() => {
document.documentElement.lang = language;
}, [language]);
return (
<TranslationContext.Provider
value={{
language,
setLanguage,
availableLanguages: Object.keys(LANGUAGES) as LanguageCode[],
}}
>
{children}
</TranslationContext.Provider>
);
};💬 Usage in Components
import { useTranslation } from '@plyaz/translations';
const LoginForm = () => {
const { t } = useTranslation();
return (
<form>
<h2>{t('auth.login_title')}</h2>
<label>
{t('auth.email_label')}
<input type='email' placeholder={t('auth.email_placeholder')} />
</label>
<button type='submit'>{t('common.submit')}</button>
</form>
);
};Backend Integration (NestJS)
📦 Module
@Global()
@Module({
providers: [TranslationService],
exports: [TranslationService],
})
export class TranslationModule {}🔧 Service
@Injectable()
export class TranslationService {
translate(
key: TranslationKey,
language: string = 'en',
params?: Record<string, string | number>
): string {
return translate(key, language, params);
}
getAvailableLanguages() {
return Object.keys(LANGUAGES);
}
}🔄 Usage in Controller
@Controller('users')
export class UserController {
constructor(
private userService: UserService,
private translationService: TranslationService
) {}
@Get(':id')
async getUser(@Param('id') id: string) {
const user = await this.userService.findById(id);
if (!user) {
throw new NotFoundError(
this.translationService.translate('resource.not_found', 'en', {
entity: 'User',
})
);
}
return user;
}
}