@questwork/q-utilities 0.1.10 → 0.1.12

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.
@@ -0,0 +1,2413 @@
1
+ (function webpackUniversalModuleDefinition(root, factory) {
2
+ if(typeof exports === 'object' && typeof module === 'object')
3
+ module.exports = factory();
4
+ else if(typeof define === 'function' && define.amd)
5
+ define([], factory);
6
+ else if(typeof exports === 'object')
7
+ exports["@questwork/q-utilities"] = factory();
8
+ else
9
+ root["@questwork/q-utilities"] = factory();
10
+ })(this, () => {
11
+ return /******/ (() => { // webpackBootstrap
12
+ /******/ // The require scope
13
+ /******/ var __webpack_require__ = {};
14
+ /******/
15
+ /************************************************************************/
16
+ /******/ /* webpack/runtime/define property getters */
17
+ /******/ (() => {
18
+ /******/ // define getter functions for harmony exports
19
+ /******/ __webpack_require__.d = (exports, definition) => {
20
+ /******/ for(var key in definition) {
21
+ /******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
22
+ /******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
23
+ /******/ }
24
+ /******/ }
25
+ /******/ };
26
+ /******/ })();
27
+ /******/
28
+ /******/ /* webpack/runtime/hasOwnProperty shorthand */
29
+ /******/ (() => {
30
+ /******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
31
+ /******/ })();
32
+ /******/
33
+ /******/ /* webpack/runtime/make namespace object */
34
+ /******/ (() => {
35
+ /******/ // define __esModule on exports
36
+ /******/ __webpack_require__.r = (exports) => {
37
+ /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
38
+ /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
39
+ /******/ }
40
+ /******/ Object.defineProperty(exports, '__esModule', { value: true });
41
+ /******/ };
42
+ /******/ })();
43
+ /******/
44
+ /************************************************************************/
45
+ var __webpack_exports__ = {};
46
+ // ESM COMPAT FLAG
47
+ __webpack_require__.r(__webpack_exports__);
48
+
49
+ // EXPORTS
50
+ __webpack_require__.d(__webpack_exports__, {
51
+ ApiResponse: () => (/* reexport */ ApiResponse),
52
+ KeyValueObject: () => (/* reexport */ KeyValueObject),
53
+ Metadata: () => (/* reexport */ Metadata),
54
+ QMeta: () => (/* reexport */ QMeta),
55
+ Repo: () => (/* reexport */ Repo),
56
+ Service: () => (/* reexport */ Service),
57
+ TemplateCompiler: () => (/* reexport */ TemplateCompiler),
58
+ UniqueKeyGenerator: () => (/* reexport */ UniqueKeyGenerator),
59
+ concatStringByArray: () => (/* reexport */ concatStringByArray),
60
+ convertString: () => (/* reexport */ convertString),
61
+ formatDate: () => (/* reexport */ formatDate),
62
+ generalPost: () => (/* reexport */ generalPost),
63
+ getValidation: () => (/* reexport */ getValidation),
64
+ getValueByKeys: () => (/* reexport */ getValueByKeys_getValueByKeys),
65
+ makeApiResponse: () => (/* reexport */ makeApiResponse),
66
+ makeService: () => (/* reexport */ makeService),
67
+ objectHelper: () => (/* reexport */ objectHelper),
68
+ pReduce: () => (/* reexport */ pReduce),
69
+ padZeros: () => (/* reexport */ padZeros),
70
+ stringFormatter: () => (/* reexport */ stringFormatter),
71
+ stringHelper: () => (/* reexport */ stringHelper)
72
+ });
73
+
74
+ ;// ./lib/helpers/getValidation/getValidation.js
75
+ function getValidation(rule, data, getDataByKey, KeyValueObject) {
76
+ if (!rule) {
77
+ return true
78
+ }
79
+ if (typeof getDataByKey !== 'function' || (KeyValueObject && typeof KeyValueObject !== 'function')) {
80
+ return false
81
+ }
82
+ const { key = '', value, keyValuePath = '' } = rule
83
+ const [valueAttribute] = Object.keys(value)
84
+
85
+ if (!key) {
86
+ switch (valueAttribute) {
87
+ case '$and': {
88
+ return value['$and'].reduce((acc, item) => (acc && getValidation(item, data, getDataByKey, KeyValueObject)), true)
89
+ }
90
+ case '$or': {
91
+ return value['$or'].reduce((acc, item) => (acc || getValidation(item, data, getDataByKey, KeyValueObject)), false)
92
+ }
93
+ default:
94
+ return false
95
+ }
96
+ }
97
+
98
+ let rowValue = getDataByKey(key, data)
99
+
100
+ // debugger
101
+
102
+ // if KeyValue object
103
+ if (keyValuePath) {
104
+ console.log('keyValuePath', keyValuePath)
105
+ const rowValueData = KeyValueObject.toObject(rowValue)
106
+ rowValue = getDataByKey(keyValuePath, rowValueData)
107
+ }
108
+
109
+ switch (valueAttribute) {
110
+ case '$empty': {
111
+ const isEmpty = rowValue === null || rowValue === undefined
112
+ return isEmpty === value['$empty']
113
+ }
114
+ case '$eq': {
115
+ return rowValue === value['$eq']
116
+ }
117
+ case '$gt': {
118
+ return rowValue > value['$gt']
119
+ }
120
+ case '$gte': {
121
+ return rowValue >= value['$gte']
122
+ }
123
+ case '$lt': {
124
+ return rowValue < value['$lt']
125
+ }
126
+ case '$lte': {
127
+ return rowValue <= value['$lte']
128
+ }
129
+ case '$in': {
130
+ if (Array.isArray(rowValue)) {
131
+ return !!rowValue.find((e) => (value['$in'].includes(e)))
132
+ }
133
+ if (typeof rowValue !== 'object') {
134
+ return !!value['$in'].includes(rowValue)
135
+ }
136
+ return false
137
+ }
138
+ case '$inValue': {
139
+ const result = getDataByKey(value['$inValue'], data)
140
+ const _value = Array.isArray(result) ? result : []
141
+ if (Array.isArray(rowValue)) {
142
+ return !!rowValue.find((e) => (_value.includes(e)))
143
+ }
144
+ if (typeof rowValue === 'string') {
145
+ return !!_value.includes(rowValue)
146
+ }
147
+ return false
148
+ }
149
+ case '$ne': {
150
+ return rowValue !== value['$ne']
151
+ }
152
+ case '$notIn': {
153
+ if (Array.isArray(rowValue)) {
154
+ return !rowValue.find((e) => (value['$notIn'].includes(e)))
155
+ }
156
+ if (typeof rowValue !== 'object') {
157
+ return !value['$notIn'].includes(rowValue)
158
+ }
159
+ return false
160
+ }
161
+ case '$intervalTimeGt': {
162
+ const now = new Date().getTime()
163
+ const timestamp = new Date(rowValue).getTime()
164
+ return (now - timestamp) > value['$intervalTimeGt']
165
+ }
166
+ case '$intervalTimeLt': {
167
+ const now = new Date().getTime()
168
+ const timestamp = new Date(rowValue).getTime()
169
+ return (now - timestamp) < value['$intervalTimeLt']
170
+ }
171
+ case '$isToday': {
172
+ const currentDate = new Date()
173
+ const start = currentDate.setHours(0,0,0,0)
174
+ const end = currentDate.setHours(23,59,59,59)
175
+ const dateValue = new Date(rowValue).getTime()
176
+ return (start <= dateValue && end >= dateValue) === value['$isToday']
177
+ }
178
+ case '$notInValue': {
179
+ const result = getDataByKey(value['$notInValue'], data)
180
+ const _value = Array.isArray(result) ? result : []
181
+ if (Array.isArray(rowValue)) {
182
+ return !rowValue.find((e) => (_value.includes(e)))
183
+ }
184
+ if (typeof rowValue !== 'object') {
185
+ return !_value.includes(rowValue)
186
+ }
187
+ return false
188
+ }
189
+ case '$range': {
190
+ const [min, max] = value['$range']
191
+ if (typeof min === 'number' && typeof max === 'number' && rowValue >= min && rowValue <= max) {
192
+ return true
193
+ }
194
+ return false
195
+ }
196
+ default:
197
+ return false
198
+ }
199
+ }
200
+
201
+ /* harmony default export */ const getValidation_getValidation = ({
202
+ getValidation
203
+ });
204
+
205
+
206
+ ;// ./lib/helpers/getValidation/index.js
207
+
208
+
209
+ ;// ./lib/helpers/formatDate/formatDate.js
210
+
211
+ function formatDate(date, format) {
212
+ const _date = date && date instanceof Date ? date : new Date(date)
213
+ const dayMapChi = ['日','一','二','三','四','五','六']
214
+ const dayMapEng = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday']
215
+ const dayMapEngShort = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat']
216
+ const _format = format || 'YYYY/MM/DD hh:mm'
217
+ const e = _date.getDay()
218
+ const ee = dayMapEngShort[e]
219
+ const eee = dayMapChi[e]
220
+ const eeee = dayMapEng[e]
221
+ const y = _date.getFullYear()
222
+ const m = _date.getMonth() + 1
223
+ const d = _date.getDate()
224
+ const h = _date.getHours()
225
+ const mm = _date.getMinutes()
226
+ const s = _date.getSeconds()
227
+
228
+ return _format.replace('YYYY', y)
229
+ .replace('MM', padding(m))
230
+ .replace('MM', padding(m))
231
+ .replace('DD', padding(d))
232
+ .replace('hh', padding(h))
233
+ .replace('mm', padding(mm))
234
+ .replace('ss', padding(s))
235
+ .replace('M', m)
236
+ .replace('D', d)
237
+ .replace('h', h)
238
+ .replace('m', mm)
239
+ .replace('s', s)
240
+ .replace('EEEE', padding(eeee))
241
+ .replace('EEE', padding(eee))
242
+ .replace('EE', padding(ee))
243
+ .replace('E', padding(e))
244
+ }
245
+
246
+ function padding(m) {
247
+ return m < 10 ? `0${m}` : m
248
+ }
249
+
250
+
251
+ /* harmony default export */ const formatDate_formatDate = ({
252
+ formatDate
253
+ });
254
+
255
+
256
+
257
+ ;// ./lib/helpers/formatDate/index.js
258
+
259
+
260
+ ;// ./lib/helpers/getValueByKeys/getValueByKeys.js
261
+ // keys can be array or object or string
262
+ function getValueByKeys_getValueByKeys(keys, data) {
263
+ let _keys = keys
264
+ let _data = data
265
+ if (typeof keys === 'string') {
266
+ _keys = _keys.split('.')
267
+ }
268
+ if (!Array.isArray(keys) && typeof keys === 'object') {
269
+ const { keys: keyArr, obj } = keys
270
+ _keys = keyArr
271
+ _data = obj
272
+ }
273
+ if (_keys.length === 0) {
274
+ return _data
275
+ }
276
+ const firstKey = _keys.shift()
277
+ if (_data && Object.prototype.hasOwnProperty.call(_data, firstKey)) {
278
+ return getValueByKeys_getValueByKeys(_keys, _data[firstKey])
279
+ }
280
+ if (_data && firstKey) {
281
+ return _data[firstKey]
282
+ }
283
+ return _data
284
+
285
+ }
286
+ /* harmony default export */ const getValueByKeys = ({
287
+ getValueByKeys: getValueByKeys_getValueByKeys
288
+ });
289
+
290
+
291
+
292
+ ;// ./lib/helpers/getValueByKeys/index.js
293
+
294
+
295
+ ;// ./lib/models/templateCompiler/templateCompilerException.js
296
+ const TEMPLATE_COMPILER_EXCEPTION_TYPE = {
297
+ argumentEmptyException: 'Argument is empty',
298
+ argumentFormatException: 'Incorrect number or format of argument',
299
+ invalidFuntionException: 'Function Name is invalid',
300
+ invalidRegExpException: 'Invalid regular expression',
301
+ isNotAFunctionException: 'Is not a function',
302
+ notExistException: 'Key does not exist',
303
+ resultEmptyException: 'Result is empty',
304
+ resultMoreThanOneException: 'More than one result'
305
+ }
306
+
307
+ class TemplateCompilerException extends Error {
308
+ constructor(message) {
309
+ super(message)
310
+ this.message = message
311
+ }
312
+ }
313
+
314
+
315
+
316
+ ;// ./lib/models/templateCompiler/constants.js
317
+ const _EMPTY = '_EMPTY'
318
+ const _FN_NAMES = [
319
+ 'get', 'map', 'join', 'concatIf', 'exec', 'filterOne', 'filterAll', 'formatDate', 'eq', 'neq', 'gt', 'lt', 'gte', 'lte', 'isEmpty', 'isNotEmpty', 'toLowerCase', 'toUpperCase'
320
+ ]
321
+ const _HIDE = '_HIDE'
322
+ const _NOT_EMPTY = '_NOT_EMPTY'
323
+ const _SELF = '_SELF'
324
+ const TAGS_EJS = ['<%=', '%>']
325
+ const TAGS_HANDLEBAR = ['{{', '}}']
326
+
327
+
328
+
329
+ ;// ./lib/models/templateCompiler/helpers/_concatIf.js
330
+
331
+
332
+
333
+
334
+ function _concatIf(data, args) {
335
+ if (typeof data !== 'string') {
336
+ throw new TemplateCompilerException(`_concatIf: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException}: the data must be string :${data.join(', ')}`)
337
+ }
338
+ if (args.length !== 3) {
339
+ throw new TemplateCompilerException(`_concatIf: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException}: ${args.join(', ')}`)
340
+ }
341
+ if (data === null || (typeof data === 'undefined')) {
342
+ return null
343
+ }
344
+ const [condition, success, failover] = args
345
+ const validConditions = [_EMPTY, _NOT_EMPTY]
346
+ if (validConditions.includes(condition) || success.length !== 2) {
347
+ throw new TemplateCompilerException(`concatIf: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentEmptyException}: ${condition}, ${success}`)
348
+ }
349
+ if (data === '' && failover.includes(_HIDE)) {
350
+ return ''
351
+ }
352
+ if (data !== '' && (data !== null || data !== undefined) && failover.includes(_HIDE)) {
353
+ return `${success[0]}${data}${success[success.length - 1]}`
354
+ }
355
+ return failover
356
+ }
357
+
358
+
359
+
360
+ ;// ./lib/models/templateCompiler/helpers/_eq.js
361
+
362
+
363
+
364
+
365
+ function _eq(data, args) {
366
+ if (args.length !== 3) {
367
+ throw new TemplateCompilerException(`eq: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException}: ${args.join(', ')}`)
368
+ }
369
+ if (data === null || (typeof data === 'undefined')) {
370
+ return null
371
+ }
372
+ if (args.includes(_SELF)) {
373
+ args = args.map((arg) => {
374
+ return (arg === _SELF) ? data : arg
375
+ })
376
+ }
377
+ const expected = args[0]
378
+ return data === expected ? args[1] : args[2]
379
+ }
380
+
381
+
382
+
383
+ ;// ./lib/models/templateCompiler/helpers/_exec.js
384
+ function _exec(data, args) {
385
+ try {
386
+ const [methodName, ..._args] = args
387
+ return data[methodName](..._args)
388
+ } catch (e) {
389
+ throw e
390
+ }
391
+ }
392
+
393
+
394
+
395
+ ;// ./lib/models/templateCompiler/helpers/_filterAll.js
396
+
397
+
398
+
399
+ // const DELIMITER = '~~~'
400
+
401
+ function _filterAll(data, args) {
402
+ try {
403
+ if (!Array.isArray(args) || args.length === 0) {
404
+ throw new TemplateCompilerException(TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentEmptyException)
405
+ }
406
+ if (!Array.isArray(data) || data.length === 0) {
407
+ return []
408
+ }
409
+ if (typeof data[0] === 'object') {
410
+ return _existObject(data, args)
411
+ }
412
+ if (typeof data[0] === 'string' || typeof data[0] === 'number') {
413
+ return _exist(data, args)
414
+ }
415
+ return []
416
+ } catch (e) {
417
+ throw e
418
+ }
419
+ }
420
+
421
+ function _exist(data, args) {
422
+ const _args = args.flat()
423
+ return data.filter((e) => _args.some((arg) => _performOperation(arg, e)))
424
+ }
425
+
426
+ function _existObject(data, args) {
427
+ if (args.length === 1) {
428
+ const arg = args[0]
429
+ return data.filter((e) => {
430
+ if (arg.includes('.')) {
431
+ return getValueByKeys_getValueByKeys(arg.split('.'), e)
432
+ }
433
+ return Object.prototype.hasOwnProperty.call(e, arg)
434
+ })
435
+ }
436
+
437
+ if (args.length > 2) {
438
+ let res = data
439
+ for (let i = 0; i < args.length; i += 2) {
440
+ const group = [args[i], args[i + 1]]
441
+ res = _existObject(res, group)
442
+ }
443
+ return res
444
+ }
445
+
446
+ const [key, ..._argsArr] = args
447
+ const _args = _argsArr.flat()
448
+ return data.filter((e) => {
449
+ const value = key.includes('.') ? getValueByKeys_getValueByKeys(key.split('.'), e) : e[key]
450
+ return _args.some((arg) => _performOperation(arg, value))
451
+ })
452
+ }
453
+
454
+ function _performOperation(arg, value) {
455
+ // the arg is undefined
456
+ if (arg === undefined && value === undefined) return true
457
+
458
+ // the arg is null
459
+ if (arg === null && value === null) return true
460
+
461
+ // the arg is boolean
462
+ if (typeof arg === 'boolean') {
463
+ return arg === value
464
+ }
465
+
466
+ // the arg is blank or *: Blank => Empty, * => Not Empty
467
+ if (arg === '' || arg === '*') {
468
+ // null and undefined are not included in either case
469
+ if (value === null || value === undefined) {
470
+ return false
471
+ }
472
+ if (typeof value === 'string') {
473
+ return arg === '' ? value === '' : value !== ''
474
+ }
475
+ if (Array.isArray(value)) {
476
+ return arg === '' ? value.length === 0 : value.length !== 0
477
+ }
478
+ return arg !== ''
479
+ }
480
+
481
+ // the arg is alphabetic or number
482
+ if (_isPureStringOrNumber(arg)) {
483
+ return arg === value
484
+ }
485
+
486
+ // the arg is array of [] or [*]: [] => Empty, [*] => Not Empty
487
+ if (arg.startsWith('[') && arg.endsWith(']')) {
488
+ if (arg === '[]') {
489
+ return Array.isArray(value) && value.length === 0
490
+ }
491
+ if (arg === '[*]') {
492
+ return Array.isArray(value) && value.length !== 0
493
+ }
494
+ return false
495
+ }
496
+
497
+ // the arg is 'operator + string | number'
498
+ const { operator, value: argValue } = _splitOperator(arg)
499
+ if (!operator || (argValue !== 0 && !argValue)) {
500
+ return false
501
+ }
502
+ switch (operator) {
503
+ case '>':
504
+ return value > argValue
505
+ case '<':
506
+ return value < argValue
507
+ case '!=':
508
+ return value !== argValue
509
+ case '>=':
510
+ return value >= argValue
511
+ case '<=':
512
+ return value <= argValue
513
+ default:
514
+ return false
515
+ }
516
+ }
517
+
518
+ function _isPureStringOrNumber(input) {
519
+ if (typeof input === 'string') {
520
+ if (input.startsWith('[') && input.endsWith(']')) {
521
+ return false
522
+ }
523
+ if (/!=|>=|<=|>|</.test(input)) {
524
+ return false
525
+ }
526
+ return true
527
+ }
528
+ return !Number.isNaN(input)
529
+ }
530
+
531
+ function _splitOperator(str) {
532
+ const operators = ['!=', '>=', '<=', '>', '<']
533
+
534
+ const matchedOp = operators.find((op) => str.startsWith(op))
535
+ if (!matchedOp) return { operator: null, value: null }
536
+
537
+ const remaining = str.slice(matchedOp.length)
538
+
539
+ // '>Primary' or '<Primary' is invalid
540
+ if (/^[a-zA-Z]*$/.test(remaining) && matchedOp !== '!=') {
541
+ return { operator: null, value: null }
542
+ }
543
+
544
+ // if it is a number it is converted to a number
545
+ const value = (!Number.isNaN(parseFloat(remaining)) && !Number.isNaN(remaining)) ? Number(remaining) : remaining
546
+
547
+ return {
548
+ operator: matchedOp,
549
+ value
550
+ }
551
+ }
552
+
553
+
554
+
555
+ ;// ./lib/models/templateCompiler/helpers/_filterOne.js
556
+
557
+
558
+
559
+ function _filterOne(data, args) {
560
+ try {
561
+ const list = _filterAll(data, args)
562
+ if (list.length === 1) {
563
+ return list[0]
564
+ }
565
+ if (list.length === 0) {
566
+ return null
567
+ }
568
+ throw new TemplateCompilerException(TEMPLATE_COMPILER_EXCEPTION_TYPE.resultMoreThanOneException)
569
+ } catch (e) {
570
+ throw e
571
+ }
572
+ }
573
+
574
+
575
+
576
+ ;// ./lib/models/templateCompiler/helpers/_formatDate.js
577
+
578
+
579
+ function _formatDate(timestamp, format) {
580
+ if (format.length === 0) {
581
+ throw new TemplateCompilerException(`_formateDate: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException}: format parts must be not empty array`)
582
+ }
583
+
584
+ if (timestamp === null || timestamp === undefined) {
585
+ return null
586
+ }
587
+
588
+ const date = new Date(timestamp)
589
+
590
+ const partsMap = {
591
+ yyyy: String(date.getFullYear()),
592
+ mm: String(date.getMonth() + 1).padStart(2, '0'),
593
+ dd: String(date.getDate()).padStart(2, '0')
594
+ }
595
+
596
+ // Check for invalid format tokens
597
+ const validTokens = ['yyyy', 'mm', 'dd']
598
+ const invalidTokens = format.filter((part) => part.length > 1 && !validTokens.includes(part))
599
+
600
+ if (invalidTokens.length > 0) {
601
+ throw new TemplateCompilerException(
602
+ `_formateDate: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException}: the format type is not valid: ${format.join(', ')}`
603
+ )
604
+ }
605
+
606
+ // Build the formatted string using reduce
607
+ return format.reduce((result, part) => result + (partsMap[part] || part), '')
608
+ }
609
+
610
+
611
+
612
+ ;// ./lib/models/templateCompiler/helpers/_get.js
613
+
614
+
615
+ function _get(data, key, failover = null) {
616
+ try {
617
+ if (key === null || (typeof key === 'undefined') || key === '') {
618
+ throw new TemplateCompilerException(TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentEmptyException)
619
+ }
620
+ if (data === null) {
621
+ return null
622
+ }
623
+ if (key.includes('.')) {
624
+ const parts = key.split('.')
625
+ if (parts.length > 1) {
626
+ const first = parts.shift()
627
+ const remainingKey = parts.join('.')
628
+ if (typeof data[first] !== 'undefined') {
629
+ return _get(data[first], remainingKey, failover)
630
+ }
631
+ return _handleFailover(key, failover)
632
+ }
633
+ }
634
+ if (typeof data[key] !== 'undefined') {
635
+ return data[key]
636
+ }
637
+ return _handleFailover(key, failover)
638
+ } catch (e) {
639
+ throw e
640
+ }
641
+ }
642
+
643
+ function _handleFailover(key, failover) {
644
+ if (failover !== null) {
645
+ return failover
646
+ }
647
+ return null
648
+ // throw new TemplateCompilerException(`Key "${key}" does not exist and no failover`)
649
+ }
650
+
651
+
652
+
653
+ ;// ./lib/models/templateCompiler/helpers/_gt.js
654
+
655
+
656
+
657
+
658
+ function _gt(data, args) {
659
+ if (args.length !== 3) {
660
+ throw new TemplateCompilerException(`_gt: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException}: ${args.join(', ')}`)
661
+ }
662
+ if (data === null || (typeof data === 'undefined')) {
663
+ return null
664
+ }
665
+ if (args.includes(_SELF)) {
666
+ args = args.map((arg) => {
667
+ return (arg === _SELF) ? data : arg
668
+ })
669
+ }
670
+ const expected = args[0]
671
+ return data > expected ? args[1] : args[2]
672
+ }
673
+
674
+
675
+
676
+ ;// ./lib/models/templateCompiler/helpers/_gte.js
677
+
678
+
679
+
680
+
681
+ function _gte(data, args) {
682
+ if (args.length !== 3) {
683
+ throw new TemplateCompilerException(`_gte: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException}: ${args.join(', ')}`)
684
+ }
685
+ if (data === null || (typeof data === 'undefined')) {
686
+ return null
687
+ }
688
+ if (args.includes(_SELF)) {
689
+ args = args.map((arg) => {
690
+ return (arg === _SELF) ? data : arg
691
+ })
692
+ }
693
+ const expected = args[0]
694
+ return data >= expected ? args[1] : args[2]
695
+ }
696
+
697
+
698
+
699
+ ;// ./lib/models/templateCompiler/helpers/_isEmpty.js
700
+
701
+
702
+
703
+
704
+ function _isEmpty(data, args) {
705
+ if (args.length !== 2) {
706
+ throw new TemplateCompilerException(`_isEmpty: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException}: ${args.join(', ')}`)
707
+ }
708
+ // if (data === null || (typeof data === 'undefined')) {
709
+ // return null
710
+ // }
711
+ if (args.includes(_SELF)) {
712
+ args = args.map((arg) => {
713
+ return (arg === _SELF) ? data : arg
714
+ })
715
+ }
716
+ if (data !== null && typeof data === 'object' && Object.keys(data).length === 0) {
717
+ return args[0]
718
+ }
719
+ return (data === '' || data === null || data === undefined || data.length === 0) ? args[0] : args[1]
720
+ }
721
+
722
+
723
+
724
+ ;// ./lib/models/templateCompiler/helpers/_isNotEmpty.js
725
+
726
+
727
+
728
+
729
+ function _isNotEmpty(data, args) {
730
+ if (args.length !== 2) {
731
+ throw new TemplateCompilerException(`_isNotEmpty: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException}: ${args.join(', ')}`)
732
+ }
733
+ // if (data === null || (typeof data === 'undefined')) {
734
+ // return null
735
+ // }
736
+ if (args.includes(_SELF)) {
737
+ args = args.map((arg) => {
738
+ return (arg === _SELF) ? data : arg
739
+ })
740
+ }
741
+ if (data !== null && typeof data === 'object' && Object.keys(data).length === 0) {
742
+ return args[1]
743
+ }
744
+ if (Array.isArray(data) && data.length === 0) {
745
+ return args[1]
746
+ }
747
+ if (typeof data === 'string' && data === '') {
748
+ return args[1]
749
+ }
750
+ if (data === null || data === undefined) {
751
+ return args[1]
752
+ }
753
+ return args[0]
754
+ }
755
+
756
+
757
+ ;// ./lib/models/templateCompiler/helpers/_join.js
758
+ function _join(data, delimiter) {
759
+ try {
760
+ if (data.length === 0) return ''
761
+ if (data.length === 1) return _stringifyObject(data[0])
762
+ return data.map((item) => _stringifyObject(item)).join(delimiter)
763
+ } catch (e) {
764
+ throw e
765
+ }
766
+ }
767
+
768
+ function _stringifyObject(obj) {
769
+ return JSON.stringify(obj).replace(/"([^"]+)":/g, '$1: ').replace(/"([^"]+)"/g, '$1').replace(/,/g, ', ')
770
+ }
771
+
772
+
773
+
774
+ ;// ./lib/models/templateCompiler/helpers/_lt.js
775
+
776
+
777
+
778
+
779
+ function _lt(data, args) {
780
+ if (args.length !== 3) {
781
+ throw new TemplateCompilerException(`_lt: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException}: ${args.join(', ')}`)
782
+ }
783
+ if (data === null || (typeof data === 'undefined')) {
784
+ return null
785
+ }
786
+ if (args.includes(_SELF)) {
787
+ args = args.map((arg) => {
788
+ return (arg === _SELF) ? data : arg
789
+ })
790
+ }
791
+ const expected = args[0]
792
+ return data < expected ? args[1] : args[2]
793
+ }
794
+
795
+
796
+
797
+ ;// ./lib/models/templateCompiler/helpers/_lte.js
798
+
799
+
800
+
801
+
802
+ function _lte(data, args) {
803
+ if (args.length !== 3) {
804
+ throw new TemplateCompilerException(`_lte: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException}: ${args.join(', ')}`)
805
+ }
806
+ if (data === null || (typeof data === 'undefined')) {
807
+ return null
808
+ }
809
+ if (args.includes(_SELF)) {
810
+ args = args.map((arg) => {
811
+ return (arg === _SELF) ? data : arg
812
+ })
813
+ }
814
+ const expected = args[0]
815
+ return data <= expected ? args[1] : args[2]
816
+ }
817
+
818
+
819
+
820
+ ;// ./lib/models/templateCompiler/helpers/_map.js
821
+
822
+
823
+
824
+ function _map(data, args) {
825
+ try {
826
+ if (args.length === 0) {
827
+ throw new TemplateCompilerException(TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentEmptyException)
828
+ }
829
+ if (data === null || (typeof data === 'undefined')) {
830
+ return null
831
+ }
832
+
833
+ const result = data.reduce((acc, item) => {
834
+ if (args.length === 1 && Array.isArray(args[0])) {
835
+ args = args[0]
836
+ acc.hasFormat = true
837
+ }
838
+ const list = args.map((key) => {
839
+ if (key.includes('.')) {
840
+ const parts = key.split('.')
841
+ const first = parts[0]
842
+ parts.shift()
843
+ const remainingKey = parts.join('.')
844
+ return _get(item[first], remainingKey)
845
+ }
846
+ if (typeof item[key] !== 'undefined') {
847
+ return item[key]
848
+ }
849
+ return null
850
+ })
851
+ if (acc.hasFormat) {
852
+ acc.content.push(list)
853
+ } else {
854
+ acc.content = acc.content.concat(list)
855
+ }
856
+ return acc
857
+ }, {
858
+ content: [],
859
+ hasFormat: false
860
+ })
861
+ return result.content
862
+ } catch (e) {
863
+ throw e
864
+ }
865
+ }
866
+
867
+
868
+
869
+ ;// ./lib/models/templateCompiler/helpers/_neq.js
870
+
871
+
872
+
873
+
874
+ function _neq(data, args) {
875
+ if (args.length !== 3) {
876
+ throw new TemplateCompilerException(`_neq: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException}: ${args.join(', ')}`)
877
+ }
878
+ if (data === null || (typeof data === 'undefined')) {
879
+ return null
880
+ }
881
+ if (args.includes(_SELF)) {
882
+ args = args.map((arg) => {
883
+ return (arg === _SELF) ? data : arg
884
+ })
885
+ }
886
+ const expected = args[0]
887
+ return data !== expected ? args[1] : args[2]
888
+ }
889
+
890
+
891
+
892
+ ;// ./lib/models/templateCompiler/helpers/_toLowerCase.js
893
+
894
+
895
+ function _toLowerCase(data, args) {
896
+ if (args !== undefined) {
897
+ throw new TemplateCompilerException(`_toLowerCase: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException}: ${args.join(', ')}`)
898
+ }
899
+ if (data === null || (typeof data === 'undefined') || typeof data !== 'string') {
900
+ return null
901
+ }
902
+ return String(data).toLowerCase()
903
+ }
904
+
905
+
906
+
907
+ ;// ./lib/models/templateCompiler/helpers/_toUpperCase.js
908
+
909
+
910
+ function _toUpperCase(data, args) {
911
+ if (typeof data !== 'string') {
912
+ throw new TemplateCompilerException(`_toUpperCase: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException}: the data must be string: ${data}`)
913
+ }
914
+ if (args !== undefined) {
915
+ throw new TemplateCompilerException(`_toUpperCase: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException}: the argument must be empty: ${args.join(', ')}`)
916
+ }
917
+ if (data === null || (typeof data === 'undefined') || typeof data !== 'string') {
918
+ return null
919
+ }
920
+ return String(data).toUpperCase()
921
+ }
922
+
923
+
924
+
925
+ ;// ./lib/models/templateCompiler/helpers/index.js
926
+
927
+
928
+
929
+
930
+
931
+
932
+
933
+
934
+
935
+
936
+
937
+
938
+
939
+
940
+
941
+
942
+
943
+
944
+
945
+
946
+
947
+ ;// ./lib/models/templateCompiler/templateCompiler.js
948
+
949
+
950
+
951
+
952
+ class TemplateCompiler {
953
+ constructor(data) {
954
+ this.data = data
955
+ }
956
+ static init(options) {
957
+ return new this(options)
958
+ }
959
+ static initFromArray(arr = []) {
960
+ if (Array.isArray(arr)) {
961
+ return arr.map((a) => this.init(a))
962
+ }
963
+ return []
964
+ }
965
+ static initOnlyValidFromArray(arr = []) {
966
+ return this.initFromArray(arr).filter((i) => i)
967
+ }
968
+ static concatIf(data, args) {
969
+ return _concatIf(data, args)
970
+ }
971
+ static eq(data, args) {
972
+ return _eq(data, args)
973
+ }
974
+
975
+ static filterAll(data, args) {
976
+ return _filterAll(data, args)
977
+ }
978
+
979
+ static formatDate(data, args) {
980
+ return _formatDate(data, args)
981
+ }
982
+
983
+ static get(data, key, failover = null) {
984
+ return _get(data, key, failover)
985
+ }
986
+ static gt(data, args) {
987
+ return _gt(data, args)
988
+ }
989
+ static gte(data, args) {
990
+ return _gte(data, args)
991
+ }
992
+ static isEmpty(data, args) {
993
+ return _isEmpty(data, args)
994
+ }
995
+ static isNotEmpty(data, args) {
996
+ return _isNotEmpty(data, args)
997
+ }
998
+ static join(data, separator = '') {
999
+ return _join(data, separator)
1000
+ }
1001
+ static lt(data, args) {
1002
+ return _lt(data, args)
1003
+ }
1004
+ static lte(data, args) {
1005
+ return _lte(data, args)
1006
+ }
1007
+ static map(data, args = []) {
1008
+ return _map(data, args)
1009
+ }
1010
+ static neq(data, args) {
1011
+ return _neq(data, args)
1012
+ }
1013
+ static toLowerCase(data, args) {
1014
+ return _toLowerCase(data, args)
1015
+ }
1016
+ static toUpperCase(data, args) {
1017
+ return _toUpperCase(data, args)
1018
+ }
1019
+ static parseFunction(expression) {
1020
+ return _parseFunction(expression, _FN_NAMES)
1021
+ }
1022
+
1023
+ pipe(expression = '') {
1024
+ this.delimiters = expression.substring(0, 2) === '{{' ? TAGS_HANDLEBAR : TAGS_EJS
1025
+ const regex = new RegExp(`${this.delimiters[0]}\\s(.*?)\\s${this.delimiters[1]}`)
1026
+ const match = expression.match(regex)
1027
+ if (match !== null) {
1028
+ try {
1029
+ const functionList = _parseFunction(match[1], _FN_NAMES)
1030
+ return functionList.reduce((acc, fn) => {
1031
+ return _callFunction(acc, fn.name, fn.args)
1032
+ }, this.data)
1033
+ } catch (e) {
1034
+ throw new TemplateCompilerException(`TemplateCompiler engine error: ${e.message}`)
1035
+ }
1036
+ }
1037
+ throw new TemplateCompilerException(`TemplateCompiler engine error: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.invalidRegExpException}`)
1038
+ }
1039
+ }
1040
+
1041
+ function _parseFunction(expression, existFunctionNames) {
1042
+ const regExp = new RegExp(/(\w+)\(([^)]*)\)/)
1043
+ let parts
1044
+ if (expression.includes('|')) {
1045
+ parts = expression.split('|')
1046
+ } else {
1047
+ parts = [expression]
1048
+ }
1049
+ return parts.reduce((acc, part) => {
1050
+ const match = part.match(regExp)
1051
+ if (match !== null) {
1052
+ const functionName = match[1]
1053
+ const parameters = match[2]
1054
+ const paramList = _parseParams(parameters)
1055
+ if (existFunctionNames.includes(functionName)) {
1056
+ acc.push({
1057
+ name: functionName,
1058
+ args: paramList
1059
+ })
1060
+ } else {
1061
+ throw new TemplateCompilerException(`${functionName} is not a valid function`)
1062
+ }
1063
+ }
1064
+ return acc
1065
+ }, [])
1066
+ }
1067
+
1068
+ function _parseParams(parameters) {
1069
+ const _parameters = parameters.trim()
1070
+ const regExp = new RegExp(/^[^\w\d\s]+$/)
1071
+ const match = _parameters.match(regExp)
1072
+ if (match !== null) {
1073
+ return [_parameters.substring(1, _parameters.length - 1)]
1074
+ }
1075
+ if (_parameters.includes(',')) {
1076
+ // 用正则表达式匹配逗号,但忽略方括号中的逗号
1077
+ const parts = _splitIgnoringBrackets(_parameters)
1078
+ return parts.map((part) => _parseSinglePart(part))
1079
+ }
1080
+ return [_parseSinglePart(_parameters)]
1081
+ }
1082
+
1083
+ function _splitIgnoringBrackets(input) {
1084
+ const regExp2 = new RegExp(/^\d+(\.\d+)?$/)
1085
+ const regExp = new RegExp(/(?![^\[]*\])\s*,\s*/)
1086
+ const parts = input.split(regExp)
1087
+ return parts.map((part) => {
1088
+ const _part = part.trim()
1089
+ if (_part !== '' && !!_part.match(regExp2)) {
1090
+ // 如果是数字,转换为 num 类型
1091
+ return Number.isNaN(_part) ? _part : parseInt(_part, 10)
1092
+ }
1093
+ // 否则当作字符串处理
1094
+ return _part
1095
+ })
1096
+ }
1097
+
1098
+ function _parseSinglePart(input) {
1099
+ if (typeof input === 'string') {
1100
+ if (input.startsWith('"') && input.endsWith('"')) {
1101
+ // 去掉双引号,返回
1102
+ return input.substring(1, input.length - 1)
1103
+ }
1104
+
1105
+ const _input = _toBasicType(input)
1106
+
1107
+ if (typeof _input !== 'string') {
1108
+ return _input
1109
+ }
1110
+
1111
+ // 如果是一个列表形式(例如 ["p", "d"] 或 [p, d])
1112
+ if (_input.startsWith('[') && _input.endsWith(']')) {
1113
+ const listContent = _input.substring(1, _input.length - 1).trim()
1114
+ if (listContent !== '') {
1115
+ return listContent.split(',').map((item) => {
1116
+ return _toBasicType(item.trim())
1117
+ })
1118
+ }
1119
+ return []
1120
+ }
1121
+ return input
1122
+ }
1123
+ return input
1124
+ }
1125
+
1126
+ function _toBasicType(input) {
1127
+ if (input.startsWith('"') && input.endsWith('"')) {
1128
+ // 去掉双引号,返回
1129
+ return input.substring(1, input.length - 1)
1130
+ }
1131
+ if (input === 'true') {
1132
+ return true
1133
+ }
1134
+ if (input === 'false') {
1135
+ return false
1136
+ }
1137
+ if (input === 'undefined') {
1138
+ return undefined
1139
+ }
1140
+ if (input === 'null') {
1141
+ return null
1142
+ }
1143
+ if (!Number.isNaN(input) && !Number.isNaN(Number.parseFloat(input))) {
1144
+ return Number(input)
1145
+ }
1146
+ return input
1147
+ }
1148
+
1149
+ function _callFunction(data, functionName, parameters) {
1150
+ try {
1151
+ let failover
1152
+ switch (functionName) {
1153
+ case 'exec':
1154
+ return _exec(data, parameters)
1155
+ case 'get':
1156
+ if (parameters.length > 2) {
1157
+ throw new TemplateCompilerException(TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException)
1158
+ }
1159
+ if (parameters.length === 2) {
1160
+ failover = parameters[parameters.length - 1]
1161
+ }
1162
+ return _get(data, parameters[0], failover)
1163
+ case 'join':
1164
+ return _join(data, parameters[0])
1165
+ case 'map':
1166
+ return _map(data, parameters)
1167
+ case 'concatIf':
1168
+ return _concatIf(data, parameters)
1169
+ case 'filterOne':
1170
+ return _filterOne(data, parameters)
1171
+ case 'filterAll':
1172
+ return _filterAll(data, parameters)
1173
+ case 'formatDate':
1174
+ return _formatDate(data, parameters)
1175
+ case 'eq':
1176
+ return _eq(data, parameters)
1177
+ case 'neq':
1178
+ return _neq(data, parameters)
1179
+ case 'gt':
1180
+ return _gt(data, parameters)
1181
+ case 'gte':
1182
+ return _gte(data, parameters)
1183
+ case 'lt':
1184
+ return _lt(data, parameters)
1185
+ case 'lte':
1186
+ return _lte(data, parameters)
1187
+ case 'isEmpty':
1188
+ return _isEmpty(data, parameters)
1189
+ case 'isNotEmpty':
1190
+ return _isNotEmpty(data, parameters)
1191
+ case 'toLowerCase':
1192
+ return _toLowerCase(data)
1193
+ case 'toUpperCase':
1194
+ return _toUpperCase(data)
1195
+ default:
1196
+ throw new Error(`${functionName} is not a valid function`)
1197
+ }
1198
+ } catch (e) {
1199
+ throw e
1200
+ }
1201
+ }
1202
+
1203
+
1204
+
1205
+ ;// ./lib/models/templateCompiler/index.js
1206
+
1207
+
1208
+
1209
+
1210
+ ;// ./lib/helpers/concatStringByArray/concatStringByArray.js
1211
+
1212
+
1213
+
1214
+
1215
+
1216
+ function concatStringByArray(arrTemplate, data) {
1217
+ return arrTemplate.reduce((acc, item) => {
1218
+ const { type, value = '', restriction, template, format, showMinutes } = item
1219
+ switch (type) {
1220
+ case('label'): {
1221
+ if (getValidation(restriction, data, getValueByKeys_getValueByKeys)) {
1222
+ acc += (value.toString())
1223
+ }
1224
+ break
1225
+ }
1226
+ case('value'): {
1227
+ if (getValidation(restriction, data, getValueByKeys_getValueByKeys)) {
1228
+ const _value = getValueByKeys_getValueByKeys(value.split('.'), data) || ''
1229
+ acc += (_value.toString())
1230
+ }
1231
+ break
1232
+ }
1233
+ case('array'): {
1234
+ if (getValidation(restriction, data, getValueByKeys_getValueByKeys)) {
1235
+ const _value = getValueByKeys_getValueByKeys(value.split('.'), data) || []
1236
+ acc += _value.reduce((_acc, item) => {
1237
+ return _acc += concatStringByArray(template, item)
1238
+ }, '')
1239
+ }
1240
+ break
1241
+ }
1242
+ case('ellipsis'): {
1243
+ if (getValidation(restriction, data, getValueByKeys_getValueByKeys)) {
1244
+ const { maxLength } = item
1245
+ const _value = getValueByKeys_getValueByKeys(value.split('.'), data) || ''
1246
+ if (_value.length <= maxLength) {
1247
+ acc += (_value.toString())
1248
+ } else {
1249
+ acc += `${_value.substr(0, maxLength)}...`
1250
+ }
1251
+ }
1252
+ break
1253
+ }
1254
+ case ('date'): {
1255
+ if (getValidation(restriction, data, getValueByKeys_getValueByKeys)) {
1256
+ const _value = getValueByKeys_getValueByKeys(value.split('.'), data) || ''
1257
+ acc += (formatDate(_value, format).toString())
1258
+ }
1259
+ break
1260
+ }
1261
+ case ('templateCompiler'): {
1262
+ if (getValidation(restriction, data, getValueByKeys_getValueByKeys)) {
1263
+ const templateCompiler = new TemplateCompiler({ data })
1264
+ acc += templateCompiler.pipe(value)
1265
+ }
1266
+ break
1267
+ }
1268
+ }
1269
+ return acc
1270
+ }, '')
1271
+ }
1272
+ /* harmony default export */ const concatStringByArray_concatStringByArray = ({
1273
+ concatStringByArray
1274
+ });
1275
+
1276
+
1277
+
1278
+ ;// ./lib/helpers/concatStringByArray/index.js
1279
+
1280
+
1281
+ ;// ./lib/helpers/convertString/convertString.js
1282
+
1283
+
1284
+ function convertString(string, patternMatch = /\$\{(.+?)\}/g, value, getValueByKeys) {
1285
+ if (!string) {
1286
+ return ''
1287
+ }
1288
+ let _getValueByKeys = typeof getValueByKeys !== 'function' ? getValueByKeys : getValueByKeys_getValueByKeys
1289
+ const reg = new RegExp(patternMatch, 'g')
1290
+ return string.replace(reg, (match, key) => {
1291
+ const result = _getValueByKeys({ keys: key.split('.'), obj: value })
1292
+ if (result === null || result === undefined) {
1293
+ return ''
1294
+ }
1295
+ return typeof result === 'object' ? JSON.stringify(result) : result
1296
+ })
1297
+ }
1298
+
1299
+ /* harmony default export */ const convertString_convertString = ({
1300
+ convertString
1301
+ });
1302
+
1303
+
1304
+ ;// ./lib/helpers/convertString/index.js
1305
+
1306
+
1307
+ ;// ./lib/helpers/objectHelper/objectHelper.js
1308
+ const objectHelper = {
1309
+ get(obj, path) {
1310
+ const parts = path.split('.')
1311
+ return parts.reduce((acc, part) => {
1312
+ if (part.endsWith('[]')) {
1313
+ // 处理数组遍历
1314
+ const key = part.slice(0, -2) // 去掉 '[]' 得到属性名
1315
+ if (Array.isArray(acc[key])) {
1316
+ return acc[key] // 返回整个数组
1317
+ }
1318
+ return [] // 如果不是数组,返回空数组
1319
+ }
1320
+ if (part.includes('[') && part.includes(']')) {
1321
+ // 处理数组索引
1322
+ const arrayMatch = part.match(/(\w+)\[(\d+)\]/)
1323
+ if (arrayMatch) {
1324
+ const key = arrayMatch[1]
1325
+ const index = arrayMatch[2]
1326
+ return acc && acc[key] && acc[key][index]
1327
+ }
1328
+ } else if (acc && Array.isArray(acc)) {
1329
+ // 如果当前值是数组,提取每个对象的指定属性
1330
+ return acc.map((item) => item[part])
1331
+ } else {
1332
+ // 处理普通属性
1333
+ return acc && acc[part]
1334
+ }
1335
+ }, obj)
1336
+ },
1337
+ merge,
1338
+ set(obj, path, value) {
1339
+ const parts = path.split('.')
1340
+ let current = obj
1341
+ for (let i = 0; i < parts.length - 1; i++) {
1342
+ const part = parts[i]
1343
+ if (part.endsWith('[]')) {
1344
+ // 处理数组遍历
1345
+ const key = part.slice(0, -2) // 去掉 '[]' 得到属性名
1346
+ if (Array.isArray(current[key])) {
1347
+ current[key].forEach((item) => set(item, parts.slice(i + 1).join('.'), value))
1348
+ }
1349
+ return // 处理完数组后直接返回
1350
+ }
1351
+ if (part.includes('[') && part.includes(']')) {
1352
+ // 处理数组索引
1353
+ const arrayMatch = part.match(/(\w+)\[(\d+)\]/)
1354
+ if (arrayMatch) {
1355
+ const key = arrayMatch[1]
1356
+ const index = arrayMatch[2]
1357
+ if (Array.isArray(current[key]) && current[key][index]) {
1358
+ current = current[key][index]
1359
+ } else {
1360
+ return // 如果数组或索引不存在,直接返回
1361
+ }
1362
+ }
1363
+ } else {
1364
+ // 处理普通属性
1365
+ if (!current[part]) {
1366
+ current[part] = {} // 如果属性不存在,创建一个空对象
1367
+ }
1368
+ current = current[part]
1369
+ }
1370
+ }
1371
+
1372
+ // 设置最终属性值
1373
+ const lastPart = parts[parts.length - 1]
1374
+ current[lastPart] = value
1375
+ }
1376
+ }
1377
+
1378
+ function merge(target, ...sources) {
1379
+ if (!sources.length) return target
1380
+
1381
+ const source = sources.shift() // 取出第一个源对象
1382
+
1383
+ if (_isObject(target) && _isObject(source)) {
1384
+ for (const key in source) {
1385
+ if (_isObject(source[key])) {
1386
+ if (!target[key]) {
1387
+ // 如果目标对象没有该属性,创建一个空对象
1388
+ target[key] = {}
1389
+ }
1390
+ // 递归合并
1391
+ merge(target[key], source[key])
1392
+ } else {
1393
+ // 直接覆盖
1394
+ target[key] = source[key]
1395
+ }
1396
+ }
1397
+ }
1398
+
1399
+ // 继续合并剩余的源对象
1400
+ return merge(target, ...sources)
1401
+ }
1402
+
1403
+ function _isObject(obj) {
1404
+ return obj && typeof obj === 'object' && !Array.isArray(obj)
1405
+ }
1406
+
1407
+
1408
+
1409
+ ;// ./lib/helpers/objectHelper/index.js
1410
+
1411
+
1412
+
1413
+
1414
+ ;// ./lib/helpers/pReduce/pReduce.js
1415
+ async function pReduce(iterable, reducer, initialValue) {
1416
+ return new Promise((resolve, reject) => {
1417
+ const iterator = iterable[Symbol.iterator]()
1418
+ let index = 0
1419
+
1420
+ const next = async total => {
1421
+ const element = iterator.next()
1422
+
1423
+ if (element.done) {
1424
+ resolve(total)
1425
+ return
1426
+ }
1427
+
1428
+ try {
1429
+ const [resolvedTotal, resolvedValue] = await Promise.all([total, element.value])
1430
+ next(reducer(resolvedTotal, resolvedValue, index++))
1431
+ } catch (error) {
1432
+ reject(error)
1433
+ }
1434
+ }
1435
+
1436
+ next(initialValue)
1437
+ })
1438
+ }
1439
+
1440
+
1441
+
1442
+ ;// ./lib/models/apiResponse/apiResponse.js
1443
+ class ApiResponse {
1444
+ constructor(options = {}) {
1445
+ options = options || {}
1446
+ this._data = options.data || options._data || []
1447
+ this.err = options.err
1448
+ this.isNew = options.isNew || false
1449
+ this.message = options.message
1450
+ this.total = options.total || 0
1451
+ this._instanceBuilder = options._instanceBuilder
1452
+ }
1453
+
1454
+ static init(options = {}) {
1455
+ if (options instanceof this) {
1456
+ return options
1457
+ }
1458
+ const instance = new this(options)
1459
+ return instance
1460
+ }
1461
+ static get _classname() {
1462
+ return 'ApiResponse'
1463
+ }
1464
+ static get _superclass() {
1465
+ return 'ApiResponse'
1466
+ }
1467
+
1468
+ // getters
1469
+ get data() {
1470
+ if (this._instanceBuilder && (typeof this._instanceBuilder === 'function')) {
1471
+ return this._data.map(this._instanceBuilder)
1472
+ }
1473
+ return this._data
1474
+ }
1475
+ }
1476
+
1477
+
1478
+
1479
+ ;// ./lib/models/apiResponse/makeApiResponse.js
1480
+
1481
+
1482
+ function makeApiResponse({ repo, result }) {
1483
+ return ApiResponse.init({
1484
+ ...result,
1485
+ _instanceBuilder: (i) => {
1486
+ return repo.init(i)
1487
+ }
1488
+ })
1489
+ }
1490
+
1491
+
1492
+
1493
+ ;// ./lib/models/apiResponse/index.js
1494
+
1495
+
1496
+
1497
+
1498
+
1499
+ ;// ./lib/models/keyValueObject/keyValueObject.js
1500
+ class KeyValueObject {
1501
+ constructor(options = {}) {
1502
+ options = options || {}
1503
+ this.key = options.key || null
1504
+ this.value = (typeof options.value !== 'undefined') ? options.value : ''
1505
+ }
1506
+
1507
+ // Class methods
1508
+ static init(options = {}) {
1509
+ if (options instanceof this) {
1510
+ return options
1511
+ }
1512
+ const instance = new this(options)
1513
+ return instance.isValid ? instance : null
1514
+ }
1515
+ static initFromArray(arr = []) {
1516
+ if (Array.isArray(arr)) {
1517
+ return arr.map((a) => this.init(a))
1518
+ }
1519
+ return []
1520
+ }
1521
+ static initOnlyValidFromArray(arr = []) {
1522
+ return this.initFromArray(arr).filter((i) => i)
1523
+ }
1524
+ static get _classname() {
1525
+ return 'KeyValueObject'
1526
+ }
1527
+ static get _superclass() {
1528
+ return 'KeyValueObject'
1529
+ }
1530
+
1531
+ static addItem(arr, key, value) {
1532
+ arr.push(this.init({ key, value }))
1533
+ }
1534
+ static addRecord(arr = [], key, value) {
1535
+ if (!this.hasKeyValue(arr, key, value)) {
1536
+ arr.push(this.init({ key, value }))
1537
+ }
1538
+ return arr
1539
+ }
1540
+ static appendRecord(arr = [], key, value) {
1541
+ return arr.map((item) => {
1542
+ if (this.sameKey(item, key)) {
1543
+ item.value = [...item.value, ...value]
1544
+ }
1545
+ return item
1546
+ })
1547
+ }
1548
+ static appendValueArray(arr = [], key, value) {
1549
+ return arr.map((item) => {
1550
+ if (this.sameKey(item, key)) {
1551
+ item.value = [...item.value, ...value]
1552
+ }
1553
+ return item
1554
+ })
1555
+ }
1556
+ static foundByKey(arr = [], key) {
1557
+ const found = arr.find((m) => {
1558
+ return this.sameKey(m, key)
1559
+ })
1560
+ return found || null
1561
+ }
1562
+ static foundValueByKey(arr = [], key) {
1563
+ const found = this.foundByKey(arr, key)
1564
+ return found ? found.value : null
1565
+ }
1566
+ static fromObject(options = {}) {
1567
+ return Object.keys(options).reduce((acc, key) => {
1568
+ acc.push(this.init({ key, value: options[key] }))
1569
+ return acc
1570
+ }, [])
1571
+ }
1572
+ static getValueByKey(arr = [], key) {
1573
+ return this.foundValueByKey(arr, key)
1574
+ }
1575
+ static getValueByKeyFromArray(arr = [], key) {
1576
+ if (arr.length === 0) {
1577
+ return null
1578
+ }
1579
+ const firstArr = arr.shift()
1580
+ const found = firstArr.find((i) => {
1581
+ return this.sameKey(i, key)
1582
+ })
1583
+ if (found && found.value) {
1584
+ return found.value
1585
+ }
1586
+ return this.getValueByKeyFromArray(arr, key)
1587
+ }
1588
+ static getValuesByKey(arr = [], key) {
1589
+ return arr.reduce((acc, item) => {
1590
+ if (this.sameKey(item, key)) {
1591
+ acc.push(item.value)
1592
+ }
1593
+ return acc
1594
+ }, [])
1595
+ }
1596
+ static hasKeyValue(arr = [], key, value) {
1597
+ if (typeof value === 'undefined') {
1598
+ return arr.filter((item) => this.sameKey(item, key)).length > 0
1599
+ }
1600
+ return arr.filter((item) => (this.sameKey(item, key) && _isSame(item.value, value))).length > 0
1601
+ }
1602
+ static insertOrUpdateRecord(arr = [], key, value) {
1603
+ let copy = [...arr]
1604
+ if (!this.hasKeyValue(arr, key)) {
1605
+ copy.push(this.init({ key, value }))
1606
+ } else {
1607
+ copy = this.updateRecord(arr, key, value)
1608
+ }
1609
+ return copy
1610
+ }
1611
+ static keys(arr = []) {
1612
+ if (Array.isArray(arr)) {
1613
+ return arr.reduce((acc, item) => {
1614
+ acc.push(item.key)
1615
+ return acc
1616
+ }, [])
1617
+ }
1618
+ return []
1619
+ }
1620
+ static merge(toArr, fromArr) {
1621
+ (fromArr || []).map((from) => {
1622
+ const found = toArr.find((to) => {
1623
+ return to.key === from.key
1624
+ })
1625
+ if (found) {
1626
+ found.value = (found.value || []).concat(from.value)
1627
+ } else {
1628
+ toArr.push(from)
1629
+ }
1630
+ })
1631
+ return toArr
1632
+ }
1633
+ static removeByKey(arr, key) {
1634
+ return arr.reduce((acc, item) => {
1635
+ if (!this.sameKey(item, key)) {
1636
+ acc.push(item)
1637
+ }
1638
+ return acc
1639
+ }, [])
1640
+ }
1641
+ static sameKey(item, key) {
1642
+ return _isSame(item.key, key)
1643
+ }
1644
+ static toObject(arr = []) {
1645
+ if (Array.isArray(arr)) {
1646
+ return arr.reduce((acc, item) => {
1647
+ acc[item.key] = item.value
1648
+ return acc
1649
+ }, {})
1650
+ }
1651
+ return {}
1652
+ }
1653
+ static toString(arr = [], delimiter = '; ') {
1654
+ if (Array.isArray(arr)) {
1655
+ return arr.reduce((acc, item) => {
1656
+ acc.push(`${item.key}: ${item.value}`)
1657
+ return acc
1658
+ }, []).join(delimiter)
1659
+ }
1660
+ return ''
1661
+ }
1662
+ static updateRecord(arr = [], key, value) {
1663
+ return arr.map((item) => {
1664
+ if (this.sameKey(item, key)) {
1665
+ return {
1666
+ ...item,
1667
+ value
1668
+ }
1669
+ }
1670
+ return item
1671
+ })
1672
+ }
1673
+ static updateOrInsertRecord(arr = [], key, value) {
1674
+ return this.insertOrUpdateRecord(arr, key, value)
1675
+ }
1676
+ static updateRecordsFromArray(arr = [], updateArr = []) {
1677
+ if (Array.isArray(arr) && Array.isArray(updateArr)) {
1678
+ const obj1 = this.toObject(arr)
1679
+ const obj2 = this.toObject(updateArr)
1680
+ return this.fromObject({
1681
+ ...obj1,
1682
+ ...obj2
1683
+ })
1684
+ }
1685
+ return []
1686
+ }
1687
+ static values(arr = []) {
1688
+ if (Array.isArray(arr)) {
1689
+ return arr.reduce((acc, item) => {
1690
+ acc.push(item.value)
1691
+ return acc
1692
+ }, [])
1693
+ }
1694
+ return []
1695
+ }
1696
+
1697
+ // getters
1698
+ get isValid() {
1699
+ return !!this.key
1700
+ }
1701
+
1702
+ get toObject() {
1703
+ const obj = {}
1704
+ if (this.isValid) {
1705
+ obj[this.key] = this.value
1706
+ }
1707
+ return obj
1708
+ }
1709
+ }
1710
+
1711
+ function _isSame(key1, key2) {
1712
+ return key1 === key2
1713
+ }
1714
+
1715
+
1716
+
1717
+ ;// ./lib/models/keyValueObject/index.js
1718
+
1719
+
1720
+
1721
+
1722
+ ;// ./lib/helpers/stringFormatter/stringFormatter.js
1723
+ function stringFormatter(str, delimiter = '_') {
1724
+ if (str === null || typeof str === 'undefined' || typeof str.toString === 'undefined') {
1725
+ return null
1726
+ }
1727
+ return str.toString()
1728
+ .trim()
1729
+ .toUpperCase()
1730
+ .replace('-', delimiter)
1731
+ .replace(' ', delimiter)
1732
+ }
1733
+
1734
+
1735
+
1736
+ ;// ./lib/models/metadata/metadata.js
1737
+
1738
+
1739
+
1740
+ const DELIMITER = '_'
1741
+
1742
+ class Metadata extends KeyValueObject {
1743
+ static init(options = {}) {
1744
+ if (options instanceof this) {
1745
+ return options
1746
+ }
1747
+ const instance = new this({
1748
+ ...options,
1749
+ key: stringFormatter(options.key, DELIMITER),
1750
+ })
1751
+ return instance.isValid ? instance : null
1752
+ }
1753
+ static get _classname() {
1754
+ return 'Metadata'
1755
+ }
1756
+
1757
+ static merge(toArr, fromArr) {
1758
+ (fromArr || []).map((from) => {
1759
+ const found = toArr.find((to) => {
1760
+ return metadata_isSame(to.key, from.key)
1761
+ })
1762
+ if (found) {
1763
+ found.value = (found.value || []).concat(from.value)
1764
+ } else {
1765
+ toArr.push(from)
1766
+ }
1767
+ })
1768
+ return toArr
1769
+ }
1770
+ static sameKey(item, key) {
1771
+ return metadata_isSame(item.key, key)
1772
+ }
1773
+ }
1774
+
1775
+ function metadata_isSame(key1, key2) {
1776
+ return stringFormatter(key1, DELIMITER) === stringFormatter(key2, DELIMITER)
1777
+ }
1778
+
1779
+
1780
+
1781
+ ;// ./lib/models/metadata/index.js
1782
+
1783
+
1784
+
1785
+
1786
+ ;// ./lib/models/qMeta/qMeta.js
1787
+
1788
+
1789
+ const updateAllowedProps = [
1790
+ 'attributes',
1791
+ 'ref'
1792
+ ]
1793
+
1794
+ class QMeta {
1795
+ constructor(options = {}) {
1796
+ options = options || {}
1797
+ this.attributes = KeyValueObject.initOnlyValidFromArray(options.attributes)
1798
+ this.ref = options.ref || {}
1799
+ }
1800
+
1801
+ static get _classname() {
1802
+ return 'QMeta'
1803
+ }
1804
+ static get _superclass() {
1805
+ return 'QMeta'
1806
+ }
1807
+
1808
+ // Class methods
1809
+ static init(options = {}) {
1810
+ if (options instanceof QMeta) {
1811
+ return options
1812
+ }
1813
+ return new QMeta(options)
1814
+ }
1815
+
1816
+ // instance methods
1817
+ addAttribute(obj) {
1818
+ const kvObject = KeyValueObject.init(obj)
1819
+ if (!kvObject) {
1820
+ throw new Error('invalid meta attribute')
1821
+ }
1822
+ this.attributes.push(kvObject)
1823
+ return this
1824
+ }
1825
+
1826
+ update(obj) {
1827
+ Object.keys(obj).forEach((key) => {
1828
+ if (updateAllowedProps.includes(key)) {
1829
+ if (key === 'attributes') {
1830
+ this[key] = KeyValueObject.initOnlyValidFromArray(obj[key])
1831
+ } else {
1832
+ this[key] = obj[key]
1833
+ }
1834
+ }
1835
+ })
1836
+ return this
1837
+ }
1838
+ }
1839
+
1840
+
1841
+
1842
+ ;// ./lib/models/qMeta/index.js
1843
+
1844
+
1845
+
1846
+
1847
+ ;// ./lib/models/repo/repo.js
1848
+ class Repo {
1849
+ constructor(options) {
1850
+ options = options || {}
1851
+ this.model = options.model
1852
+ this._sharedOptions = options._sharedOptions // { session: this.dbTransaction }
1853
+ this._queryOptions = options._queryOptions
1854
+ this._saveOptions = options._saveOptions
1855
+ this._Class = options._constructor && options._constructor._Class
1856
+ ? options._constructor._Class
1857
+ : null
1858
+ }
1859
+ static init(options = {}) {
1860
+ if (options instanceof this) {
1861
+ return options
1862
+ }
1863
+ const instance = new this(options)
1864
+ return instance.isValid ? instance : null
1865
+ }
1866
+ static get _classname() {
1867
+ return 'Repo'
1868
+ }
1869
+ static get _superclass() {
1870
+ return 'Repo'
1871
+ }
1872
+
1873
+ get _classname() {
1874
+ return 'Repo'
1875
+ }
1876
+
1877
+ get _superclass() {
1878
+ return 'Repo'
1879
+ }
1880
+
1881
+ get isValid() {
1882
+ return this.model
1883
+ && (typeof this.model.deleteOne === 'function')
1884
+ && (typeof this.model.findAll === 'function')
1885
+ && (typeof this.model.saveOne === 'function')
1886
+ }
1887
+
1888
+ get queryOptions() {
1889
+ return {
1890
+ ...this._sharedOptions,
1891
+ ...this._queryOptions,
1892
+ }
1893
+ }
1894
+
1895
+ get saveOptions() {
1896
+ return {
1897
+ ...this._sharedOptions,
1898
+ ...this._saveOptions,
1899
+ }
1900
+ }
1901
+
1902
+ init(options) {
1903
+ if (this._Class && typeof this._Class.init === 'function') {
1904
+ return this._Class.init(options)
1905
+ }
1906
+ return options
1907
+ }
1908
+
1909
+ async deleteOne({ id }) {
1910
+ try {
1911
+ const result = await this.model.deleteOne({ _id: id })
1912
+ return {
1913
+ ...result, // { message: 'ok', total }
1914
+ isNew: false,
1915
+ data: []
1916
+ }
1917
+ } catch (err) {
1918
+ throw err
1919
+ }
1920
+ }
1921
+
1922
+ // systemLog is optional
1923
+ findAll({ query, systemLog }) {
1924
+ const log = _makeLog({
1925
+ systemLog,
1926
+ label: 'REPO_READ',
1927
+ message: `fn ${this._classname}.prototype.findAll`,
1928
+ input: [{ query: { ...query }, systemLog: { ...systemLog } }]
1929
+ })
1930
+ return new Promise((resolve, reject) => {
1931
+ this.model.findAll(query, this.queryOptions, (err, data, total) => {
1932
+ if (err) {
1933
+ log({ level: 'warn', output: err.toString() })
1934
+ reject(err)
1935
+ } else {
1936
+ const result = {
1937
+ isNew: false,
1938
+ data,
1939
+ total: total || data.length
1940
+ }
1941
+ log({ level: 'info', output: { ...result } })
1942
+ resolve(result)
1943
+ }
1944
+ })
1945
+ })
1946
+ }
1947
+
1948
+ findOne({ query, systemLog }) {
1949
+ const log = _makeLog({
1950
+ systemLog,
1951
+ label: 'REPO_READ',
1952
+ message: `fn ${this._classname}.prototype.findOne`,
1953
+ input: [{ query: { ...query }, systemLog: { ...systemLog } }]
1954
+ })
1955
+ return new Promise((resolve, reject) => {
1956
+ this.model.findAll(query, this.queryOptions, (err, data) => {
1957
+ if (err) {
1958
+ reject(err)
1959
+ } else if (data.length === 1) {
1960
+ const result = {
1961
+ isNew: false,
1962
+ data,
1963
+ total: 1
1964
+ }
1965
+ log({ level: 'info', output: { ...result } })
1966
+ resolve(result)
1967
+ } else if (data.length === 0) {
1968
+ reject(new Error('record not found'))
1969
+ } else {
1970
+ reject(new Error('more than one is found'))
1971
+ }
1972
+ })
1973
+ })
1974
+ .catch((err) => {
1975
+ log({ level: 'warn', output: err.toString() })
1976
+ throw err
1977
+ })
1978
+ }
1979
+
1980
+ saveAll({ docs, systemLog }) {
1981
+ let isNew
1982
+ const log = _makeLog({
1983
+ systemLog,
1984
+ label: 'REPO_WRITE',
1985
+ message: `fn ${this._classname}.prototype.saveAll`,
1986
+ input: [{ docs: [...docs], systemLog: { ...systemLog } }]
1987
+ })
1988
+ const promise = typeof this.model.saveAll === 'function'
1989
+ ? this.model.saveAll({ docs })
1990
+ : Promise.all(docs.map(async (doc) => {
1991
+ if (doc) {
1992
+ const result = await this.saveOne({ doc })
1993
+ isNew = result.isNew
1994
+ const _data = result._data || result.data
1995
+ return _data[0]
1996
+ }
1997
+ return null
1998
+ }))
1999
+ return promise.then((savedData) => {
2000
+ if (savedData.length !== 1) isNew = null
2001
+ const result = {
2002
+ data: savedData,
2003
+ isNew,
2004
+ total: savedData.length
2005
+ }
2006
+ log({ level: 'info', output: { ...result } })
2007
+ return result
2008
+ }).catch((err) => {
2009
+ log({ level: 'warn', output: err.toString() })
2010
+ throw err
2011
+ })
2012
+ }
2013
+
2014
+ saveOne({ doc, systemLog }) {
2015
+ const log = _makeLog({
2016
+ systemLog,
2017
+ label: 'REPO_WRITE',
2018
+ message: `fn ${this._classname}.prototype.saveOne`,
2019
+ input: [{ doc: { ...doc }, systemLog: { ...systemLog } }]
2020
+ })
2021
+ return new Promise((resolve, reject) => {
2022
+ this.model.saveOne(doc, this.saveOptions, (err, result) => {
2023
+ if (err) {
2024
+ log({ level: 'warn', output: err.toString() })
2025
+ reject(err)
2026
+ } else {
2027
+ log({ level: 'info', output: { ...result } })
2028
+ resolve(result)
2029
+ }
2030
+ })
2031
+ })
2032
+ }
2033
+ }
2034
+
2035
+ function _makeLog({ systemLog, label, message: message1, input } = {}) {
2036
+ return ({ level, messgae: massage2, output } = {}) => {
2037
+ if (systemLog && systemLog.systemLogHelper) {
2038
+ systemLog.systemLogHelper.log({
2039
+ batchId: systemLog.batchId,
2040
+ label,
2041
+ level,
2042
+ message: massage2 || message1,
2043
+ data: {
2044
+ payload: {
2045
+ input,
2046
+ output
2047
+ }
2048
+ }
2049
+ })
2050
+ }
2051
+ }
2052
+ }
2053
+
2054
+
2055
+
2056
+ ;// ./lib/models/repo/index.js
2057
+
2058
+
2059
+
2060
+
2061
+ ;// ./lib/models/service/service.js
2062
+
2063
+
2064
+
2065
+ class Service {
2066
+ constructor({ repo }) {
2067
+ this.repo = repo
2068
+ }
2069
+
2070
+ static get _classname() {
2071
+ return 'Service'
2072
+ }
2073
+ static get _superclass() {
2074
+ return 'Service'
2075
+ }
2076
+
2077
+ deleteOne({ id }) {
2078
+ return this.repo.deleteOne({ id })
2079
+ .catch(() => {
2080
+ throw new Error(`Not found for query: ${id}`)
2081
+ })
2082
+ }
2083
+
2084
+ async findAll({ query = {}, systemLog } = {}) {
2085
+ const result = await this.repo.findAll({ query, systemLog })
2086
+ return makeApiResponse({
2087
+ repo: this.repo,
2088
+ result
2089
+ })
2090
+ }
2091
+
2092
+ async findOne({ query = {}, systemLog } = {}) {
2093
+ const result = await this.repo.findOne({ query, systemLog })
2094
+ return makeApiResponse({
2095
+ repo: this.repo,
2096
+ result
2097
+ })
2098
+ }
2099
+
2100
+ init(options) {
2101
+ return this.repo.init(options)
2102
+ }
2103
+ initFromArray(arr = []) {
2104
+ if (Array.isArray(arr)) {
2105
+ return arr.map((a) => this.init(a))
2106
+ }
2107
+ return []
2108
+ }
2109
+ initOnlyValidFromArray(arr = []) {
2110
+ return this.initFromArray(arr).filter((i) => i)
2111
+ }
2112
+
2113
+ async saveAll({ docs = [], systemLog } = {}) {
2114
+ const copies = docs.map((doc) => {
2115
+ return this.init(doc)
2116
+ })
2117
+ const result = await this.repo.saveAll({ docs: copies, systemLog })
2118
+ return makeApiResponse({
2119
+ repo: this.repo,
2120
+ result
2121
+ })
2122
+ }
2123
+
2124
+ async saveOne({ doc = {}, systemLog } = {}) {
2125
+ const copy = this.init(doc)
2126
+ if (copy) {
2127
+ const result = await this.repo.saveOne({ doc: copy, systemLog })
2128
+ return makeApiResponse({
2129
+ repo: this.repo,
2130
+ result
2131
+ })
2132
+ }
2133
+ return {
2134
+ isNew: null,
2135
+ data: [],
2136
+ err: new Error('doc is not a valid instance')
2137
+ }
2138
+ }
2139
+ }
2140
+
2141
+ function makeService({ repo }) {
2142
+ if (repo === undefined) {
2143
+ throw new Error('repo is required.')
2144
+ }
2145
+ if (repo._superclass !== Repo._superclass) {
2146
+ throw new Error('repo is not an instance of Repo.')
2147
+ }
2148
+ return new Service({ repo })
2149
+ }
2150
+
2151
+
2152
+
2153
+ ;// ./lib/models/service/index.js
2154
+
2155
+
2156
+
2157
+
2158
+ ;// ./lib/models/uniqueKeyGenerator/uniqueKeyGenerator.js
2159
+
2160
+
2161
+ class UniqueKeyGenerator {
2162
+ static get _classname() {
2163
+ return 'UniqueKeyGenerator'
2164
+ }
2165
+ static get _superclass() {
2166
+ return 'UniqueKeyGenerator'
2167
+ }
2168
+ static makeFormatter({ fieldName, format, options }) {
2169
+ switch (format) {
2170
+ case 'set_code':
2171
+ return _makeSetCode(fieldName, options)
2172
+ default:
2173
+ return _makeSetCode(fieldName, options)
2174
+ }
2175
+ }
2176
+ static makeGenerator(arr) {
2177
+ const fns = arr.map((item) => this.makeFormatter(item))
2178
+ return async (obj) => {
2179
+ const output = await pReduce(fns, async (acc, fn) => {
2180
+ const _obj = await fn(obj)
2181
+ return Object.assign(acc, _obj)
2182
+ }, obj)
2183
+ return output
2184
+ }
2185
+ }
2186
+ }
2187
+
2188
+ function _makeSetCode(fieldName, options) {
2189
+ return async (obj = {}) => {
2190
+ if (obj[fieldName]) {
2191
+ return {}
2192
+ }
2193
+ return {
2194
+ [fieldName]: stringHelper.setCode()
2195
+ }
2196
+ }
2197
+ }
2198
+
2199
+
2200
+
2201
+ ;// ./lib/models/uniqueKeyGenerator/index.js
2202
+
2203
+
2204
+
2205
+
2206
+ ;// ./lib/models/index.js
2207
+
2208
+
2209
+
2210
+
2211
+
2212
+
2213
+
2214
+
2215
+
2216
+ ;// ./lib/helpers/generalPost/generalPost.js
2217
+
2218
+
2219
+
2220
+
2221
+ async function generalPost({ body = {}, GeneralModel, UniqueKeyGenerator, resourceInfo }) {
2222
+ const { resources, data, globalShared = {}, shared = {}, relationship = {} } = body
2223
+ const _resourceInfo = resourceInfo || body.resourceInfo
2224
+ _attachShared(data, globalShared, shared)
2225
+ const obj = await pReduce(resources, async (acc, resource) => {
2226
+ const service = _makeService(resource, _resourceInfo, UniqueKeyGenerator, GeneralModel)
2227
+ _createRelationship(data, relationship[resource], acc)
2228
+ const _data = data[resource]
2229
+ const result = await service.saveAll({ docs: [].concat(_data) })
2230
+ acc[resource] = Array.isArray(_data) ? result._data : result._data[0]
2231
+ return acc
2232
+ }, {})
2233
+ return obj
2234
+ }
2235
+
2236
+ function _attachShared(data, globalShared = {}, shared = {}) {
2237
+ Object.keys(shared).forEach((key) => {
2238
+ const _data = data[key]
2239
+ data[key] = objectHelper.merge({}, _data, globalShared, shared[key] || {})
2240
+ })
2241
+ }
2242
+
2243
+ function _createRelationship(data, relationship = {}, object) {
2244
+ Object.keys(relationship).forEach((key) => {
2245
+ const path = relationship[key]
2246
+ const val = objectHelper.get(object, path)
2247
+ objectHelper.set(data, key, val)
2248
+ })
2249
+ }
2250
+
2251
+ function _makeService(resource, resourceInfo, UniqueKeyGenerator, GeneralModel) {
2252
+ const { collectionName, fields } = resourceInfo[resource]
2253
+ const uniqueKeyGenerator = UniqueKeyGenerator.makeGenerator(fields)
2254
+ const model = new GeneralModel({ collectionName, uniqueKeyGenerator })
2255
+ return makeService({
2256
+ repo: new Repo({ model })
2257
+ })
2258
+ }
2259
+
2260
+
2261
+
2262
+ ;// ./lib/helpers/generalPost/index.js
2263
+
2264
+
2265
+
2266
+
2267
+ ;// ./lib/helpers/padZeros/padZeros.js
2268
+ function padZeros(num, minLength = 6) {
2269
+ num = num.toString()
2270
+ if (num.length < minLength) {
2271
+ return padZeros('0' + num, minLength)
2272
+ }
2273
+ return num
2274
+ }
2275
+
2276
+
2277
+
2278
+ ;// ./lib/helpers/padZeros/index.js
2279
+
2280
+
2281
+
2282
+
2283
+ ;// ./lib/helpers/pReduce/index.js
2284
+
2285
+
2286
+
2287
+
2288
+ ;// ./lib/helpers/stringFormatter/index.js
2289
+
2290
+
2291
+
2292
+
2293
+ ;// ./lib/helpers/stringHelper/stringHelper.js
2294
+ function baseXEncode(num, base = 34) {
2295
+ const charset = getBaseCharset(base)
2296
+ return encode(num, charset)
2297
+ }
2298
+
2299
+ function encode(int, charset) {
2300
+ let byCode = charset.byCode;
2301
+ if (int === 0) {
2302
+ return byCode[0];
2303
+ }
2304
+
2305
+ var res = "",
2306
+ max = charset.length;
2307
+ while (int > 0) {
2308
+ res = byCode[int % max] + res;
2309
+ int = Math.floor(int / max);
2310
+ }
2311
+ return res;
2312
+ }
2313
+
2314
+ function getBaseCharset(base) {
2315
+ let charset = '9876543210ABCDEFGHJKLMNPQRSTUVWXYZ'
2316
+ if (base === 58) {
2317
+ charset = '9876543210ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz'
2318
+ }
2319
+ return indexCharset(charset)
2320
+ }
2321
+
2322
+ function indexCharset(str) {
2323
+ var byCode = {},
2324
+ byChar = {},
2325
+ length = str.length,
2326
+ i, char;
2327
+ for (i = 0; i < length; i++) {
2328
+ char = str[i];
2329
+ byCode[i] = char;
2330
+ byChar[char] = i;
2331
+ }
2332
+ return { byCode: byCode, byChar: byChar, length: length };
2333
+ }
2334
+
2335
+ function randomString({ len = 16, pattern = 'a1' } = {}) {
2336
+ const A = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
2337
+ const a = 'abcdefghijklmnopqrstuvwxyz'
2338
+ const num = '1234567890'
2339
+ const mark = '~!@#$%^&*_+-='
2340
+ let str = ''
2341
+ if (pattern.includes('A')) {
2342
+ str += A
2343
+ }
2344
+ if (pattern.includes('a')) {
2345
+ str += a
2346
+ }
2347
+ if (pattern.includes('1')) {
2348
+ str += num
2349
+ }
2350
+ if (pattern.includes('#')) {
2351
+ str += mark
2352
+ }
2353
+ const chars = [...str]
2354
+ return [...Array(len)].map(i => {
2355
+ return chars[(Math.random() * chars.length) | 0]
2356
+ }).join``
2357
+ }
2358
+
2359
+ function reverse(str) {
2360
+ if (typeof str !== 'string') {
2361
+ str = str.toString()
2362
+ }
2363
+ const splitString = str.split('')
2364
+ const reverseArray = splitString.reverse()
2365
+ return reverseArray.join('')
2366
+ }
2367
+
2368
+ function setCode(base = 34) {
2369
+ const now = (new Date()).valueOf()
2370
+ const random = randomString({
2371
+ len: 8,
2372
+ pattern: '1'
2373
+ })
2374
+ const str = reverse(`${now}${random}`)
2375
+ // const str = `${now}${random}`
2376
+ return baseXEncode(str, base)
2377
+ }
2378
+
2379
+ const stringHelper = {
2380
+ setCode
2381
+ }
2382
+
2383
+
2384
+ ;// ./lib/helpers/stringHelper/index.js
2385
+
2386
+
2387
+
2388
+
2389
+
2390
+ ;// ./lib/helpers/index.js
2391
+
2392
+
2393
+
2394
+
2395
+
2396
+
2397
+
2398
+
2399
+
2400
+
2401
+
2402
+
2403
+ ;// ./lib/index.js
2404
+
2405
+
2406
+
2407
+ ;// ./index.js
2408
+
2409
+
2410
+ /******/ return __webpack_exports__;
2411
+ /******/ })()
2412
+ ;
2413
+ });