39 lines
1.1 KiB
TypeScript
39 lines
1.1 KiB
TypeScript
import { Inject, Injectable, PLATFORM_ID } from '@angular/core';
|
|
import { isPlatformBrowser } from '@angular/common';
|
|
import { EMPTY, Observable, Subject, fromEvent, merge } from 'rxjs';
|
|
import { filter, map } from 'rxjs';
|
|
|
|
@Injectable({ providedIn: 'root' })
|
|
export class TenantSyncService {
|
|
private readonly storageKey = 'linegestao.tenants.updatedAt';
|
|
private readonly localChangesSubject = new Subject<void>();
|
|
readonly changes$: Observable<void>;
|
|
|
|
private readonly isBrowser: boolean;
|
|
|
|
constructor(@Inject(PLATFORM_ID) platformId: object) {
|
|
this.isBrowser = isPlatformBrowser(platformId);
|
|
|
|
const storageChanges$ = this.isBrowser
|
|
? fromEvent<StorageEvent>(window, 'storage').pipe(
|
|
filter((event) => event.key === this.storageKey && !!event.newValue),
|
|
map(() => void 0)
|
|
)
|
|
: EMPTY;
|
|
|
|
this.changes$ = merge(this.localChangesSubject.asObservable(), storageChanges$);
|
|
}
|
|
|
|
notifyTenantsChanged(): void {
|
|
this.localChangesSubject.next();
|
|
|
|
if (!this.isBrowser) return;
|
|
|
|
try {
|
|
localStorage.setItem(this.storageKey, String(Date.now()));
|
|
} catch {
|
|
// ignore
|
|
}
|
|
}
|
|
}
|