Paginated entities service: search support

This commit is contained in:
Adina Țeudan 2024-03-06 17:02:44 +02:00
parent 3ea4e45b87
commit bf628b33a2

View File

@ -19,6 +19,8 @@ interface PaginatedConfig<Options> {
readonly totalHits: number;
}
const DEFAULT_PAGE_SIZE = 100;
@Injectable()
/**
* By default, if no implementation (class) is provided, Class = Interface & IListable
@ -26,41 +28,65 @@ interface PaginatedConfig<Options> {
export class PaginatedEntitiesService<
Interface,
Class extends Interface & IListable<PrimaryKey>,
Options,
SearchOptions,
PrimaryKey extends Id = Class['id'],
> extends EntitiesService<Interface, Class, PrimaryKey> {
protected _currentConfig: PaginatedConfig<Options> = { options: {} as Options, page: 0, pageSize: 0, totalHits: 0 };
protected _currentConfig: PaginatedConfig<SearchOptions> = {
options: {} as SearchOptions,
page: 0,
pageSize: DEFAULT_PAGE_SIZE,
totalHits: 0,
};
get config(): PaginatedConfig<Options> {
searchQuery = '';
get config(): PaginatedConfig<SearchOptions> {
return this._currentConfig;
}
reloadPage(): Observable<Class[]> {
return this.loadPage(this._currentConfig.options, this._currentConfig.page, this._currentConfig.pageSize);
constructor() {
super();
console.log('PaginatedEntitiesService');
}
loadPage(options: Options = {} as Options, page = 0, size = 100): Observable<Class[]> {
return super._post<PaginatedResponse<Interface>>({ page, size, options }).pipe(
tap(
response =>
(this._currentConfig = {
options,
page: response.page,
pageSize: response.pageSize,
totalHits: response.totalHits,
}),
),
map(response => response.data),
mapEach(entity => (this._entityClass ? new this._entityClass(entity) : (entity as unknown as Class))),
tap((entities: Class[]) => this.setEntities(entities)),
);
updateSearchOptionsAndReloadPage(options: SearchOptions): Observable<Class[]> {
this._currentConfig = { ...this._currentConfig, options };
return this.loadPage();
}
reloadPage(): Observable<Class[]> {
return this.loadPage(this._currentConfig.page);
}
loadPage(page = 0, pageSize?: number): Observable<Class[]> {
const options = this._currentConfig.options;
return super
._post<PaginatedResponse<Interface>>({
page,
size: pageSize ?? this._currentConfig.pageSize,
options,
})
.pipe(
tap(
response =>
(this._currentConfig = {
options,
page: response.page,
pageSize: response.pageSize,
totalHits: response.totalHits,
}),
),
map(response => response.data),
mapEach(entity => (this._entityClass ? new this._entityClass(entity) : (entity as unknown as Class))),
tap((entities: Class[]) => this.setEntities(entities)),
);
}
loadNextPage(): Observable<Class[]> {
return this.loadPage(this._currentConfig.options, this._currentConfig.page + 1, this._currentConfig.pageSize);
return this.loadPage(this._currentConfig.page + 1);
}
loadPreviousPage(): Observable<Class[]> {
return this.loadPage(this._currentConfig.options, this._currentConfig.page - 1, this._currentConfig.pageSize);
return this.loadPage(this._currentConfig.page - 1);
}
}