]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - client/src/app/shared/rest/rest-data-source.ts
Begin user quota
[github/Chocobozzz/PeerTube.git] / client / src / app / shared / rest / rest-data-source.ts
CommitLineData
df98563e 1import { Http, RequestOptionsArgs, URLSearchParams, Response } from '@angular/http'
28798b5d 2
df98563e 3import { ServerDataSource } from 'ng2-smart-table'
28798b5d
C
4
5export class RestDataSource extends ServerDataSource {
b0f9f39e
C
6 private updateResponse: (input: any[]) => any[]
7
8 constructor (http: Http, endpoint: string, updateResponse?: (input: any[]) => any[]) {
df98563e
C
9 const options = {
10 endPoint: endpoint,
11 sortFieldKey: 'sort',
12 dataKey: 'data'
13 }
df98563e 14 super(http, options)
b0f9f39e
C
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
df98563e
C
31 }
32
33 protected extractTotalFromResponse (res: Response) {
34 const rawData = res.json()
35 return rawData ? parseInt(rawData.total, 10) : 0
28798b5d
C
36 }
37
df98563e 38 protected addSortRequestOptions (requestOptions: RequestOptionsArgs) {
42374cf5 39 const searchParams = requestOptions.params as URLSearchParams
28798b5d
C
40
41 if (this.sortConf) {
42 this.sortConf.forEach((fieldConf) => {
df98563e 43 const sortPrefix = fieldConf.direction === 'desc' ? '-' : ''
28798b5d 44
df98563e
C
45 searchParams.set(this.conf.sortFieldKey, sortPrefix + fieldConf.field)
46 })
28798b5d
C
47 }
48
df98563e 49 return requestOptions
28798b5d
C
50 }
51
df98563e 52 protected addPagerRequestOptions (requestOptions: RequestOptionsArgs) {
42374cf5 53 const searchParams = requestOptions.params as URLSearchParams
28798b5d
C
54
55 if (this.pagingConf && this.pagingConf['page'] && this.pagingConf['perPage']) {
df98563e
C
56 const perPage = this.pagingConf['perPage']
57 const page = this.pagingConf['page']
28798b5d 58
df98563e
C
59 const start = (page - 1) * perPage
60 const count = perPage
28798b5d 61
df98563e
C
62 searchParams.set('start', start.toString())
63 searchParams.set('count', count.toString())
28798b5d
C
64 }
65
df98563e 66 return requestOptions
28798b5d
C
67 }
68}