/
example5.ts
223 lines (206 loc) · 8.15 KB
/
example5.ts
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
import { autoinject } from 'aurelia-framework';
import { HttpClient } from 'aurelia-http-client';
import { CaseType, Column, GridOption, FieldType, FilterType, Formatters, GridOdataService, OperatorType } from 'aurelia-slickgrid';
const defaultPageSize = 20;
const sampleDataRoot = 'assets/data';
@autoinject()
export class Example5 {
title = 'Example 5: Grid with Backend OData Service';
subTitle = `
Use it when you need to support Pagination with a OData endpoint (for simple JSON, use a regular grid)<br/>
Take a look at the (<a href="https://github.com/ghiscoding/aurelia-slickgrid/wiki/OData" target="_blank">Wiki documentation</a>)
<br/>
<ul class="small">
<li>Only "Name" field is sortable for the demo (because we use JSON files), however "multiColumnSort: true" is also supported</li>
<li>String column also support operator (>, >=, <, <=, <>, !=, =, ==, *)
<ul>
<li>The (*) can be used as startsWith (ex.: "abc*" => startsWith "abc") / endsWith (ex.: "*xyz" => endsWith "xyz")</li>
<li>The other operators can be used on column type number for example: ">=100" (greater than or equal to 100)</li>
</ul>
<li>OData Service could be replaced by other Service type in the future (GraphQL or whichever you provide)</li>
<li>You can also preload a grid with certain "presets" like Filters / Sorters / Pagination <a href="https://github.com/ghiscoding/aurelia-slickgrid/wiki/Grid-State-&-Preset" target="_blank">Wiki - Grid Preset</a>
</ul>
`;
columnDefinitions: Column[];
gridOptions: GridOption;
dataset = [];
odataQuery = '';
processing = false;
status = { text: '', class: '' };
constructor(private http: HttpClient, private odataService: GridOdataService) {
// define the grid options & columns and then create the grid itself
this.defineGrid();
}
defineGrid() {
this.columnDefinitions = [
{
id: 'name', name: 'Name', field: 'name', sortable: true, type: FieldType.string,
filterable: true,
filter: {
type: FilterType.compoundInput
}
},
{
id: 'gender', name: 'Gender', field: 'gender', filterable: true, sortable: true,
filter: {
type: FilterType.singleSelect,
collection: [{ value: '', label: '' }, { value: 'male', label: 'male' }, { value: 'female', label: 'female' }]
}
},
{ id: 'company', name: 'Company', field: 'company' }
];
this.gridOptions = {
enableAutoResize: true,
autoResize: {
containerId: 'demo-container',
sidePadding: 15
},
enableFiltering: true,
enableCellNavigation: true,
enableCheckboxSelector: true,
enableRowSelection: true,
pagination: {
pageSizes: [10, 15, 20, 25, 30, 40, 50, 75, 100],
pageSize: defaultPageSize,
totalItems: 0
},
backendServiceApi: {
service: this.odataService,
preProcess: () => this.displaySpinner(true),
process: (query) => this.getCustomerApiCall(query),
postProcess: (response) => {
this.displaySpinner(false);
this.getCustomerCallback(response);
}
}
};
}
displaySpinner(isProcessing) {
this.processing = isProcessing;
this.status = (isProcessing)
? { text: 'processing...', class: 'alert alert-danger' }
: { text: 'done', class: 'alert alert-success' };
}
getCustomerCallback(data) {
// totalItems property needs to be filled for pagination to work correctly
// however we need to force Aurelia to do a dirty check, doing a clone object will do just that
this.gridOptions.pagination.totalItems = data['totalRecordCount'];
this.gridOptions = { ...{}, ...this.gridOptions };
// once pagination totalItems is filled, we can update the dataset
this.dataset = data['items'];
this.odataQuery = data['query'];
}
getCustomerApiCall(query) {
// in your case, you will call your WebAPI function (wich needs to return a Promise)
// for the demo purpose, we will call a mock WebAPI function
return this.getCustomerDataApiMock(query);
}
/**
* This function is only here to mock a WebAPI call (since we are using a JSON file for the demo)
* in your case the getCustomer() should be a WebAPI function returning a Promise
*/
getCustomerDataApiMock(query) {
// the mock is returning a Promise, just like a WebAPI typically does
return new Promise((resolve, reject) => {
const queryParams = query.toLowerCase().split('&');
let top: number;
let skip = 0;
let orderBy = '';
let countTotalItems = 100;
const columnFilters = {};
for (const param of queryParams) {
if (param.includes('$top=')) {
top = +(param.substring('$top='.length));
}
if (param.includes('$skip=')) {
skip = +(param.substring('$skip='.length));
}
if (param.includes('$orderby=')) {
orderBy = param.substring('$orderby='.length);
}
if (param.includes('$filter=')) {
const filterBy = param.substring('$filter='.length);
if (filterBy.includes('substringof')) {
const filterMatch = filterBy.match(/substringof\('(.*?)',([a-zA-Z ]*)/);
const fieldName = filterMatch[2].trim();
columnFilters[fieldName] = {
type: 'substring',
term: filterMatch[1].trim()
};
}
if (filterBy.includes('eq')) {
const filterMatch = filterBy.match(/([a-zA-Z ]*) eq '(.*?)'/);
const fieldName = filterMatch[1].trim();
columnFilters[fieldName] = {
type: 'equal',
term: filterMatch[2].trim()
};
}
if (filterBy.includes('startswith')) {
const filterMatch = filterBy.match(/startswith\(([a-zA-Z ]*),\s?'(.*?)'/);
const fieldName = filterMatch[1].trim();
columnFilters[fieldName] = {
type: 'starts',
term: filterMatch[2].trim()
};
}
if (filterBy.includes('endswith')) {
const filterMatch = filterBy.match(/endswith\(([a-zA-Z ]*),\s?'(.*?)'/);
const fieldName = filterMatch[1].trim();
columnFilters[fieldName] = {
type: 'ends',
term: filterMatch[2].trim()
};
}
}
}
const sort = orderBy.includes('asc')
? 'ASC'
: orderBy.includes('desc')
? 'DESC'
: '';
let url;
switch (sort) {
case 'ASC':
url = `${sampleDataRoot}/customers_100_ASC.json`;
break;
case 'DESC':
url = `${sampleDataRoot}/customers_100_DESC.json`;
break;
default:
url = `${sampleDataRoot}/customers_100.json`;
break;
}
this.http.createRequest(url)
.asGet()
.send()
.then(response => {
const dataArray = response.content as any[];
// Read the result field from the JSON response.
const firstRow = skip;
let filteredData = dataArray;
if (columnFilters) {
for (const columnId in columnFilters) {
if (columnFilters.hasOwnProperty(columnId)) {
filteredData = filteredData.filter(column => {
const filterType = columnFilters[columnId].type;
const searchTerm = columnFilters[columnId].term;
switch (filterType) {
case 'equal': return column[columnId] === searchTerm;
case 'ends': return column[columnId].toLowerCase().endsWith(searchTerm);
case 'starts': return column[columnId].toLowerCase().startsWith(searchTerm);
case 'substring': return column[columnId].toLowerCase().includes(searchTerm);
}
});
}
}
countTotalItems = filteredData.length;
}
const updatedData = filteredData.slice(firstRow, firstRow + top);
setTimeout(() => {
resolve({ items: updatedData, totalRecordCount: countTotalItems, query });
}, 500);
});
});
}
}