UNPKG

33.8 kBJavaScriptView Raw
1(function (global, factory) {
2 typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@angular/core'), require('@angular/common'), require('@ng-bootstrap/ng-bootstrap'), require('@angular/common/http'), require('@angular/router'), require('@ngrx/store'), require('rxjs'), require('rxjs/add/operator/share')) :
3 typeof define === 'function' && define.amd ? define(['exports', '@angular/core', '@angular/common', '@ng-bootstrap/ng-bootstrap', '@angular/common/http', '@angular/router', '@ngrx/store', 'rxjs', 'rxjs/add/operator/share'], factory) :
4 (factory((global['@mello-labs/api-tools'] = {}),global.core,global.common,global.ngBootstrap,global.http,global.router,global.store,global.rxjs));
5}(this, (function (exports,core,common,ngBootstrap,http,router,store,rxjs) { 'use strict';
6
7/**
8 * @fileoverview added by tsickle
9 * @suppress {checkTypes} checked by tsc
10 */
11/**
12 * <api-error *ngIf="state.modifyError" [error]="state.modifyError"></api-error>
13 * @record
14 */
15
16var ApiErrorComponent = (function () {
17 function ApiErrorComponent() {
18 /**
19 * An error response passed by the API or the application
20 */
21 this.message = 'An unknown error occured';
22 /**
23 * Whether or not to show all the error details passed by the API. If false will only show the error.msg
24 */
25 this.showDetails = true;
26 /**
27 * API response keys to ignore
28 */
29 this.ignoreProps = ['headers', 'errorMsg'];
30 }
31 /**
32 * @return {?}
33 */
34 ApiErrorComponent.prototype.ngOnInit = /**
35 * @return {?}
36 */
37 function () {
38 };
39 /**
40 * @return {?}
41 */
42 ApiErrorComponent.prototype.ngOnChanges = /**
43 * @return {?}
44 */
45 function () {
46 if (this.error) {
47 this.createError();
48 }
49 };
50 /**
51 * @return {?}
52 */
53 ApiErrorComponent.prototype.createError = /**
54 * @return {?}
55 */
56 function () {
57 var _this = this;
58 // Create an array of keys to loop through and filter out anything on the ignore list
59 this.errorOfKeys = Object.keys(this.error).filter(function (key) {
60 if (_this.ignoreProps.indexOf(key) == -1) {
61 return key;
62 }
63 });
64 // If errorMsg was not set and an error message was found in the server response, use the server message instead
65 //if (!this.errorMessage && this.error && this.error._body && this.error._body.message) {
66 // this.errorMessage = JSON.parse(this.error._body).message;
67 //}
68 // If 404
69 if (!this.errorMessage && this.error.status == 404) {
70 this.errorMessage = '404 Error. Unable to connect to the Api.';
71 }
72 else if (!this.errorMessage) {
73 this.errorMessage = 'Unknown error. Please see error details for more information.';
74 }
75 };
76 /**
77 * Hide alert message
78 * @return {?}
79 */
80 ApiErrorComponent.prototype.closeAlert = /**
81 * Hide alert message
82 * @return {?}
83 */
84 function () {
85 this.error = null;
86 };
87 ApiErrorComponent.decorators = [
88 { type: core.Component, args: [{
89 selector: 'error',
90 template: "<div class=\"alert alert-danger icon p-2 pl-3 pr-3\" *ngIf=\"error\"> <button type=\"button\" class=\"close\" aria-label=\"Close\" (click)=\"closeAlert()\"> <span aria-hidden=\"true\">&times;</span> </button> <i class=\"fa fa-alert\"></i> {{message}} <ng-container *ngIf=\"showDetails && errorOfKeys.length\"> <hr class=\"mt-2 mb-2\"/> <ngb-accordion #acc=\"ngbAccordion\" class=\"accordion-inline\"> <ngb-panel> <ng-template ngbPanelTitle> <span>See error details:</span> </ng-template> <ng-template ngbPanelContent> <table class=\"table table-sm\"> <tbody> <tr *ngFor=\"let key of errorOfKeys\"> <td><strong>{{key}}</strong></td> <td style=\"word-break: break-all;\">{{error[key]}}</td> </tr> </tbody> </table> </ng-template> </ngb-panel> </ngb-accordion> </ng-container> </div> ",
91 changeDetection: core.ChangeDetectionStrategy.OnPush
92 },] },
93 ];
94 /** @nocollapse */
95 ApiErrorComponent.ctorParameters = function () { return []; };
96 ApiErrorComponent.propDecorators = {
97 "error": [{ type: core.Input },],
98 "message": [{ type: core.Input },],
99 "showDetails": [{ type: core.Input },],
100 };
101 return ApiErrorComponent;
102}());
103
104/**
105 * @fileoverview added by tsickle
106 * @suppress {checkTypes} checked by tsc
107 */
108/**
109 * <api-state [state]="conditions.state" ignore="modifying" [hover]="true" *ngIf="conditionsState$ | async as conditions">
110 * Transcluded content here
111 * </api-state>
112 * @record
113 */
114
115var ApiStateComponent = (function () {
116 function ApiStateComponent() {
117 /**
118 * Should the success/loading/error messages appear inline or as a toaster pop in the lower right of the screen
119 */
120 this.toaster = true;
121 /**
122 * Should the success message be visible or not
123 */
124 this.showSuccess = true;
125 /**
126 * Set this flag after the initial load of data
127 */
128 this.initialLoadComplete = false;
129 /**
130 * Toggle the visibility of the success message
131 */
132 this.successVisible = true;
133 }
134 /**
135 * @return {?}
136 */
137 ApiStateComponent.prototype.ngOnInit = /**
138 * @return {?}
139 */
140 function () { };
141 /**
142 * @return {?}
143 */
144 ApiStateComponent.prototype.ngOnChanges = /**
145 * @return {?}
146 */
147 function () {
148 if (this.state.loaded) {
149 this.initialLoadComplete = true;
150 }
151 this.successVisible = true;
152 };
153 /**
154 * Close the alert and clear success state
155 * @return {?}
156 */
157 ApiStateComponent.prototype.closeSuccess = /**
158 * Close the alert and clear success state
159 * @return {?}
160 */
161 function () {
162 this.successVisible = false;
163 //this.api.resetSuccess();
164 };
165 /**
166 * @return {?}
167 */
168 ApiStateComponent.prototype.ngOnDestroy = /**
169 * @return {?}
170 */
171 function () { };
172 ApiStateComponent.decorators = [
173 { type: core.Component, args: [{
174 selector: 'api-state',
175 template: "<ng-container *ngIf=\"state\"> <!--GET/loading --> <div *ngIf=\"state.loading && !initialLoadComplete\" class=\"p-3\"><i class=\"fa fa-spinner fa-spin\"></i> Loading data from server...</div> <div *ngIf=\"state.loading && initialLoadComplete\" class=\"p-3\" [ngClass]=\"{'toaster': toaster }\"> <i class=\"fa fa-spinner fa-spin\" [ngClass]=\"{'toaster-lg': toaster }\"></i> <ng-container *ngIf=\"!toaster\"> Refreshing data from server... </ng-container> </div> <error *ngIf=\"state.loadError\" [error]=\"state.loadError\" [ngClass]=\"{'toaster': toaster && initialLoadComplete }\"></error> <!-- Create/Update/Delete --> <div *ngIf=\"state.modified && showSuccess && successVisible\" class=\"alert alert-success icon p-2\" [ngClass]=\"{'toaster': toaster }\"> <button type=\"button\" class=\"close\" aria-label=\"Close\" (click)=\"closeSuccess()\" *ngIf=\"!toaster\"> <span aria-hidden=\"true\">&times;</span> </button> Success! </div> <error *ngIf=\"state.modifyError\" [error]=\"state.modifyError\" [ngClass]=\"{'toaster': toaster }\"></error> <!-- Content --> <ng-container *ngIf=\"state.loaded || (initialLoadComplete && toaster)\"> <ng-content></ng-content> </ng-container> </ng-container> ",
176 styles: ["\n .toaster{position:fixed;bottom:10px;right:20px;z-index:1000;}\n .toaster-lg{font-size:3rem;}\n "],
177 changeDetection: core.ChangeDetectionStrategy.OnPush
178 },] },
179 ];
180 /** @nocollapse */
181 ApiStateComponent.ctorParameters = function () { return []; };
182 ApiStateComponent.propDecorators = {
183 "state": [{ type: core.Input },],
184 "toaster": [{ type: core.Input },],
185 "showSuccess": [{ type: core.Input },],
186 };
187 return ApiStateComponent;
188}());
189
190/**
191 * @fileoverview added by tsickle
192 * @suppress {checkTypes} checked by tsc
193 */
194/** @enum {string} */
195var ApiActions = {
196 RESET: 'RESET',
197 STATE_CHANGE: 'STATE_CHANGE',
198 RESET_ERRORS: 'RESET_ERRORS',
199 RESET_SUCCESS: 'RESET_SUCCESS',
200 GET_COMPLETE: 'GET_COMPLETE',
201 POST_COMPLETE: 'POST_COMPLETE',
202 PUT_COMPLETE: 'PUT_COMPLETE',
203 DELETE_COMPLETE: 'DELETE_COMPLETE',
204};
205
206/**
207 * @fileoverview added by tsickle
208 * @suppress {checkTypes} checked by tsc
209 */
210var ApiHttpService = (function () {
211 function ApiHttpService(httpSvc, storeSvc, routerSvc) {
212 this.httpSvc = httpSvc;
213 this.storeSvc = storeSvc;
214 this.routerSvc = routerSvc;
215 /**
216 * Hold GET requests from an API using the URL as a primary key
217 */
218 this.cache = {};
219 }
220 /**
221 * Make a GET request with simple caching
222 * @template T
223 * @param {?} url - The URL location of the webapi
224 * @param {?=} updateCache - Refresh the version in the cache
225 * @return {?}
226 */
227 ApiHttpService.prototype.get = /**
228 * Make a GET request with simple caching
229 * @template T
230 * @param {?} url - The URL location of the webapi
231 * @param {?=} updateCache - Refresh the version in the cache
232 * @return {?}
233 */
234 function (url, updateCache) {
235 if (updateCache === void 0) { updateCache = false; }
236 // If this request is not in the cache or updateCache was requested (default behavior), load content into cache
237 if (!this.cache[url] || updateCache) {
238 this.cache[url] = this.httpSvc.get(url)
239 .publishReplay(1)
240 .refCount();
241 }
242 return this.cache[url];
243 };
244 /**
245 * Make a GET request and load the results into the store
246 * @param url - The URL location of the webapi
247 * @param id - The location to put the results in the store
248 * @param updateCache - Refresh the version in the cache
249 */
250 /**
251 * Make a GET request and load the results into the store
252 * @template T
253 * @param {?} url - The URL location of the webapi
254 * @param {?=} apiMap
255 * @param {?=} updateCache - Refresh the version in the cache
256 * @return {?}
257 */
258 ApiHttpService.prototype.getStore = /**
259 * Make a GET request and load the results into the store
260 * @template T
261 * @param {?} url - The URL location of the webapi
262 * @param {?=} apiMap
263 * @param {?=} updateCache - Refresh the version in the cache
264 * @return {?}
265 */
266 function (url, apiMap, updateCache) {
267 var _this = this;
268 if (updateCache === void 0) { updateCache = false; }
269 // If this request is not in the cache or updateCache was requested (default behavior), load content into cache
270 if (this.cache[url] == null || updateCache) {
271 // Set status to waiting
272 var /** @type {?} */ newState_1 = { loading: true, loadError: false, loaded: false };
273 this.storeSvc.dispatch({ type: ApiActions.STATE_CHANGE, payload: { apiMap: apiMap, newState: newState_1 } }); // Update store with new state
274 this.cache[url] = this.httpSvc.get(url)
275 .share()
276 .map(function (res) {
277 //Set status to success
278 //Set status to success
279 newState_1 = { loading: false, loadError: false, loaded: true };
280 _this.storeSvc.dispatch({ type: ApiActions.STATE_CHANGE, payload: { apiMap: apiMap, newState: newState_1 } }); // Update store with new state
281 var /** @type {?} */ data = apiMap.map ? apiMap.map(res) : res;
282 _this.storeSvc.dispatch({ type: ApiActions.GET_COMPLETE, payload: { apiMap: apiMap, data: data } }); // Load content into store
283 return data;
284 }).catch(function (error) {
285 if (error.status == 401 || error.status == 403) {
286 error.errorMsg = 'Please log in ';
287 return _this.endSession(error);
288 }
289 else {
290 newState_1 = { loading: false, loadError: error, loaded: false };
291 _this.storeSvc.dispatch({ type: ApiActions.STATE_CHANGE, payload: { apiMap: apiMap, newState: newState_1 } }); // Update store with new state
292 return rxjs.Observable.throw(error);
293 }
294 });
295 return this.cache[url];
296 }
297 else {
298 return rxjs.Observable.of(/** @type {?} */ (true));
299 }
300 //return this.cache[url];
301 };
302 /**
303 * Make a POST request and load the results into the store
304 * @param url - The URL location of the endpoint
305 * @param id - The location to put the results in the store
306 * @param data - The data to pass to the server
307 */
308 /**
309 * Make a POST request and load the results into the store
310 * @template T
311 * @param {?} url - The URL location of the endpoint
312 * @param {?} apiMap
313 * @param {?} data - The data to pass to the server
314 * @return {?}
315 */
316 ApiHttpService.prototype.postStore = /**
317 * Make a POST request and load the results into the store
318 * @template T
319 * @param {?} url - The URL location of the endpoint
320 * @param {?} apiMap
321 * @param {?} data - The data to pass to the server
322 * @return {?}
323 */
324 function (url, apiMap, data) {
325 var _this = this;
326 // Set status to modifying
327 var /** @type {?} */ newState = { modifying: true, modified: false, modifyError: false };
328 this.storeSvc.dispatch({ type: ApiActions.STATE_CHANGE, payload: { apiMap: apiMap, newState: newState } }); // Update store with new state
329 return this.httpSvc.post(url, data)
330 .map(function (res) {
331 // Set status to complete
332 var /** @type {?} */ newState = { modifying: false, modified: true, modifyError: false };
333 _this.storeSvc.dispatch({ type: ApiActions.STATE_CHANGE, payload: { apiMap: apiMap, newState: newState } }); // Update store with new state
334 // Check if the response has a payload or not
335 var /** @type {?} */ dataNew = res ? res : data;
336 _this.storeSvc.dispatch({ type: ApiActions.POST_COMPLETE, payload: { apiMap: apiMap, data: dataNew } }); // Load content into store
337 return rxjs.Observable.of(res);
338 }).catch(function (error) {
339 if (error.status == 401 || error.status == 403) {
340 error.errorMsg = 'Please log in ';
341 return _this.endSession(error);
342 }
343 else {
344 error.errorMsg = 'Unable to create ' + apiMap.storeProperty;
345 // Set status to error
346 var /** @type {?} */ newState_2 = { modifying: false, modified: false, modifyError: error };
347 _this.storeSvc.dispatch({ type: ApiActions.STATE_CHANGE, payload: { apiMap: apiMap, newState: newState_2 } }); // Update store with new state
348 return rxjs.Observable.throw(error);
349 }
350 });
351 }; // end post
352 /**
353 * Make a PUT request
354 * @param url - The URL location of the webapi
355 * @param data - The data to pass to the server
356 */
357 /**
358 * Make a PUT request
359 * @template T
360 * @param {?} url - The URL location of the webapi
361 * @param {?} apiMap
362 * @param {?} data - The data to pass to the server
363 * @return {?}
364 */
365 ApiHttpService.prototype.putStore = /**
366 * Make a PUT request
367 * @template T
368 * @param {?} url - The URL location of the webapi
369 * @param {?} apiMap
370 * @param {?} data - The data to pass to the server
371 * @return {?}
372 */
373 function (url, apiMap, data) {
374 var _this = this;
375 //console.warn('Putting ', url, apiMap, data);
376 // Set status to modifying
377 var /** @type {?} */ newState = { modifying: true, modified: false, modifyError: false };
378 this.storeSvc.dispatch({ type: ApiActions.STATE_CHANGE, payload: { apiMap: apiMap, newState: newState } }); // Update store with new state
379 return this.httpSvc.put(url, data)
380 .map(function (res) {
381 // Set status to complete
382 var /** @type {?} */ newState = { modifying: false, modified: true, modifyError: false };
383 _this.storeSvc.dispatch({ type: ApiActions.STATE_CHANGE, payload: { apiMap: apiMap, newState: newState } }); // Update store with new state
384 // Check if the response has a payload or not, if not then this is an upSert
385 var /** @type {?} */ dataNew = res ? res : data;
386 _this.storeSvc.dispatch({ type: ApiActions.PUT_COMPLETE, payload: { apiMap: apiMap, data: dataNew } }); // Load content into store
387 return rxjs.Observable.of(res);
388 }).catch(function (error) {
389 console.warn('PUT Error, handle 403 unauth errors here', error);
390 if (error.status == 401 || error.status == 403) {
391 error.errorMsg = 'Please log in ';
392 return _this.endSession(error);
393 }
394 else {
395 error.errorMsg = 'Unable to update ' + apiMap.storeProperty;
396 // Set status to error
397 var /** @type {?} */ newState_3 = { modifying: false, modified: false, modifyError: error };
398 _this.storeSvc.dispatch({ type: ApiActions.STATE_CHANGE, payload: { apiMap: apiMap, newState: newState_3 } }); // Update store with new state
399 return rxjs.Observable.throw(error);
400 }
401 });
402 }; // end put
403 /**
404 * Make a DELETE request
405 * @param url - The URL location of the webapi
406 * @param apiMap - The ApiMap object
407 * @param element - The element or collection of elements being deleted
408 */
409 /**
410 * Make a DELETE request
411 * @template T
412 * @param {?} url - The URL location of the webapi
413 * @param {?} apiMap - The ApiMap object
414 * @param {?} element - The element or collection of elements being deleted
415 * @return {?}
416 */
417 ApiHttpService.prototype.deleteStore = /**
418 * Make a DELETE request
419 * @template T
420 * @param {?} url - The URL location of the webapi
421 * @param {?} apiMap - The ApiMap object
422 * @param {?} element - The element or collection of elements being deleted
423 * @return {?}
424 */
425 function (url, apiMap, element) {
426 var _this = this;
427 // Set status to modifying
428 var /** @type {?} */ newState = { modifying: true, modified: false, modifyError: false };
429 this.storeSvc.dispatch({ type: ApiActions.STATE_CHANGE, payload: { apiMap: apiMap, newState: newState } }); // Update store with new state
430 // Delete doesn't natively support a body so this adds it in for deleting collections or other uncommon operations
431 return this.httpSvc.request('delete', url, { body: element })
432 .map(function (res) {
433 // Set status to complete
434 var /** @type {?} */ newState = { modifying: false, modified: true, modifyError: false };
435 _this.storeSvc.dispatch({ type: ApiActions.STATE_CHANGE, payload: { apiMap: apiMap, newState: newState } }); // Update store with new state
436 _this.storeSvc.dispatch({ type: ApiActions.DELETE_COMPLETE, payload: { apiMap: apiMap, data: element } }); // Load content into store
437 return rxjs.Observable.of(res);
438 }).catch(function (error) {
439 console.warn('DELETE Error, handle 403 unauth errors here', error);
440 if (error.status == 401 || error.status == 403) {
441 error.errorMsg = 'Please log in ';
442 return _this.endSession(error);
443 }
444 else {
445 error.errorMsg = 'Unable to delete ' + apiMap.storeProperty;
446 // Set status to error
447 var /** @type {?} */ newState_4 = { modifying: false, modified: false, modifyError: error };
448 _this.storeSvc.dispatch({ type: ApiActions.STATE_CHANGE, payload: { apiMap: apiMap, newState: newState_4 } }); // Update store with new state
449 return rxjs.Observable.throw(error);
450 }
451 });
452 }; // end post
453 /**
454 * When an authentication check fails
455 * @param {?} error
456 * @return {?}
457 */
458 ApiHttpService.prototype.endSession = /**
459 * When an authentication check fails
460 * @param {?} error
461 * @return {?}
462 */
463 function (error) {
464 this.cache = {};
465 window.localStorage.removeItem('token');
466 window.sessionStorage.clear();
467 this.routerSvc.navigate(['/login'], { queryParams: { session: 'expired' } });
468 return rxjs.Observable.throw(error);
469 };
470 ApiHttpService.decorators = [
471 { type: core.Injectable },
472 ];
473 /** @nocollapse */
474 ApiHttpService.ctorParameters = function () { return [
475 { type: http.HttpClient, },
476 { type: store.Store, },
477 { type: router.Router, },
478 ]; };
479 return ApiHttpService;
480}());
481
482var __assign = (undefined && undefined.__assign) || Object.assign || function(t) {
483 for (var s, i = 1, n = arguments.length; i < n; i++) {
484 s = arguments[i];
485 for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
486 t[p] = s[p];
487 }
488 return t;
489};
490/**
491 * @fileoverview added by tsickle
492 * @suppress {checkTypes} checked by tsc
493 */
494/**
495 * @param {?=} state
496 * @param {?=} __1
497 * @return {?}
498 */
499function ApiReducer(state, _a) {
500 if (state === void 0) { state = {}; }
501 var type = _a.type, payload = _a.payload;
502 //console.log('STORE REDUCER:', type, payload);
503 var /** @type {?} */ srcData;
504 switch (type) {
505 // Reset State
506 case ApiActions.RESET:
507 return {};
508 // Get response
509 case ApiActions.GET_COMPLETE:
510 // If response is an array
511 if (Array.isArray(payload.data)) {
512 state[payload.apiMap.storeProperty] = payload.data.slice();
513 }
514 else if (typeof payload.data == 'object') {
515 state[payload.apiMap.storeProperty] = __assign({}, payload.data);
516 }
517 else if (typeof payload.data == 'string') {
518 state[payload.apiMap.storeProperty][payload.apiMap.data] = payload.data;
519 }
520 else {
521 console.error('GET_COMPLETE was not an object/array/string, please write a condition for this in the api.reducer', type, payload);
522 }
523 break;
524 // Post response
525 case ApiActions.POST_COMPLETE:
526 // If a map and mapSrc element are present, grab the unfiltered content from the mapSrc property. Otherwise just get data straight out of the store
527 srcData = (payload.apiMap.map && payload.apiMap.mapSrc) ? state[payload.apiMap.storeProperty][payload.apiMap.mapSrc] : state[payload.apiMap.storeProperty];
528 // If destination is an array and response is an array, concat with new data up front
529 if (Array.isArray(srcData) && Array.isArray(payload.data)) {
530 srcData = payload.data.concat(srcData);
531 }
532 else if (srcData && typeof payload.data === 'object') {
533 /* TODO: Figure out how to do upserts. Maybe pass an additional prop
534 if (payload.data[payload.apiMap.uniqueId]) {
535
536 } else {
537 srcData = [payload.data, ...srcData];
538 }
539 */
540 srcData = [payload.data].concat(srcData);
541 }
542 else if (typeof srcData === 'object' && typeof payload.data === 'object') {
543 srcData = __assign({}, payload.data);
544 }
545 else {
546 console.error('POST_COMPLETE was not an object or an array, please write a condition for this in the api.reducer');
547 }
548 // If map and mapSrc are present, remap the data before returning it to the store, otherwise just return the store data
549 state[payload.apiMap.storeProperty] = (payload.apiMap.map && payload.apiMap.mapSrc) ? payload.apiMap.map(srcData) : srcData;
550 break;
551 // PUT response
552 case ApiActions.PUT_COMPLETE:
553 //console.warn('PUT_COMPLETE', payload)
554 // If a map and mapSrc element are present, grab the unfiltered content from the mapSrc property. Otherwise just get data straight out of the store
555 srcData = (payload.apiMap.map && payload.apiMap.mapSrc) ? state[payload.apiMap.storeProperty][payload.apiMap.mapSrc] : state[payload.apiMap.storeProperty];
556 // If destination is an array and response is an array, loop through the destination array and update all entries with the new ones
557 if (Array.isArray(srcData) && Array.isArray(payload.data)) {
558 //console.warn('Array into array')
559 for (var /** @type {?} */ i = 0; i < payload.data.length; i++) {
560 // Loop through payload
561 for (var /** @type {?} */ j = 0; j < srcData.length; j++) {
562 // Loop through response object
563 if (payload.data[i][payload.apiMap.uniqueId] == srcData[j][payload.apiMap.uniqueId]) {
564 srcData[j] = payload.data[i];
565 srcData = srcData.slice();
566 j = srcData.length + 1; // Cheap way to break the second for loop
567 }
568 }
569 }
570 }
571 else if (Array.isArray(srcData) && typeof payload.data === 'object') {
572 //console.warn('Object into array')
573 // Loop through the destination array and when the unique ID is found, update the entry
574 for (var /** @type {?} */ i = 0; i < srcData.length; i++) {
575 if (srcData[i][payload.apiMap.uniqueId] == payload.data[payload.apiMap.uniqueId]) {
576 srcData[i] = payload.data;
577 srcData = srcData.slice();
578 break;
579 }
580 }
581 }
582 else if (typeof srcData === 'object' && typeof payload.data === 'object') {
583 //console.warn('Replace object')
584 srcData = __assign({}, payload.data);
585 }
586 else {
587 console.error('PUT_COMPLETE was not an object or an array, please write a condition for this in the api.reducer');
588 }
589 // If map and mapSrc are present, remap the data before returning it to the store, otherwise just return the store data
590 state[payload.apiMap.storeProperty] = (payload.apiMap.map && payload.apiMap.mapSrc) ? payload.apiMap.map(srcData) : srcData;
591 break;
592 // Delete response
593 case ApiActions.DELETE_COMPLETE:
594 //console.warn('Delete Reducer ', payload)
595 // If a map and mapSrc element are present, grab the unfiltered content from the mapSrc property. Otherwise just get data straight out of the store
596 srcData = (payload.apiMap.map && payload.apiMap.mapSrc) ? state[payload.apiMap.storeProperty][payload.apiMap.mapSrc] : state[payload.apiMap.storeProperty];
597 // If destination is an array and response is an array, loop through the destination array and update all entries with the new ones
598 if (Array.isArray(srcData) && Array.isArray(payload.data)) {
599 //console.warn('Delete array from array')
600 for (var /** @type {?} */ i = 0; i < payload.data.length; i++) {
601 // Loop through payload
602 for (var /** @type {?} */ j = 0; j < srcData.length; j++) {
603 // Loop through response object
604 //console.warn('Looping 2', payload.data[i][payload.apiMap.uniqueId], srcData[j][payload.apiMap.uniqueId]);
605 if (payload.data[i][payload.apiMap.uniqueId] == srcData[j][payload.apiMap.uniqueId]) {
606 srcData.splice(j, 1);
607 srcData = srcData.slice();
608 j = srcData.length + 1; // Cheap way to break the second for loop
609 }
610 }
611 }
612 }
613 else if (Array.isArray(srcData)) {
614 // If this delete operation only has a single unique ID
615 if (typeof payload.apiMap.uniqueId == 'string') {
616 srcData = srcData.filter(function (element) { return element[payload.apiMap.uniqueId] != payload.data[payload.apiMap.uniqueId]; });
617 }
618 else if (payload.apiMap.uniqueId.length) {
619 srcData = srcData.filter(function (element, index) {
620 // Loop through the uniqueID's list. If the number of unique ID's match what is in the API Map then relete it
621 var /** @type {?} */ hasMatches = 0;
622 payload.apiMap.uniqueId.forEach(function (id) {
623 if (element[id] == payload.data[id]) {
624 hasMatches++;
625 }
626 });
627 return hasMatches != payload.apiMap.uniqueId.length ? true : false;
628 });
629 }
630 }
631 else if (typeof srcData === 'object' && typeof payload.data === 'object') {
632 delete srcData[payload.data];
633 }
634 else {
635 console.error('DELETE_COMPLETE was not an object or an array, please write a condition for this in the api.reducer');
636 }
637 // If map and mapSrc are present, remap the data before returning it to the store, otherwise just return the store data
638 state[payload.apiMap.storeProperty] = (payload.apiMap.map && payload.apiMap.mapSrc) ? payload.apiMap.map(srcData) : srcData;
639 break;
640 }
641 return state;
642}
643
644var __assign$1 = (undefined && undefined.__assign) || Object.assign || function(t) {
645 for (var s, i = 1, n = arguments.length; i < n; i++) {
646 s = arguments[i];
647 for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
648 t[p] = s[p];
649 }
650 return t;
651};
652/**
653 * @fileoverview added by tsickle
654 * @suppress {checkTypes} checked by tsc
655 */
656var ApiStatusStore = {};
657/**
658 * @param {?=} state
659 * @param {?=} __1
660 * @return {?}
661 */
662function ApiStatusReducer(state, _a) {
663 if (state === void 0) { state = ApiStatusStore; }
664 var type = _a.type, payload = _a.payload;
665 //console.log('STORE REDUCER: ApiStatusReducer', type, payload);
666 switch (type) {
667 // Reset State
668 case ApiActions.RESET:
669 return ApiStatusStore;
670 // State change
671 case ApiActions.STATE_CHANGE:
672 state[payload.apiMap.storeProperty] = __assign$1({}, state[payload.apiMap.storeProperty], payload.newState);
673 break;
674 // Reset API errors
675 case ApiActions.RESET_ERRORS:
676 Object.keys(state).forEach(function (key) {
677 state[key].modifyError = false;
678 state[key] = __assign$1({}, state[key]);
679 });
680 break;
681 // Reset API errors
682 case ApiActions.RESET_SUCCESS:
683 Object.keys(state).forEach(function (key) {
684 state[key].modified = false;
685 state[key] = __assign$1({}, state[key]);
686 });
687 break;
688 }
689 return state;
690}
691
692/**
693 * @fileoverview added by tsickle
694 * @suppress {checkTypes} checked by tsc
695 */
696var ApiToolsModule = (function () {
697 function ApiToolsModule() {
698 }
699 /**
700 * @return {?}
701 */
702 ApiToolsModule.forRoot = /**
703 * @return {?}
704 */
705 function () {
706 return {
707 ngModule: ApiToolsModule,
708 providers: []
709 };
710 };
711 ApiToolsModule.decorators = [
712 { type: core.NgModule, args: [{
713 imports: [
714 common.CommonModule,
715 ngBootstrap.NgbModule.forRoot()
716 ],
717 declarations: [
718 ApiErrorComponent,
719 ApiStateComponent
720 ],
721 exports: [
722 ApiErrorComponent,
723 ApiStateComponent
724 ]
725 },] },
726 ];
727 /** @nocollapse */
728 ApiToolsModule.ctorParameters = function () { return []; };
729 return ApiToolsModule;
730}());
731
732exports.ApiToolsModule = ApiToolsModule;
733exports.ApiErrorComponent = ApiErrorComponent;
734exports.ApiStateComponent = ApiStateComponent;
735exports.ApiActions = ApiActions;
736exports.ApiHttpService = ApiHttpService;
737exports.ApiReducer = ApiReducer;
738exports.ApiStatusReducer = ApiStatusReducer;
739
740Object.defineProperty(exports, '__esModule', { value: true });
741
742})));