aboutsummaryrefslogtreecommitdiffhomepage
path: root/client/src/app/shared/rest/rest-data-source.ts
blob: 847dd7c560ef157b1ee8082ead36d08b3166b866 (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
import { Http, RequestOptionsArgs, URLSearchParams,  } from '@angular/http';

import { ServerDataSource } from 'ng2-smart-table';

export class RestDataSource extends ServerDataSource {
 constructor(http: Http, endpoint: string) {
   const options = {
     endPoint: endpoint,
     sortFieldKey: 'sort',
     dataKey: 'data'
   }

   super(http, options);
 }

 protected extractTotalFromResponse(res) {
    const rawData = res.json();
    return rawData ? parseInt(rawData.total): 0;
  }

 protected addSortRequestOptions(requestOptions: RequestOptionsArgs) {
    let searchParams: URLSearchParams = <URLSearchParams> requestOptions.search;

    if (this.sortConf) {
      this.sortConf.forEach((fieldConf) => {
        const sortPrefix = fieldConf.direction === 'desc' ? '-' : '';

        searchParams.set(this.conf.sortFieldKey, sortPrefix + fieldConf.field);
      });
    }

    return requestOptions;
  }

  protected addPagerRequestOptions(requestOptions: RequestOptionsArgs) {
    let searchParams: URLSearchParams = <URLSearchParams> requestOptions.search;

    if (this.pagingConf && this.pagingConf['page'] && this.pagingConf['perPage']) {
      const perPage = this.pagingConf['perPage'];
      const page = this.pagingConf['page'];

      const start = (page - 1) * perPage;
      const count = perPage;

      searchParams.set('start', start.toString());
      searchParams.set('count', count.toString());
    }

    return requestOptions;
  }
}