From 3876a45c28d177a78ea55f46187d9dd43c8764dc Mon Sep 17 00:00:00 2001 From: "Maxence G. de Montauzan" Date: Sun, 29 Oct 2017 02:21:56 +0100 Subject: [PATCH] Continue to refactor service --- dashboard/src/app/els.service.ts | 55 ++++++++++++++++---------------- 1 file changed, 27 insertions(+), 28 deletions(-) diff --git a/dashboard/src/app/els.service.ts b/dashboard/src/app/els.service.ts index 7f5399a..e7e2fce 100644 --- a/dashboard/src/app/els.service.ts +++ b/dashboard/src/app/els.service.ts @@ -171,20 +171,7 @@ export class ElsService { }, 'size': ElsService.DEFAULT_SIZE }), {headers: this.headers}) - .map(res => this.responseToAlbum(res, albumName)); - } - - private responseToAlbum(res: Response, name: string): Album { - const hits = res.json().hits.hits; - if (hits.length < 1) { - console.info('No album "' + name + '" found.'); - return undefined; - } - if (hits.length > 1) { - // TODO Cumul results - console.error('More than one album "' + name + '" found (' + hits.length + '), return the first.'); - } - return hits[0]._source; + .map(res => this.responseToOneTypedResult(res, albumName)); } getArtist(artistName: string): Observable { @@ -196,20 +183,7 @@ export class ElsService { }, 'size': ElsService.DEFAULT_SIZE }), {headers: this.headers}) - .map(res => res.json().hits.hits) - .map((hits: Array) => { - // Theorically, my script prevent to found two documents with this query. - // But Prevention is better than cure as Shakespeare said - if (hits.length < 1) { - console.info('No artist "' + artistName + '" found.'); - return undefined; - } - if (hits.length > 1) { - console.error('More than one artist "' + artistName + '" found (' + hits.length + '), return the first.'); - console.error('This is not normal!'); - } - return hits[0]._source; - }); + .map(res => this.responseToOneTypedResult(res, artistName)); } getGenres(ordering: string = 'desc'): Observable { @@ -297,6 +271,31 @@ export class ElsService { }); } + /** Process a result to return just one result. + * Used to get an album or an artist. + * Take a name to put in console output if no result or more than one result. + * + * @param res Response to process + * @param name The searched name - for console output + */ + private responseToOneTypedResult(res: Response, name: string): T { + const hits = res.json().hits.hits; + + if (hits.length < 1) { + console.info('No result found for name: "' + name); + return undefined; + } + if (hits.length > 1) { + // TODO Cumul results (for album) + console.error('More than one result for name: "' + name + '". Found (' + hits.length + '), return the first.'); + } + return hits[0]._source; + } + + /** Process a response to a array of songs. + * + * @param res Response to process + */ private responseToSongs(res: Response): Song[] { const result: Array = []; res.json().hits.hits.forEach((hit) => {