From 94643559cc5e257637d8c6ea63a138dda4f054c3 Mon Sep 17 00:00:00 2001 From: wer Date: Fri, 13 Sep 2019 15:30:28 +0200 Subject: [PATCH] working parallel --- src/app/api/employees.service.ts | 48 +++++++++++++++++-- .../employee-container.component.html | 2 +- .../employee-container.component.ts | 10 ++-- tsconfig.json | 2 +- 4 files changed, 52 insertions(+), 10 deletions(-) diff --git a/src/app/api/employees.service.ts b/src/app/api/employees.service.ts index db808d8..b2c4238 100644 --- a/src/app/api/employees.service.ts +++ b/src/app/api/employees.service.ts @@ -1,8 +1,16 @@ import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; -import { Observable } from 'rxjs'; +import { Observable, of, merge, concat } from 'rxjs'; import { Employee } from 'src/typings'; -import {map} from 'rxjs/operators'; +import { map, flatMap, tap, scan } from 'rxjs/operators'; + + +const MAX_PAGE_SIZE = 50; + +type Chunk = { + data: Employee[] + idx: number +}; @Injectable({ providedIn: 'root' @@ -11,7 +19,39 @@ export class EmployeesService { constructor(private http: HttpClient) { } - getEmployees() { - return this.http.get('http://localhost:3000/employees'); + getEmployees(page = 1) { + return this.http.get(`http://localhost:3000/employees?_page=${page}`); } + + getAllEmployees(): Observable { + return this.getFirstPage().pipe( + flatMap(({ total, data }) => { + const pageCount = Math.ceil(total / MAX_PAGE_SIZE); + const pages = Array(pageCount - 1).fill(0).map((_, idx) => idx + 2); + return merge( + of({ data, idx: 1 }), + ...pages.map(idx => this.getEmployees(idx).pipe( + map(data => ({ data, idx })) + )) + ) + }), + scan((sparseChunks, { data, idx }: Chunk) => { + sparseChunks[idx] = data + return sparseChunks; + }, [] as Employee[][]), + map(sparseChunks => sparseChunks.flat()) + // scan((allItems, chunk: Chunk) => allItems.concat(chunk.data), [] as Employee[] ), + + ); + } + + private getFirstPage(): Observable<{ total: number, data: Employee[] }> { + return this.http.get(`http://localhost:3000/employees`, { observe: 'response' }).pipe( + map(res => ({ + total: parseInt(res.headers.get('X-Total-Count')), + data: res.body, + })), + ); + } + } diff --git a/src/app/employees/employee-container/employee-container.component.html b/src/app/employees/employee-container/employee-container.component.html index ae5ebf0..cd91b1a 100644 --- a/src/app/employees/employee-container/employee-container.component.html +++ b/src/app/employees/employee-container/employee-container.component.html @@ -1,5 +1,5 @@

Employees

- +
this.isLoading = false), + shareReplay(), + // share ); // employees: Employee[]; diff --git a/tsconfig.json b/tsconfig.json index 30956ae..5a95d44 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -15,7 +15,7 @@ "node_modules/@types" ], "lib": [ - "es2018", + "es2019", "dom" ] },