refactor(settings): replace unsubscribe logic with takeUntilDestroyed for better resource management (#443)

* refactor(settings): replace unsubscribe logic with takeUntilDestroyed for better resource management

* refactor(settings): streamline saveSettings method and improve error handling

* fix(settings): improve error handling in saveSetting method

* refactor(settings): update tab structure

* refactor(settings): implement OnDestroy interface and clean up unused destroyRef instances
This commit is contained in:
brios
2026-04-22 17:27:11 -04:00
committed by Zach Yale
parent 85e8d235b6
commit 7abac02b0c
25 changed files with 218 additions and 180 deletions
@@ -15,7 +15,6 @@ import { AuthService } from '../../service/auth.service';
import { UserService } from '../../../features/settings/user-management/user.service';
import { Popover } from 'primeng/popover';
import { MetadataProgressService } from '../../service/metadata-progress.service';
import { MetadataBatchProgressNotification } from '../../model/metadata-batch-progress.model';
import { BookdropFileService } from '../../../features/bookdrop/service/bookdrop-file.service';
import { DialogLauncherService } from '../../services/dialog-launcher.service';
@@ -69,8 +68,8 @@ export class AppTopBarComponent implements OnDestroy {
hasAnyTasks = false;
hasPendingBookdropFiles = false;
private eventTimer: number | undefined;
private readonly destroyRef = inject(DestroyRef);
private eventTimer: number | undefined;
private latestTasks: Record<string, MetadataBatchProgressNotification> = {};
private latestHasPendingFiles = false;
@@ -85,6 +84,8 @@ export class AppTopBarComponent implements OnDestroy {
this.subscribeToMetadataProgress();
this.subscribeToNotifications();
this.destroyRef.onDestroy(() => clearTimeout(this.eventTimer));
this.metadataProgressService.activeTasks$
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe((tasks) => {
@@ -158,7 +159,7 @@ export class AppTopBarComponent implements OnDestroy {
switchLanguage(lang: string) {
if (lang === this.activeLang) return;
this.translocoService.load(lang).subscribe(() => {
this.translocoService.load(lang).pipe(takeUntilDestroyed(this.destroyRef)).subscribe(() => {
this.translocoService.setActiveLang(lang);
localStorage.setItem(LANG_STORAGE_KEY, lang);
this.activeLang = lang;
@@ -1,7 +1,7 @@
import {computed, effect, inject, Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {lastValueFrom, Observable, of} from 'rxjs';
import {catchError, map, switchMap} from 'rxjs/operators';
import {lastValueFrom, Observable} from 'rxjs';
import {map, switchMap} from 'rxjs/operators';
import {API_CONFIG} from '../../core/config/api-config';
import {AppSettings, OidcProviderDetails, OidcTestResult} from '../model/app-settings.model';
import {AuthService} from './auth.service';
@@ -99,15 +99,8 @@ export class AppSettingsService {
}));
return this.http.put<void>(this.apiUrl, payload).pipe(
switchMap(() => {
void this.queryClient.invalidateQueries({queryKey: APP_SETTINGS_QUERY_KEY});
return of(void 0);
}),
map(() => void 0),
catchError(err => {
console.error('Error saving settings:', err);
return of();
})
switchMap(() => this.queryClient.invalidateQueries({queryKey: APP_SETTINGS_QUERY_KEY})),
map(() => void 0)
);
}
@@ -121,10 +114,6 @@ export class AppSettingsService {
this.queryClient.setQueryData(APP_SETTINGS_QUERY_KEY, updated);
this.syncPublicSettings(updated);
}
}),
catchError(err => {
console.error('Error toggling OIDC:', err);
return of();
})
);
}
@@ -1,6 +1,6 @@
import {TestBed} from '@angular/core/testing';
import {MessageService} from 'primeng/api';
import {firstValueFrom, of, throwError} from 'rxjs';
import {of, throwError} from 'rxjs';
import {beforeEach, describe, expect, it, vi} from 'vitest';
import {TranslocoService} from '@jsverse/transloco';
@@ -39,10 +39,10 @@ describe('SettingsHelperService', () => {
service = TestBed.inject(SettingsHelperService);
});
it('saves a setting and shows a success message', async () => {
it('saves a setting and shows a success message', () => {
appSettingsService.saveSettings.mockReturnValue(of(undefined));
await firstValueFrom(service.saveSetting('theme', 'dark'));
service.saveSetting('theme', 'dark');
expect(appSettingsService.saveSettings).toHaveBeenCalledWith([{key: 'theme', newValue: 'dark'}]);
expect(messageService.add).toHaveBeenCalledWith({
@@ -52,12 +52,12 @@ describe('SettingsHelperService', () => {
});
});
it('shows an error message when saving fails', async () => {
it('shows an error message when saving fails', () => {
const error = new Error('save failed');
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined);
appSettingsService.saveSettings.mockReturnValue(throwError(() => error));
await expect(firstValueFrom(service.saveSetting('theme', 'dark'))).rejects.toThrow('save failed');
service.saveSetting('theme', 'dark');
expect(errorSpy).toHaveBeenCalledWith('Failed to save setting:', error);
expect(messageService.add).toHaveBeenCalledWith({
@@ -1,8 +1,9 @@
import {Injectable, inject} from '@angular/core';
import {of} from 'rxjs';
import {AppSettingsService} from './app-settings.service';
import {MessageService} from 'primeng/api';
import {TranslocoService} from '@jsverse/transloco';
import {Observable} from 'rxjs';
import {catchError, map} from 'rxjs/operators';
@Injectable({
providedIn: 'root'
@@ -13,18 +14,20 @@ export class SettingsHelperService {
private readonly messageService = inject(MessageService);
private readonly t = inject(TranslocoService);
saveSetting(key: string, value: unknown): Observable<void> {
const observable = this.appSettingsService.saveSettings([{key, newValue: value}]);
observable.subscribe({
next: () => this.showSuccessMessage(),
error: (error) => {
saveSetting(key: string, value: unknown): void {
this.appSettingsService.saveSettings([{key, newValue: value}]).pipe(
map(() => true),
catchError((error) => {
console.error('Failed to save setting:', error);
return of(false);
})
).subscribe((saved) => {
if (saved) {
this.showSuccessMessage();
} else {
this.showErrorMessage();
}
});
return observable;
}
private showSuccessMessage(): void {
@@ -17,6 +17,7 @@ export class NotificationEventService {
notificationHighlight$ = this.notificationHighlightSubject.asObservable();
private highlightTimeout: ReturnType<typeof setTimeout> | undefined;
private clearTimeout: ReturnType<typeof setTimeout> | undefined;
handleNewNotification(notification: LogNotification): void {
this.latestNotificationSubject.next(notification);
@@ -25,12 +26,15 @@ export class NotificationEventService {
if (this.highlightTimeout) {
clearTimeout(this.highlightTimeout);
}
if (this.clearTimeout) {
clearTimeout(this.clearTimeout);
}
this.highlightTimeout = setTimeout(() => {
this.notificationHighlightSubject.next(false);
}, 7500);
setTimeout(() => {
this.clearTimeout = setTimeout(() => {
if (!this.notificationHighlightSubject.value) {
this.latestNotificationSubject.next(null);
}