aboutsummaryrefslogtreecommitdiffhomepage
path: root/client/src/app/videos/shared/video.service.ts
blob: ad855753344a2f289a2713bdda9f46c8b5b62062 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Observable } from 'rxjs/Observable';

import { Search } from '../../shared';
import { SortField } from './sort-field.type';
import { AuthHttp, AuthService, RestExtractor, RestPagination, RestService, ResultList } from '../../shared';
import { Video } from './video.model';

@Injectable()
export class VideoService {
  private static BASE_VIDEO_URL = '/api/v1/videos/';

  constructor(
    private authService: AuthService,
    private authHttp: AuthHttp,
    private http: Http,
    private restExtractor: RestExtractor,
    private restService: RestService
  ) {}

  getVideo(id: string): Observable<Video> {
    return this.http.get(VideoService.BASE_VIDEO_URL + id)
                    .map(this.restExtractor.extractDataGet)
                    .catch((res) => this.restExtractor.handleError(res));
  }

  getVideos(pagination: RestPagination, sort: SortField) {
    const params = this.restService.buildRestGetParams(pagination, sort);

    return this.http.get(VideoService.BASE_VIDEO_URL, { search: params })
                    .map(res => res.json())
                    .map(this.extractVideos)
                    .catch((res) => this.restExtractor.handleError(res));
  }

  removeVideo(id: string) {
    return this.authHttp.delete(VideoService.BASE_VIDEO_URL + id)
                        .map(this.restExtractor.extractDataBool)
                        .catch((res) => this.restExtractor.handleError(res));
  }

  searchVideos(search: Search, pagination: RestPagination, sort: SortField) {
    const params = this.restService.buildRestGetParams(pagination, sort);

    if (search.field) params.set('field', search.field);

    return this.http.get(VideoService.BASE_VIDEO_URL + 'search/' + encodeURIComponent(search.value), { search: params })
                    .map(this.restExtractor.extractDataList)
                    .map(this.extractVideos)
                    .catch((res) => this.restExtractor.handleError(res));
  }

  private extractVideos(result: ResultList) {
    const videosJson = result.data;
    const totalVideos = result.total;
    const videos = [];
    for (const videoJson of videosJson) {
      videos.push(new Video(videoJson));
    }

    return { videos, totalVideos };
  }
}