-
Notifications
You must be signed in to change notification settings - Fork 0
/
resteasy.js
675 lines (581 loc) · 23.1 KB
/
resteasy.js
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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
class RESTeasy {
/**
* Initializes a resteasy editor.
* @param {string} endpoint REST API endpoint
* @param {<table>} tableElement Table for listing items
* @param {string[]} tableFields item fields corresponding to each column in tableElement
* @param {<form>} formElement Form for editing item
* @param {function} [log] for logging
* @param {string[]} [tableClasses] Array of classNames corresponding to each column in tableElement
* @param {<input>} [searchElement] Input or Form for search term
* @param {string} [searchParam=q] querystring parameter name for search term
* @param {string} [pageSizeParam] querystring parameter name for pagination page size
* @param {string} [pageNumberParam] querystring parameter name for pagination page number
* @param {integer} [pageSize=10] Number of items to request per pagination page
* @param {integer} [pageIncrement=1] Amount to increase or decrease page number by
* @param {string} [pageTotalProperty] Search response property for the total number of paginated items, supports nested properties. e.g. "meta.total"
* @param {<button>} [pageNextElement] Button for requesting the next pagination page
* @param {<button>} [pagePreviousElement] Button for requesting the previous pagination page
* @param {<p>} [pageStatusElement] Text element for displaying the current and total number of pagination pages
* @param {<p>} [statusElement] Text element for displaying status and errors
* @param {<button>} [deleteElement] Button for deleting items
* @param {<button>} [createElement] Button for creating items
* @param {string} [idField=id] item field used for identification
* @param {string} [nameField=name] item field to use for display name
*/
constructor({
endpoint, tableElement, tableFields, formElement,
log, tableClasses = [], searchElement = {}, searchParam = 'q',
pageSizeParam, pageNumberParam, pageSize = 10, pageIncrement = 1, pageTotalProperty,
pageNextElement = {}, pagePreviousElement = {}, pageStatusElement = {},
statusElement = {}, deleteElement = {}, createElement = {}, idField = 'id', nameField = 'name', headers = {},
preSearch, preUpdateTable, preFindByID, preUpdateForm, preSave, preDelete,
postUpdateTable, postUpdateForm, postSave, postDelete
}) {
// BINDINGS ----------------------------------------------------------------
if (typeof endpoint !== 'string' || !endpoint.length)
throw 'Invalid endpoint passed to RESTeasy: must be non-empty string';
if (!(tableElement instanceof HTMLElement) || tableElement.nodeName !== 'TABLE')
throw 'Invalid tableElement passed to RESTeasy: must be a <table> object';
if (!Array.isArray(tableFields))
throw 'Invalid tableFields passed to RESTeasy: must be an array';
if (!(formElement instanceof HTMLElement) || formElement.nodeName !== 'FORM')
throw 'Invalid endpoint passed to RESTeasy: must be a <form> object';
if (!tableElement.tBodies.length)
throw 'tableElement passed to RESTeasy is missing <tbody>';
if (!formElement.elements[idField])
throw 'formElement passed to RESTeasy is missing <input name=[idField]>';
if (typeof headers !== 'object')
throw 'headers passed to RESTeasy was not an object';
if (!headers['Content-Type']) headers['Content-Type'] = 'application/json';
if (typeof log !== 'function') log = () => { };
// Programmatic ways of triggering operations
tableElement.easySelect = (id) => this.actionSelect(id);
tableElement.easyCreate = () => this.actionCreate();
tableElement.easyDelete = () => this.actionDelete();
tableElement.easySearch = () => this.actionSearch();
tableElement.easyNextPage = () => this.actionNextPage();
tableElement.easyPreviousPage = () => this.actionPreviousPage();
let me = this;
formElement.onsubmit = function (e) {
e.preventDefault();
me.actionSave();
}
formElement.onreset = function (e) {
e.preventDefault();
me.actionReset();
}
searchElement.onchange = function (e) {
e.preventDefault();
me.actionSearch();
}
searchElement.onsubmit = function (e) {
e.preventDefault();
}
deleteElement.onclick = function (e) {
e.preventDefault();
me.actionDelete();
}
createElement.onclick = function (e) {
e.preventDefault();
me.actionCreate();
}
pageNextElement.onclick = function (e) {
e.preventDefault();
me.actionNextPage();
}
pagePreviousElement.onclick = function (e) {
e.preventDefault();
me.actionPreviousPage();
}
// Set instance properties
this.endpoint = endpoint;
this.tableElement = tableElement;
this.tableFields = tableFields;
this.formElement = formElement;
this.log = log;
this.tableClasses = tableClasses;
this.searchElement = searchElement;
this.searchParam = searchParam;
this.pageSizeParam = pageSizeParam;
this.pageNumberParam = pageNumberParam;
this.pageSize = pageSize;
this.pageIncrement = pageIncrement;
this.pageTotalProperty = pageTotalProperty;
this.pageNextElement = pageNextElement;
this.pagePreviousElement = pagePreviousElement;
this.pageStatusElement = pageStatusElement;
this.statusElement = statusElement;
this.deleteElement = deleteElement;
this.createElement = createElement;
this.idField = idField;
this.nameField = nameField;
this.headers = headers;
this.preSearch = preSearch;
this.preUpdateTable = preUpdateTable;
this.preFindByID = preFindByID;
this.preUpdateForm = preUpdateForm;
this.preSave = preSave;
this.preDelete = preDelete;
this.postUpdateTable = postUpdateTable;
this.postUpdateForm = postUpdateForm;
this.postSave = postSave;
this.postDelete = postDelete;
this.tbody = tableElement.tBodies[0];
this.fid = formElement.elements[idField];
this.endpointBase = endpoint.includes('?') ? endpoint.split('?')[0] : endpoint;
this.pageNumber = 0;
this.pageTotal = 0;
this._updateTable();
}
// ACTIONS -----------------------------------------------------------------
/**
* Search for items in tableElement.
*/
async actionSearch() {
try {
this._updateStatus('Searching...');
this.pageNumber = 0;
await this._updateTable();
this._updateStatus('');
} catch (err) { this.log(err) }
}
/**
* Show the next page of items in tableElement.
*/
async actionNextPage() {
try {
this.pageNumber += this.pageIncrement;
await this._updateTable();
} catch (err) { this.log(err) }
}
/**
* Show the previous page of items in tableElement.
*/
async actionPreviousPage() {
try {
this.pageNumber -= this.pageIncrement;
if (this.pageNumber < 0) this.pageNumber = 0;
await this._updateTable();
} catch (err) { this.log(err) }
}
/**
* Select item with id in tableElement.
*/
async actionSelect(id) {
try {
this._updateStatus('Working...');
this._updateSelected(id);
const item = await this._updateForm({ id });
this._updateStatus('Editing existing item', item[this.nameField] || id);
} catch (err) { this.log(err) }
}
/**
* Delete the item selected in tableElement.
*/
async actionDelete() {
try {
this._updateStatus('Working...');
await this._deleteSelected();
await this._updateTable();
await this._updateForm({});
this._updateStatus('Item deleted');
} catch (err) { this.log(err) }
}
/**
* Begin editing a new item in formElement.
*/
async actionCreate() {
try {
this._updateStatus('Working...');
this._updateSelected();
await this._updateForm({});
this._updateStatus('Editing new item');
} catch (err) { this.log(err) }
}
/**
* Save changes made in formElement.
*/
async actionSave() {
try {
this._updateStatus('Working...');
const item = await this._save();
if (item) {
await this._updateForm({ item });
await this._updateTable();
this._updateSelected(item[this.idField]);
this._updateStatus('Item saved\nEditing existing item', item[this.nameField] || item[this.idField]);
}
} catch (err) { this.log(err) }
}
/**
* Cancel unsaved changes in formElement.
*/
async actionReset() {
try {
this._updateStatus('Working...');
const item = await this._updateForm({ reload: true });
if (item !== {}) this._updateStatus('Editing existing item', item[this.nameField] || item[this.idField]);
else this._updateStatus('Editing new item');
} catch (err) { this.log(err) }
}
/**
* Returns the URI encoded value of searchElement.
* A value will only be returned if searchElement is an HTML <input> or <form>.
*/
getSearchValue() {
let se = this.searchElement;
// Handle as <input>
if (se instanceof HTMLInputElement) {
return this.searchParam + '=' + se.value;
}
// Handle as <form>
if (se instanceof HTMLFormElement) {
let obj = this._readFormFields(se);
let strings = Object.keys(obj).reduce(
(a, k) => { a.push(k + '=' + obj[k]); return a; }, []
);
return strings.join('&');
}
}
// BEHAVIORS ---------------------------------------------------------------
/**
* Sets the class of row with id in tableElement to 'selected'.
* All other rows will have their class reset.
* If id is not set, no rows will be selected.
*/
_updateSelected(id) {
Array.from(this.tableElement.rows).map(row => {
if (row.id === id) row.classList.add('selected');
else row.classList.remove('selected');
});
}
/**
* Fetches results matching the current search in searchElement and updates tableElement.
*/
async _updateTable() {
try {
// Support searching
const meta = { url: this.endpoint };
let searchValue = this.getSearchValue();
searchValue = await this._doHook(this.preSearch, searchValue, meta);
// Determine query parameters
let params = [];
if (searchValue) params.push(searchValue);
if (this.pageSizeParam) params.push(this.pageSizeParam + '=' + this.pageSize);
if (this.pageNumberParam) params.push(this.pageNumberParam + '=' + this.pageNumber);
if (params.length) {
// Support endpoints with other query parameters
meta.url += meta.url.includes('?') ? '&' : '?';
meta.url += params.join('&');
}
let data = await this.fetchJSON(meta.url, { headers: this.headers }, { array: true, count: true });
data = await this._doHook(this.preUpdateTable, data);
// Update table
if (!Array.isArray(data) || !data.length) {
// Display no items notice
this.tbody.innerHTML = '\
<tr>\
<td style="text-align:center" colspan=' + this.tableFields.length + '>\
<strong>No items found</strong>\
</td>\
</tr>';
} else {
// Display items
this.tbody.innerHTML = '';
for (let item of data) {
let tr = document.createElement('tr');
tr.id = item[this.idField];
tr.addEventListener("click", this.actionSelect.bind(this, tr.id));
for (let col = 0; col < this.tableFields.length; col++) {
let td = document.createElement('td');
td.innerText = RESTeasy.deepFind(item, this.tableFields[col]);
if (this.tableClasses.length > col) td.className = this.tableClasses[col];
tr.appendChild(td);
}
this.tbody.appendChild(tr);
}
}
await this._doHook(this.postUpdateTable, data);
// Update pagination status
if (this.pageTotal) {
let current = Math.floor(this.pageNumber / this.pageIncrement) + 1;
let total = Math.floor(this.pageTotal / this.pageIncrement) + 1;
this.pageStatusElement.innerText = 'Page ' + current + ' of ' + total;
this.pageNextElement.disabled = current === total;
this.pagePreviousElement.disabled = current === 1;
}
} catch (err) {
this._updateStatus('Failed to load items', err);
throw err;
}
}
/**
* Sets fields in formElement to match supplied item, item with id, or empty.
* If reload is true, the current item, if any will be re-fetched.
* Returns the item.
*/
async _updateForm({ item, id, reload }) {
try {
// Support reload
if (reload) id = this.fid.value;
// Support find by id
if (!item && id) {
let meta = { url: this.endpointBase };
id = await this._doHook(this.preFindByID, id, meta);
item = await this.fetchJSON(meta.url + '/' + id, { headers: this.headers }, { first: true });
}
// Support reset
if (!item) item = {};
item = await this._doHook(this.preUpdateForm, item);
this._writeFormFields(item);
// Clear any errors
this._highlightErrors({});
await this._doHook(this.postUpdateForm, item);
return item;
} catch (err) {
this._updateStatus('Failed to load item', err);
throw err;
}
}
/**
* Creates or updates a item using values form formElement.
* Returns the updated item if the server returns it.
*/
async _save() {
try {
let data = this._readFormFields(this.formElement);
let meta = { url: this.endpointBase };
data = await this._doHook(this.preSave, data, meta);
// Determine method and URL for create/update
let method = 'POST';
if (this.fid.value) {
method = 'PUT';
meta.url += '/' + this.fid.value;
}
let result;
try {
result = await this.fetchJSON(meta.url, {
headers: this.headers,
method,
body: JSON.stringify(data)
}, { first: true });
} catch (err) {
this._highlightErrors(err.errors || err.error || err);
throw err;
}
await this._doHook(this.postSave, result);
return result;
} catch (err) {
this._updateStatus('Item not saved', err);
throw err;
}
}
/**
* Deletes the selected item.
*/
async _deleteSelected() {
try {
const meta = { url: this.endpointBase };
const id = await this._doHook(this.preDelete, this.fid.value, meta);
if (!id) throw 'Nothing selected'; // NEVER DELETE endpoint/
meta.url = meta.url + '/' + id;
let data = await this.fetchJSON(meta.url, { headers: this.headers, method: 'DELETE' }, { first: true });
await this._doHook(this.postDelete, data);
} catch (err) {
this._updateStatus('Item not deleted', err);
throw err;
}
}
/**
* Set's the text content of statusElement to match status.
*/
_updateStatus(text, status) {
this.log(text, status);
let msg = text;
if (status) {
if (typeof status === 'object' && status.message) status = status.message;
else if (typeof status === 'object' && status.statusMessage) status = status.statusMessage;
else if (typeof status !== 'string') status = JSON.stringify(val, null, 2);
msg += ':\n' + status;
}
this.statusElement.innerText = msg;
}
/**
* Highlights erroneous fields in formElement.
*/
_highlightErrors(errors) {
const elements = this.formElement.elements;
for (let field of elements) {
let match = errors.hasOwnProperty(field.name);
if (match) field.classList.add('invalidField');
else field.classList.remove('invalidField');
}
}
/**
* Set's formElement's fields to match obj.
*/
_writeFormFields(obj) {
const elements = this.formElement.elements;
for (let field of elements) {
let val = RESTeasy.deepFind(obj, field.name);
if (field.name) {
// Checkbox
if (field.type === 'checkbox') {
field.checked = val ? true : false;
}
// Date
else if (field.type === 'date') {
field.value = val ? RESTeasy.htmlDate(val) : '';
}
// Select
else if (field.nodeName === 'SELECT' && typeof val === 'object') {
field.value = val[this.idField];
}
// Other input types
else {
let value;
// JSON
if (field.classList.contains('formatJSON')) {
if (val === undefined || val === null) value = '';
else value = JSON.stringify(val, null, 2);
}
// Array
else if (field.classList.contains('formatArray')) {
if (!Array.isArray(val)) value = '';
else value = val.join('\n');
}
// Unformatted (text, numbers, etc)
else {
if (val === undefined || val === null) value = '';
else value = val;
}
field.value = value;
field.placeholder = value;
}
}
}
}
/**
* Returns an object containing all values from formElement's inputs.
*/
_readFormFields(form) {
let obj = {};
const elements = form.elements;
for (let field of elements) {
// Ignore unnamed or disabled controls
if (!field.name || field.disabled) continue;
let value = field.value;
// Checkbox
if (field.type === 'checkbox') {
value = field.checked ? true : false;
}
// Date
else if (field.type === 'date') {
value = field.value ? new Date(field.value) : null;
}
// JSON
else if (field.classList.contains('formatJSON')) {
try {
value = JSON.parse(field.value);
} catch (e) { }
}
// Array
else if (field.classList.contains('formatArray')) {
value = field.value.split('\n').filter(l => l.trim().length);
}
// Assign value to object
obj = RESTeasy.deepSet(obj, field.name, value);
}
return obj;
}
/**
* Executes hook with data if it is a , otherwise returns data.
* Returns the result of the hook, or data if nothing is returned.
* Failed hooks will be caught and logged, data will be returned.
*/
async _doHook(hook, data, meta) {
try {
if (typeof hook === 'function') return await hook(data, meta) || data;
else return data;
} catch (err) {
log('Exception thrown by hook:\n', err);
throw err;
}
}
// UTILITIES ---------------------------------------------------------------
async fetchJSON(url, options, { array, first, count }) {
const response = await fetch(url, options);
let data = {};
// Support 204 (no content) when no results
if (response.status === 204) return array ? [] : undefined;
data = await response.json();
// Check for HTTP error
if (!response.ok) throw data;
// Update page total if needed
if (count && this.pageTotalProperty && typeof data === 'object') {
this.pageTotal = RESTeasy.deepFind(data, this.pageTotalProperty) || 0;
}
// Support either [item] or {results:[{item}]}
if (array && Array.isArray(data)) return data;
if (array && Array.isArray(data.results)) return data.results;
if (array) return [];
if (first && Array.isArray(data)) {
if (!data.length) return;
return data[0];
}
if (first && Array.isArray(data.results)) {
if (!data.results.length) return;
return data.results[0];
}
return data;
}
/**
* Gets value from obj at path.
* Path can be shallow or deep
* e.g. obj[a] or obj[a[b]]
*/
static deepFind(obj, path) {
// Shallow (e.g. {name})
if (!path.includes('.')) return obj[path];
// Deep (e.g. {address:{street}})
const parts = path.split('.')
let cursor = obj;
for (let field of parts) {
if (cursor[field] == undefined) return undefined;
else cursor = cursor[field];
}
return cursor;
}
/**
* Sets value in obj at path.
* Path can be shallow or deep
* e.g. obj[a] or obj[a[b]]
*/
static deepSet(obj, path, value) {
// Shallow (e.g. {name})
if (!path.includes('.')) {
obj[path] = value;
return obj;
}
// Deep (e.g. {address:{street}})
let parts = path.split('.');
let cursor = obj;
for (let field of parts.slice(0, -1)) {
if (cursor[field] === undefined) cursor[field] = {};
cursor = cursor[field];
}
cursor[parts.pop()] = value;
return obj;
}
/**
* Converts a JSON date string to a HTML date string.
*/
static htmlDate(str) {
const date = new Date(str);
const d = ("0" + date.getDate()).slice(-2);
const m = ("0" + (date.getMonth() + 1)).slice(-2);
const y = date.getFullYear();
return y + "-" + m + "-" + d;
}
}