UNPKG

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