forked from openiap/opencore
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCommonControllers.ts
More file actions
737 lines (685 loc) · 29.4 KB
/
Copy pathCommonControllers.ts
File metadata and controls
737 lines (685 loc) · 29.4 KB
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
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
import angular = require("angular");
import { WebSocketClientService } from "./WebSocketClientService";
import { NoderedUtil } from "@openiap/openflow-api";
export class api {
static $inject = ["$rootScope", "$location", "WebSocketClientService"];
constructor(public $rootScope: ng.IRootScopeService, public $location, public WebSocketClientService: WebSocketClientService) {
}
}
function _timeSince(timeStamp) {
const now: Date = new Date(),
secondsPast: number = (now.getTime() - timeStamp.getTime()) / 1000;
if (secondsPast < 60) {
return parseInt(secondsPast.toString()) + 's';
}
if (secondsPast < 3600) {
return parseInt((secondsPast / 60).toString()) + 'm';
}
if (secondsPast <= 86400) {
return parseInt((secondsPast / 3600).toString()) + 'h';
}
if (secondsPast > 86400) {
let day = timeStamp.getDate();
let month = timeStamp.toDateString().match(/ [a-zA-Z]*/)[0].replace(" ", "");
let year = timeStamp.getFullYear() == now.getFullYear() ? "" : " " + timeStamp.getFullYear();
return day + " " + month + year;
}
}
export class timesince implements ng.IDirective {
// restrict = 'E';
require = 'ngModel';
replace = true;
constructor(public $location: ng.ILocationService, public $timeout: ng.ITimeoutService) {
}
link: ng.IDirectiveLinkFn = (scope: ng.IScope, element: ng.IAugmentedJQuery, attr: ng.IAttributes, ngModelCtrl: any) => {
scope.$watch(() => {
if (ngModelCtrl.$viewValue === null || ngModelCtrl.$viewValue === undefined) { return; }
const timeStamp = ngModelCtrl.$viewValue;
element.text(_timeSince(new Date(timeStamp)));
});
}
static factory(): ng.IDirectiveFactory {
const directive = ($location: ng.ILocationService, $timeout: ng.ITimeoutService) => new timesince($location, $timeout);
directive.$inject = ['$location', '$timeout'];
return directive;
}
}
export class formatBytes implements ng.IDirective {
// restrict = 'E';
require = 'ngModel';
replace = true;
constructor(public $location: ng.ILocationService, public $timeout: ng.ITimeoutService) {
}
formatBytes(bytes, decimals = 2) {
if (bytes === 0) return '0 Bytes';
const k = 1024;
const dm = decimals < 0 ? 0 : decimals;
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
}
link: ng.IDirectiveLinkFn = (scope: ng.IScope, element: ng.IAugmentedJQuery, attr: ng.IAttributes, ngModelCtrl: any) => {
scope.$watch(() => {
if (ngModelCtrl.$viewValue === null || ngModelCtrl.$viewValue === undefined) { return; }
const size = ngModelCtrl.$viewValue;
try {
element.text(this.formatBytes(size));
} catch (error) {
console.error(error);
}
});
}
static factory(): ng.IDirectiveFactory {
const directive = ($location: ng.ILocationService, $timeout: ng.ITimeoutService) => new formatBytes($location, $timeout);
directive.$inject = ['$location', '$timeout'];
return directive;
}
}
export class whenScrolled implements ng.IDirective {
constructor(public $rootScope: ng.IRootScopeService, public $window: ng.IWindowService, public $timeout: ng.ITimeoutService) {
}
link: ng.IDirectiveLinkFn = (scope: ng.IScope, elem: ng.IAugmentedJQuery, attrs: ng.IAttributes, ngModelCtrl: any) => {
var checkWhenEnabled, handler, scrollDistance, scrollEnabled;
// var $window = angular.element(this.$window);
scrollDistance = 1;
if (attrs.whenScrolledDistance != null) {
scope.$watch(attrs.whenScrolledDistance, (value: any) => {
return scrollDistance = parseInt(value, 10);
});
}
scrollEnabled = true;
checkWhenEnabled = false;
if (attrs.whenScrolledDisabled != null) {
scope.$watch(attrs.whenScrolledDisabled, (value) => {
scrollEnabled = !value;
if (scrollEnabled && checkWhenEnabled) {
checkWhenEnabled = false;
return handler();
}
});
}
handler = (e) => {
var ele = elem[0].getBoundingClientRect();
var scrollTop = window.scrollY || window.pageYOffset || document.body.scrollTop + (document.documentElement && document.documentElement.scrollTop || 0)
var elementBottom, remaining, shouldScroll, windowBottom;
windowBottom = window.innerHeight + scrollTop;
elementBottom = ele.top + ele.height;
remaining = elementBottom - windowBottom;
shouldScroll = remaining <= this.$window.innerHeight * scrollDistance;
if (shouldScroll && scrollEnabled && ele.height > 300) {
if (this.$rootScope.$$phase) {
return scope.$eval(attrs.whenScrolled);
} else {
return scope.$apply(attrs.whenScrolled);
}
} else if (shouldScroll) {
return checkWhenEnabled = true;
}
};
var mousewheelevt = (/Firefox/i.test(navigator.userAgent)) ? "DOMMouseScroll" : "mousewheel" //FF doesn't recognize mousewheel as of FF3.x
var doc = document as any;
if (doc.attachEvent)
doc.attachEvent("on" + mousewheelevt, handler)
else if (document.addEventListener) //WC3 browsers
document.addEventListener(mousewheelevt, handler, false)
// angular.element(this.$window).on('scroll', handler);
scope.$on('$destroy', () => {
var doc = document as any;
if (doc.detachEvent)
doc.detachEvent("on" + mousewheelevt, handler)
else if (document.removeEventListener) //WC3 browsers
document.removeEventListener(mousewheelevt, handler, false)
// return this.$window.off('scroll', handler);
});
return this.$timeout((() => {
if (attrs.whenScrolledImmediateCheck) {
if (scope.$eval(attrs.whenScrolledImmediateCheck)) {
return handler();
}
} else {
return handler();
}
}))
}
static factory(): ng.IDirectiveFactory {
const directive = ($rootScope: ng.IRootScopeService, $window: ng.IWindowService, $timeout: ng.ITimeoutService) => new whenScrolled($rootScope, $window, $timeout);
directive.$inject = ['$rootScope', '$window', '$timeout'];
return directive;
}
}
export class textarea implements ng.IDirective {
// restrict = 'E';
// require = 'ngModel';
replace = true;
constructor(public $location: ng.ILocationService, public $timeout: ng.ITimeoutService) {
}
link: ng.IDirectiveLinkFn = (scope: ng.IScope, element: ng.IAugmentedJQuery, attr: ng.IAttributes, ngModelCtrl: any) => {
if (!element.hasClass("autogrow")) {
// no autogrow for you today
return;
}
// get possible minimum height style
const minHeight = parseInt(window.getComputedStyle(element[0]).getPropertyValue("min-height")) || 0;
// prevent newlines in textbox
// element.on("keydown", function (evt) {
// if (evt.which === 13) {
// evt.preventDefault();
// }
// });
element.on("input", function (evt) {
const contentHeight2 = (this as any).scrollHeight;
const firstrun = element.attr("firstrun");
if (contentHeight2 > 1000) {
if (firstrun === null || firstrun === undefined) {
element.attr("firstrun", "false");
} else {
return;
}
}
{
element.css({
paddingTop: 0,
height: 0,
minHeight: 0
});
const contentHeight = (this as any).scrollHeight;
const borderHeight = (this as any).offsetHeight;
element.css({
paddingTop: ~~Math.max(0, minHeight - contentHeight) / 2 + "px",
minHeight: null, // remove property
height: contentHeight + borderHeight + "px" // because we're using border-box
});
}
});
// watch model changes from the outside to adjust height
scope.$watch(attr.ngModel, trigger);
// set initial size
trigger();
function trigger() {
setTimeout(element.triggerHandler.bind(element, "input"), 1);
}
}
static factory(): ng.IDirectiveFactory {
const directive = ($location: ng.ILocationService, $timeout: ng.ITimeoutService) => new textarea($location, $timeout);
directive.$inject = ['$location', '$timeout'];
return directive;
}
}
async function getString(locale: any, lib: string, key: string): Promise<any> {
return new Promise((resolve) => {
try {
if (locale === null || locale === undefined) { return }
locale.ready(lib).then(function () {
const value = locale.getString(lib + "." + key);
if (value !== null && value !== undefined && value !== "") {
resolve(value);
} else {
resolve(key);
}
});
} catch (error) {
}
});
}
const global_translate_notfound: string[] = [];
export class translate implements ng.IDirective {
require = '?ngModel';
replace = true;
constructor(public $location: ng.ILocationService, public $timeout: ng.ITimeoutService, public locale) {
}
link: ng.IDirectiveLinkFn = (scope: ng.IScope, element: ng.IAugmentedJQuery, attr: ng.IAttributes, ngModelCtrl: any) => {
const calculateValue = (value: string): string => {
try {
if (value === null || value === undefined || value === "") return value;
const lib = (attr.lib ? attr.lib : "common");
if ((value.toString()).startsWith(lib + ".")) { return; }
const key: string = (lib + "." + value).toLowerCase();
let result = this.locale.getString(key);
if (result.startsWith(lib + ".")) { result = result.slice((lib + ".").length); }
// const result = await getString(this.locale, lib, value);
if (result == "%%KEY_NOT_FOUND%%" || result == "") {
if (global_translate_notfound.indexOf(lib + "." + value) === -1) {
global_translate_notfound.push(lib + "." + value);
console.debug("KEY_NOT_FOUND " + lib + "." + value);
}
result = value;
}
return result;
} catch (error) {
console.error(error);
return "error";
}
};
const lib = (attr.lib ? attr.lib : "common");
this.locale.ready(lib).then(() => {
let value: string = null;
if (ngModelCtrl !== null) {
ngModelCtrl.$formatters.push(function (value) {
return calculateValue(value);
});
} else {
const hashCode = (s: string) => {
return s.split("").reduce(function (a, b) { a = ((a << 5) - a) + b.charCodeAt(0); return a & a }, 0);
}
if (attr.value !== null && attr.value !== undefined && element[0].tagName !== "OPTION") {
value = calculateValue(attr.value);
attr.$set('value', value);
} else {
value = element.text();
if (value !== null || value !== undefined) {
const result = calculateValue(value);
element.text(result);
}
}
}
});
}
static factory(): ng.IDirectiveFactory {
const directive = ($location: ng.ILocationService, $timeout: ng.ITimeoutService, locale) => new translate($location, $timeout, locale);
directive.$inject = ['$location', '$timeout', 'locale'];
return directive;
}
}
export class userdata {
public data: any;
constructor() {
this.data = {};
}
}
export class copytext implements ng.IDirective {
restrict = 'A';
require = '?ngModel';
constructor(public $location: ng.ILocationService, public $timeout: ng.ITimeoutService, public locale) {
}
link: ng.IDirectiveLinkFn = (scope: ng.IScope, element: ng.IAugmentedJQuery, attr: ng.IAttributes, ngModelCtrl: any) => {
console.debug("copytext", element);
if (!ngModelCtrl) return;
element.attr('unselectable', 'on');
element.on('mousedown', function (e, eventData) {
/* istanbul ignore else: this is for catching the jqLite testing*/
if (eventData) angular.extend(e, eventData);
// this prevents focusout from firing on the editor when clicking toolbar buttons
e.preventDefault();
console.debug("Prevent mousedown");
return false;
});
}
static factory(): ng.IDirectiveFactory {
const directive = ($location: ng.ILocationService, $timeout: ng.ITimeoutService, locale) => new copytext($location, $timeout, locale);
directive.$inject = ['$location', '$timeout', 'locale'];
return directive;
}
}
export class jsonText implements ng.IDirective {
restrict = 'A';
require = '?ngModel';
constructor(public $location: ng.ILocationService, public $timeout: ng.ITimeoutService, public locale) {
}
link: ng.IDirectiveLinkFn = (scope: ng.IScope, element: ng.IAugmentedJQuery, attr: ng.IAttributes, ngModelCtrl: any) => {
function into(input) {
return JSON.parse(input);
}
function out(data) {
return JSON.stringify(data, null, 2);
}
ngModelCtrl.$parsers.push(into);
ngModelCtrl.$formatters.push(out);
}
static factory(): ng.IDirectiveFactory {
const directive = ($location: ng.ILocationService, $timeout: ng.ITimeoutService, locale) => new jsonText($location, $timeout, locale);
directive.$inject = ['$location', '$timeout', 'locale'];
return directive;
}
}
export class fileread implements ng.IDirective {
restrict = 'A';
require = '?ngModel';
constructor(public $location: ng.ILocationService, public $timeout: ng.ITimeoutService, public locale) {
}
link: ng.IDirectiveLinkFn = (scope: ng.IScope, element: ng.IAugmentedJQuery, attr: ng.IAttributes, ngModelCtrl: any) => {
if (!ngModelCtrl) return;
ngModelCtrl.$render = function () { };
element.bind('change', function (changeEvent) {
const reader = new FileReader();
reader.onload = function (loadEvent) {
scope.$apply(function () {
const base64result = ((loadEvent.target as any).result as string).split(',')[1];
ngModelCtrl.$setViewValue(base64result);
(scope as any).filename = (changeEvent.target as any).files[0].name;
(scope as any).type = (changeEvent.target as any).files[0].type;
});
}
if ((changeEvent.target as any).files != null && (changeEvent.target as any).files.length > 0) {
reader.readAsDataURL((changeEvent.target as any).files[0]);
}
}); //change
}
static factory(): ng.IDirectiveFactory {
const directive = ($location: ng.ILocationService, $timeout: ng.ITimeoutService, locale) => new fileread($location, $timeout, locale);
directive.$inject = ['$location', '$timeout', 'locale'];
return directive;
}
}
export class entitiesCtrl<T> {
public loading: boolean = false;
public basequery: any = {};
public baseprojection: any = {};
public collection: string = "entities";
public models: T[] = [];
public orderby: any = { _id: -1 };
public autorefresh: boolean = false;
public autorefreshinterval: number = 30 * 1000;
public pagesize: number = 100;
public autorefreshpromise: any = null;
public preloadData: any = null;
public postloadData: any = null;
public searchstring: string = "";
public searchfields: string[] = ["name"];
public basequeryas: string = null;
public errormessage: string = "";
public skipcustomerfilter: boolean = false;
public page: number = 0;
public static $inject = [
"$rootScope",
"$scope",
"$location",
"$routeParams",
"$interval",
"WebSocketClientService",
"api",
"userdata"
];
constructor(
public $rootScope: ng.IRootScopeService,
public $scope: ng.IScope,
public $location: ng.ILocationService,
public $routeParams: ng.route.IRouteParamsService,
public $interval: ng.IIntervalService,
public WebSocketClientService: WebSocketClientService,
public api: api,
public userdata: userdata
) {
if (this.userdata.data != null && this.userdata.data) {
if (this.userdata.data.basequery != null) {
this.basequery = this.userdata.data.basequery;
delete this.userdata.data.basequery;
}
if (this.userdata.data.searchstring != null) {
this.searchstring = this.userdata.data.searchstring;
this.$rootScope.$broadcast("setsearch", this.searchstring);
delete this.userdata.data.searchstring;
}
if (this.userdata.data.basequeryas != null) {
this.basequeryas = this.userdata.data.basequeryas;
delete this.userdata.data.basequeryas;
}
}
this.$scope.$on('search', (event, data) => {
this.searchstring = data;
this.loadData();
});
}
public static parseJson(txt, reviver, context) {
context = context || 20
try {
return JSON.parse(txt, reviver)
} catch (e) {
if (typeof txt !== "string") {
const isEmptyArray = Array.isArray(txt) && txt.length === 0
const errorMessage = "Cannot parse " +
(isEmptyArray ? "an empty array" : String(txt))
throw new TypeError(errorMessage)
}
const syntaxErr = e.message.match(/^Unexpected token.*position\s+(\d+)/i)
const errIdx = syntaxErr
? +syntaxErr[1]
: e.message.match(/^Unexpected end of JSON.*/i)
? txt.length - 1
: null
if (errIdx != null) {
const start = errIdx <= context
? 0
: errIdx - context
const end = errIdx + context >= txt.length
? txt.length
: errIdx + context
e.message += ` while parsing near "${start === 0 ? "" : "..."
}${txt.slice(start, end)}${end === txt.length ? "" : "..."
}"`
} else {
e.message += ` while parsing "${txt.slice(0, context * 2)}"`
}
throw e
}
}
async loadData(): Promise<void> {
try {
if (this.loading == true) { console.debug("allready loading data, exit"); return; }
this.$rootScope.$broadcast("setsearch", this.searchstring);
this.errormessage = "";
this.loading = true;
if (this.preloadData != null) {
this.preloadData();
}
let query: object = Object.assign({}, this.basequery);
let exactquery: object = null;
let basequeryas = this.basequeryas;
if (this.collection == "users" && (this.basequery._type == "user" || this.basequery._type == "role") && !this.skipcustomerfilter && this.WebSocketClientService.multi_tenant) {
// if (!NoderedUtil.IsNullUndefinded(this.WebSocketClientService.customer) && !this.skipcustomerfilter) {
// basequeryas = this.WebSocketClientService.customer._id;
// }
if (this.WebSocketClientService.customer && !NoderedUtil.IsNullEmpty(this.WebSocketClientService.customer._id)) {
query["customerid"] = this.WebSocketClientService.customer._id;
}
}
if (this.searchstring !== "" && this.searchstring != null) {
if ((this.searchstring as string).indexOf("{") == 0) {
if ((this.searchstring as string).lastIndexOf("}") == ((this.searchstring as string).length - 1)) {
try {
query = entitiesCtrl.parseJson(this.searchstring, null, null);
} catch (error) {
this.errormessage = error.message ? error.message : error;
}
}
} else {
const finalor = [];
const finalexactor = [];
for (let i = 0; i < this.searchfields.length; i++) {
const newq: any = {};
const newexactq: any = {};
// exact match case sensitive
// newq[this.searchfields[i]] = this.searchstring;
// exact match case insensitive
newexactq[this.searchfields[i]] = new RegExp(["^", this.searchstring, "$"].join(""), "i");
// exact match string contains
newq[this.searchfields[i]] = new RegExp([this.searchstring].join(""), "i");
finalor.push(newq);
finalexactor.push(newexactq);
}
if (Object.keys(query).length == 0) {
query = { $or: finalor.concat() };
exactquery = { $or: finalexactor.concat() };
} else {
query = { $and: [query, { $or: finalor.concat() }] };
exactquery = { $and: [query, { $or: finalexactor.concat() }] };
}
}
}
if (this.page == 0) {
this.models = await NoderedUtil.Query(this.collection, query, this.baseprojection, this.orderby, this.pagesize, 0, null, basequeryas, null, 2);
} else {
var temp = await NoderedUtil.Query(this.collection, query, this.baseprojection, this.orderby, this.pagesize, this.pagesize * this.page, null, basequeryas, null, 2);
this.models = this.models.concat(temp);
}
if (exactquery != null && this.page == 0) {
var temp = await NoderedUtil.Query(this.collection, exactquery, this.baseprojection, this.orderby, 1, 0, null, basequeryas, null, 2);
if (temp.length > 0) {
this.models = this.models.filter(x => (x as any)._id != temp[0]._id);
this.models = temp.concat(this.models);
}
}
this.loading = false;
if (this.autorefresh) {
if (this.models.length >= this.pagesize || this.page > 0) {
// console.warn("Disabling auto refresh, result has more than pagesize entries");
} else {
if (this.autorefreshpromise == null && this.searchstring === "") {
this.autorefreshpromise = this.$interval(() => {
this.loadData();
}, this.autorefreshinterval);
this.$scope.$on('$destroy', () => {
this.$interval.cancel(this.autorefreshpromise);
});
}
}
}
if (this.postloadData != null) {
this.postloadData();
} else {
if (!this.$scope.$$phase) { this.$scope.$apply(); }
}
} catch (error) {
this.loading = false;
this.errormessage = JSON.stringify(error);
if (!this.$scope.$$phase) { this.$scope.$apply(); }
}
}
more() {
if (this.loading == true) { console.debug("allready loading data, exit"); return; }
if (this.models.length < (this.pagesize - 15)) { console.debug("Seems there are no more data, exit"); return; }
this.page++;
console.log("loading more ... page: " + (this.page + 1))
this.loadData();
}
ToggleOrder(field: string) {
if (this.orderby == null) this.orderby = {};
if (this.orderby[field] == undefined) {
this.orderby = {};
}
if (this.orderby[field] == -1) {
this.orderby[field] = 1;
} else {
this.orderby[field] = -1;
}
if (field === '_type') {
this.orderby["type"] = this.orderby[field];
}
this.page = 0;
this.loadData();
}
async DeleteOne(model: any): Promise<any> {
this.loading = true;
this.errormessage = "";
try {
await NoderedUtil.DeleteOne(this.collection, model._id, null, 2);
this.models = this.models.filter(function (m: any): boolean { return m._id !== model._id; });
} catch (error) {
this.errormessage = error.message ? error.message : error;
}
this.loading = false;
if (!this.$scope.$$phase) { this.$scope.$apply(); }
}
async Search() {
await this.loadData();
}
}
export function nestedassign(target, source) {
if (source === null || source === undefined) return null;
const keys = Object.keys(source);
for (let i = 0; i < keys.length; i++) {
const sourcekey = keys[i];
if (Object.keys(source).find(targetkey => targetkey === sourcekey) !== undefined &&
Object.keys(source).find(targetkey => targetkey === sourcekey) !== null
&& typeof source === "object" && typeof source[sourcekey] === "object") {
target[sourcekey] = nestedassign(target[sourcekey], source[sourcekey]);
} else {
target[sourcekey] = source[sourcekey];
}
}
return target;
}
export class entityCtrl<T> {
public loading: boolean = false;
public basequery: any = {};
public baseprojection: any = {};
public collection: string = "entities";
public model: T = null;
public id: string = null;
public keys: string[] = [];
public autorefresh: boolean = false;
public autorefreshinterval: number = 30 * 1000;
public autorefreshpromise: any = null;
public preloadData: any = null;
public postloadData: any = null;
public errormessage: string = "";
public static $inject = [
"$rootScope",
"$scope",
"$location",
"$routeParams",
"$interval",
"WebSocketClientService",
"api"
];
constructor(
public $rootScope: ng.IRootScopeService,
public $scope: ng.IScope,
public $location: ng.ILocationService,
public $routeParams: ng.route.IRouteParamsService,
public $interval: ng.IIntervalService,
public WebSocketClientService: WebSocketClientService,
public api: api
) {
this.id = $routeParams.id;
this.basequery = { _id: this.id };
}
async loadData(): Promise<void> {
try {
if (this.loading == true) { console.debug("allready loading data, exit"); return; }
this.errormessage = "";
let updated: boolean = false;
this.loading = true;
if (this.preloadData != null) {
this.preloadData();
}
const result = await NoderedUtil.Query(this.collection, this.basequery, this.baseprojection, null, 1, 0, null, null, null, 2);
if (result.length > 0) {
if (this.model == null) {
this.model = result[0];
updated = true;
} else {
if (!angular.equals(this.model, result[0])) {
this.model = result[0];
updated = true;
}
}
}
if (updated) {
this.keys = Object.keys(this.model);
for (let i: number = this.keys.length - 1; i >= 0; i--) {
if (this.keys[i].startsWith('_')) this.keys.splice(i, 1);
}
}
this.loading = false;
if (this.postloadData != null) {
this.postloadData();
} else {
if (!this.$scope.$$phase) { this.$scope.$apply(); }
}
if (this.autorefresh) {
if (this.autorefreshpromise == null) {
this.autorefreshpromise = this.$interval(() => {
this.loadData();
}, this.autorefreshinterval);
this.$scope.$on('$destroy', () => {
this.$interval.cancel(this.autorefreshpromise);
});
}
}
} catch (error) {
this.loading = false;
this.errormessage = JSON.stringify(error);
if (!this.$scope.$$phase) { this.$scope.$apply(); }
}
}
}