Home4/src/main/angular/src/app/api/CrudLiveList.ts

63 lines
1.4 KiB
TypeScript

import {CrudService} from "./CrudService";
import {Subscription} from "rxjs";
import {Next} from './types';
interface UUID {
uuid: string;
}
export class CrudLiveList<ENTITY extends UUID> extends Subscription {
private readonly subs: Subscription[] = [];
private unfiltered: ENTITY[] = [];
list: ENTITY[] = [];
constructor(
readonly crudService: CrudService<ENTITY>,
readonly allowAppending: boolean,
readonly filter: (item: ENTITY) => boolean = _ => true,
readonly all: (next: Next<ENTITY[]>) => any = next => this.crudService.list(next),
readonly equals: (a: ENTITY, b: ENTITY) => boolean = (a, b) => a.uuid === b.uuid,
) {
super(() => {
this.subs.forEach(sub => sub.unsubscribe());
});
this.subs.push(crudService.api.connected(_ => this.refresh()));
this.subs.push(crudService.subscribe(item => this.update(item)));
}
refresh() {
this.all(list => {
this.unfiltered = list;
this.updateFiltered();
});
}
clear() {
this.unfiltered = [];
this.updateFiltered();
}
private update(item: ENTITY) {
const index = this.unfiltered.findIndex(i => this.equals(i, item));
if (index >= 0) {
this.unfiltered[index] = item;
} else {
if (!this.allowAppending) {
return;
}
this.unfiltered.push(item);
}
this.updateFiltered();
}
private updateFiltered() {
this.list = this.unfiltered.filter(this.filter);
}
}