@questwork/q-utilities 0.1.16 → 0.1.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,3521 +0,0 @@
1
-
2
- ;// ./lib/helpers/authorize/authorize.js
3
- function authorize({ allowCoordinator, allowOwner, query = {}, required, user }) {
4
- if (!user) {
5
- throw new Error('Require login.')
6
- }
7
- if (!user.permission) {
8
- // throw new Error('You do not have any permission.')
9
- }
10
- const scopes = user.permission.getScopes(required || {}) || []
11
- if (!scopes || scopes.length === 0) {
12
- // throw new Error('You are not allowed in this scope.')
13
- }
14
- if (!scopes.includes('*')) {
15
- query.tenantCode = user.tenantCode
16
- }
17
- if (!scopes.includes('TENANT')) {
18
- query.eventShortCode = user.eventShortCode
19
- }
20
- // if (!scopes.includes('EVENT')) {
21
- // query.eventRegistrationCode = user.eventRegistrationCode
22
- // }
23
- if (allowCoordinator) {
24
- if (query.registrationGroupCode && user.myManagedRegistrationGroupCodes.includes(query.registrationGroupCode)) {
25
- query.__ALLOW_COORDINATOR = true
26
- } else {
27
- if (!scopes.includes('EVENT')) {
28
- query.eventRegistrationCode = user.eventRegistrationCode
29
- }
30
- }
31
- } else {
32
- if (!scopes.includes('EVENT')) {
33
- query.eventRegistrationCode = user.eventRegistrationCode
34
- }
35
- }
36
- if (allowOwner) {
37
- query.__ALLOW_OWNER = true
38
- }
39
- // not good, just use it as example
40
- if (user.hasExcludedFields) {
41
- query.__EXCLUDED_FIELDS = user.getExcludedFields(required)
42
- }
43
- query.__LOGIN_SUBJECT_CODE = user.loginSubjectCode
44
- return query
45
- }
46
-
47
- ;// ./lib/helpers/authorize/index.js
48
-
49
-
50
- ;// ./lib/helpers/changeCreatorOwner/changeCreatorOwner.js
51
- function changeCreatorOwner(that, { source, target }) {
52
- if (that.meta) {
53
- if (!that.meta.creator || that.meta.creator === source.getId()) {
54
- that.meta.creator = target.getId()
55
- }
56
- if (!that.meta.owner || that.meta.owner === source.getId()) {
57
- that.meta.owner = target.getId()
58
- }
59
- } else {
60
- if (!that.creator || that.creator === source.getId()) {
61
- that.creator = target.getId()
62
- }
63
- if (!that.owner || that.owner === source.getId()) {
64
- that.owner = target.getId()
65
- }
66
- }
67
- return that
68
- }
69
-
70
- ;// ./lib/helpers/changeCreatorOwner/index.js
71
-
72
-
73
- ;// ./lib/helpers/getValidation/getValidation.js
74
- function getValidation(rule, data, getDataByKey, KeyValueObject) {
75
- if (!rule) {
76
- return true
77
- }
78
- if (typeof getDataByKey !== 'function' || (KeyValueObject && typeof KeyValueObject !== 'function')) {
79
- return false
80
- }
81
- const { key = '', value, placeholder, keyValuePath = '' } = rule
82
- const [valueAttribute] = Object.keys(value)
83
-
84
- if (!key && typeof placeholder === 'undefined') {
85
- switch (valueAttribute) {
86
- case '$and': {
87
- return value['$and'].reduce((acc, item) => (acc && getValidation(item, data, getDataByKey, KeyValueObject)), true)
88
- }
89
- case '$or': {
90
- return value['$or'].reduce((acc, item) => (acc || getValidation(item, data, getDataByKey, KeyValueObject)), false)
91
- }
92
- default:
93
- return false
94
- }
95
- }
96
- let rowValue = typeof placeholder === 'undefined' ? getDataByKey(key, data) : placeholder
97
-
98
- // if KeyValue object
99
- if (keyValuePath) {
100
- const rowValueData = KeyValueObject.toObject(rowValue)
101
- rowValue = getDataByKey(keyValuePath, rowValueData)
102
- }
103
-
104
- switch (valueAttribute) {
105
- case '$empty': {
106
- const isEmpty = rowValue === null || rowValue === undefined
107
- return isEmpty === value['$empty']
108
- }
109
- case '$eq': {
110
- return rowValue === value['$eq']
111
- }
112
- case '$gt': {
113
- return rowValue > value['$gt']
114
- }
115
- case '$gte': {
116
- return rowValue >= value['$gte']
117
- }
118
- case '$hasOverlap': {
119
- return _hasOverlap(rowValue, value['$hasOverlap'])
120
- }
121
- case '$lt': {
122
- return rowValue < value['$lt']
123
- }
124
- case '$lte': {
125
- return rowValue <= value['$lte']
126
- }
127
- case '$in': {
128
- if (Array.isArray(rowValue)) {
129
- return !!rowValue.find((e) => (value['$in'].includes(e)))
130
- }
131
- if (typeof rowValue !== 'object') {
132
- return !!value['$in'].includes(rowValue)
133
- }
134
- return false
135
- }
136
- case '$inValue': {
137
- const result = getDataByKey(value['$inValue'], data)
138
- const _value = Array.isArray(result) ? result : []
139
- if (Array.isArray(rowValue)) {
140
- return !!rowValue.find((e) => (_value.includes(e)))
141
- }
142
- if (typeof rowValue === 'string') {
143
- return !!_value.includes(rowValue)
144
- }
145
- return false
146
- }
147
- case '$ne': {
148
- return rowValue !== value['$ne']
149
- }
150
- case '$notIn': {
151
- if (Array.isArray(rowValue)) {
152
- return !rowValue.find((e) => (value['$notIn'].includes(e)))
153
- }
154
- if (typeof rowValue !== 'object') {
155
- return !value['$notIn'].includes(rowValue)
156
- }
157
- return false
158
- }
159
- case '$intervalTimeGt': {
160
- const now = new Date().getTime()
161
- const timestamp = new Date(rowValue).getTime()
162
- return (now - timestamp) > value['$intervalTimeGt']
163
- }
164
- case '$intervalTimeLt': {
165
- const now = new Date().getTime()
166
- const timestamp = new Date(rowValue).getTime()
167
- return (now - timestamp) < value['$intervalTimeLt']
168
- }
169
- case '$isToday': {
170
- const currentDate = new Date()
171
- const start = currentDate.setHours(0,0,0,0)
172
- const end = currentDate.setHours(23,59,59,59)
173
- const dateValue = new Date(rowValue).getTime()
174
- return (start <= dateValue && end >= dateValue) === value['$isToday']
175
- }
176
- case '$notInValue': {
177
- const result = getDataByKey(value['$notInValue'], data)
178
- const _value = Array.isArray(result) ? result : []
179
- if (Array.isArray(rowValue)) {
180
- return !rowValue.find((e) => (_value.includes(e)))
181
- }
182
- if (typeof rowValue !== 'object') {
183
- return !_value.includes(rowValue)
184
- }
185
- return false
186
- }
187
- case '$range': {
188
- const [min, max] = value['$range']
189
- if (typeof min === 'number' && typeof max === 'number' && rowValue >= min && rowValue <= max) {
190
- return true
191
- }
192
- return false
193
- }
194
- default:
195
- return false
196
- }
197
-
198
- }
199
-
200
- function _hasOverlap(item1, item2) {
201
- let arr1 = item1
202
- let arr2 = item2
203
- if (typeof arr1 === 'string') {
204
- arr1 = arr1.split(',')
205
- }
206
- if (typeof arr2 === 'string') {
207
- arr2 = arr2.split(',')
208
- }
209
- const set1 = new Set(arr1)
210
- return arr2.find((i) => (set1.has(i)))
211
- }
212
-
213
- /* harmony default export */ const getValidation_getValidation = ({
214
- getValidation
215
- });
216
-
217
-
218
- ;// ./lib/helpers/getValidation/index.js
219
-
220
-
221
- ;// ./lib/helpers/formatDate/formatDate.js
222
-
223
- function formatDate(date, format) {
224
- const _date = date && date instanceof Date ? date : new Date(date)
225
- const dayMapChi = ['日','一','二','三','四','五','六']
226
- const dayMapEng = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday']
227
- const dayMapEngShort = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat']
228
- const _format = format || 'YYYY/MM/DD hh:mm'
229
- const e = _date.getDay()
230
- const ee = dayMapEngShort[e]
231
- const eee = dayMapChi[e]
232
- const eeee = dayMapEng[e]
233
- const y = _date.getFullYear()
234
- const m = _date.getMonth() + 1
235
- const d = _date.getDate()
236
- const h = _date.getHours()
237
- const mm = _date.getMinutes()
238
- const s = _date.getSeconds()
239
-
240
- return _format.replace('YYYY', y)
241
- .replace('MM', padding(m))
242
- .replace('MM', padding(m))
243
- .replace('DD', padding(d))
244
- .replace('hh', padding(h))
245
- .replace('mm', padding(mm))
246
- .replace('ss', padding(s))
247
- .replace('M', m)
248
- .replace('D', d)
249
- .replace('h', h)
250
- .replace('m', mm)
251
- .replace('s', s)
252
- .replace('EEEE', padding(eeee))
253
- .replace('EEE', padding(eee))
254
- .replace('EE', padding(ee))
255
- .replace('E', padding(e))
256
- }
257
-
258
- function padding(m) {
259
- return m < 10 ? `0${m}` : m
260
- }
261
-
262
-
263
- /* harmony default export */ const formatDate_formatDate = ({
264
- formatDate
265
- });
266
-
267
-
268
-
269
- ;// ./lib/helpers/formatDate/index.js
270
-
271
-
272
- ;// ./lib/helpers/getValueByKeys/getValueByKeys.js
273
- // keys can be array or object or string
274
- function getValueByKeys_getValueByKeys(keys, data) {
275
- let _keys = keys
276
- let _data = data
277
- if (typeof keys === 'string') {
278
- _keys = _keys.split('.')
279
- }
280
- if (!Array.isArray(keys) && typeof keys === 'object') {
281
- const { keys: keyArr, obj } = keys
282
- _keys = keyArr
283
- _data = obj
284
- }
285
- if (_keys.length === 0) {
286
- return _data
287
- }
288
- const firstKey = _keys.shift()
289
- if (_data && Object.prototype.hasOwnProperty.call(_data, firstKey)) {
290
- return getValueByKeys_getValueByKeys(_keys, _data[firstKey])
291
- }
292
- if (_data && firstKey) {
293
- return _data[firstKey]
294
- }
295
- return _data
296
-
297
- }
298
- /* harmony default export */ const getValueByKeys = ({
299
- getValueByKeys: getValueByKeys_getValueByKeys
300
- });
301
-
302
-
303
- ;// ./lib/helpers/getValueByKeys/index.js
304
-
305
-
306
- ;// ./lib/models/templateCompiler/templateCompilerException.js
307
- const TEMPLATE_COMPILER_EXCEPTION_TYPE = {
308
- argumentEmptyException: 'Argument is empty',
309
- argumentFormatException: 'Incorrect number or format of argument',
310
- invalidFuntionException: 'Function Name is invalid',
311
- invalidRegExpException: 'Invalid regular expression',
312
- isNotAFunctionException: 'Is not a function',
313
- notExistException: 'Key does not exist',
314
- resultEmptyException: 'Result is empty',
315
- resultMoreThanOneException: 'More than one result'
316
- }
317
-
318
- class TemplateCompilerException extends Error {
319
- constructor(message) {
320
- super(message)
321
- this.message = message
322
- }
323
- }
324
-
325
-
326
-
327
- ;// ./lib/models/templateCompiler/constants.js
328
- const _EMPTY = '_EMPTY'
329
- const _FN_NAMES = [
330
- 'concatIf',
331
- 'divide',
332
- 'eq',
333
- 'exec',
334
- 'filterAll',
335
- 'filterOne',
336
- 'formatDate',
337
- 'get',
338
- 'gt',
339
- 'gte',
340
- 'isEmpty',
341
- 'isNotEmpty',
342
- 'join',
343
- 'lt',
344
- 'lte',
345
- 'map',
346
- 'neq',
347
- 'removeHtml',
348
- 'toLowerCase',
349
- 'toUpperCase',
350
- ]
351
- const _HIDE = '_HIDE'
352
- const _NOT_EMPTY = '_NOT_EMPTY'
353
- const _SELF = '_SELF'
354
- const TAGS_EJS = ['<%=', '%>']
355
- const TAGS_HANDLEBAR = ['{{', '}}']
356
-
357
-
358
-
359
- ;// ./lib/models/templateCompiler/helpers/_concatIf.js
360
-
361
-
362
-
363
-
364
- function _concatIf(data, args) {
365
- if (typeof data !== 'string') {
366
- throw new TemplateCompilerException(`_concatIf: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException}: the data must be string :${data.join(', ')}`)
367
- }
368
- if (args.length !== 3) {
369
- throw new TemplateCompilerException(`_concatIf: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException}: ${args.join(', ')}`)
370
- }
371
- if (data === null || (typeof data === 'undefined')) {
372
- return null
373
- }
374
- const [condition, success, failover] = args
375
- const validConditions = [_EMPTY, _NOT_EMPTY]
376
- if (validConditions.includes(condition) || success.length !== 2) {
377
- throw new TemplateCompilerException(`concatIf: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentEmptyException}: ${condition}, ${success}`)
378
- }
379
- if (data === '' && failover.includes(_HIDE)) {
380
- return ''
381
- }
382
- if (data !== '' && (data !== null || data !== undefined) && failover.includes(_HIDE)) {
383
- return `${success[0]}${data}${success[success.length - 1]}`
384
- }
385
- return failover
386
- }
387
-
388
-
389
-
390
- ;// ./lib/models/templateCompiler/helpers/_divide.js
391
- function _divide(value, divisor) {
392
- try {
393
- if (Number.isNaN(value)) {
394
- return value
395
- }
396
- return (value / divisor)
397
- } catch (e) {
398
- throw e
399
- }
400
- }
401
-
402
-
403
-
404
- ;// ./lib/models/templateCompiler/helpers/_eq.js
405
-
406
-
407
-
408
-
409
- function _eq(data, args) {
410
- if (args.length !== 3) {
411
- throw new TemplateCompilerException(`eq: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException}: ${args.join(', ')}`)
412
- }
413
- if (data === null || (typeof data === 'undefined')) {
414
- return null
415
- }
416
- if (args.includes(_SELF)) {
417
- args = args.map((arg) => {
418
- return (arg === _SELF) ? data : arg
419
- })
420
- }
421
- const expected = args[0]
422
- return data === expected ? args[1] : args[2]
423
- }
424
-
425
-
426
-
427
- ;// ./lib/models/templateCompiler/helpers/_exec.js
428
- function _exec(data, args) {
429
- try {
430
- const [methodName, ..._args] = args
431
- return data[methodName](..._args)
432
- } catch (e) {
433
- throw e
434
- }
435
- }
436
-
437
-
438
-
439
- ;// ./lib/models/templateCompiler/helpers/_filterAll.js
440
-
441
-
442
-
443
- // const DELIMITER = '~~~'
444
-
445
- function _filterAll(data, args) {
446
- try {
447
- if (!Array.isArray(args) || args.length === 0) {
448
- throw new TemplateCompilerException(TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentEmptyException)
449
- }
450
- if (!Array.isArray(data) || data.length === 0) {
451
- return []
452
- }
453
- if (typeof data[0] === 'object') {
454
- return _existObject(data, args)
455
- }
456
- if (typeof data[0] === 'string' || typeof data[0] === 'number') {
457
- return _exist(data, args)
458
- }
459
- return []
460
- } catch (e) {
461
- throw e
462
- }
463
- }
464
-
465
- function _exist(data, args) {
466
- const _args = args.flat()
467
- return data.filter((e) => _args.some((arg) => _performOperation(arg, e)))
468
- }
469
-
470
- function _existObject(data, args) {
471
- if (args.length === 1) {
472
- const arg = args[0]
473
- return data.filter((e) => {
474
- if (arg.includes('.')) {
475
- return getValueByKeys_getValueByKeys(arg.split('.'), e)
476
- }
477
- return Object.prototype.hasOwnProperty.call(e, arg)
478
- })
479
- }
480
-
481
- if (args.length > 2) {
482
- let res = data
483
- for (let i = 0; i < args.length; i += 2) {
484
- const group = [args[i], args[i + 1]]
485
- res = _existObject(res, group)
486
- }
487
- return res
488
- }
489
-
490
- const [key, ..._argsArr] = args
491
- const _args = _argsArr.flat()
492
- return data.filter((e) => {
493
- const value = key.includes('.') ? getValueByKeys_getValueByKeys(key.split('.'), e) : e[key]
494
- return _args.some((arg) => _performOperation(arg, value))
495
- })
496
- }
497
-
498
- function _performOperation(arg, value) {
499
- // the arg is undefined
500
- if (arg === undefined && value === undefined) return true
501
-
502
- // the arg is null
503
- if (arg === null && value === null) return true
504
-
505
- // the arg is boolean
506
- if (typeof arg === 'boolean') {
507
- return arg === value
508
- }
509
-
510
- // the arg is blank or *: Blank => Empty, * => Not Empty
511
- if (arg === '' || arg === '*') {
512
- // null and undefined are not included in either case
513
- if (value === null || value === undefined) {
514
- return false
515
- }
516
- if (typeof value === 'string') {
517
- return arg === '' ? value === '' : value !== ''
518
- }
519
- if (Array.isArray(value)) {
520
- return arg === '' ? value.length === 0 : value.length !== 0
521
- }
522
- return arg !== ''
523
- }
524
-
525
- // the arg is alphabetic or number
526
- if (_isPureStringOrNumber(arg)) {
527
- return arg === value
528
- }
529
-
530
- // the arg is array of [] or [*]: [] => Empty, [*] => Not Empty
531
- if (arg.startsWith('[') && arg.endsWith(']')) {
532
- if (arg === '[]') {
533
- return Array.isArray(value) && value.length === 0
534
- }
535
- if (arg === '[*]') {
536
- return Array.isArray(value) && value.length !== 0
537
- }
538
- return false
539
- }
540
-
541
- // the arg is 'operator + string | number'
542
- const { operator, value: argValue } = _splitOperator(arg)
543
- if (!operator || (argValue !== 0 && !argValue)) {
544
- return false
545
- }
546
- switch (operator) {
547
- case '>':
548
- return value > argValue
549
- case '<':
550
- return value < argValue
551
- case '!=':
552
- return value !== argValue
553
- case '>=':
554
- return value >= argValue
555
- case '<=':
556
- return value <= argValue
557
- default:
558
- return false
559
- }
560
- }
561
-
562
- function _isPureStringOrNumber(input) {
563
- if (typeof input === 'string') {
564
- if (input.startsWith('[') && input.endsWith(']')) {
565
- return false
566
- }
567
- if (/!=|>=|<=|>|</.test(input)) {
568
- return false
569
- }
570
- return true
571
- }
572
- return !Number.isNaN(input)
573
- }
574
-
575
- function _splitOperator(str) {
576
- const operators = ['!=', '>=', '<=', '>', '<']
577
-
578
- const matchedOp = operators.find((op) => str.startsWith(op))
579
- if (!matchedOp) return { operator: null, value: null }
580
-
581
- const remaining = str.slice(matchedOp.length)
582
-
583
- // '>Primary' or '<Primary' is invalid
584
- if (/^[a-zA-Z]*$/.test(remaining) && matchedOp !== '!=') {
585
- return { operator: null, value: null }
586
- }
587
-
588
- // if it is a number it is converted to a number
589
- const value = (!Number.isNaN(parseFloat(remaining)) && !Number.isNaN(remaining)) ? Number(remaining) : remaining
590
-
591
- return {
592
- operator: matchedOp,
593
- value
594
- }
595
- }
596
-
597
-
598
-
599
- ;// ./lib/models/templateCompiler/helpers/_filterOne.js
600
-
601
-
602
-
603
- function _filterOne(data, args) {
604
- try {
605
- const list = _filterAll(data, args)
606
- if (list.length === 1) {
607
- return list[0]
608
- }
609
- if (list.length === 0) {
610
- return null
611
- }
612
- throw new TemplateCompilerException(TEMPLATE_COMPILER_EXCEPTION_TYPE.resultMoreThanOneException)
613
- } catch (e) {
614
- throw e
615
- }
616
- }
617
-
618
-
619
-
620
- ;// ./lib/models/templateCompiler/helpers/_formatDate.js
621
-
622
-
623
- function _formatDate(timestamp, format) {
624
- if (format.length === 0) {
625
- throw new TemplateCompilerException(`_formateDate: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException}: format parts must be not empty array`)
626
- }
627
-
628
- if (timestamp === null || timestamp === undefined) {
629
- return null
630
- }
631
-
632
- const date = new Date(timestamp)
633
-
634
- const partsMap = {
635
- yyyy: String(date.getFullYear()),
636
- mm: String(date.getMonth() + 1).padStart(2, '0'),
637
- dd: String(date.getDate()).padStart(2, '0')
638
- }
639
-
640
- // Check for invalid format tokens
641
- const validTokens = ['yyyy', 'mm', 'dd']
642
- const invalidTokens = format.filter((part) => part.length > 1 && !validTokens.includes(part))
643
-
644
- if (invalidTokens.length > 0) {
645
- throw new TemplateCompilerException(
646
- `_formateDate: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException}: the format type is not valid: ${format.join(', ')}`
647
- )
648
- }
649
-
650
- // Build the formatted string using reduce
651
- return format.reduce((result, part) => result + (partsMap[part] || part), '')
652
- }
653
-
654
-
655
-
656
- ;// ./lib/models/templateCompiler/helpers/_get.js
657
-
658
-
659
- function _get(data, key, failover = null) {
660
- try {
661
- if (key === null || (typeof key === 'undefined') || key === '') {
662
- throw new TemplateCompilerException(TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentEmptyException)
663
- }
664
- if (data === null) {
665
- return null
666
- }
667
- if (key.includes('.')) {
668
- const parts = key.split('.')
669
- if (parts.length > 1) {
670
- const first = parts.shift()
671
- const remainingKey = parts.join('.')
672
- if (typeof data[first] !== 'undefined') {
673
- return _get(data[first], remainingKey, failover)
674
- }
675
- return _handleFailover(key, failover)
676
- }
677
- }
678
- if (typeof data[key] !== 'undefined') {
679
- return data[key]
680
- }
681
- return _handleFailover(key, failover)
682
- } catch (e) {
683
- throw e
684
- }
685
- }
686
-
687
- function _handleFailover(key, failover) {
688
- if (failover !== null) {
689
- return failover
690
- }
691
- return null
692
- // throw new TemplateCompilerException(`Key "${key}" does not exist and no failover`)
693
- }
694
-
695
-
696
-
697
- ;// ./lib/models/templateCompiler/helpers/_gt.js
698
-
699
-
700
-
701
-
702
- function _gt(data, args) {
703
- if (args.length !== 3) {
704
- throw new TemplateCompilerException(`_gt: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException}: ${args.join(', ')}`)
705
- }
706
- if (data === null || (typeof data === 'undefined')) {
707
- return null
708
- }
709
- if (args.includes(_SELF)) {
710
- args = args.map((arg) => {
711
- return (arg === _SELF) ? data : arg
712
- })
713
- }
714
- const expected = args[0]
715
- return data > expected ? args[1] : args[2]
716
- }
717
-
718
-
719
-
720
- ;// ./lib/models/templateCompiler/helpers/_gte.js
721
-
722
-
723
-
724
-
725
- function _gte(data, args) {
726
- if (args.length !== 3) {
727
- throw new TemplateCompilerException(`_gte: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException}: ${args.join(', ')}`)
728
- }
729
- if (data === null || (typeof data === 'undefined')) {
730
- return null
731
- }
732
- if (args.includes(_SELF)) {
733
- args = args.map((arg) => {
734
- return (arg === _SELF) ? data : arg
735
- })
736
- }
737
- const expected = args[0]
738
- return data >= expected ? args[1] : args[2]
739
- }
740
-
741
-
742
-
743
- ;// ./lib/models/templateCompiler/helpers/_isEmpty.js
744
-
745
-
746
-
747
-
748
- function _isEmpty(data, args) {
749
- if (args.length !== 2) {
750
- throw new TemplateCompilerException(`_isEmpty: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException}: ${args.join(', ')}`)
751
- }
752
- // if (data === null || (typeof data === 'undefined')) {
753
- // return null
754
- // }
755
- if (args.includes(_SELF)) {
756
- args = args.map((arg) => {
757
- return (arg === _SELF) ? data : arg
758
- })
759
- }
760
- if (data !== null && typeof data === 'object' && Object.keys(data).length === 0) {
761
- return args[0]
762
- }
763
- return (data === '' || data === null || data === undefined || data.length === 0) ? args[0] : args[1]
764
- }
765
-
766
-
767
-
768
- ;// ./lib/models/templateCompiler/helpers/_isNotEmpty.js
769
-
770
-
771
-
772
-
773
- function _isNotEmpty(data, args) {
774
- if (args.length !== 2) {
775
- throw new TemplateCompilerException(`_isNotEmpty: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException}: ${args.join(', ')}`)
776
- }
777
- // if (data === null || (typeof data === 'undefined')) {
778
- // return null
779
- // }
780
- if (args.includes(_SELF)) {
781
- args = args.map((arg) => {
782
- return (arg === _SELF) ? data : arg
783
- })
784
- }
785
- if (data !== null && typeof data === 'object' && Object.keys(data).length === 0) {
786
- return args[1]
787
- }
788
- if (Array.isArray(data) && data.length === 0) {
789
- return args[1]
790
- }
791
- if (typeof data === 'string' && data === '') {
792
- return args[1]
793
- }
794
- if (data === null || data === undefined) {
795
- return args[1]
796
- }
797
- return args[0]
798
- }
799
-
800
-
801
- ;// ./lib/models/templateCompiler/helpers/_join.js
802
- function _join(data, delimiter) {
803
- try {
804
- if (data.length === 0) return ''
805
- if (data.length === 1) return _stringifyObject(data[0])
806
- return data.map((item) => _stringifyObject(item)).join(delimiter)
807
- } catch (e) {
808
- throw e
809
- }
810
- }
811
-
812
- function _stringifyObject(obj) {
813
- return JSON.stringify(obj).replace(/"([^"]+)":/g, '$1: ').replace(/"([^"]+)"/g, '$1').replace(/,/g, ', ')
814
- }
815
-
816
-
817
-
818
- ;// ./lib/models/templateCompiler/helpers/_lt.js
819
-
820
-
821
-
822
-
823
- function _lt(data, args) {
824
- if (args.length !== 3) {
825
- throw new TemplateCompilerException(`_lt: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException}: ${args.join(', ')}`)
826
- }
827
- if (data === null || (typeof data === 'undefined')) {
828
- return null
829
- }
830
- if (args.includes(_SELF)) {
831
- args = args.map((arg) => {
832
- return (arg === _SELF) ? data : arg
833
- })
834
- }
835
- const expected = args[0]
836
- return data < expected ? args[1] : args[2]
837
- }
838
-
839
-
840
-
841
- ;// ./lib/models/templateCompiler/helpers/_lte.js
842
-
843
-
844
-
845
-
846
- function _lte(data, args) {
847
- if (args.length !== 3) {
848
- throw new TemplateCompilerException(`_lte: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException}: ${args.join(', ')}`)
849
- }
850
- if (data === null || (typeof data === 'undefined')) {
851
- return null
852
- }
853
- if (args.includes(_SELF)) {
854
- args = args.map((arg) => {
855
- return (arg === _SELF) ? data : arg
856
- })
857
- }
858
- const expected = args[0]
859
- return data <= expected ? args[1] : args[2]
860
- }
861
-
862
-
863
-
864
- ;// ./lib/models/templateCompiler/helpers/_map.js
865
-
866
-
867
-
868
- function _map(data, args) {
869
- try {
870
- if (args.length === 0) {
871
- throw new TemplateCompilerException(TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentEmptyException)
872
- }
873
- if (data === null || (typeof data === 'undefined')) {
874
- return null
875
- }
876
-
877
- const result = data.reduce((acc, item) => {
878
- if (args.length === 1 && Array.isArray(args[0])) {
879
- args = args[0]
880
- acc.hasFormat = true
881
- }
882
- const list = args.map((key) => {
883
- if (key.includes('.')) {
884
- const parts = key.split('.')
885
- const first = parts[0]
886
- parts.shift()
887
- const remainingKey = parts.join('.')
888
- return _get(item[first], remainingKey)
889
- }
890
- if (typeof item[key] !== 'undefined') {
891
- return item[key]
892
- }
893
- return null
894
- })
895
- if (acc.hasFormat) {
896
- acc.content.push(list)
897
- } else {
898
- acc.content = acc.content.concat(list)
899
- }
900
- return acc
901
- }, {
902
- content: [],
903
- hasFormat: false
904
- })
905
- return result.content
906
- } catch (e) {
907
- throw e
908
- }
909
- }
910
-
911
-
912
-
913
- ;// ./lib/models/templateCompiler/helpers/_neq.js
914
-
915
-
916
-
917
-
918
- function _neq(data, args) {
919
- if (args.length !== 3) {
920
- throw new TemplateCompilerException(`_neq: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException}: ${args.join(', ')}`)
921
- }
922
- if (data === null || (typeof data === 'undefined')) {
923
- return null
924
- }
925
- if (args.includes(_SELF)) {
926
- args = args.map((arg) => {
927
- return (arg === _SELF) ? data : arg
928
- })
929
- }
930
- const expected = args[0]
931
- return data !== expected ? args[1] : args[2]
932
- }
933
-
934
-
935
-
936
- ;// ./lib/models/templateCompiler/helpers/_removeHtml.js
937
-
938
-
939
- function _removeHtml(html, args) {
940
- if (html === null || html === undefined) {
941
- return null
942
- }
943
- if (!Array.isArray(args)) {
944
- throw new TemplateCompilerException(`_removeHtml: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException}: args parts must be array`)
945
- }
946
-
947
- return _htmlToPlainText(html, args[0])
948
- }
949
-
950
- function _htmlToPlainText(html, delimiter = '\n') {
951
- if (typeof delimiter !== 'string') {
952
- delimiter = '\n'; // Fallback to default if not a string
953
- }
954
-
955
- // First decode HTML entities and normalize whitespace
956
- const decodedHtml = html
957
- .replace(/&nbsp;/g, ' ')
958
- .replace(/\s+/g, ' '); // Collapse all whitespace to single spaces
959
-
960
- // Process HTML tags
961
- let text = decodedHtml
962
- // Replace block tags with temporary marker (~~~)
963
- .replace(/<\/?(p|div|h[1-6]|ul|ol|li|pre|section|article|table|tr|td|th)(\s[^>]*)?>/gi, '~~~')
964
- // Replace <br> tags with temporary marker (~~~)
965
- .replace(/<br\s*\/?>/gi, '~~~')
966
- // Remove all other tags
967
- .replace(/<[^>]+>/g, '')
968
- // Convert markers to specified delimiter
969
- .replace(/~~~+/g, delimiter)
970
- // Trim and clean whitespace
971
- .trim();
972
-
973
- // Special handling for empty delimiter
974
- if (delimiter === '') {
975
- // Collapse all whitespace to single space
976
- text = text.replace(/\s+/g, ' ');
977
- } else {
978
-
979
-
980
- // Collapse multiple delimiters to single
981
- text = text.replace(new RegExp(`${escapeRegExp(delimiter)}+`, 'g'), delimiter);
982
- // Remove leading/trailing delimiters
983
- text = text.replace(new RegExp(`^${escapeRegExp(delimiter)}|${escapeRegExp(delimiter)}$`, 'g'), '');
984
- }
985
-
986
- return text;
987
- }
988
-
989
-
990
- function escapeRegExp(string) {
991
- return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
992
- }
993
-
994
-
995
-
996
- ;// ./lib/models/templateCompiler/helpers/_toLowerCase.js
997
-
998
-
999
- function _toLowerCase(data, args) {
1000
- if (args !== undefined) {
1001
- throw new TemplateCompilerException(`_toLowerCase: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException}: ${args.join(', ')}`)
1002
- }
1003
- if (data === null || (typeof data === 'undefined') || typeof data !== 'string') {
1004
- return null
1005
- }
1006
- return String(data).toLowerCase()
1007
- }
1008
-
1009
-
1010
-
1011
- ;// ./lib/models/templateCompiler/helpers/_toUpperCase.js
1012
-
1013
-
1014
- function _toUpperCase(data, args) {
1015
- if (typeof data !== 'string') {
1016
- throw new TemplateCompilerException(`_toUpperCase: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException}: the data must be string: ${data}`)
1017
- }
1018
- if (args !== undefined) {
1019
- throw new TemplateCompilerException(`_toUpperCase: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException}: the argument must be empty: ${args.join(', ')}`)
1020
- }
1021
- if (data === null || (typeof data === 'undefined') || typeof data !== 'string') {
1022
- return null
1023
- }
1024
- return String(data).toUpperCase()
1025
- }
1026
-
1027
-
1028
-
1029
- ;// ./lib/models/templateCompiler/helpers/index.js
1030
-
1031
-
1032
-
1033
-
1034
-
1035
-
1036
-
1037
-
1038
-
1039
-
1040
-
1041
-
1042
-
1043
-
1044
-
1045
-
1046
-
1047
-
1048
-
1049
-
1050
-
1051
-
1052
-
1053
- ;// ./lib/models/templateCompiler/templateCompiler.js
1054
-
1055
-
1056
-
1057
-
1058
- class TemplateCompiler {
1059
- constructor(data) {
1060
- this.data = data
1061
- }
1062
- static init(options) {
1063
- return new this(options)
1064
- }
1065
- static initFromArray(arr = []) {
1066
- if (Array.isArray(arr)) {
1067
- return arr.map((a) => this.init(a))
1068
- }
1069
- return []
1070
- }
1071
- static initOnlyValidFromArray(arr = []) {
1072
- return this.initFromArray(arr).filter((i) => i)
1073
- }
1074
- static concatIf(data, args) {
1075
- return _concatIf(data, args)
1076
- }
1077
- static divide(data, args) {
1078
- return _divide(data, args)
1079
- }
1080
- static eq(data, args) {
1081
- return _eq(data, args)
1082
- }
1083
-
1084
- static filterAll(data, args) {
1085
- return _filterAll(data, args)
1086
- }
1087
-
1088
- static formatDate(data, args) {
1089
- return _formatDate(data, args)
1090
- }
1091
- static get(data, key, failover = null) {
1092
- return _get(data, key, failover)
1093
- }
1094
- static gt(data, args) {
1095
- return _gt(data, args)
1096
- }
1097
- static gte(data, args) {
1098
- return _gte(data, args)
1099
- }
1100
- static isEmpty(data, args) {
1101
- return _isEmpty(data, args)
1102
- }
1103
- static isNotEmpty(data, args) {
1104
- return _isNotEmpty(data, args)
1105
- }
1106
- static join(data, separator = '') {
1107
- return _join(data, separator)
1108
- }
1109
- static lt(data, args) {
1110
- return _lt(data, args)
1111
- }
1112
- static lte(data, args) {
1113
- return _lte(data, args)
1114
- }
1115
- static map(data, args = []) {
1116
- return _map(data, args)
1117
- }
1118
- static neq(data, args) {
1119
- return _neq(data, args)
1120
- }
1121
- static removeHtml(data, args) {
1122
- return _removeHtml(data, args)
1123
- }
1124
- static toLowerCase(data, args) {
1125
- return _toLowerCase(data, args)
1126
- }
1127
- static toUpperCase(data, args) {
1128
- return _toUpperCase(data, args)
1129
- }
1130
- static parseFunction(expression) {
1131
- return _parseFunction(expression, _FN_NAMES)
1132
- }
1133
- static parseParams(parameters) {
1134
- return _parseParams(parameters)
1135
- }
1136
-
1137
- pipe(expression = '') {
1138
- this.delimiters = expression.substring(0, 2) === '{{' ? TAGS_HANDLEBAR : TAGS_EJS
1139
- const regex = new RegExp(`${this.delimiters[0]}\\s(.*?)\\s${this.delimiters[1]}`)
1140
- const match = expression.match(regex)
1141
- if (match !== null) {
1142
- try {
1143
- const functionList = _parseFunction(match[1], _FN_NAMES)
1144
- return functionList.reduce((acc, fn) => {
1145
- return _callFunction(acc, fn.name, fn.args)
1146
- }, this.data)
1147
- } catch (e) {
1148
- throw new TemplateCompilerException(`TemplateCompiler engine error: ${e.message}`)
1149
- }
1150
- }
1151
- throw new TemplateCompilerException(`TemplateCompiler engine error: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.invalidRegExpException}`)
1152
- }
1153
- }
1154
-
1155
- function _parseFunction(expression, existFunctionNames) {
1156
- const regExp = new RegExp(/(\w+)\(([^)]*)\)/)
1157
- let parts
1158
- if (expression.includes('|')) {
1159
- parts = expression.split('|')
1160
- } else {
1161
- parts = [expression]
1162
- }
1163
- return parts.reduce((acc, part) => {
1164
- const match = part.match(regExp)
1165
- if (match !== null) {
1166
- const functionName = match[1]
1167
- const parameters = match[2]
1168
- const paramList = _parseParams(parameters)
1169
- if (existFunctionNames.includes(functionName)) {
1170
- acc.push({
1171
- name: functionName,
1172
- args: paramList
1173
- })
1174
- } else {
1175
- throw new TemplateCompilerException(`${functionName} is not a valid function`)
1176
- }
1177
- }
1178
- return acc
1179
- }, [])
1180
- }
1181
-
1182
- function _parseParams(parameters) {
1183
- const _parameters = parameters.trim()
1184
- const regExp = new RegExp(/^[^\w\d\s]+$/)
1185
- const match = _parameters.match(regExp)
1186
- if (match !== null) {
1187
- return [_parameters.substring(1, _parameters.length - 1)]
1188
- }
1189
- if (_parameters.includes(',')) {
1190
- // 用正则表达式匹配逗号,但忽略方括号中的逗号
1191
- const parts = _splitIgnoringBrackets(_parameters)
1192
- return parts.map((part) => _parseSinglePart(part))
1193
- }
1194
- return [_parseSinglePart(_parameters)]
1195
- }
1196
-
1197
- function _splitIgnoringBrackets(input) {
1198
- const regExp2 = new RegExp(/^\d+(\.\d+)?$/)
1199
- const regExp = new RegExp(/(?![^\[]*\])\s*,\s*/)
1200
- const parts = input.split(regExp)
1201
- return parts.map((part) => {
1202
- const _part = part.trim()
1203
- if (_part !== '' && !!_part.match(regExp2)) {
1204
- // 如果是数字,转换为 num 类型
1205
- return Number.isNaN(_part) ? _part : parseInt(_part, 10)
1206
- }
1207
- // 否则当作字符串处理
1208
- return _part
1209
- })
1210
- }
1211
-
1212
- function _parseSinglePart(input) {
1213
- if (typeof input === 'string') {
1214
- if (input.startsWith('"') && input.endsWith('"')) {
1215
- // 去掉双引号,返回
1216
- return input.substring(1, input.length - 1)
1217
- }
1218
- if (input.startsWith("'") && input.endsWith("'")) {
1219
- // 去掉双引号,返回
1220
- return input.substring(1, input.length - 1)
1221
- }
1222
-
1223
- const _input = _toBasicType(input)
1224
-
1225
- if (typeof _input !== 'string') {
1226
- return _input
1227
- }
1228
-
1229
- // 如果是一个列表形式(例如 ["p", "d"] 或 [p, d])
1230
- if (_input.startsWith('[') && _input.endsWith(']')) {
1231
- const listContent = _input.substring(1, _input.length - 1).trim()
1232
- if (listContent !== '') {
1233
- return listContent.split(',').map((item) => {
1234
- return _toBasicType(item.trim())
1235
- })
1236
- }
1237
- return []
1238
- }
1239
- return input
1240
- }
1241
- return input
1242
- }
1243
-
1244
- function _toBasicType(input) {
1245
- if (input.startsWith('"') && input.endsWith('"')) {
1246
- // 去掉双引号,返回
1247
- return input.substring(1, input.length - 1)
1248
- }
1249
- if (input.startsWith("'") && input.endsWith("'")) {
1250
- // 去掉双引号,返回
1251
- return input.substring(1, input.length - 1)
1252
- }
1253
- if (input === 'true') {
1254
- return true
1255
- }
1256
- if (input === 'false') {
1257
- return false
1258
- }
1259
- if (input === 'undefined') {
1260
- return undefined
1261
- }
1262
- if (input === 'null') {
1263
- return null
1264
- }
1265
- if (!Number.isNaN(input) && !Number.isNaN(Number.parseFloat(input))) {
1266
- return Number(input)
1267
- }
1268
- return input
1269
- }
1270
-
1271
- function _callFunction(data, functionName, parameters) {
1272
- try {
1273
- let failover
1274
- switch (functionName) {
1275
- case 'concatIf':
1276
- return _concatIf(data, parameters)
1277
- case 'divide':
1278
- return _divide(data, parameters)
1279
- case 'eq':
1280
- return _eq(data, parameters)
1281
- case 'exec':
1282
- return _exec(data, parameters)
1283
- case 'filterAll':
1284
- return _filterAll(data, parameters)
1285
- case 'filterOne':
1286
- return _filterOne(data, parameters)
1287
- case 'formatDate':
1288
- return _formatDate(data, parameters)
1289
- case 'get':
1290
- if (parameters.length > 2) {
1291
- throw new TemplateCompilerException(TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException)
1292
- }
1293
- if (parameters.length === 2) {
1294
- failover = parameters[parameters.length - 1]
1295
- }
1296
- return _get(data, parameters[0], failover)
1297
- case 'gt':
1298
- return _gt(data, parameters)
1299
- case 'gte':
1300
- return _gte(data, parameters)
1301
- case 'isEmpty':
1302
- return _isEmpty(data, parameters)
1303
- case 'isNotEmpty':
1304
- return _isNotEmpty(data, parameters)
1305
- case 'join':
1306
- return _join(data, parameters[0])
1307
- case 'lt':
1308
- return _lt(data, parameters)
1309
- case 'lte':
1310
- return _lte(data, parameters)
1311
- case 'map':
1312
- return _map(data, parameters)
1313
- case 'neq':
1314
- return _neq(data, parameters)
1315
- case 'removeHtml':
1316
- return _removeHtml(data, parameters)
1317
- case 'toLowerCase':
1318
- return _toLowerCase(data)
1319
- case 'toUpperCase':
1320
- return _toUpperCase(data)
1321
- default:
1322
- throw new Error(`${functionName} is not a valid function`)
1323
- }
1324
- } catch (e) {
1325
- throw e
1326
- }
1327
- }
1328
-
1329
-
1330
-
1331
- ;// ./lib/models/templateCompiler/index.js
1332
-
1333
-
1334
-
1335
-
1336
- ;// ./lib/helpers/concatStringByArray/concatStringByArray.js
1337
-
1338
-
1339
-
1340
-
1341
-
1342
- function concatStringByArray(arrTemplate, data) {
1343
- return arrTemplate.reduce((acc, item) => {
1344
- const { type, value = '', restriction, template, format, showMinutes } = item
1345
- switch (type) {
1346
- case('label'): {
1347
- if (getValidation(restriction, data, getValueByKeys_getValueByKeys)) {
1348
- acc += (value.toString())
1349
- }
1350
- break
1351
- }
1352
- case('value'): {
1353
- if (getValidation(restriction, data, getValueByKeys_getValueByKeys)) {
1354
- const _value = getValueByKeys_getValueByKeys(value.split('.'), data) || ''
1355
- acc += (_value.toString())
1356
- }
1357
- break
1358
- }
1359
- case('array'): {
1360
- if (getValidation(restriction, data, getValueByKeys_getValueByKeys)) {
1361
- const _value = getValueByKeys_getValueByKeys(value.split('.'), data) || []
1362
- acc += _value.reduce((_acc, item) => {
1363
- return _acc += concatStringByArray(template, item)
1364
- }, '')
1365
- }
1366
- break
1367
- }
1368
- case('ellipsis'): {
1369
- if (getValidation(restriction, data, getValueByKeys_getValueByKeys)) {
1370
- const { maxLength } = item
1371
- const _value = getValueByKeys_getValueByKeys(value.split('.'), data) || ''
1372
- if (_value.length <= maxLength) {
1373
- acc += (_value.toString())
1374
- } else {
1375
- acc += `${_value.substr(0, maxLength)}...`
1376
- }
1377
- }
1378
- break
1379
- }
1380
- case ('date'): {
1381
- if (getValidation(restriction, data, getValueByKeys_getValueByKeys)) {
1382
- const _value = getValueByKeys_getValueByKeys(value.split('.'), data) || ''
1383
- acc += (formatDate(_value, format).toString())
1384
- }
1385
- break
1386
- }
1387
- case ('templateCompiler'): {
1388
- if (getValidation(restriction, data, getValueByKeys_getValueByKeys)) {
1389
- const templateCompiler = new TemplateCompiler({ data })
1390
- acc += templateCompiler.pipe(value)
1391
- }
1392
- break
1393
- }
1394
- }
1395
- return acc
1396
- }, '')
1397
- }
1398
- /* harmony default export */ const concatStringByArray_concatStringByArray = ({
1399
- concatStringByArray
1400
- });
1401
-
1402
-
1403
-
1404
- ;// ./lib/helpers/concatStringByArray/index.js
1405
-
1406
-
1407
- ;// ./lib/helpers/convertString/convertString.js
1408
-
1409
-
1410
- function convertString(string, patternMatch = /\$\{(.+?)\}/g, value, getValueByKeys) {
1411
- if (!string) {
1412
- return ''
1413
- }
1414
- let _getValueByKeys = typeof getValueByKeys === 'function' ? getValueByKeys : getValueByKeys_getValueByKeys
1415
- const reg = new RegExp(patternMatch, 'g')
1416
- return string.replace(reg, (match, key) => {
1417
- const result = _getValueByKeys({ keys: key.split('.'), obj: value })
1418
- if (result === null || result === undefined) {
1419
- return ''
1420
- }
1421
- return typeof result === 'object' ? JSON.stringify(result) : result
1422
- })
1423
- }
1424
-
1425
- /* harmony default export */ const convertString_convertString = ({
1426
- convertString
1427
- });
1428
-
1429
-
1430
- ;// ./lib/helpers/convertString/index.js
1431
-
1432
-
1433
- ;// ./lib/helpers/escapeRegex/escapeRegex.js
1434
- function escapeRegex(string) {
1435
- return String(string).replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')
1436
- }
1437
-
1438
- ;// ./lib/helpers/escapeRegex/index.js
1439
-
1440
-
1441
- ;// ./lib/helpers/expressHelper/customHandler.js
1442
- function customHandler({ responseHelper, handler, ignoreError = false }) {
1443
- return async (req, res, next) => {
1444
- try {
1445
- await handler({ req, res })
1446
- await next()
1447
- } catch (err) {
1448
- if (ignoreError) {
1449
- await next()
1450
- } else {
1451
- res.status(400).json(responseHelper.standardizeResponse({ err, message: err.message || err }))
1452
- }
1453
- }
1454
- }
1455
- }
1456
-
1457
- ;// ./lib/helpers/expressHelper/findAllResult.js
1458
- function findAllResult({ responseHelper, service }) {
1459
- return async (req, res, next) => {
1460
- try {
1461
- const { query } = req
1462
- const result = await service.findAll({ query })
1463
- res.locals.findAllResult = result
1464
- await next()
1465
- } catch (err) {
1466
- res.status(400).json(responseHelper.standardizeResponse({ err, message: err.message || err }))
1467
- }
1468
- }
1469
- }
1470
-
1471
- ;// ./lib/helpers/expressHelper/findOneResult.js
1472
- function findOneResult({ responseHelper, service }) {
1473
- return async (req, res, next) => {
1474
- try {
1475
- const { params, query } = req
1476
- const { id } = params
1477
- const result = await service.findOne({
1478
- query: {
1479
- ...query,
1480
- id
1481
- }
1482
- })
1483
- res.locals.findOneResult = result
1484
- await next()
1485
- } catch (err) {
1486
- res.status(400).json(responseHelper.standardizeResponse({ err, message: err.message || err }))
1487
- }
1488
- }
1489
- }
1490
-
1491
- ;// ./lib/helpers/expressHelper/postResult.js
1492
- function postResult({ responseHelper, service }) {
1493
- return async (req, res, next) => {
1494
- try {
1495
- const { body } = req
1496
- let result
1497
- if (Array.isArray(body)) {
1498
- result = await service.saveAll({ docs: body })
1499
- } else {
1500
- result = await service.saveOne({ doc: body })
1501
- }
1502
- res.locals.postResult = result
1503
- await next()
1504
- } catch (err) {
1505
- res.status(400).json(responseHelper.standardizeResponse({ err, message: err.message || err }))
1506
- }
1507
- }
1508
- }
1509
-
1510
- ;// ./lib/helpers/expressHelper/updateOneResult.js
1511
- function updateOneResult({ responseHelper, service }) {
1512
- return async (req, res, next) => {
1513
- try {
1514
- const { body, params } = req
1515
- const { id } = params
1516
- if (id !== body.id) {
1517
- throw new Error('id in params and body must be same')
1518
- }
1519
- const { data } = await service.findOne({ query: { id } })
1520
- const doc = data[0]
1521
- doc.update(body)
1522
- const result = await service.saveOne({ doc })
1523
- res.locals.updateOneResult = result
1524
- await next()
1525
- } catch (err) {
1526
- res.status(400).json(responseHelper.standardizeResponse({ err, message: err.message || err }))
1527
- }
1528
- }
1529
- }
1530
-
1531
- ;// ./lib/helpers/expressHelper/index.js
1532
-
1533
-
1534
-
1535
-
1536
-
1537
-
1538
-
1539
- const expressHelper = {
1540
- customHandler: customHandler,
1541
- findAllResult: findAllResult,
1542
- findOneResult: findOneResult,
1543
- postResult: postResult,
1544
- updateOneResult: updateOneResult,
1545
- }
1546
-
1547
- ;// ./lib/helpers/extractEmails/extractEmails.js
1548
- /**
1549
- * Extracts and normalizes unique email addresses from an array containing messy entries
1550
- * @param {Array} dirtyArray - Array that may contain emails in various formats (may include null/empty entries)
1551
- * @returns {Array} Sorted array of unique, lowercase email addresses
1552
- */
1553
- function extractEmails(dirtyArray) {
1554
- const emailRegex = /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g
1555
- const emails = new Set()
1556
-
1557
- // Handle null/undefined input array
1558
- if (!dirtyArray) return []
1559
-
1560
- dirtyArray.forEach(entry => {
1561
- // Skip null, undefined, empty, or whitespace-only entries
1562
- if (!entry || typeof entry !== 'string' || !entry.trim()) return
1563
-
1564
- try {
1565
- const cleanEntry = entry
1566
- .replace(/[\u200B-\u200D\uFEFF\u202A-\u202E]/g, '') // Remove hidden chars
1567
- .replace(/[<>]/g, ' ') // Convert email delimiters to spaces
1568
- .replace(/\s+/g, ' ') // Collapse multiple whitespace
1569
- .trim()
1570
-
1571
- // Extract all email matches
1572
- const matches = cleanEntry.match(emailRegex)
1573
- if (matches) {
1574
- matches.forEach(email => emails.add(email.toLowerCase())) // Normalize to lowercase
1575
- }
1576
- } catch (e) {
1577
- console.warn('Failed to process entry:', entry, e)
1578
- }
1579
- })
1580
-
1581
- // Convert Set to array and sort alphabetically
1582
- return Array.from(emails).sort((a, b) => a.localeCompare(b))
1583
- }
1584
-
1585
- ;// ./lib/helpers/extractEmails/index.js
1586
-
1587
-
1588
- ;// ./lib/helpers/objectHelper/objectHelper.js
1589
- const objectHelper = {
1590
- get(obj, path) {
1591
- const parts = path.split('.')
1592
- return parts.reduce((acc, part) => {
1593
- if (part.endsWith('[]')) {
1594
- // 处理数组遍历
1595
- const key = part.slice(0, -2) // 去掉 '[]' 得到属性名
1596
- if (Array.isArray(acc[key])) {
1597
- return acc[key] // 返回整个数组
1598
- }
1599
- return [] // 如果不是数组,返回空数组
1600
- }
1601
- if (part.includes('[') && part.includes(']')) {
1602
- // 处理数组索引
1603
- const arrayMatch = part.match(/(\w+)\[(\d+)\]/)
1604
- if (arrayMatch) {
1605
- const key = arrayMatch[1]
1606
- const index = arrayMatch[2]
1607
- return acc && acc[key] && acc[key][index]
1608
- }
1609
- } else if (acc && Array.isArray(acc)) {
1610
- // 如果当前值是数组,提取每个对象的指定属性
1611
- return acc.map((item) => item[part])
1612
- } else {
1613
- // 处理普通属性
1614
- return acc && acc[part]
1615
- }
1616
- }, obj)
1617
- },
1618
- merge,
1619
- set(obj, path, value) {
1620
- const parts = path.split('.');
1621
- let current = obj;
1622
-
1623
- // 处理所有中间部分
1624
- for (let i = 0; i < parts.length - 1; i++) {
1625
- const part = parts[i];
1626
- let key, index;
1627
-
1628
- // 检查是否是数组索引格式,如key[0]
1629
- const arrayMatch = part.match(/^(\w+)\[(\d+)\]$/);
1630
- if (arrayMatch) {
1631
- key = arrayMatch[1];
1632
- index = parseInt(arrayMatch[2], 10);
1633
- // 确保当前层级的数组存在
1634
- if (!current[key] || !Array.isArray(current[key])) {
1635
- current[key] = [];
1636
- }
1637
- // 扩展数组到足够大
1638
- while (current[key].length <= index) {
1639
- current[key].push(undefined);
1640
- }
1641
- // 如果当前位置未定义或为null,初始化为对象
1642
- if (current[key][index] == null) {
1643
- current[key][index] = {};
1644
- }
1645
- current = current[key][index];
1646
- } else {
1647
- // 处理普通属性
1648
- if (!current[part]) {
1649
- current[part] = {};
1650
- }
1651
- current = current[part];
1652
- }
1653
- }
1654
-
1655
- // 处理最后一部分
1656
- const lastPart = parts[parts.length - 1];
1657
- const arrayMatch = lastPart.match(/^(\w+)\[(\d+)\]$/);
1658
- if (arrayMatch) {
1659
- const key = arrayMatch[1];
1660
- const index = parseInt(arrayMatch[2], 10);
1661
- // 确保数组存在
1662
- if (!current[key] || !Array.isArray(current[key])) {
1663
- current[key] = [];
1664
- }
1665
- // 扩展数组到所需索引
1666
- while (current[key].length <= index) {
1667
- current[key].push(undefined);
1668
- }
1669
- current[key][index] = value;
1670
- } else {
1671
- current[lastPart] = value;
1672
- }
1673
- }
1674
- }
1675
-
1676
- function merge(target, ...sources) {
1677
- if (!sources.length) return target
1678
-
1679
- const source = sources.shift() // 取出第一个源对象
1680
-
1681
- if (_isObject(target) && _isObject(source)) {
1682
- for (const key in source) {
1683
- if (_isObject(source[key])) {
1684
- if (!target[key]) {
1685
- // 如果目标对象没有该属性,创建一个空对象
1686
- target[key] = {}
1687
- }
1688
- // 递归合并
1689
- merge(target[key], source[key])
1690
- } else {
1691
- // 直接覆盖
1692
- target[key] = source[key]
1693
- }
1694
- }
1695
- }
1696
-
1697
- // 继续合并剩余的源对象
1698
- return merge(target, ...sources)
1699
- }
1700
-
1701
- function _isObject(obj) {
1702
- return obj && typeof obj === 'object' && !Array.isArray(obj)
1703
- }
1704
-
1705
-
1706
-
1707
- ;// ./lib/helpers/objectHelper/index.js
1708
-
1709
-
1710
-
1711
-
1712
- ;// ./lib/helpers/pReduce/pReduce.js
1713
- async function pReduce(iterable, reducer, initialValue) {
1714
- return new Promise((resolve, reject) => {
1715
- const iterator = iterable[Symbol.iterator]()
1716
- let index = 0
1717
-
1718
- const next = async total => {
1719
- const element = iterator.next()
1720
-
1721
- if (element.done) {
1722
- resolve(total)
1723
- return
1724
- }
1725
-
1726
- try {
1727
- const [resolvedTotal, resolvedValue] = await Promise.all([total, element.value])
1728
- next(reducer(resolvedTotal, resolvedValue, index++))
1729
- } catch (error) {
1730
- reject(error)
1731
- }
1732
- }
1733
-
1734
- next(initialValue)
1735
- })
1736
- }
1737
-
1738
-
1739
-
1740
- ;// ./lib/models/repo/repo.js
1741
-
1742
-
1743
- class Repo {
1744
- constructor(options) {
1745
- options = options || {}
1746
- this.model = options.model
1747
- this._sharedOptions = options._sharedOptions // { session: this.dbTransaction }
1748
- this._queryOptions = options._queryOptions
1749
- this._saveOptions = options._saveOptions
1750
- this._Class = options._constructor && options._constructor._Class
1751
- ? options._constructor._Class
1752
- : null
1753
- }
1754
- static init(options = {}) {
1755
- return init(this, options)
1756
- }
1757
- static get _classname() {
1758
- return 'Repo'
1759
- }
1760
- static get _superclass() {
1761
- return 'Repo'
1762
- }
1763
-
1764
- get _classname() {
1765
- return 'Repo'
1766
- }
1767
-
1768
- get _superclass() {
1769
- return 'Repo'
1770
- }
1771
-
1772
- get isValid() {
1773
- return this.model
1774
- && (typeof this.model.deleteOne === 'function')
1775
- && (typeof this.model.findAll === 'function')
1776
- && (typeof this.model.saveOne === 'function')
1777
- }
1778
-
1779
- get queryOptions() {
1780
- return {
1781
- ...this._sharedOptions,
1782
- ...this._queryOptions,
1783
- }
1784
- }
1785
-
1786
- get saveOptions() {
1787
- return {
1788
- ...this._sharedOptions,
1789
- ...this._saveOptions,
1790
- }
1791
- }
1792
-
1793
- init(options) {
1794
- if (this._Class && typeof this._Class.init === 'function') {
1795
- return this._Class.init(options)
1796
- }
1797
- return options
1798
- }
1799
-
1800
- async deleteOne({ id }) {
1801
- try {
1802
- const result = await this.model.deleteOne({ _id: id })
1803
- return {
1804
- ...result, // { message: 'ok', total }
1805
- isNew: false,
1806
- data: []
1807
- }
1808
- } catch (err) {
1809
- throw err
1810
- }
1811
- }
1812
-
1813
- // systemLog is optional
1814
- findAll({ query, systemLog }) {
1815
- const log = _makeLog({
1816
- systemLog,
1817
- label: 'REPO_READ',
1818
- message: `fn ${this._classname}.prototype.findAll`,
1819
- input: [{ query: { ...query }, systemLog: { ...systemLog } }]
1820
- })
1821
- return new Promise((resolve, reject) => {
1822
- this.model.findAll(query, this.queryOptions, (err, data, total) => {
1823
- if (err) {
1824
- log({ level: 'warn', output: err.toString() })
1825
- reject(err)
1826
- } else {
1827
- const result = {
1828
- isNew: false,
1829
- data,
1830
- total: total || data.length
1831
- }
1832
- log({ level: 'info', output: { ...result } })
1833
- resolve(result)
1834
- }
1835
- })
1836
- })
1837
- }
1838
-
1839
- findOne({ query, systemLog }) {
1840
- const log = _makeLog({
1841
- systemLog,
1842
- label: 'REPO_READ',
1843
- message: `fn ${this._classname}.prototype.findOne`,
1844
- input: [{ query: { ...query }, systemLog: { ...systemLog } }]
1845
- })
1846
- return new Promise((resolve, reject) => {
1847
- this.model.findAll(query, this.queryOptions, (err, data) => {
1848
- if (err) {
1849
- reject(err)
1850
- } else if (data.length === 1) {
1851
- const result = {
1852
- isNew: false,
1853
- data,
1854
- total: 1
1855
- }
1856
- log({ level: 'info', output: { ...result } })
1857
- resolve(result)
1858
- } else if (data.length === 0) {
1859
- reject(new Error('record not found'))
1860
- } else {
1861
- reject(new Error('more than one is found'))
1862
- }
1863
- })
1864
- })
1865
- .catch((err) => {
1866
- log({ level: 'warn', output: err.toString() })
1867
- throw err
1868
- })
1869
- }
1870
-
1871
- saveAll({ config = {}, docs, systemLog }) {
1872
- let isNew
1873
- const log = _makeLog({
1874
- systemLog,
1875
- label: 'REPO_WRITE',
1876
- message: `fn ${this._classname}.prototype.saveAll`,
1877
- input: [{ config, docs: [...docs], systemLog: { ...systemLog } }]
1878
- })
1879
- const promise = typeof this.model.saveAll === 'function'
1880
- ? this.model.saveAll({ config, docs })
1881
- : Promise.all(docs.map(async (doc) => {
1882
- if (doc) {
1883
- const result = await this.saveOne({ config, doc })
1884
- isNew = result.isNew
1885
- const _data = result._data || result.data
1886
- return _data[0]
1887
- }
1888
- return null
1889
- }))
1890
- return promise.then((savedData) => {
1891
- if (savedData.length !== 1) isNew = null
1892
- const result = {
1893
- data: savedData,
1894
- isNew,
1895
- total: savedData.length
1896
- }
1897
- log({ level: 'info', output: { ...result } })
1898
- return result
1899
- }).catch((err) => {
1900
- log({ level: 'warn', output: err.toString() })
1901
- throw err
1902
- })
1903
- }
1904
-
1905
- saveOne({ config = {}, doc, systemLog }) {
1906
- const log = _makeLog({
1907
- systemLog,
1908
- label: 'REPO_WRITE',
1909
- message: `fn ${this._classname}.prototype.saveOne`,
1910
- input: [{ config, doc: { ...doc }, systemLog: { ...systemLog } }]
1911
- })
1912
- const saveOptions = {
1913
- ...this.saveOptions,
1914
- ...config,
1915
- }
1916
- return new Promise((resolve, reject) => {
1917
- this.model.saveOne(doc, saveOptions, (err, result) => {
1918
- if (err) {
1919
- log({ level: 'warn', output: err.toString() })
1920
- reject(err)
1921
- } else {
1922
- log({ level: 'info', output: { ...result } })
1923
- resolve(result)
1924
- }
1925
- })
1926
- })
1927
- }
1928
- }
1929
-
1930
- function _makeLog({ systemLog, label, message: message1, input } = {}) {
1931
- return ({ level, messgae: massage2, output } = {}) => {
1932
- if (systemLog && systemLog.systemLogHelper) {
1933
- systemLog.systemLogHelper.log({
1934
- batchId: systemLog.batchId,
1935
- label,
1936
- level,
1937
- message: massage2 || message1,
1938
- data: {
1939
- payload: {
1940
- input,
1941
- output
1942
- }
1943
- }
1944
- })
1945
- }
1946
- }
1947
- }
1948
-
1949
-
1950
-
1951
- ;// ./lib/models/repo/index.js
1952
-
1953
-
1954
-
1955
-
1956
- ;// ./lib/models/apiResponse/apiResponse.js
1957
- class ApiResponse {
1958
- constructor(options = {}) {
1959
- options = options || {}
1960
- this._data = options.data || options._data || []
1961
- this.err = options.err
1962
- this.isNew = options.isNew || false
1963
- this.message = options.message
1964
- this.total = options.total || 0
1965
- this._instanceBuilder = options._instanceBuilder
1966
- }
1967
-
1968
- static init(options = {}) {
1969
- if (options instanceof this) {
1970
- return options
1971
- }
1972
- const instance = new this(options)
1973
- return instance
1974
- }
1975
- static get _classname() {
1976
- return 'ApiResponse'
1977
- }
1978
- static get _superclass() {
1979
- return 'ApiResponse'
1980
- }
1981
-
1982
- // getters
1983
- get data() {
1984
- if (this._instanceBuilder && (typeof this._instanceBuilder === 'function')) {
1985
- return this._data.map(this._instanceBuilder)
1986
- }
1987
- return this._data
1988
- }
1989
- }
1990
-
1991
-
1992
-
1993
- ;// ./lib/models/apiResponse/makeApiResponse.js
1994
-
1995
-
1996
- function makeApiResponse({ repo, result }) {
1997
- return ApiResponse.init({
1998
- ...result,
1999
- _instanceBuilder: (i) => {
2000
- return repo.init(i)
2001
- }
2002
- })
2003
- }
2004
-
2005
-
2006
-
2007
- ;// ./lib/models/service/service.js
2008
-
2009
-
2010
-
2011
- class Service {
2012
- constructor({ repo }) {
2013
- this.repo = repo
2014
- }
2015
-
2016
- static get _classname() {
2017
- return 'Service'
2018
- }
2019
- static get _superclass() {
2020
- return 'Service'
2021
- }
2022
-
2023
- deleteOne({ id }) {
2024
- return this.repo.deleteOne({ id })
2025
- .catch(() => {
2026
- throw new Error(`Not found for query: ${id}`)
2027
- })
2028
- }
2029
-
2030
- async findAll({ query = {}, systemLog } = {}) {
2031
- const result = await this.repo.findAll({ query, systemLog })
2032
- return makeApiResponse({
2033
- repo: this.repo,
2034
- result
2035
- })
2036
- }
2037
-
2038
- async findOne({ query = {}, systemLog } = {}) {
2039
- const result = await this.repo.findOne({ query, systemLog })
2040
- return makeApiResponse({
2041
- repo: this.repo,
2042
- result
2043
- })
2044
- }
2045
-
2046
- init(options) {
2047
- return this.repo.init(options)
2048
- }
2049
- initFromArray(arr = []) {
2050
- if (Array.isArray(arr)) {
2051
- return arr.map((a) => this.init(a))
2052
- }
2053
- return []
2054
- }
2055
- initOnlyValidFromArray(arr = []) {
2056
- return this.initFromArray(arr).filter((i) => i)
2057
- }
2058
-
2059
- async saveAll({ config = {}, docs = [], systemLog } = {}) {
2060
- const copies = docs.map((doc) => {
2061
- return config.skipInit ? doc : this.init(doc)
2062
- })
2063
- const result = await this.repo.saveAll({ config, docs: copies, systemLog })
2064
- return makeApiResponse({
2065
- repo: this.repo,
2066
- result
2067
- })
2068
- }
2069
-
2070
- // set skipInit to true if we want to use POST for query
2071
- async saveOne({ config = {}, doc = {}, systemLog } = {}) {
2072
- const copy = config.skipInit ? doc : this.init(doc)
2073
- if (copy) {
2074
- const result = await this.repo.saveOne({ config, doc: copy, systemLog })
2075
- return makeApiResponse({
2076
- repo: this.repo,
2077
- result
2078
- })
2079
- }
2080
- return {
2081
- isNew: null,
2082
- data: [],
2083
- err: new Error('doc is not a valid instance')
2084
- }
2085
- }
2086
- }
2087
-
2088
- function makeService({ repo }) {
2089
- if (repo === undefined) {
2090
- throw new Error('repo is required.')
2091
- }
2092
- if (repo._superclass !== Repo._superclass) {
2093
- throw new Error('repo is not an instance of Repo.')
2094
- }
2095
- return new Service({ repo })
2096
- }
2097
-
2098
-
2099
-
2100
- ;// ./lib/models/service/index.js
2101
-
2102
-
2103
-
2104
-
2105
- ;// ./lib/helpers/generalPost/generalPost.js
2106
-
2107
-
2108
-
2109
-
2110
-
2111
- async function generalPost({ body = {}, GeneralModel, UniqueKeyGenerator, resourceInfo }) {
2112
- const { resources, data, globalShared = {}, shared = {}, relationship = {} } = body
2113
- const _resourceInfo = resourceInfo || body.resourceInfo
2114
- _attachShared(data, globalShared, shared)
2115
- const obj = await pReduce(resources, async (acc, resource) => {
2116
- const service = _makeService(resource, _resourceInfo, UniqueKeyGenerator, GeneralModel)
2117
- _createRelationship(data, relationship[resource], acc)
2118
- const _data = data[resource]
2119
- const result = await service.saveAll({ docs: [].concat(_data) })
2120
- acc[resource] = Array.isArray(_data) ? result._data : result._data[0]
2121
- return acc
2122
- }, {})
2123
- return obj
2124
- }
2125
-
2126
- function _attachShared(data, globalShared = {}, shared = {}) {
2127
- Object.keys(shared).forEach((key) => {
2128
- const _data = data[key]
2129
- if (Array.isArray(_data)) {
2130
- data[key] = _data.map((_dataItem) => {
2131
- return objectHelper.merge({}, _dataItem, globalShared, shared[key] || {})
2132
- })
2133
- } else {
2134
- data[key] = objectHelper.merge({}, _data, globalShared, shared[key] || {})
2135
- }
2136
- })
2137
- }
2138
-
2139
- function _createRelationship(data, relationship = {}, object) {
2140
- Object.keys(relationship).forEach((key) => {
2141
- const path = relationship[key]
2142
- const val = objectHelper.get(object, path)
2143
- objectHelper.set(data, key, val)
2144
- })
2145
- }
2146
-
2147
- function _makeService(resource, resourceInfo, UniqueKeyGenerator, GeneralModel) {
2148
- const { collectionName, fields } = resourceInfo[resource]
2149
- const uniqueKeyGenerator = UniqueKeyGenerator.makeGenerator(fields)
2150
- const model = new GeneralModel({ collectionName, uniqueKeyGenerator })
2151
- return makeService({
2152
- repo: new Repo({ model })
2153
- })
2154
- }
2155
-
2156
-
2157
-
2158
- ;// ./lib/helpers/generalPost/index.js
2159
-
2160
-
2161
-
2162
-
2163
- ;// ./lib/helpers/init/init.js
2164
- function init(_class, options) {
2165
- if (options instanceof _class) {
2166
- return options
2167
- }
2168
- try {
2169
- const instance = new _class(options)
2170
- return instance.isValid !== false ? instance : null
2171
- } catch (e) {
2172
- console.log(`init failed for class: ${_class._classname || 'no _classname'}`, e)
2173
- return null
2174
- }
2175
- }
2176
-
2177
- ;// ./lib/helpers/init/index.js
2178
-
2179
-
2180
- ;// ./lib/helpers/initFromArray/initFromArray.js
2181
-
2182
-
2183
- function initFromArray(_class, arr) {
2184
- if (Array.isArray(arr)) {
2185
- return arr.map((a) => init(_class, a))
2186
- }
2187
- return []
2188
- }
2189
-
2190
- ;// ./lib/helpers/initFromArray/index.js
2191
-
2192
-
2193
- ;// ./lib/helpers/initOnlyValidFromArray/initOnlyValidFromArray.js
2194
-
2195
-
2196
- function initOnlyValidFromArray(_class, arr) {
2197
- return initFromArray(_class, arr).filter((i) => i)
2198
- }
2199
-
2200
- ;// ./lib/helpers/initOnlyValidFromArray/index.js
2201
-
2202
-
2203
- ;// ./lib/helpers/mergeArraysByKey/mergeArraysByKey.js
2204
- function mergeArraysByKey(arr1, arr2) {
2205
- // Handle undefined/null inputs by defaulting to empty arrays
2206
- const safeArr1 = Array.isArray(arr1) ? arr1 : []
2207
- const safeArr2 = Array.isArray(arr2) ? arr2 : []
2208
-
2209
- const mergedMap = new Map()
2210
-
2211
- // Helper function to merge values based on their type
2212
- const mergeValues = (existingValue, newValue) => {
2213
- if (existingValue === undefined) return newValue
2214
-
2215
- // Handle arrays by concatenating
2216
- if (Array.isArray(existingValue) && Array.isArray(newValue)) {
2217
- return [...new Set([...existingValue, ...newValue])]
2218
- }
2219
-
2220
- // Handle objects by merging
2221
- if (typeof existingValue === 'object' && typeof newValue === 'object' &&
2222
- !Array.isArray(existingValue) && !Array.isArray(newValue)) {
2223
- return { ...existingValue, ...newValue }
2224
- }
2225
-
2226
- // // Handle numbers by adding
2227
- // if (typeof existingValue === 'number' && typeof newValue === 'number') {
2228
- // return existingValue
2229
- // }
2230
-
2231
- // // Handle strings by concatenating
2232
- // if (typeof existingValue === 'string' && typeof newValue === 'string') {
2233
- // return existingValue
2234
- // }
2235
-
2236
- // Default: use the new value
2237
- return newValue
2238
- }
2239
-
2240
- // Process first array
2241
- safeArr1.forEach(item => {
2242
- mergedMap.set(item.key, item.value)
2243
- })
2244
-
2245
- // Process second array and merge values
2246
- safeArr2.forEach(item => {
2247
- const existingValue = mergedMap.get(item.key)
2248
- mergedMap.set(item.key, mergeValues(existingValue, item.value))
2249
- })
2250
-
2251
- // Convert back to array format
2252
- return Array.from(mergedMap.entries()).map(([key, value]) => ({
2253
- key,
2254
- value
2255
- }))
2256
- }
2257
-
2258
- ;// ./lib/helpers/mergeArraysByKey/index.js
2259
-
2260
-
2261
- ;// ./lib/helpers/padZeros/padZeros.js
2262
- function padZeros(num, minLength = 6) {
2263
- num = num.toString()
2264
- if (num.length < minLength) {
2265
- return padZeros('0' + num, minLength)
2266
- }
2267
- return num
2268
- }
2269
-
2270
-
2271
-
2272
- ;// ./lib/helpers/padZeros/index.js
2273
-
2274
-
2275
-
2276
-
2277
- ;// ./lib/helpers/pReduce/index.js
2278
-
2279
-
2280
-
2281
-
2282
- ;// ./lib/helpers/replacePlaceholders/replacePlaceholders.js
2283
- function replacePlaceholders({ content, mapping }) {
2284
- let isObjectMode = false
2285
-
2286
- if (typeof content === 'object' && content !== null) {
2287
- content = JSON.stringify(content)
2288
- isObjectMode = true
2289
- }
2290
-
2291
- // [[ eventRegistration.eventRegistrationCode | 0 ]]
2292
- const regex = /(\[*)\[\[\s*([\w.\-_]+)(?:\s*\|\s*([^:\]\s]+))?(?:\s*:\s*([^\]\s]+))?\s*\]\](\]*)/g;
2293
-
2294
- const result = content.replace(regex, (match, leadingBrackets, path, defaultValue, type, trailingBrackets) => {
2295
-
2296
- // Split the path into parts
2297
- const keys = path.trim().split('.')
2298
-
2299
- // Traverse the nested object structure
2300
- let value = mapping
2301
- for (const key of keys) {
2302
- // Handle empty keys (in case of double dots or leading/trailing dots)
2303
- if (!key) continue
2304
-
2305
- value = value?.[key]
2306
- if (value === undefined) {
2307
- break
2308
- }
2309
- }
2310
-
2311
- // Apply default if missing
2312
- if (value === undefined) value = defaultValue?.trim();
2313
- if (value === undefined) return isObjectMode ? undefined : match;
2314
-
2315
- value = value !== undefined
2316
- ? leadingBrackets + value + trailingBrackets
2317
- : match
2318
-
2319
- // Return replacement or original if not found
2320
- return value
2321
- })
2322
-
2323
- if (isObjectMode) {
2324
- return JSON.parse(result)
2325
- }
2326
- return result
2327
- }
2328
-
2329
- ;// ./lib/helpers/replacePlaceholders/index.js
2330
-
2331
-
2332
- ;// ./lib/helpers/sanitizeText/sanitizeText.js
2333
- /**
2334
- * Sanitizes input by removing hidden/control characters with customizable whitespace handling.
2335
- * @param {string} input - The string to sanitize.
2336
- * @param {Object} [options] - Configuration options.
2337
- * @param {boolean} [options.normalizeWhitespace=true] - Collapse multiple spaces/tabs into one space.
2338
- * @param {boolean} [options.removeNewlines=false] - If true, replaces newlines with spaces.
2339
- * @param {boolean} [options.trim=true] - If true, trims leading/trailing whitespace.
2340
- * @returns {string} The sanitized string.
2341
- */
2342
- function sanitizeText(input, options = {}) {
2343
- const {
2344
- normalizeWhitespace = true,
2345
- removeNewlines = false,
2346
- trim = true,
2347
- } = options
2348
-
2349
- if (typeof input !== 'string') {
2350
- return input
2351
- }
2352
-
2353
- let result = input
2354
-
2355
- // Phase 1: Remove hidden/control characters
2356
- result = result.replace(/[\u200B-\u200D\uFEFF\u202A-\u202E]/g, '')
2357
-
2358
- // Phase 2: Handle whitespace transformations
2359
- if (removeNewlines) {
2360
- result = result.replace(/[\r\n]+/g, ' ') // Convert newlines to spaces
2361
- }
2362
-
2363
- if (normalizeWhitespace) {
2364
- result = result.replace(/[ \t]+/g, ' ') // Collapse spaces/tabs to single space
2365
- }
2366
-
2367
- // Phase 3: Final trimming
2368
- if (trim) {
2369
- result = result.trim()
2370
- }
2371
-
2372
- return result
2373
- }
2374
-
2375
- ;// ./lib/helpers/sanitizeText/index.js
2376
-
2377
-
2378
- ;// ./lib/helpers/stringFormatter/stringFormatter.js
2379
- function stringFormatter(str, delimiter = '_') {
2380
- if (str === null || typeof str === 'undefined' || typeof str.toString === 'undefined') {
2381
- return null
2382
- }
2383
- return str.toString()
2384
- .trim()
2385
- .toUpperCase()
2386
- .replace('-', delimiter)
2387
- .replace(' ', delimiter)
2388
- }
2389
-
2390
-
2391
-
2392
- ;// ./lib/helpers/stringFormatter/index.js
2393
-
2394
-
2395
-
2396
-
2397
- ;// ./lib/helpers/stringHelper/stringHelper.js
2398
- function baseXEncode(num, base = 34) {
2399
- const charset = getBaseCharset(base)
2400
- return encode(num, charset)
2401
- }
2402
-
2403
- function encode(int, charset) {
2404
- const { byCode } = charset
2405
- if (int === 0) {
2406
- return byCode[0]
2407
- }
2408
-
2409
- let res = ''
2410
- const max = charset.length
2411
- while (int > 0) {
2412
- res = byCode[int % max] + res
2413
- int = Math.floor(int / max)
2414
- }
2415
- return res
2416
- }
2417
-
2418
- function getBaseCharset(base) {
2419
- let charset = '9876543210ABCDEFGHJKLMNPQRSTUVWXYZ'
2420
- if (base === 58) {
2421
- charset = '9876543210ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz'
2422
- }
2423
- return indexCharset(charset)
2424
- }
2425
-
2426
- function indexCharset(str) {
2427
- const byCode = {}
2428
- const byChar = {}
2429
- const { length } = str
2430
- let char
2431
- for (let i = 0; i < length; i++) {
2432
- char = str[i]
2433
- byCode[i] = char
2434
- byChar[char] = i;
2435
- }
2436
- return { byCode, byChar, length }
2437
- }
2438
-
2439
- function isSame(str1, str2) {
2440
- if (typeof str1 !== 'string' || typeof str2 !== 'string') {
2441
- return false
2442
- }
2443
- return str1.trim().toUpperCase() === str2.trim().toUpperCase()
2444
- }
2445
-
2446
- function randomString({ len = 16, pattern = 'a1' } = {}) {
2447
- const A = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
2448
- const a = 'abcdefghijklmnopqrstuvwxyz'
2449
- const num = '1234567890'
2450
- const mark = '~!@#$%^&*_+-='
2451
- let str = ''
2452
- if (pattern.includes('A')) {
2453
- str += A
2454
- }
2455
- if (pattern.includes('a')) {
2456
- str += a
2457
- }
2458
- if (pattern.includes('1')) {
2459
- str += num
2460
- }
2461
- if (pattern.includes('#')) {
2462
- str += mark
2463
- }
2464
- const chars = [...str]
2465
- return [...Array(len)].map(i => {
2466
- return chars[(Math.random() * chars.length) | 0]
2467
- }).join``
2468
- }
2469
-
2470
- function reverse(str) {
2471
- const _str = (typeof str !== 'string') ? str.toString() : str
2472
- const splitString = _str.split('')
2473
- const reverseArray = splitString.reverse()
2474
- return reverseArray.join('')
2475
- }
2476
-
2477
- function setCode(base = 34) {
2478
- const now = (new Date()).valueOf()
2479
- const random = randomString({
2480
- len: 8,
2481
- pattern: '1'
2482
- })
2483
- const str = reverse(`${now}${random}`)
2484
- // const str = `${now}${random}`
2485
- return baseXEncode(str, base)
2486
- }
2487
-
2488
- function toCamelCase(str) {
2489
- if (!str) return ''
2490
- return str
2491
- .trim()
2492
- .split(/\s+/)
2493
- .map((word, index) => {
2494
- if (!word) return ''
2495
- if (index === 0) {
2496
- return word.toLowerCase()
2497
- }
2498
- return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()
2499
- })
2500
- .join('')
2501
- }
2502
-
2503
- function toLowerCase(str) {
2504
- if (!str) return ''
2505
- return str
2506
- .trim()
2507
- .toLowerCase()
2508
- }
2509
-
2510
- const stringHelper = {
2511
- isSame,
2512
- setCode,
2513
- toCamelCase,
2514
- toLowerCase,
2515
- }
2516
-
2517
-
2518
-
2519
- ;// ./lib/helpers/stringHelper/index.js
2520
-
2521
-
2522
-
2523
-
2524
- ;// ./lib/helpers/trackingPlugin/trackingPlugin.js
2525
- function trackingPlugin(schema, options) {
2526
- // Add meta fields
2527
- schema.add({
2528
- meta: {
2529
- active: { type: Boolean, default: true },
2530
- created: { type: Number },
2531
- creator: { type: String },
2532
- deleted: { type: Boolean, default: false },
2533
- modified: { type: Number },
2534
- owner: { type: String },
2535
- }
2536
- })
2537
-
2538
- // Auto-update hook
2539
- schema.pre('save', function(next) {
2540
- this.meta.modified = Date.now()
2541
- next()
2542
- })
2543
-
2544
- // Add core indexes
2545
- schema.index({
2546
- 'meta.active': 1,
2547
- 'meta.deleted': 1
2548
- }, {
2549
- name: 'tracking_status_index',
2550
- background: true,
2551
- partialFilterExpression: {
2552
- 'meta.active': true,
2553
- 'meta.deleted': false
2554
- }
2555
- })
2556
-
2557
- // Optional: Add helper methods
2558
- // schema.methods.touch = function(userId) {
2559
- // this.meta.updatedAt = new Date()
2560
- // this.meta.updatedBy = userId
2561
- // }
2562
- }
2563
-
2564
- ;// ./lib/helpers/tenantPlugin/tenantPlugin.js
2565
-
2566
-
2567
- function tenantPlugin(schema, options) {
2568
- // Apply tracking plugin first if not already present
2569
- if (!schema.path('meta')) {
2570
- trackingPlugin(schema, options)
2571
- }
2572
-
2573
- // Add tenant-specific fields
2574
- schema.add({
2575
- metadata: [{ type: Object }], // Instead of Schema.Types.Mixed
2576
- remarks: [{ type: Object }],
2577
- tenantCode: { type: String, required: true }
2578
- })
2579
-
2580
- // Add core indexes
2581
- schema.index({
2582
- 'tenantCode': 1
2583
- }, {
2584
- name: 'tenant_core_index',
2585
- background: true
2586
- })
2587
-
2588
- // 1. ENHANCE EXISTING TRACKING INDEXES
2589
- const existingIndexes = schema.indexes()
2590
-
2591
- // Check if tracking_status_index exists
2592
- const hasTenantStatusIndex = existingIndexes.some(idx =>
2593
- idx.name === 'tenant_status_index' // Check by name for reliability
2594
- )
2595
-
2596
- if (!hasTenantStatusIndex) {
2597
- schema.index({
2598
- 'tenantCode': 1, // Unique field first
2599
- _type: 1, // Low-cardinality field last
2600
- }, {
2601
- name: 'tenant_status_index',
2602
- background: true,
2603
- partialFilterExpression: {
2604
- '_type': 'Tenant',
2605
- 'meta.active': true,
2606
- 'meta.deleted': false
2607
- }
2608
- })
2609
- }
2610
- }
2611
-
2612
- ;// ./lib/helpers/tenantPlugin/index.js
2613
-
2614
-
2615
- ;// ./lib/helpers/trackingPlugin/index.js
2616
-
2617
-
2618
- ;// ./lib/helpers/index.js
2619
-
2620
-
2621
-
2622
-
2623
-
2624
-
2625
-
2626
-
2627
-
2628
-
2629
-
2630
-
2631
-
2632
-
2633
-
2634
-
2635
-
2636
-
2637
-
2638
-
2639
-
2640
-
2641
-
2642
-
2643
-
2644
- ;// ./lib/models/apiResponse/index.js
2645
-
2646
-
2647
-
2648
-
2649
-
2650
- ;// ./lib/models/awsStsS3Client/awsStsS3Client.js
2651
- class AwsStsS3Client {
2652
- constructor(options) {
2653
- options = options || {}
2654
-
2655
- this.expiration = options.expiration || null
2656
- this.s3Client = options.s3Client || null
2657
- this.getIdToken = options.getIdToken
2658
- this.region = options.region || 'ap-east-1'
2659
- this.roleArn = options.roleArn
2660
- this.roleSessionName = options.roleSessionName || 'web-identity-session'
2661
- this.durationSession = options.durationSession || 3600
2662
- this.awsClientSts = options.awsClientSts
2663
- this.awsClientS3 = options.awsClientS3
2664
- }
2665
-
2666
- static dummyData() {
2667
- return {
2668
- getIdToken: () => 'mock-web-identity-token',
2669
- roleArn: 'arn:aws:iam::846252828949:role/oidcS3Jccpa',
2670
- awsClientSts: {
2671
- STSClient: class {},
2672
- AssumeRoleWithWebIdentityCommand: class {}
2673
- },
2674
- awsClientS3: {
2675
- S3Client: class {},
2676
- PutObjectCommand: class {},
2677
- GetObjectCommand: class {},
2678
- DeleteObjectCommand: class {}
2679
- }
2680
- }
2681
- }
2682
-
2683
- static init(options = {}) {
2684
- if (options instanceof this) {
2685
- return options
2686
- }
2687
- try {
2688
- const instance = new this(options)
2689
- if (!instance.isValid) {
2690
- return null
2691
- }
2692
- return instance
2693
- } catch (error) {
2694
- return null
2695
- }
2696
- }
2697
-
2698
- get isExpired() {
2699
- if (!this.expiration) return true;
2700
- const now = new Date();
2701
- const bufferMs = 1 * 60 * 1000; // 一分钟缓冲
2702
- return now >= new Date(this.expiration.getTime() - bufferMs);
2703
- }
2704
-
2705
- get isValid() {
2706
- if (!this.getIdToken) {
2707
- throw new Error('Missing required configuration: getIdToken function')
2708
- }
2709
- if (!this.roleArn) {
2710
- throw new Error('Missing required configuration: roleArn')
2711
- }
2712
- if (!this.awsClientSts) {
2713
- throw new Error('Missing required AWS awsClientSts client configuration')
2714
- }
2715
- if (!this.awsClientSts.STSClient) {
2716
- throw new Error('Missing STSClient in AWS awsClientSts client configuration')
2717
- }
2718
- if (!this.awsClientSts.AssumeRoleWithWebIdentityCommand) {
2719
- throw new Error('Missing AssumeRoleWithWebIdentityCommand in AWS awsClientSts client configuration')
2720
- }
2721
- if (!this.awsClientS3) {
2722
- throw new Error('Missing required AWS awsClientS3 client configuration')
2723
- }
2724
-
2725
- const requiredS3Components = [
2726
- 'S3Client',
2727
- 'PutObjectCommand',
2728
- 'GetObjectCommand',
2729
- 'DeleteObjectCommand'
2730
- ]
2731
-
2732
- for (const component of requiredS3Components) {
2733
- if (!this.awsClientS3[component]) {
2734
- throw new Error(`Missing ${component} in AWS awsClientS3 client configuration`)
2735
- }
2736
- }
2737
-
2738
- return true
2739
- }
2740
-
2741
- async refreshCredentials() {
2742
- try {
2743
- const webIdentityToken = await this.getIdToken()
2744
- if (!webIdentityToken) {
2745
- throw new Error('getIdToken function returned empty or invalid token')
2746
- }
2747
-
2748
- const stsClient = new this.awsClientSts.STSClient({ region: this.region })
2749
-
2750
- const stsResponse = await stsClient.send(
2751
- new this.awsClientSts.AssumeRoleWithWebIdentityCommand({
2752
- RoleArn: this.roleArn,
2753
- RoleSessionName: this.roleSessionName,
2754
- WebIdentityToken: await this.getIdToken(),
2755
- DurationSeconds: this.durationSession,
2756
- })
2757
- )
2758
-
2759
- const credentials = stsResponse.Credentials
2760
- if (!credentials) {
2761
- throw new Error('No credentials returned from awsClientSts')
2762
- }
2763
-
2764
- this.expiration = credentials.Expiration
2765
-
2766
- this.s3Client = new this.awsClientS3.S3Client({
2767
- region: this.region,
2768
- credentials: {
2769
- accessKeyId: credentials.AccessKeyId,
2770
- secretAccessKey: credentials.SecretAccessKey,
2771
- sessionToken: credentials.SessionToken,
2772
- }
2773
- })
2774
-
2775
- return this
2776
- } catch (error) {
2777
- throw new Error(`Failed to refresh credentials: ${error.message}`)
2778
- }
2779
- }
2780
-
2781
- async getS3Client() {
2782
- if (this.isExpired || !this.s3Client) {
2783
- await this.refreshCredentials()
2784
- }
2785
- return this.s3Client
2786
- }
2787
-
2788
- async putObject(params) {
2789
- try {
2790
- const client = await this.getS3Client()
2791
- const command = new this.awsClientS3.PutObjectCommand(params)
2792
- await client.send(command)
2793
- const fileArr = params.Key.split('/')
2794
- return {
2795
- url: `https://s3.${this.region}.amazonaws.com/${params.Bucket}/${params.Key}`,
2796
- filename: fileArr.pop(),
2797
- folder: params.Bucket,
2798
- subFolders: fileArr
2799
- }
2800
- } catch (error) {
2801
- throw new Error(`Failed to put object: ${error.message}`)
2802
- }
2803
- }
2804
-
2805
- async getObject(params) {
2806
- try {
2807
- const client = await this.getS3Client()
2808
- const command = new this.awsClientS3.GetObjectCommand(params)
2809
- const response = await client.send(command)
2810
- return {
2811
- body: response.Body,
2812
- contentType: response.ContentType,
2813
- lastModified: response.LastModified,
2814
- contentLength: response.ContentLength,
2815
- }
2816
- } catch (error) {
2817
- throw new Error(`Failed to get object: ${error.message}`)
2818
- }
2819
- }
2820
-
2821
- async deleteObject(params) {
2822
- try {
2823
- const client = await this.getS3Client()
2824
- const command = new this.awsClientS3.DeleteObjectCommand(params)
2825
- await client.send(command)
2826
- return true
2827
- } catch (error) {
2828
- throw new Error(`Failed to delete object: ${error.message}`)
2829
- }
2830
- }
2831
- }
2832
-
2833
-
2834
-
2835
- ;// ./lib/models/awsStsS3Client/index.js
2836
-
2837
-
2838
-
2839
-
2840
- ;// ./lib/models/keyValueObject/keyValueObject.js
2841
- class KeyValueObject {
2842
- constructor(options = {}) {
2843
- options = options || {}
2844
- this.key = options.key || null
2845
- this.value = (typeof options.value !== 'undefined') ? options.value : ''
2846
- }
2847
-
2848
- // Class methods
2849
- static init(options = {}) {
2850
- if (options instanceof this) {
2851
- return options
2852
- }
2853
- const instance = new this(options)
2854
- return instance.isValid ? instance : null
2855
- }
2856
- static initFromArray(arr = []) {
2857
- if (Array.isArray(arr)) {
2858
- return arr.map((a) => this.init(a))
2859
- }
2860
- return []
2861
- }
2862
- static initOnlyValidFromArray(arr = []) {
2863
- return this.initFromArray(arr).filter((i) => i)
2864
- }
2865
- static get _classname() {
2866
- return 'KeyValueObject'
2867
- }
2868
- static get _superclass() {
2869
- return 'KeyValueObject'
2870
- }
2871
-
2872
- static addItem(arr, key, value) {
2873
- arr.push(this.init({ key, value }))
2874
- }
2875
- static addRecord(arr = [], key, value) {
2876
- if (!this.hasKeyValue(arr, key, value)) {
2877
- arr.push(this.init({ key, value }))
2878
- }
2879
- return arr
2880
- }
2881
- static appendRecord(arr = [], key, value) {
2882
- return arr.map((item) => {
2883
- if (this.sameKey(item, key)) {
2884
- item.value = [...item.value, ...value]
2885
- }
2886
- return item
2887
- })
2888
- }
2889
- static appendValueArray(arr = [], key, value) {
2890
- return arr.map((item) => {
2891
- if (this.sameKey(item, key)) {
2892
- item.value = [...item.value, ...value]
2893
- }
2894
- return item
2895
- })
2896
- }
2897
- static foundByKey(arr = [], key) {
2898
- const found = arr.find((m) => {
2899
- return this.sameKey(m, key)
2900
- })
2901
- return found || null
2902
- }
2903
- static foundValueByKey(arr = [], key) {
2904
- const found = this.foundByKey(arr, key)
2905
- return found ? found.value : null
2906
- }
2907
- static fromObject(options = {}) {
2908
- return Object.keys(options).reduce((acc, key) => {
2909
- acc.push(this.init({ key, value: options[key] }))
2910
- return acc
2911
- }, [])
2912
- }
2913
- static getValueByKey(arr = [], key) {
2914
- return this.foundValueByKey(arr, key)
2915
- }
2916
- static getValueByKeyFromArray(arr = [], key) {
2917
- if (arr.length === 0) {
2918
- return null
2919
- }
2920
- const firstArr = arr.shift()
2921
- const found = firstArr.find((i) => {
2922
- return this.sameKey(i, key)
2923
- })
2924
- if (found && found.value) {
2925
- return found.value
2926
- }
2927
- return this.getValueByKeyFromArray(arr, key)
2928
- }
2929
- static getValuesByKey(arr = [], key) {
2930
- return arr.reduce((acc, item) => {
2931
- if (this.sameKey(item, key)) {
2932
- acc.push(item.value)
2933
- }
2934
- return acc
2935
- }, [])
2936
- }
2937
- static hasKeyValue(arr = [], key, value) {
2938
- if (typeof value === 'undefined') {
2939
- return arr.filter((item) => this.sameKey(item, key)).length > 0
2940
- }
2941
- return arr.filter((item) => (this.sameKey(item, key) && _isSame(item.value, value))).length > 0
2942
- }
2943
- static insertOrUpdateRecord(arr = [], key, value) {
2944
- let copy = [...arr]
2945
- if (!this.hasKeyValue(arr, key)) {
2946
- copy.push(this.init({ key, value }))
2947
- } else {
2948
- copy = this.updateRecord(arr, key, value)
2949
- }
2950
- return copy
2951
- }
2952
- static keys(arr = []) {
2953
- if (Array.isArray(arr)) {
2954
- return arr.reduce((acc, item) => {
2955
- acc.push(item.key)
2956
- return acc
2957
- }, [])
2958
- }
2959
- return []
2960
- }
2961
- static merge(toArr, fromArr) {
2962
- (fromArr || []).map((from) => {
2963
- const found = toArr.find((to) => {
2964
- return to.key === from.key
2965
- })
2966
- if (found) {
2967
- found.value = _mergeValues(from.value, found.value)
2968
- } else {
2969
- toArr.push(from)
2970
- }
2971
- })
2972
- return toArr
2973
- }
2974
- static removeByKey(arr, key) {
2975
- return arr.reduce((acc, item) => {
2976
- if (!this.sameKey(item, key)) {
2977
- acc.push(item)
2978
- }
2979
- return acc
2980
- }, [])
2981
- }
2982
- static sameKey(item, key) {
2983
- if (item) {
2984
- return _isSame(item.key, key)
2985
- }
2986
- return false
2987
- }
2988
- static toObject(arr = []) {
2989
- if (Array.isArray(arr)) {
2990
- return arr.reduce((acc, item) => {
2991
- acc[item.key] = item.value
2992
- return acc
2993
- }, {})
2994
- }
2995
- return {}
2996
- }
2997
- static toString(arr = [], delimiter = '; ') {
2998
- if (Array.isArray(arr)) {
2999
- return arr.reduce((acc, item) => {
3000
- acc.push(`${item.key}: ${item.value}`)
3001
- return acc
3002
- }, []).join(delimiter)
3003
- }
3004
- return ''
3005
- }
3006
- static updateRecord(arr = [], key, value) {
3007
- return arr.map((item) => {
3008
- if (this.sameKey(item, key)) {
3009
- return {
3010
- ...item,
3011
- value
3012
- }
3013
- }
3014
- return item
3015
- })
3016
- }
3017
- static updateOrInsertRecord(arr = [], key, value) {
3018
- return this.insertOrUpdateRecord(arr, key, value)
3019
- }
3020
- static updateRecordsFromArray(arr = [], updateArr = []) {
3021
- if (Array.isArray(arr) && Array.isArray(updateArr)) {
3022
- const obj1 = this.toObject(arr)
3023
- const obj2 = this.toObject(updateArr)
3024
- return this.fromObject({
3025
- ...obj1,
3026
- ...obj2
3027
- })
3028
- }
3029
- return []
3030
- }
3031
- static values(arr = []) {
3032
- if (Array.isArray(arr)) {
3033
- return arr.reduce((acc, item) => {
3034
- acc.push(item.value)
3035
- return acc
3036
- }, [])
3037
- }
3038
- return []
3039
- }
3040
-
3041
- // getters
3042
- get isValid() {
3043
- return !!this.key
3044
- }
3045
-
3046
- get toObject() {
3047
- const obj = {}
3048
- if (this.isValid) {
3049
- obj[this.key] = this.value
3050
- }
3051
- return obj
3052
- }
3053
- }
3054
-
3055
- function _mergeValues(existingValue, newValue) {
3056
- if (existingValue === undefined) return newValue
3057
-
3058
- // Handle arrays by concatenating
3059
- if (Array.isArray(existingValue) && Array.isArray(newValue)) {
3060
- return [...new Set([...existingValue, ...newValue])]
3061
- }
3062
-
3063
- // Handle objects by merging
3064
- if (typeof existingValue === 'object' && typeof newValue === 'object' &&
3065
- !Array.isArray(existingValue) && !Array.isArray(newValue)) {
3066
- return { ...existingValue, ...newValue }
3067
- }
3068
-
3069
- // // Handle numbers by adding
3070
- // if (typeof existingValue === 'number' && typeof newValue === 'number') {
3071
- // return existingValue
3072
- // }
3073
-
3074
- // // Handle strings by concatenating
3075
- // if (typeof existingValue === 'string' && typeof newValue === 'string') {
3076
- // return existingValue
3077
- // }
3078
-
3079
- // Default: use the new value
3080
- return newValue
3081
- }
3082
-
3083
- function _isSame(key1, key2) {
3084
- return key1 === key2
3085
- }
3086
-
3087
-
3088
-
3089
- ;// ./lib/models/keyValueObject/index.js
3090
-
3091
-
3092
-
3093
-
3094
- ;// ./lib/models/metadata/metadata.js
3095
-
3096
-
3097
-
3098
- const DELIMITER = '_'
3099
-
3100
- class Metadata extends KeyValueObject {
3101
- static init(options = {}) {
3102
- if (options instanceof this) {
3103
- return options
3104
- }
3105
- const instance = new this({
3106
- ...options,
3107
- key: stringFormatter(options.key, DELIMITER),
3108
- })
3109
- return instance.isValid ? instance : null
3110
- }
3111
- static get _classname() {
3112
- return 'Metadata'
3113
- }
3114
-
3115
- static merge(toArr, fromArr) {
3116
- (fromArr || []).map((from) => {
3117
- const found = toArr.find((to) => {
3118
- return metadata_isSame(to.key, from.key)
3119
- })
3120
- if (found) {
3121
- found.value = metadata_mergeValues(from.value, found.value)
3122
- } else {
3123
- toArr.push(from)
3124
- }
3125
- })
3126
- return toArr
3127
- }
3128
- static sameKey(item, key) {
3129
- return metadata_isSame(item.key, key)
3130
- }
3131
- }
3132
-
3133
- function metadata_isSame(key1, key2) {
3134
- return stringFormatter(key1, DELIMITER) === stringFormatter(key2, DELIMITER)
3135
- }
3136
-
3137
- function metadata_mergeValues(existingValue, newValue) {
3138
- if (existingValue === undefined) return newValue
3139
-
3140
- // Handle arrays by concatenating
3141
- if (Array.isArray(existingValue) && Array.isArray(newValue)) {
3142
- return [...new Set([...existingValue, ...newValue])]
3143
- }
3144
-
3145
- // Handle objects by merging
3146
- if (typeof existingValue === 'object' && typeof newValue === 'object' &&
3147
- !Array.isArray(existingValue) && !Array.isArray(newValue)) {
3148
- return { ...existingValue, ...newValue }
3149
- }
3150
-
3151
- // // Handle numbers by adding
3152
- // if (typeof existingValue === 'number' && typeof newValue === 'number') {
3153
- // return existingValue
3154
- // }
3155
-
3156
- // // Handle strings by concatenating
3157
- // if (typeof existingValue === 'string' && typeof newValue === 'string') {
3158
- // return existingValue
3159
- // }
3160
-
3161
- // Default: use the new value
3162
- return newValue
3163
- }
3164
-
3165
-
3166
-
3167
- ;// ./lib/models/metadata/index.js
3168
-
3169
-
3170
-
3171
-
3172
- ;// ./lib/models/qMeta/qMeta.js
3173
-
3174
-
3175
- const updateAllowedProps = [
3176
- 'attributes',
3177
- 'ref'
3178
- ]
3179
-
3180
- class QMeta {
3181
- constructor(options = {}) {
3182
- options = options || {}
3183
- this.attributes = KeyValueObject.initOnlyValidFromArray(options.attributes)
3184
- this.ref = options.ref || {}
3185
- }
3186
-
3187
- static get _classname() {
3188
- return 'QMeta'
3189
- }
3190
- static get _superclass() {
3191
- return 'QMeta'
3192
- }
3193
-
3194
- // Class methods
3195
- static init(options = {}) {
3196
- if (options instanceof QMeta) {
3197
- return options
3198
- }
3199
- return new QMeta(options)
3200
- }
3201
-
3202
- // instance methods
3203
- addAttribute(obj) {
3204
- const kvObject = KeyValueObject.init(obj)
3205
- if (!kvObject) {
3206
- throw new Error('invalid meta attribute')
3207
- }
3208
- this.attributes.push(kvObject)
3209
- return this
3210
- }
3211
-
3212
- update(obj) {
3213
- Object.keys(obj).forEach((key) => {
3214
- if (updateAllowedProps.includes(key)) {
3215
- if (key === 'attributes') {
3216
- this[key] = KeyValueObject.initOnlyValidFromArray(obj[key])
3217
- } else {
3218
- this[key] = obj[key]
3219
- }
3220
- }
3221
- })
3222
- return this
3223
- }
3224
- }
3225
-
3226
-
3227
-
3228
- ;// ./lib/models/qMeta/index.js
3229
-
3230
-
3231
-
3232
-
3233
- ;// ./lib/models/trackedEntity/trackedEntity.js
3234
-
3235
-
3236
- class TrackedEntity {
3237
- constructor(options = {}) {
3238
- options = options || {}
3239
- const timestamp = Date.now()
3240
- this.meta = {
3241
- active: options.meta?.active ?? options.active ?? true,
3242
- created: options.meta?.created ?? (options.created
3243
- ? new Date(options.created).getTime()
3244
- : timestamp),
3245
- creator: options.meta?.creator ?? options.creator ?? '',
3246
- deleted: options.meta?.deleted ?? options.deleted ?? false,
3247
- modified: options.meta?.modified ?? (options.modified
3248
- ? new Date(options.modified).getTime()
3249
- : timestamp),
3250
- owner: options.meta?.owner ?? options.owner ?? '',
3251
- }
3252
-
3253
- // if (trackFlat) {
3254
- // Object.assign(this, _tracking)
3255
- // } else {
3256
- // this.meta = { ..._tracking, ...options.meta }
3257
- // }
3258
- }
3259
-
3260
- // Class methods
3261
- static get _classname() {
3262
- return 'TrackedEntity'
3263
- }
3264
- static get _superclass() {
3265
- return 'TrackedEntity'
3266
- }
3267
-
3268
- static init(options = {}) {
3269
- return init(this, options)
3270
- }
3271
- static initFromArray(arr = []) {
3272
- return initFromArray(this, arr)
3273
- }
3274
- static initOnlyValidFromArray(arr = []) {
3275
- return initOnlyValidFromArray(this, arr)
3276
- }
3277
- // static nest(entity) {
3278
- // const { active, created, creator, deleted, modified, owner, ...rest } = entity
3279
- // return { ...rest, meta: { active, created, creator, deleted, modified, owner } }
3280
- // }
3281
-
3282
- // getters
3283
- get isValid() {
3284
- return !!this
3285
- }
3286
- get active() {
3287
- return this.meta?.active ?? this.active
3288
- }
3289
- get created() {
3290
- return this.meta?.created ?? this.created
3291
- }
3292
- get creator() {
3293
- return this.meta?.creator ?? this.creator
3294
- }
3295
- get deleted() {
3296
- return this.meta?.deleted ?? this.deleted
3297
- }
3298
- get modified() {
3299
- return this.meta?.modified ?? this.modified
3300
- }
3301
- get owner() {
3302
- return this.meta?.owner ?? this.owner
3303
- }
3304
- changeCreatorOwner({ source, target }) {
3305
- return changeCreatorOwner(this, { source, target }).setModified()
3306
- }
3307
- delete() {
3308
- return this.setDeleted()
3309
- }
3310
- setActive() {
3311
- if (this.meta) {
3312
- this.meta.active = true
3313
- } else {
3314
- this.active = true
3315
- }
3316
- return this
3317
- }
3318
- setDeleted() {
3319
- if (this.meta) {
3320
- this.meta.deleted = true
3321
- } else {
3322
- this.deleted = true
3323
- }
3324
- return this
3325
- }
3326
- setModified() {
3327
- const timestamp = Date.now()
3328
- if (this.meta) {
3329
- this.meta.modified = timestamp
3330
- } else {
3331
- this.modified = timestamp
3332
- }
3333
- return this
3334
- }
3335
- setOwner(owner) {
3336
- if (!owner) {
3337
- return this
3338
- }
3339
- if (this.meta) {
3340
- this.meta.owner = owner
3341
- } else {
3342
- this.owner = owner
3343
- }
3344
- return this
3345
- }
3346
- unsetActive() {
3347
- if (this.meta) {
3348
- this.meta.active = false
3349
- } else {
3350
- this.active = false
3351
- }
3352
- return this
3353
- }
3354
- unsetDeleted() {
3355
- if (this.meta) {
3356
- this.meta.deleted = false
3357
- } else {
3358
- this.deleted = false
3359
- }
3360
- return this
3361
- }
3362
-
3363
- update(update) {
3364
- if (update.meta) {
3365
- this.meta = { ...this.meta, ...update.meta }
3366
- }
3367
- return this.setModified()
3368
- }
3369
- }
3370
-
3371
- ;// ./lib/models/trackedEntity/index.js
3372
-
3373
- // Explicit named export (optional)
3374
-
3375
- ;// ./lib/models/tenantAwareEntity/tenantAwareEntity.js
3376
-
3377
-
3378
-
3379
-
3380
- class TenantAwareEntity extends TrackedEntity {
3381
- constructor(options = {}) {
3382
- options = options || {}
3383
-
3384
- /**
3385
- * instead of throw error, we choose to implement the isValid checking
3386
- */
3387
- // if (!options.tenantCode) {
3388
- // throw new Error('tenantCode required')
3389
- // }
3390
-
3391
- super(options)
3392
-
3393
- this._tenant = options._tenant
3394
-
3395
- this.metadata = Metadata.initOnlyValidFromArray(options.metadata)
3396
- this.remarks = KeyValueObject.initOnlyValidFromArray(options.remarks)
3397
- this.tenantCode = options.tenantCode // Required for multi-tenancy
3398
- }
3399
-
3400
- // Class methods
3401
- static get _classname() {
3402
- return 'TenantAwareEntity'
3403
- }
3404
- static get _superclass() {
3405
- return 'TenantAwareEntity'
3406
- }
3407
-
3408
- // getters
3409
- get isValid() {
3410
- return super.isValid && !!this.tenantCode // Required for multi-tenancy
3411
- }
3412
-
3413
- // instance methods
3414
- getMetadata() {
3415
- return this.metadata
3416
- }
3417
- getMetadataByKey(key) {
3418
- return Metadata.foundByKey(this.metadata, key)
3419
- }
3420
- getMetadataValueByKey(key) {
3421
- const found = this.getMetadataByKey(key)
3422
- return found ? found.value : null
3423
- }
3424
- getRemarks() {
3425
- return this.remarks
3426
- }
3427
- getRemarkByKey(key) {
3428
- return KeyValueObject.foundByKey(this.remarks, key)
3429
- }
3430
- getRemarksValueByKey(key) {
3431
- const found = this.getRemarkByKey(key)
3432
- return found ? found.value : null
3433
- }
3434
- getTenantCode() {
3435
- return this.tenantCode
3436
- }
3437
-
3438
- update(update) {
3439
- if (update.metadata && Array.isArray(update.metadata)) {
3440
- this.metadata = Metadata.initOnlyValidFromArray(update.metadata)
3441
- }
3442
- if (update.remarks && Array.isArray(update.remarks)) {
3443
- this.remarks = KeyValueObject.initOnlyValidFromArray(update.remarks)
3444
- }
3445
- return super.update(update)
3446
- }
3447
- }
3448
-
3449
- ;// ./lib/models/tenantAwareEntity/index.js
3450
-
3451
-
3452
-
3453
- ;// ./lib/models/uniqueKeyGenerator/uniqueKeyGenerator.js
3454
-
3455
-
3456
- class UniqueKeyGenerator {
3457
- static get _classname() {
3458
- return 'UniqueKeyGenerator'
3459
- }
3460
- static get _superclass() {
3461
- return 'UniqueKeyGenerator'
3462
- }
3463
- static makeFormatter({ fieldName, format, options }) {
3464
- switch (format) {
3465
- case 'set_code':
3466
- return _makeSetCode(fieldName, options)
3467
- default:
3468
- return _makeSetCode(fieldName, options)
3469
- }
3470
- }
3471
- static makeGenerator(arr) {
3472
- const fns = arr.map((item) => this.makeFormatter(item))
3473
- return async (obj) => {
3474
- const output = await pReduce(fns, async (acc, fn) => {
3475
- const _obj = await fn(obj)
3476
- return Object.assign(acc, _obj)
3477
- }, obj)
3478
- return output
3479
- }
3480
- }
3481
- }
3482
-
3483
- function _makeSetCode(fieldName, options) {
3484
- return async (obj = {}) => {
3485
- if (obj[fieldName]) {
3486
- return {}
3487
- }
3488
- return {
3489
- [fieldName]: stringHelper.setCode()
3490
- }
3491
- }
3492
- }
3493
-
3494
-
3495
-
3496
- ;// ./lib/models/uniqueKeyGenerator/index.js
3497
-
3498
-
3499
-
3500
-
3501
- ;// ./lib/models/index.js
3502
-
3503
-
3504
-
3505
-
3506
-
3507
-
3508
-
3509
-
3510
-
3511
-
3512
-
3513
-
3514
- ;// ./lib/index.js
3515
-
3516
-
3517
-
3518
- ;// ./index.js
3519
-
3520
-
3521
- export { ApiResponse, AwsStsS3Client, KeyValueObject, Metadata, QMeta, Repo, Service, TemplateCompiler, TenantAwareEntity, TrackedEntity, UniqueKeyGenerator, authorize, changeCreatorOwner, concatStringByArray, convertString, escapeRegex, expressHelper, extractEmails, formatDate, generalPost, getValidation, getValueByKeys_getValueByKeys as getValueByKeys, init, initFromArray, initOnlyValidFromArray, makeApiResponse, makeService, mergeArraysByKey, objectHelper, pReduce, padZeros, replacePlaceholders, sanitizeText, stringFormatter, stringHelper, tenantPlugin, trackingPlugin };