89 lines
2.6 KiB
TypeScript
89 lines
2.6 KiB
TypeScript
import { Injectable, inject } from '@angular/core';
|
|
import { Observable, of, map, shareReplay, catchError } from 'rxjs';
|
|
import { ApiService } from './api.service';
|
|
import { AuthService } from './auth.service';
|
|
import { ChannelWithSubscription } from '../models';
|
|
|
|
export interface ResolvedChannel {
|
|
channelId: string;
|
|
displayName: string;
|
|
internalName: string;
|
|
}
|
|
|
|
@Injectable({
|
|
providedIn: 'root'
|
|
})
|
|
export class ChannelCacheService {
|
|
private apiService = inject(ApiService);
|
|
private authService = inject(AuthService);
|
|
|
|
private channelsCache$: Observable<Map<string, ChannelWithSubscription>> | null = null;
|
|
|
|
getAllChannels(): Observable<ChannelWithSubscription[]> {
|
|
const userId = this.authService.getUserId();
|
|
if (!userId) {
|
|
return of([]);
|
|
}
|
|
return this.apiService.getChannels(userId, 'owned').pipe(
|
|
map(response => response.channels),
|
|
catchError(() => of([]))
|
|
);
|
|
}
|
|
|
|
resolveChannel(channelId: string): Observable<ResolvedChannel> {
|
|
return this.getChannelsMap().pipe(
|
|
map(channelsMap => {
|
|
const channel = channelsMap.get(channelId);
|
|
return {
|
|
channelId,
|
|
displayName: channel?.display_name || channel?.internal_name || channelId,
|
|
internalName: channel?.internal_name || channelId
|
|
};
|
|
})
|
|
);
|
|
}
|
|
|
|
resolveChannels(channelIds: string[]): Observable<Map<string, ResolvedChannel>> {
|
|
return this.getChannelsMap().pipe(
|
|
map(channelsMap => {
|
|
const resolved = new Map<string, ResolvedChannel>();
|
|
for (const channelId of channelIds) {
|
|
const channel = channelsMap.get(channelId);
|
|
resolved.set(channelId, {
|
|
channelId,
|
|
displayName: channel?.display_name || channel?.internal_name || channelId,
|
|
internalName: channel?.internal_name || channelId
|
|
});
|
|
}
|
|
return resolved;
|
|
})
|
|
);
|
|
}
|
|
|
|
private getChannelsMap(): Observable<Map<string, ChannelWithSubscription>> {
|
|
const userId = this.authService.getUserId();
|
|
if (!userId) {
|
|
return of(new Map());
|
|
}
|
|
|
|
if (!this.channelsCache$) {
|
|
this.channelsCache$ = this.apiService.getChannels(userId, 'owned').pipe(
|
|
map(response => {
|
|
const map = new Map<string, ChannelWithSubscription>();
|
|
for (const channel of response.channels) {
|
|
map.set(channel.channel_id, channel);
|
|
}
|
|
return map;
|
|
}),
|
|
catchError(() => of(new Map())),
|
|
shareReplay(1)
|
|
);
|
|
}
|
|
return this.channelsCache$;
|
|
}
|
|
|
|
clearCache(): void {
|
|
this.channelsCache$ = null;
|
|
}
|
|
}
|