Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: improve detecting missing translations #659

Merged
merged 6 commits into from
Jun 10, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions src/app/app.server.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,13 @@ import { AppComponent } from './app.component';
import { AppModule } from './app.module';

export class UniversalErrorHandler implements ErrorHandler {
handleError(error: Error): void {
handleError(error: unknown): void {
if (error instanceof HttpErrorResponse) {
console.error('ERROR', error.message);
} else {
} else if (error instanceof Error) {
console.error('ERROR', error.name, error.message, error.stack?.split('\n')?.[1]?.trim());
} else {
console.error('ERROR', error?.toString());
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/app/core/configurations/ngrx-state-transfer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { mergeDeep } from 'ish-core/utils/functions';

export const NGRX_STATE_SK = makeStateKey<object>('ngrxState');

const STATE_ACTION_TYPE = '[Internal] Import NgRx State';
export const STATE_ACTION_TYPE = '[Internal] Import NgRx State';

let transferredState: object;

Expand Down
4 changes: 0 additions & 4 deletions src/app/core/configurations/state-keys.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,7 @@
import { makeStateKey } from '@angular/platform-browser';

import { Translations } from 'ish-core/internationalization.module';

export const DISPLAY_VERSION = makeStateKey<string>('displayVersion');

export const COOKIE_CONSENT_VERSION = makeStateKey<number>('cookieConsentVersion');

export const SSR_LOCALE = makeStateKey<string>('ssrLocale');

export const SSR_TRANSLATIONS = makeStateKey<Translations>('ssrTranslation');
92 changes: 12 additions & 80 deletions src/app/core/internationalization.module.ts
Original file line number Diff line number Diff line change
@@ -1,94 +1,26 @@
import { isPlatformBrowser, isPlatformServer, registerLocaleData } from '@angular/common';
import { HttpClient } from '@angular/common/http';
import { registerLocaleData } from '@angular/common';
import localeDe from '@angular/common/locales/de';
import localeFr from '@angular/common/locales/fr';
import { Inject, Injectable, LOCALE_ID, NgModule, PLATFORM_ID } from '@angular/core';
import { Inject, LOCALE_ID, NgModule } from '@angular/core';
import { TransferState } from '@angular/platform-browser';
import { Store, select } from '@ngrx/store';
import { TranslateLoader, TranslateModule, TranslateService } from '@ngx-translate/core';
import { from, of } from 'rxjs';
import { catchError, map, switchMap, take, tap, withLatestFrom } from 'rxjs/operators';
import { MissingTranslationHandler, TranslateLoader, TranslateModule, TranslateService } from '@ngx-translate/core';

import { SSR_LOCALE, SSR_TRANSLATIONS } from './configurations/state-keys';
import { getCurrentLocale, getRestEndpoint } from './store/core/configuration';
import { whenTruthy } from './utils/operators';

export type Translations = Record<string, string | Record<string, string>>;

function maybeJSON(val: string) {
if (val.startsWith('{')) {
try {
return JSON.parse(val);
} catch {
// default
}
}
return val;
}

function filterAndTransformKeys(translations: Record<string, string>): Translations {
return Object.entries(translations)
.filter(([key]) => key.startsWith('pwa-'))
.map(([key, value]) => [key.substring(4), maybeJSON(value)])
.reduce((acc, [key, value]) => ({ ...acc, [key]: value }), {});
}

@Injectable()
class ICMTranslateLoader implements TranslateLoader {
constructor(
private httpClient: HttpClient,
private transferState: TransferState,
@Inject(PLATFORM_ID) private platformId: string,
private store: Store
) {}

getTranslation(lang: string) {
if (isPlatformBrowser(this.platformId) && this.transferState.hasKey(SSR_TRANSLATIONS)) {
return of(this.transferState.get(SSR_TRANSLATIONS, undefined));
}
const local$ = from(import(`../../assets/i18n/${lang}.json`)).pipe(
catchError(() =>
this.store.pipe(
select(getCurrentLocale),
whenTruthy(),
take(1),
switchMap(defaultLang => from(import(`../../assets/i18n/${defaultLang}.json`)))
)
)
);
return this.store.pipe(
select(getRestEndpoint),
whenTruthy(),
take(1),
switchMap(url =>
this.httpClient.get(`${url};loc=${lang}/localizations`, {
params: {
searchKeys: 'pwa-',
},
})
),
map(filterAndTransformKeys),
withLatestFrom(local$),
map(([translations, localTranslations]) => ({
...localTranslations,
...translations,
})),
tap((translations: Translations) => {
if (isPlatformServer(this.platformId)) {
this.transferState.set(SSR_TRANSLATIONS, translations);
}
}),
catchError(() => local$)
);
}
}
import { SSR_LOCALE } from './configurations/state-keys';
import {
FALLBACK_LANG,
FallbackMissingTranslationHandler,
} from './utils/translate/fallback-missing-translation-handler';
import { ICMTranslateLoader } from './utils/translate/icm-translate-loader';

@NgModule({
imports: [
TranslateModule.forRoot({
loader: { provide: TranslateLoader, useClass: ICMTranslateLoader },
missingTranslationHandler: { provide: MissingTranslationHandler, useClass: FallbackMissingTranslationHandler },
useDefaultLang: false,
}),
],
providers: [{ provide: FALLBACK_LANG, useValue: 'en_US' }],
})
export class InternationalizationModule {
constructor(
Expand Down
21 changes: 21 additions & 0 deletions src/app/core/services/localizations/localizations.service.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { TestBed } from '@angular/core/testing';
import { provideMockStore } from '@ngrx/store/testing';

import { LocalizationsService } from './localizations.service';

describe('Localizations Service', () => {
let localizationsService: LocalizationsService;

beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [provideMockStore()],
});
localizationsService = TestBed.inject(LocalizationsService);
});

it('should be created', () => {
expect(localizationsService).toBeTruthy();
});
});
57 changes: 57 additions & 0 deletions src/app/core/services/localizations/localizations.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Store, select } from '@ngrx/store';
import { Observable, of } from 'rxjs';
import { catchError, concatMap, map, take } from 'rxjs/operators';

import { getRestEndpoint } from 'ish-core/store/core/configuration';
import { whenTruthy } from 'ish-core/utils/operators';
import { Translations } from 'ish-core/utils/translate/translations.type';

function maybeJSON(val: string) {
if (val.startsWith('{')) {
try {
return JSON.parse(val);
} catch {
// default
}
}
return val;
}

function filterAndTransformKeys(translations: Record<string, string>): Translations {
return Object.entries(translations)
.filter(([key]) => key.startsWith('pwa-'))
.map(([key, value]) => [key.substring(4), maybeJSON(value)])
.reduce((acc, [key, value]) => ({ ...acc, [key]: value }), {});
}

@Injectable({ providedIn: 'root' })
export class LocalizationsService {
private icmEndpoint$: Observable<string>;

constructor(private httpClient: HttpClient, store: Store) {
this.icmEndpoint$ = store.pipe(select(getRestEndpoint), whenTruthy(), take(1));
}

getServerTranslations(lang: string) {
return this.icmEndpoint$.pipe(
concatMap(url =>
this.httpClient
.get(`${url};loc=${lang}/localizations`, {
params: {
searchKeys: 'pwa-',
},
})
.pipe(map(filterAndTransformKeys))
)
);
}

getSpecificTranslation(lang: string, key: string) {
return this.icmEndpoint$.pipe(
concatMap(url => this.httpClient.get(`${url};loc=${lang}/localizations/${key}`, { responseType: 'text' })),
catchError(() => of(''))
);
}
}
28 changes: 27 additions & 1 deletion src/app/core/store/core/configuration/configuration.actions.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,35 @@
import { createAction } from '@ngrx/store';

import { payload } from 'ish-core/utils/ngrx-creators';
import { httpError, payload } from 'ish-core/utils/ngrx-creators';
import { Translations } from 'ish-core/utils/translate/translations.type';

import { ConfigurationState } from './configuration.reducer';

type ConfigurationType = Partial<ConfigurationState>;

export const applyConfiguration = createAction('[Configuration] Apply Configuration', payload<ConfigurationType>());

export const loadServerTranslations = createAction(
'[Configuration] Load Server Translations',
payload<{ lang: string }>()
);

export const loadServerTranslationsSuccess = createAction(
'[Configuration] Load Server Translations Success',
payload<{ lang: string; translations: Translations }>()
);

export const loadServerTranslationsFail = createAction(
'[Configuration] Load Server Translations Fail',
httpError<{ lang: string }>()
);

export const loadSingleServerTranslation = createAction(
'[Configuration] Load Single Server Translation',
payload<{ lang: string; key: string }>()
);

export const loadSingleServerTranslationSuccess = createAction(
'[Configuration] Load Single Server Translation Success',
payload<{ lang: string; key: string; translation: string }>()
);
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@ import { Action } from '@ngrx/store';
import { TranslateModule, TranslateService } from '@ngx-translate/core';
import { Observable, Subject, of } from 'rxjs';
import { take } from 'rxjs/operators';
import { instance, mock } from 'ts-mockito';

import { LocalizationsService } from 'ish-core/services/localizations/localizations.service';
import { CoreStoreModule } from 'ish-core/store/core/core-store.module';

import { applyConfiguration } from './configuration.actions';
Expand All @@ -24,7 +26,10 @@ describe('Configuration Effects', () => {
CoreStoreModule.forTesting(['configuration', 'serverConfig'], [ConfigurationEffects]),
TranslateModule.forRoot(),
],
providers: [provideMockActions(() => actions$)],
providers: [
provideMockActions(() => actions$),
{ provide: LocalizationsService, useFactory: () => instance(mock(LocalizationsService)) },
],
});

effects = TestBed.inject(ConfigurationEffects);
Expand Down
55 changes: 48 additions & 7 deletions src/app/core/store/core/configuration/configuration.effects.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,11 @@ import { Store, select } from '@ngrx/store';
import { TranslateService } from '@ngx-translate/core';
import { defer, fromEvent, iif, merge } from 'rxjs';
import {
debounceTime,
distinct,
distinctUntilChanged,
map,
mapTo,
mergeMap,
shareReplay,
switchMap,
take,
Expand All @@ -21,10 +22,25 @@ import { LARGE_BREAKPOINT_WIDTH, MEDIUM_BREAKPOINT_WIDTH } from 'ish-core/config
import { NGRX_STATE_SK } from 'ish-core/configurations/ngrx-state-transfer';
import { SSR_LOCALE } from 'ish-core/configurations/state-keys';
import { DeviceType } from 'ish-core/models/viewtype/viewtype.types';
import { distinctCompareWith, mapToProperty, whenTruthy } from 'ish-core/utils/operators';
import { LocalizationsService } from 'ish-core/services/localizations/localizations.service';
import {
distinctCompareWith,
mapErrorToAction,
mapToPayload,
mapToPayloadProperty,
mapToProperty,
whenTruthy,
} from 'ish-core/utils/operators';
import { StatePropertiesService } from 'ish-core/utils/state-transfer/state-properties.service';

import { applyConfiguration } from './configuration.actions';
import {
applyConfiguration,
loadServerTranslations,
loadServerTranslationsFail,
loadServerTranslationsSuccess,
loadSingleServerTranslation,
loadSingleServerTranslationSuccess,
} from './configuration.actions';
import { getCurrentLocale, getDeviceType } from './configuration.selectors';

@Injectable()
Expand All @@ -38,7 +54,8 @@ export class ConfigurationEffects {
@Inject(MEDIUM_BREAKPOINT_WIDTH) private mediumBreakpointWidth: number,
@Inject(LARGE_BREAKPOINT_WIDTH) private largeBreakpointWidth: number,
translateService: TranslateService,
appRef: ApplicationRef
appRef: ApplicationRef,
private localizationsService: LocalizationsService
) {
appRef.isStable
.pipe(takeWhile(() => isPlatformBrowser(platformId)))
Expand All @@ -53,12 +70,10 @@ export class ConfigurationEffects {
select(getCurrentLocale),
mapToProperty('lang'),
distinctUntilChanged(),
// https://github.com/ngx-translate/core/issues/1030
debounceTime(0),
whenTruthy(),
switchMap(lang => languageChanged$.pipe(mapTo(lang), take(1)))
)
.subscribe((lang: string) => {
.subscribe(lang => {
dhhyi marked this conversation as resolved.
Show resolved Hide resolved
this.transferState.set(SSR_LOCALE, lang);
translateService.use(lang);
});
Expand Down Expand Up @@ -136,4 +151,30 @@ export class ConfigurationEffects {
)
)
);

loadServerTranslations$ = createEffect(() =>
this.actions$.pipe(
ofType(loadServerTranslations),
mapToPayloadProperty('lang'),
distinct(),
mergeMap(lang =>
this.localizationsService.getServerTranslations(lang).pipe(
map(translations => loadServerTranslationsSuccess({ lang, translations })),
mapErrorToAction(loadServerTranslationsFail, { lang })
)
)
)
);

loadSingleServerTranslation$ = createEffect(() =>
this.actions$.pipe(
ofType(loadSingleServerTranslation),
mapToPayload(),
mergeMap(({ lang, key }) =>
this.localizationsService
.getSpecificTranslation(lang, key)
.pipe(map(translation => loadSingleServerTranslationSuccess({ lang, key, translation })))
)
)
);
}
Loading