Merge pull request #702 from GNS3/Basic-cache-for-some-of-the-services

Basic cache for some of the services
This commit is contained in:
piotrpekala7 2020-02-27 10:14:41 +01:00 committed by GitHub
commit f9938db312
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 18 additions and 25 deletions

View File

@ -8,6 +8,7 @@ import { getTestServer } from './testing';
import { SymbolService } from './symbol.service';
import { Symbol } from '../models/symbol';
import { AppTestingModule } from '../testing/app-testing/app-testing.module';
import { of } from 'rxjs';
describe('SymbolService', () => {
let httpClient: HttpClient;
@ -50,20 +51,11 @@ describe('SymbolService', () => {
}));
it('should load symbols', inject([SymbolService], (service: SymbolService) => {
service.load(server).subscribe();
spyOn(service, 'load').and.returnValue(of([]));
const req = httpTestingController.expectOne('http://127.0.0.1:3080/v2/symbols');
service.list(server).subscribe();
req.flush([{ symbol_id: 'myid' }]);
const raw = httpTestingController.expectOne('http://127.0.0.1:3080/v2/symbols/myid/raw');
raw.flush('myraw');
service.symbols.subscribe(symbols => {
expect(symbols.length).toEqual(1);
expect(symbols[0].symbol_id).toEqual('myid');
expect(symbols[0].raw).toEqual('myraw');
});
expect(service.load).toHaveBeenCalled();
}));
it('should get symbols', inject([SymbolService], (service: SymbolService) => {

View File

@ -1,13 +1,17 @@
import { Injectable } from '@angular/core';
import { BehaviorSubject, forkJoin, Observable } from 'rxjs';
import { BehaviorSubject, forkJoin, Observable, of } from 'rxjs';
import { Symbol } from '../models/symbol';
import { Server } from '../models/server';
import { HttpServer } from './http-server.service';
import { shareReplay } from 'rxjs/operators';
const CACHE_SIZE = 1;
@Injectable()
export class SymbolService {
public symbols: BehaviorSubject<Symbol[]> = new BehaviorSubject<Symbol[]>([]);
private cache: Observable<Symbol[]>;
constructor(private httpServer: HttpServer) {}
@ -16,25 +20,22 @@ export class SymbolService {
}
add(server: Server, symbolName: string, symbol: string) {
this.cache = null;
return this.httpServer.post(server, `/symbols/${symbolName}/raw`, symbol)
}
load(server: Server): Observable<Symbol[]> {
const subscription = this.list(server).subscribe((symbols: Symbol[]) => {
const streams = symbols.map(symbol => this.raw(server, symbol.symbol_id));
forkJoin(streams).subscribe(results => {
symbols.forEach((symbol: Symbol, i: number) => {
symbol.raw = results[i];
});
this.symbols.next(symbols);
subscription.unsubscribe();
});
});
return this.symbols.asObservable();
return this.httpServer.get<Symbol[]>(server, '/symbols');
}
list(server: Server) {
return this.httpServer.get<Symbol[]>(server, '/symbols');
if(!this.cache) {
this.cache = this.load(server).pipe(
shareReplay(CACHE_SIZE)
);
}
return this.cache;
}
raw(server: Server, symbol_id: string) {