]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blobdiff - client/angular/videos/videos.service.ts
Add trivial sort for the client
[github/Chocobozzz/PeerTube.git] / client / angular / videos / videos.service.ts
index f4790b5111ddbfa80c010cedfdfc31b5788ae274..43e3346aab457c323b87e990b0c2f65c7b20ce17 100644 (file)
@@ -1,9 +1,12 @@
 import { Injectable } from '@angular/core';
-import { Http, Response } from '@angular/http';
+import { Http, Response, RequestOptions, URLSearchParams } from '@angular/http';
 import { Observable } from 'rxjs/Rx';
 
+import { Pagination } from './pagination';
 import { Video } from './video';
 import { AuthService } from '../users/services/auth.service';
+import { Search } from '../app/search';
+import { SortField } from './components/list/sort';
 
 @Injectable()
 export class VideosService {
@@ -11,8 +14,12 @@ export class VideosService {
 
   constructor (private http: Http, private _authService: AuthService) {}
 
-  getVideos() {
-    return this.http.get(this._baseVideoUrl)
+  getVideos(pagination: Pagination, sort: SortField) {
+    const params = this.createPaginationParams(pagination);
+
+    if (sort) params.set('sort', sort)
+
+    return this.http.get(this._baseVideoUrl, { search: params })
                     .map(res => res.json())
                     .map(this.extractVideos)
                     .catch(this.handleError);
@@ -31,24 +38,42 @@ export class VideosService {
                     .catch(this.handleError);
   }
 
-  searchVideos(search: string) {
-    return this.http.get(this._baseVideoUrl + 'search/' + search)
+  searchVideos(search: Search, pagination: Pagination, sort: SortField) {
+    const params = this.createPaginationParams(pagination);
+
+    if (search.field) params.set('field', search.field);
+    if (sort) params.set('sort', sort)
+
+    return this.http.get(this._baseVideoUrl + 'search/' + encodeURIComponent(search.value), { search: params })
                     .map(res => res.json())
                     .map(this.extractVideos)
                     .catch(this.handleError);
   }
 
-  private extractVideos (body: any[]) {
+  private extractVideos (body: any) {
+    const videos_json = body.data;
+    const totalVideos = body.total;
     const videos = [];
-    for (const video_json of body) {
+    for (const video_json of videos_json) {
       videos.push(new Video(video_json));
     }
 
-    return videos;
+    return { videos, totalVideos };
   }
 
   private handleError (error: Response) {
     console.error(error);
     return Observable.throw(error.json().error || 'Server error');
   }
+
+  private createPaginationParams(pagination: Pagination) {
+    const params = new URLSearchParams();
+    const start: number = (pagination.currentPage - 1) * pagination.itemsPerPage;
+    const count: number = pagination.itemsPerPage;
+
+    params.set('start', start.toString());
+    params.set('count', count.toString());
+
+    return params;
+  }
 }