1 import { Injectable } from '@angular/core';
2 import { Http, Response, URLSearchParams } from '@angular/http';
3 import { Observable } from 'rxjs/Rx';
5 import { Pagination } from './pagination.model';
6 import { Search } from '../../shared/index';
7 import { SortField } from './sort-field.type';
8 import { AuthService } from '../../users/index';
9 import { Video } from './video.model';
12 export class VideoService {
13 private _baseVideoUrl = '/api/v1/videos/';
15 constructor (private http: Http, private _authService: AuthService) {}
17 getVideos(pagination: Pagination, sort: SortField) {
18 const params = this.createPaginationParams(pagination);
20 if (sort) params.set('sort', sort);
22 return this.http.get(this._baseVideoUrl, { search: params })
23 .map(res => res.json())
24 .map(this.extractVideos)
25 .catch(this.handleError);
28 getVideo(id: string) {
29 return this.http.get(this._baseVideoUrl + id)
30 .map(res => <Video> res.json())
31 .catch(this.handleError);
34 removeVideo(id: string) {
35 const options = this._authService.getAuthRequestOptions();
36 return this.http.delete(this._baseVideoUrl + id, options)
37 .map(res => <number> res.status)
38 .catch(this.handleError);
41 searchVideos(search: Search, pagination: Pagination, sort: SortField) {
42 const params = this.createPaginationParams(pagination);
44 if (search.field) params.set('field', search.field);
45 if (sort) params.set('sort', sort);
47 return this.http.get(this._baseVideoUrl + 'search/' + encodeURIComponent(search.value), { search: params })
48 .map(res => res.json())
49 .map(this.extractVideos)
50 .catch(this.handleError);
53 private extractVideos (body: any) {
54 const videos_json = body.data;
55 const totalVideos = body.total;
57 for (const video_json of videos_json) {
58 videos.push(new Video(video_json));
61 return { videos, totalVideos };
64 private handleError (error: Response) {
66 return Observable.throw(error.json().error || 'Server error');
69 private createPaginationParams(pagination: Pagination) {
70 const params = new URLSearchParams();
71 const start: number = (pagination.currentPage - 1) * pagination.itemsPerPage;
72 const count: number = pagination.itemsPerPage;
74 params.set('start', start.toString());
75 params.set('count', count.toString());