fix: create stringService

This commit is contained in:
cihatata authored and cihat committed 2025-02-11 07:43:38 +03:00
1 parent e18f1d9b85
commit 6fc0e31743
10 files changed
+760 -86

No files matched your search

+102
View File
@@ -13,6 +13,8 @@ const UPROCK_ENDPOINT = "https://api.uprock.com/checkmate/push";
*/
class NetworkService {
static SERVICE_NAME = SERVICE_NAME;
static POEDITOR_BASE_URL = 'https://api.poeditor.com/v2';
constructor(axios, ping, logger, http, Docker, net) {
this.TYPE_PING = "ping";
this.TYPE_HTTP = "http";
@@ -30,6 +32,17 @@ class NetworkService {
this.http = http;
this.Docker = Docker;
this.net = net;
this.apiToken = process.env.POEDITOR_API_TOKEN;
this.projectId = process.env.POEDITOR_PROJECT_ID;
if (!this.apiToken || !this.projectId) {
this.logger.error({
message: 'POEditor API token or project ID is missing in environment variables',
service: this.SERVICE_NAME,
method: 'constructor'
});
}
}
/**
@@ -398,6 +411,95 @@ class NetworkService {
return this.handleUnsupportedType(type);
}
}
async getPoEditorLanguages() {
try {
const params = new URLSearchParams();
params.append('api_token', this.apiToken);
params.append('id', this.projectId);
const response = await this.axios.post(`${NetworkService.POEDITOR_BASE_URL}/languages/list`, params, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
return response.data.result.languages.map(lang => lang.code);
} catch (error) {
error.service = this.SERVICE_NAME;
error.method = "getPoEditorLanguages";
throw error;
}
}
async exportPoEditorTranslations(language) {
try {
const params = new URLSearchParams();
params.append('api_token', this.apiToken);
params.append('id', this.projectId);
params.append('language', language);
params.append('type', 'key_value_json');
const exportResponse = await this.axios.post(`${NetworkService.POEDITOR_BASE_URL}/projects/export`, params, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
const { url } = exportResponse.data.result;
const translationsResponse = await this.axios.get(url);
return translationsResponse.data;
} catch (error) {
error.service = this.SERVICE_NAME;
error.method = "exportPoEditorTranslations";
throw error;
}
}
async getPoEditorTerms() {
try {
const params = new URLSearchParams();
params.append('api_token', this.apiToken);
params.append('id', this.projectId);
const response = await this.axios.post(`${NetworkService.POEDITOR_BASE_URL}/terms/list`, params, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
return response.data.result?.terms?.map(term => term.term.trim()) || [];
} catch (error) {
error.service = this.SERVICE_NAME;
error.method = "getPoEditorTerms";
throw error;
}
}
async addPoEditorTerms(terms) {
try {
const formattedTerms = terms.map(termObj => ({
term: Object.keys(termObj)[0]
}));
const params = new URLSearchParams();
params.append('api_token', this.apiToken);
params.append('id', this.projectId);
params.append('data', JSON.stringify(formattedTerms));
const response = await this.axios.post(`${NetworkService.POEDITOR_BASE_URL}/terms/add`, params, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
return response.data;
} catch (error) {
error.service = this.SERVICE_NAME;
error.method = "addPoEditorTerms";
throw error;
}
}
}
export default NetworkService;
+322
View File
@@ -0,0 +1,322 @@
class StringService {
static SERVICE_NAME = "StringService";
constructor(translationService) {
if (StringService.instance) {
return StringService.instance;
}
this.translationService = translationService;
this._language = 'en'; // default language
StringService.instance = this;
}
setLanguage(language) {
this._language = language;
}
get language() {
return this._language;
}
// Auth Messages
get dontHaveAccount() {
return this.translationService.getTranslation('dontHaveAccount');
}
get email() {
return this.translationService.getTranslation('email');
}
get forgotPassword() {
return this.translationService.getTranslation('forgotPassword');
}
get password() {
return this.translationService.getTranslation('password');
}
get signUp() {
return this.translationService.getTranslation('signUp');
}
get submit() {
return this.translationService.getTranslation('submit');
}
get title() {
return this.translationService.getTranslation('title');
}
get continue() {
return this.translationService.getTranslation('continue');
}
get enterEmail() {
return this.translationService.getTranslation('enterEmail');
}
get authLoginTitle() {
return this.translationService.getTranslation('authLoginTitle');
}
get authLoginEnterPassword() {
return this.translationService.getTranslation('authLoginEnterPassword');
}
get commonPassword() {
return this.translationService.getTranslation('commonPassword');
}
get commonBack() {
return this.translationService.getTranslation('commonBack');
}
get authForgotPasswordTitle() {
return this.translationService.getTranslation('authForgotPasswordTitle');
}
get authForgotPasswordResetPassword() {
return this.translationService.getTranslation('authForgotPasswordResetPassword');
}
get createPassword() {
return this.translationService.getTranslation('createPassword');
}
get createAPassword() {
return this.translationService.getTranslation('createAPassword');
}
get authRegisterAlreadyHaveAccount() {
return this.translationService.getTranslation('authRegisterAlreadyHaveAccount');
}
get commonAppName() {
return this.translationService.getTranslation('commonAppName');
}
get authLoginEnterEmail() {
return this.translationService.getTranslation('authLoginEnterEmail');
}
get authRegisterTitle() {
return this.translationService.getTranslation('authRegisterTitle');
}
get monitorGetAll() {
return this.translationService.getTranslation('monitorGetAll');
}
get monitorGetById() {
return this.translationService.getTranslation('monitorGetById');
}
get monitorCreate() {
return this.translationService.getTranslation('monitorCreate');
}
get monitorEdit() {
return this.translationService.getTranslation('monitorEdit');
}
get monitorDelete() {
return this.translationService.getTranslation('monitorDelete');
}
get monitorPause() {
return this.translationService.getTranslation('monitorPause');
}
get monitorResume() {
return this.translationService.getTranslation('monitorResume');
}
get monitorDemoAdded() {
return this.translationService.getTranslation('monitorDemoAdded');
}
get monitorStatsById() {
return this.translationService.getTranslation('monitorStatsById');
}
get monitorCertificate() {
return this.translationService.getTranslation('monitorCertificate');
}
// Maintenance Window Messages
get maintenanceWindowCreate() {
return this.translationService.getTranslation('maintenanceWindowCreate');
}
get maintenanceWindowGetById() {
return this.translationService.getTranslation('maintenanceWindowGetById');
}
get maintenanceWindowGetByTeam() {
return this.translationService.getTranslation('maintenanceWindowGetByTeam');
}
get maintenanceWindowDelete() {
return this.translationService.getTranslation('maintenanceWindowDelete');
}
get maintenanceWindowEdit() {
return this.translationService.getTranslation('maintenanceWindowEdit');
}
// Error Messages
get unknownError() {
return this.translationService.getTranslation('unknownError');
}
get friendlyError() {
return this.translationService.getTranslation('friendlyError');
}
get authIncorrectPassword() {
return this.translationService.getTranslation('authIncorrectPassword');
}
get unauthorized() {
return this.translationService.getTranslation('unauthorized');
}
get authAdminExists() {
return this.translationService.getTranslation('authAdminExists');
}
get authInviteNotFound() {
return this.translationService.getTranslation('authInviteNotFound');
}
get unknownService() {
return this.translationService.getTranslation('unknownService');
}
get noAuthToken() {
return this.translationService.getTranslation('noAuthToken');
}
get invalidAuthToken() {
return this.translationService.getTranslation('invalidAuthToken');
}
get expiredAuthToken() {
return this.translationService.getTranslation('expiredAuthToken');
}
// Queue Messages
get queueGetMetrics() {
return this.translationService.getTranslation('queueGetMetrics');
}
get queueAddJob() {
return this.translationService.getTranslation('queueAddJob');
}
get queueObliterate() {
return this.translationService.getTranslation('queueObliterate');
}
// Job Queue Messages
get jobQueueDeleteJobSuccess() {
return this.translationService.getTranslation('jobQueueDeleteJobSuccess');
}
get jobQueuePauseJob() {
return this.translationService.getTranslation('jobQueuePauseJob');
}
get jobQueueResumeJob() {
return this.translationService.getTranslation('jobQueueResumeJob');
}
// Status Page Messages
get statusPageByUrl() {
return this.translationService.getTranslation('statusPageByUrl');
}
get statusPageCreate() {
return this.translationService.getTranslation('statusPageCreate');
}
get statusPageNotFound() {
return this.translationService.getTranslation('statusPageNotFound');
}
get statusPageUrlNotUnique() {
return this.translationService.getTranslation('statusPageUrlNotUnique');
}
// Docker Messages
get dockerFail() {
return this.translationService.getTranslation('dockerFail');
}
get dockerNotFound() {
return this.translationService.getTranslation('dockerNotFound');
}
get dockerSuccess() {
return this.translationService.getTranslation('dockerSuccess');
}
// Port Messages
get portFail() {
return this.translationService.getTranslation('portFail');
}
get portSuccess() {
return this.translationService.getTranslation('portSuccess');
}
// Alert Messages
get alertCreate() {
return this.translationService.getTranslation('alertCreate');
}
get alertGetByUser() {
return this.translationService.getTranslation('alertGetByUser');
}
get alertGetByMonitor() {
return this.translationService.getTranslation('alertGetByMonitor');
}
get alertGetById() {
return this.translationService.getTranslation('alertGetById');
}
get alertEdit() {
return this.translationService.getTranslation('alertEdit');
}
get alertDelete() {
return this.translationService.getTranslation('alertDelete');
}
getDeletedCount(count) {
return this.translationService.getTranslation('deletedCount')
.replace('{count}', count);
}
get pingSuccess() {
return this.translationService.getTranslation('pingSuccess');
}
get getAppSettings() {
return this.translationService.getTranslation('getAppSettings');
}
get updateAppSettings() {
return this.translationService.getTranslation('updateAppSettings');
}
getDbFindMonitorById(monitorId) {
return this.translationService.getTranslation('dbFindMonitorById')
.replace('${monitorId}', monitorId);
}
}
export default StringService;
+146 -39
View File
@@ -1,27 +1,34 @@
import axios from 'axios';
import fs from 'fs';
import path from 'path';
import { formattedKey } from '../utils/formattedKey.js';
class TranslationService {
static SERVICE_NAME = 'TranslationService';
constructor(logger) {
constructor(logger, networkService) {
this.logger = logger;
this.networkService = networkService;
this.translations = {};
this.apiToken = process.env.POEDITOR_API_TOKEN;
this.projectId = process.env.POEDITOR_PROJECT_ID;
this.baseUrl = 'https://api.poeditor.com/v2';
this._language = 'en';
this.localesDir = path.join(process.cwd(), 'locales');
}
setLanguage(language) {
this._language = language;
}
get language() {
return this._language;
}
async initialize() {
try {
const loadedFromFiles = await this.loadFromFiles();
if (!loadedFromFiles) {
await this.loadTranslations();
}
// Yeni eklenen terimleri POEditor'e gönder
await this.syncTermsWithPOEditor();
} catch (error) {
this.logger.error({
message: error.message,
@@ -70,16 +77,47 @@ class TranslationService {
}
async loadTranslations() {
let hasError = false;
try {
const languages = await this.getLanguages();
for (const language of languages) {
const translations = await this.exportTranslations(language);
this.translations[language] = translations;
try {
const translations = await this.exportTranslations(language);
this.translations[language] = translations;
} catch (error) {
hasError = true;
this.logger.error({
message: `Failed to fetch translations from POEditor for language ${language}: ${error.message}`,
service: 'TranslationService',
method: 'loadTranslations',
stack: error.stack
});
}
}
if (hasError || Object.keys(this.translations[this._language]).length === 0) {
this.logger.error({
message: 'Failed to fetch translations from POEditor, using locales_en.json',
service: 'TranslationService',
method: 'loadTranslations'
});
// Load translations from locales_en.json in utils directory
const utilsPath = path.join(process.cwd(), 'utils');
const utilsFilePath = path.join(utilsPath, 'locales_en.json');
if (fs.existsSync(utilsFilePath)) {
const content = fs.readFileSync(utilsFilePath, 'utf8');
this.translations['en'] = JSON.parse(content);
} else {
throw new Error('locales_en.json file not found');
}
}
await this.saveTranslations();
} catch (error) {
hasError = true;
this.logger.error({
message: error.message,
service: 'TranslationService',
@@ -91,17 +129,7 @@ class TranslationService {
async getLanguages() {
try {
const params = new URLSearchParams();
params.append('api_token', this.apiToken);
params.append('id', this.projectId);
const response = await axios.post(`${this.baseUrl}/languages/list`, params, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
return response.data.result.languages.map(lang => lang.code);
return await this.networkService.getPoEditorLanguages();
} catch (error) {
this.logger.error({
message: error.message,
@@ -115,22 +143,7 @@ class TranslationService {
async exportTranslations(language) {
try {
const params = new URLSearchParams();
params.append('api_token', this.apiToken);
params.append('id', this.projectId);
params.append('language', language);
params.append('type', 'key_value_json');
const exportResponse = await axios.post(`${this.baseUrl}/projects/export`, params, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
const { url } = exportResponse.data.result;
const translationsResponse = await axios.get(url);
return translationsResponse.data;
return await this.networkService.exportPoEditorTranslations(language);
} catch (error) {
this.logger.error({
message: error.message,
@@ -153,6 +166,11 @@ class TranslationService {
fs.writeFileSync(filePath, JSON.stringify(translations, null, 2));
}
const utilsPath = path.join(process.cwd(), 'utils');
const enTranslations = this.translations['en'] || {};
const utilsFilePath = path.join(utilsPath, 'locales_en.json');
fs.writeFileSync(utilsFilePath, JSON.stringify(enTranslations, null, 2));
this.logger.info({
message: 'Translations saved to files successfully',
service: 'TranslationService',
@@ -168,10 +186,11 @@ class TranslationService {
}
}
getTranslation(key, language = 'en') {
const formattedKeyText = formattedKey(key);
getTranslation(key) {
let language = this._language;
try {
return this.translations[language]?.[formattedKeyText] || this.translations['en']?.[formattedKeyText] || formattedKeyText;
return this.translations[language]?.[key] || this.translations['en']?.[key] || key;
} catch (error) {
this.logger.error({
message: error.message,
@@ -182,6 +201,94 @@ class TranslationService {
return key;
}
}
async getTermsFromPOEditor() {
try {
return await this.networkService.getPoEditorTerms();
} catch (error) {
this.logger.error({
message: error.message,
service: 'TranslationService',
method: 'getTermsFromPOEditor',
stack: error.stack
});
return [];
}
}
async addTermsToPOEditor(terms) {
try {
if (!terms.length) return;
const response = await this.networkService.addPoEditorTerms(terms);
if (response.response?.status === 'fail') {
throw new Error(response.response.message || 'Failed to add terms to POEditor');
}
this.logger.info({
message: `${terms.length} new terms added to POEditor`,
service: 'TranslationService',
method: 'addTermsToPOEditor',
response: response
});
return response;
} catch (error) {
this.logger.error({
message: `Failed to add terms to POEditor: ${error.message}`,
service: 'TranslationService',
method: 'addTermsToPOEditor',
stack: error.stack,
terms: terms
});
throw error;
}
}
async syncTermsWithPOEditor() {
try {
const utilsPath = path.join(process.cwd(), 'utils');
const utilsFilePath = path.join(utilsPath, 'locales_en.json');
const enTranslations = JSON.parse(fs.readFileSync(utilsFilePath, 'utf8'));
const localTerms = Object.keys(enTranslations)
.map(term => term);
const poeditorTerms = await this.getTermsFromPOEditor();
const newTerms = localTerms?.filter(term => !poeditorTerms?.includes(term));
this.logger.info({
message: `Comparison results - New terms found: ${newTerms.length}`,
sampleNewTerms: newTerms.slice(0, 5),
service: 'TranslationService',
method: 'syncTermsWithPOEditor'
});
if (newTerms.length > 0) {
const formattedTerms = newTerms.map(term => ({
[term]: enTranslations[term] || '',
}));
await this.addTermsToPOEditor(formattedTerms);
} else {
this.logger.info({
message: 'No new terms found to synchronize',
service: 'TranslationService',
method: 'syncTermsWithPOEditor'
});
}
} catch (error) {
this.logger.error({
message: error.message,
service: 'TranslationService',
method: 'syncTermsWithPOEditor',
stack: error.stack
});
}
}
}
export default TranslationService;