-
-
Notifications
You must be signed in to change notification settings - Fork 117
/
grid-graphql.component.ts
420 lines (392 loc) · 17.8 KB
/
grid-graphql.component.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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
import { GraphqlService, GraphqlPaginatedResult, GraphqlServiceApi, GraphqlServiceOption, } from '@slickgrid-universal/graphql';
import { Component, OnInit, OnDestroy, ChangeDetectorRef } from '@angular/core';
import { addDay, format as tempoFormat } from '@formkit/tempo';
import { TranslateService } from '@ngx-translate/core';
import { Subscription } from 'rxjs';
import {
AngularGridInstance,
type Column,
type CursorPageInfo,
FieldType,
Filters,
Formatters,
type GridOption,
type GridStateChange,
type Metrics,
type MultipleSelectOption,
OperatorType,
SortDirection,
unsubscribeAllObservables,
} from './../modules/angular-slickgrid';
const defaultPageSize = 20;
const GRAPHQL_QUERY_DATASET_NAME = 'users';
const LOCAL_STORAGE_KEY = 'gridStateGraphql';
const FAKE_SERVER_DELAY = 250;
@Component({
templateUrl: './grid-graphql.component.html'
})
export class GridGraphqlComponent implements OnInit, OnDestroy {
title = 'Example 6: Grid connected to Backend Server with GraphQL';
subTitle = `
Sorting/Paging connected to a Backend GraphQL Service (<a href="https://ghiscoding.gitbook.io/angular-slickgrid/backend-services/graphql" target="_blank">Wiki docs</a>).
<br/>
<ul class="small">
<li><span class="red">(*) NO DATA SHOWING</span> - just change Filters & Pages and look at the "GraphQL Query" changing :)</li>
<li>This example also demos the Grid State feature, open the console log to see the changes</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" (bigger or equal than 100)</li>
</ul>
<li>You can also preload a grid with certain "presets" like Filters / Sorters / Pagination <a href="https://ghiscoding.gitbook.io/angular-slickgrid/grid-functionalities/grid-state-and-preset" target="_blank">Wiki - Grid Preset</a></li>
<li>Also note that the column Name has a filter with a custom %% operator that behaves like an SQL LIKE operator supporting % wildcards.</li>
<li>Depending on your configuration, your GraphQL Server might already support regex querying (e.g. Hasura <a href="https://hasura.io/docs/latest/queries/postgres/filters/text-search-operators/#_regex" target="_blank">_regex</a>)
or you could add your own implementation (e.g. see this SO <a href="https://stackoverflow.com/a/37981802/1212166">Question</a>).</li>
</ul>
`;
private subscriptions: Subscription[] = [];
angularGrid!: AngularGridInstance;
columnDefinitions!: Column[];
gridOptions!: GridOption;
dataset = [];
metrics!: Metrics;
isWithCursor = false;
graphqlQuery = '';
processing = true;
status = { text: 'processing...', class: 'alert alert-danger' };
selectedLanguage: string;
serverWaitDelay = FAKE_SERVER_DELAY; // server simulation with default of 250ms but 50ms for Cypress tests
constructor(private readonly cd: ChangeDetectorRef, private translate: TranslateService) {
// always start with English for Cypress E2E tests to be consistent
const defaultLang = 'en';
this.translate.use(defaultLang);
this.selectedLanguage = defaultLang;
}
ngOnDestroy() {
// also unsubscribe all Angular Subscriptions
unsubscribeAllObservables(this.subscriptions);
}
ngOnInit(): void {
this.columnDefinitions = [
{
id: 'name', field: 'name', nameKey: 'NAME', width: 60, columnGroupKey: 'CUSTOMER_INFORMATION',
type: FieldType.string,
sortable: true,
filterable: true,
filter: {
model: Filters.compoundInput,
compoundOperatorList: [
{ operator: '', desc: 'Contains' },
{ operator: '<>', desc: 'Not Contains' },
{ operator: '=', desc: 'Equals' },
{ operator: '!=', desc: 'Not equal to' },
{ operator: 'a*', desc: 'Starts With' },
{ operator: 'Custom', desc: 'SQL Like' },
],
}
},
{
id: 'gender', field: 'gender', nameKey: 'GENDER', filterable: true, sortable: true, width: 60, columnGroupKey: 'CUSTOMER_INFORMATION',
filter: {
model: Filters.singleSelect,
collection: [{ value: '', label: '' }, { value: 'male', label: 'male', labelKey: 'MALE' }, { value: 'female', label: 'female', labelKey: 'FEMALE' }]
}
},
{
id: 'company', field: 'company', nameKey: 'COMPANY', width: 60, columnGroupKey: 'CUSTOMER_INFORMATION',
sortable: true, filterable: true,
filter: {
model: Filters.multipleSelect,
collection: [{ value: 'acme', label: 'Acme' }, { value: 'abc', label: 'Company ABC' }, { value: 'xyz', label: 'Company XYZ' }],
filterOptions: {
filter: true // adds a filter on top of the multi-select dropdown
} as MultipleSelectOption
}
},
{
id: 'billingAddressStreet', field: 'billing.address.street', nameKey: 'BILLING.ADDRESS.STREET',
width: 60, filterable: true, sortable: true, columnGroupKey: 'BILLING.INFORMATION',
},
{
id: 'billingAddressZip', field: 'billing.address.zip', nameKey: 'BILLING.ADDRESS.ZIP', width: 60,
type: FieldType.number,
columnGroupKey: 'BILLING.INFORMATION', // or use "columnGroup" without Translate
filterable: true, sortable: true,
filter: {
model: Filters.compoundInput
},
formatter: Formatters.multiple, params: { formatters: [Formatters.complexObject, Formatters.translate] }
},
{
id: 'finish', field: 'finish', name: 'Date', formatter: Formatters.dateIso, sortable: true, minWidth: 90, width: 120, exportWithFormatter: true,
type: FieldType.date,
columnGroupKey: 'BILLING.INFORMATION', // or use "columnGroup" without Translate
filterable: true,
filter: {
model: Filters.dateRange,
filterShortcuts: [
{
titleKey: 'NEXT_20_DAYS',
iconCssClass: 'mdi mdi-calendar',
searchTerms: [tempoFormat(new Date(), 'YYYY-MM-DD'), tempoFormat(addDay(new Date(), 20), 'YYYY-MM-DD')],
},
]
}
},
];
const currentYear = new Date().getFullYear();
const presetLowestDay = `${currentYear}-01-01`;
const presetHighestDay = `${currentYear}-02-15`;
this.gridOptions = {
gridHeight: 200,
gridWidth: 900,
compoundOperatorAltTexts: {
// where '=' is any of the `OperatorString` type shown above
text: { 'Custom': { operatorAlt: '%%', descAlt: 'SQL Like' } },
},
enableFiltering: true,
enableCellNavigation: true,
enableTranslate: true,
createPreHeaderPanel: true,
showPreHeaderPanel: true,
preHeaderPanelHeight: 28,
i18n: this.translate,
gridMenu: {
resizeOnShowHeaderRow: true,
commandItems: [
{
iconCssClass: 'mdi mdi-close text-danger',
title: 'Reset Grid',
disabled: false,
command: 'reset-grid',
positionOrder: 60
}
],
onCommand: (e, args) => {
if (args.command === 'reset-grid') {
this.angularGrid.gridService.resetGrid(this.columnDefinitions);
localStorage[LOCAL_STORAGE_KEY] = null;
}
}
},
enablePagination: true, // you could optionally disable the Pagination
pagination: {
pageSizes: [10, 15, 20, 25, 30, 40, 50, 75, 100],
pageSize: defaultPageSize,
totalItems: 0
},
presets: {
columns: [
{ columnId: 'name', width: 100 },
{ columnId: 'gender', width: 55 },
{ columnId: 'company' },
{ columnId: 'billingAddressZip' }, // flip column position of Street/Zip to Zip/Street
{ columnId: 'billingAddressStreet', width: 120 },
{ columnId: 'finish', width: 130 },
],
filters: [
// you can use OperatorType or type them as string, e.g.: operator: 'EQ'
{ columnId: 'gender', searchTerms: ['male'], operator: OperatorType.equal },
// { columnId: 'name', searchTerms: ['John Doe'], operator: OperatorType.contains },
{ columnId: 'name', searchTerms: ['Joh*oe'], operator: OperatorType.startsWithEndsWith },
{ columnId: 'company', searchTerms: ['xyz'], operator: 'IN' },
// use a date range with 2 searchTerms values
{ columnId: 'finish', searchTerms: [presetLowestDay, presetHighestDay], operator: OperatorType.rangeInclusive },
],
sorters: [
// direction can written as 'asc' (uppercase or lowercase) and/or use the SortDirection type
{ columnId: 'name', direction: 'asc' },
{ columnId: 'company', direction: SortDirection.DESC }
],
pagination: { pageNumber: this.isWithCursor ? 1 : 2, pageSize: 20 } // if cursor based, start at page 1
},
backendServiceApi: {
service: new GraphqlService(),
options: {
datasetName: GRAPHQL_QUERY_DATASET_NAME, // the only REQUIRED property
addLocaleIntoQuery: true, // optionally add current locale into the query
extraQueryArguments: [{ // optionally add some extra query arguments as input query arguments
field: 'userId',
value: 123
}],
filterQueryOverride: ({ fieldName, columnDef, columnFilterOperator, searchValues }) => {
if (columnFilterOperator === OperatorType.custom && columnDef?.id === 'name') {
// technically speaking GraphQL isn't a database query language like SQL, it's an application query language.
// What that means is that GraphQL won't let you write arbitrary queries out of the box.
// It will only support the types of queries defined in your GraphQL schema.
// see this SO: https://stackoverflow.com/a/37981802/1212166
return { field: fieldName, operator: 'Like', value: searchValues[0] };
}
return;
},
useCursor: this.isWithCursor, // sets pagination strategy, if true requires a call to setPageInfo() when graphql call returns
// when dealing with complex objects, we want to keep our field name with double quotes
// example with gender: query { users (orderBy:[{field:"gender",direction:ASC}]) {}
keepArgumentFieldDoubleQuotes: true
},
// you can define the onInit callback OR enable the "executeProcessCommandOnInit" flag in the service init
// onInit: (query) => this.getCustomerApiCall(query)
preProcess: () => this.displaySpinner(true),
process: (query) => this.getCustomerApiCall(query),
postProcess: (result: GraphqlPaginatedResult) => {
this.metrics = result.metrics as Metrics;
this.displaySpinner(false);
this.cd.detectChanges();
}
} as GraphqlServiceApi
};
}
angularGridReady(angularGrid: AngularGridInstance) {
this.angularGrid = angularGrid;
}
displaySpinner(isProcessing: boolean) {
this.processing = isProcessing;
this.status = (isProcessing)
? { text: 'processing...', class: 'alert alert-danger' }
: { text: 'finished', class: 'alert alert-success' };
}
/**
* Calling your GraphQL backend server should always return a Promise or Observable of type GraphqlPaginatedResult (or GraphqlResult without Pagination)
* @param query
* @return Promise<GraphqlPaginatedResult> | Observable<GraphqlResult>
*/
getCustomerApiCall(_query: string): Promise<GraphqlPaginatedResult> {
let pageInfo: CursorPageInfo;
if (this.angularGrid?.paginationService) {
const { paginationService } = this.angularGrid;
// there seems to a timing issue where when you click "cursor" it requests the data before the pagination-service is initialized...
const pageNumber = (paginationService as any)._initialized ? paginationService.getCurrentPageNumber() : 1;
// In the real world, each node item would be A,B,C...AA,AB,AC, etc and so each page would actually be something like A-T, T-AN
// but for this mock data it's easier to represent each page as
// Page1: A-B
// Page2: B-C
// Page3: C-D
// Page4: D-E
// Page5: E-F
const startCursor = String.fromCharCode('A'.charCodeAt(0) + pageNumber - 1);
const endCursor = String.fromCharCode(startCursor.charCodeAt(0) + 1);
pageInfo = {
hasPreviousPage: paginationService.dataFrom === 0,
hasNextPage: paginationService.dataTo === 100,
startCursor,
endCursor
};
} else {
pageInfo = {
hasPreviousPage: false,
hasNextPage: true,
startCursor: 'A',
endCursor: 'B'
};
}
// 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
const mockedResult = {
// the dataset name is the only unknown property
// will be the same defined in your GraphQL Service init, in our case GRAPHQL_QUERY_DATASET_NAME
data: {
[GRAPHQL_QUERY_DATASET_NAME]: {
nodes: [],
totalCount: 100,
pageInfo
}
}
};
return new Promise(resolve => {
window.setTimeout(() => {
this.graphqlQuery = this.angularGrid.backendService!.buildQuery();
if (this.isWithCursor) {
// When using cursor pagination, the pagination service needs to be updated with the PageInfo data from the latest request
// This might be done automatically if using a framework specific slickgrid library
// Note because of this timeout, this may cause race conditions with rapid clicks!
this.angularGrid?.paginationService?.setCursorPageInfo((mockedResult.data[GRAPHQL_QUERY_DATASET_NAME].pageInfo));
}
resolve(mockedResult);
}, this.serverWaitDelay);
});
}
goToFirstPage() {
this.angularGrid.paginationService!.goToFirstPage();
}
goToLastPage() {
this.angularGrid.paginationService!.goToLastPage();
}
/** Dispatched event of a Grid State Changed event */
gridStateChanged(gridStateChanges: GridStateChange) {
console.log('GraphQL Example, Grid State changed:: ', gridStateChanges);
localStorage[LOCAL_STORAGE_KEY] = JSON.stringify(gridStateChanges.gridState);
}
clearAllFiltersAndSorts() {
if (this.angularGrid?.gridService) {
this.angularGrid.gridService.clearAllFiltersAndSorts();
}
}
/** Save current Filters, Sorters in LocaleStorage or DB */
saveCurrentGridState() {
console.log('GraphQL current grid state', this.angularGrid.gridStateService.getCurrentGridState());
}
setFiltersDynamically() {
const currentYear = new Date().getFullYear();
const presetLowestDay = `${currentYear}-01-01`;
const presetHighestDay = `${currentYear}-02-15`;
// we can Set Filters Dynamically (or different filters) afterward through the FilterService
this.angularGrid.filterService.updateFilters([
{ columnId: 'gender', searchTerms: ['female'], operator: OperatorType.equal },
{ columnId: 'name', searchTerms: ['Jane'], operator: OperatorType.startsWith },
{ columnId: 'company', searchTerms: ['acme'], operator: 'IN' },
{ columnId: 'billingAddressZip', searchTerms: ['11'], operator: OperatorType.greaterThanOrEqual },
{ columnId: 'finish', searchTerms: [presetLowestDay, presetHighestDay], operator: OperatorType.rangeInclusive },
]);
}
setSortingDynamically() {
this.angularGrid.sortService.updateSorting([
// orders matter, whichever is first in array will be the first sorted column
{ columnId: 'billingAddressZip', direction: 'DESC' },
{ columnId: 'company', direction: 'ASC' },
]);
}
resetToOriginalPresets() {
const currentYear = new Date().getFullYear();
const presetLowestDay = `${currentYear}-01-01`;
const presetHighestDay = `${currentYear}-02-15`;
this.angularGrid.filterService.updateFilters([
// you can use OperatorType or type them as string, e.g.: operator: 'EQ'
{ columnId: 'gender', searchTerms: ['male'], operator: OperatorType.equal },
// { columnId: 'name', searchTerms: ['John Doe'], operator: OperatorType.contains },
{ columnId: 'name', searchTerms: ['Joh*oe'], operator: OperatorType.startsWithEndsWith },
{ columnId: 'company', searchTerms: ['xyz'], operator: 'IN' },
// use a date range with 2 searchTerms values
{ columnId: 'finish', searchTerms: [presetLowestDay, presetHighestDay], operator: OperatorType.rangeInclusive },
]);
this.angularGrid.sortService.updateSorting([
// direction can written as 'asc' (uppercase or lowercase) and/or use the SortDirection type
{ columnId: 'name', direction: 'asc' },
{ columnId: 'company', direction: SortDirection.DESC }
]);
window.setTimeout(() => {
this.angularGrid.paginationService?.changeItemPerPage(20);
this.angularGrid.paginationService?.goToPageNumber(2);
});
}
setIsWithCursor(isWithCursor: boolean) {
this.isWithCursor = isWithCursor;
this.resetOptions({ useCursor: this.isWithCursor });
return true;
}
private resetOptions(options: Partial<GraphqlServiceOption>) {
this.displaySpinner(true);
const graphqlService = this.gridOptions.backendServiceApi!.service as GraphqlService;
this.angularGrid.paginationService!.setCursorBased(options.useCursor as boolean);
graphqlService.updateOptions(options);
this.gridOptions = { ...this.gridOptions };
this.angularGrid.paginationService?.goToFirstPage();
}
switchLanguage() {
const nextLanguage = (this.selectedLanguage === 'en') ? 'fr' : 'en';
this.subscriptions.push(
this.translate.use(nextLanguage).subscribe(() => {
this.selectedLanguage = nextLanguage;
})
);
}
}