]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/shared/rest/rest-data-source.ts
5c205d280ce1ecaad453817a09f1d652ffacac44
[github/Chocobozzz/PeerTube.git] / client / src / app / shared / rest / rest-data-source.ts
1 import { Http, RequestOptionsArgs, URLSearchParams, Response } from '@angular/http'
2
3 import { ServerDataSource } from 'ng2-smart-table'
4
5 export class RestDataSource extends ServerDataSource {
6 private updateResponse: (input: any[]) => any[]
7
8 constructor (http: Http, endpoint: string, updateResponse?: (input: any[]) => any[]) {
9 const options = {
10 endPoint: endpoint,
11 sortFieldKey: 'sort',
12 dataKey: 'data'
13 }
14 super(http, options)
15
16 if (updateResponse) {
17 this.updateResponse = updateResponse
18 }
19 }
20
21 protected extractDataFromResponse (res: Response) {
22 const json = res.json()
23 if (!json) return []
24 let data = json.data
25
26 if (this.updateResponse !== undefined) {
27 data = this.updateResponse(data)
28 }
29
30 return data
31 }
32
33 protected extractTotalFromResponse (res: Response) {
34 const rawData = res.json()
35 return rawData ? parseInt(rawData.total, 10) : 0
36 }
37
38 protected addSortRequestOptions (requestOptions: RequestOptionsArgs) {
39 const searchParams = requestOptions.params as URLSearchParams
40
41 if (this.sortConf) {
42 this.sortConf.forEach((fieldConf) => {
43 const sortPrefix = fieldConf.direction === 'desc' ? '-' : ''
44
45 searchParams.set(this.conf.sortFieldKey, sortPrefix + fieldConf.field)
46 })
47 }
48
49 return requestOptions
50 }
51
52 protected addPagerRequestOptions (requestOptions: RequestOptionsArgs) {
53 const searchParams = requestOptions.params as URLSearchParams
54
55 if (this.pagingConf && this.pagingConf['page'] && this.pagingConf['perPage']) {
56 const perPage = this.pagingConf['perPage']
57 const page = this.pagingConf['page']
58
59 const start = (page - 1) * perPage
60 const count = perPage
61
62 searchParams.set('start', start.toString())
63 searchParams.set('count', count.toString())
64 }
65
66 return requestOptions
67 }
68 }