@questwork/q-utilities 0.1.12 → 0.1.13

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