@questwork/q-utilities 0.1.1 → 0.1.2

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,1140 @@
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
+ lc: () => (/* reexport */ Repo),
31
+ kl: () => (/* reexport */ Service),
32
+ l0: () => (/* reexport */ convertString),
33
+ Yq: () => (/* reexport */ formatDate),
34
+ G8: () => (/* reexport */ getValidation),
35
+ pY: () => (/* reexport */ getValueByKeys),
36
+ Q_: () => (/* reexport */ jwtHelper),
37
+ su: () => (/* reexport */ makeApiResponse),
38
+ Q6: () => (/* reexport */ makeService),
39
+ Lv: () => (/* reexport */ padZeros),
40
+ Qy: () => (/* reexport */ stringFormatter)
41
+ });
42
+
43
+ ;// ./lib/helpers/convertString/convertString.js
44
+ function convertString(string, patternMatch = /\$\{(.+?)\}/g, value, getValueByKeys) {
45
+ if (!string || typeof getValueByKeys !== 'function') {
46
+ return ''
47
+ }
48
+ const reg = new RegExp(patternMatch, 'g')
49
+ return string.replace(reg, (match, key) => {
50
+ const result = getValueByKeys({ keys: key.split('.'), obj: value })
51
+ if (result === null || result === undefined) {
52
+ return ''
53
+ }
54
+ return typeof result === 'object' ? JSON.stringify(result) : result
55
+ })
56
+ }
57
+
58
+ /* harmony default export */ const convertString_convertString = ({
59
+ convertString
60
+ });
61
+
62
+
63
+ ;// ./lib/helpers/convertString/index.js
64
+
65
+
66
+ ;// ./lib/helpers/formatDate/formatDate.js
67
+
68
+ function formatDate(date, format) {
69
+ const _date = date && date instanceof Date ? date : new Date(date)
70
+ const dayMapChi = ['日','一','二','三','四','五','六']
71
+ const dayMapEng = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday']
72
+ const dayMapEngShort = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat']
73
+ const _format = format || 'YYYY/MM/DD hh:mm'
74
+ const e = _date.getDay()
75
+ const ee = dayMapEngShort[e]
76
+ const eee = dayMapChi[e]
77
+ const eeee = dayMapEng[e]
78
+ const y = _date.getFullYear()
79
+ const m = _date.getMonth() + 1
80
+ const d = _date.getDate()
81
+ const h = _date.getHours()
82
+ const mm = _date.getMinutes()
83
+ const s = _date.getSeconds()
84
+
85
+ return _format.replace('YYYY', y)
86
+ .replace('MM', padding(m))
87
+ .replace('MM', padding(m))
88
+ .replace('DD', padding(d))
89
+ .replace('hh', padding(h))
90
+ .replace('mm', padding(mm))
91
+ .replace('ss', padding(s))
92
+ .replace('M', m)
93
+ .replace('D', d)
94
+ .replace('h', h)
95
+ .replace('m', mm)
96
+ .replace('s', s)
97
+ .replace('EEEE', padding(eeee))
98
+ .replace('EEE', padding(eee))
99
+ .replace('EE', padding(ee))
100
+ .replace('E', padding(e))
101
+ }
102
+
103
+ function padding(m) {
104
+ return m < 10 ? `0${m}` : m
105
+ }
106
+
107
+
108
+ /* harmony default export */ const formatDate_formatDate = ({
109
+ formatDate
110
+ });
111
+
112
+
113
+
114
+ ;// ./lib/helpers/formatDate/index.js
115
+
116
+
117
+ ;// ./lib/helpers/getValidation/getValidation.js
118
+ function getValidation(rule, data, getDataByKey, KeyValueObject) {
119
+ if (!rule) {
120
+ return true
121
+ }
122
+ if (typeof getDataByKey !== 'function' || typeof KeyValueObject !== 'function') {
123
+ return false
124
+ }
125
+ const { key = '', value, keyValuePath = '' } = rule
126
+ const [valueAttribute] = Object.keys(value)
127
+
128
+ if (!key) {
129
+ switch (valueAttribute) {
130
+ case '$and': {
131
+ return value['$and'].reduce((acc, item) => (acc && getValidation(item, data, getDataByKey, KeyValueObject)), true)
132
+ }
133
+ case '$or': {
134
+ return value['$or'].reduce((acc, item) => (acc || getValidation(item, data, getDataByKey, KeyValueObject)), false)
135
+ }
136
+ default:
137
+ return false
138
+ }
139
+ }
140
+
141
+ let rowValue = getDataByKey(key, data)
142
+
143
+ // debugger
144
+
145
+ // if KeyValue object
146
+ if (keyValuePath) {
147
+ console.log('keyValuePath', keyValuePath)
148
+ const rowValueData = KeyValueObject.toObject(rowValue)
149
+ rowValue = getDataByKey(keyValuePath, rowValueData)
150
+ }
151
+
152
+ switch (valueAttribute) {
153
+ case '$empty': {
154
+ const isEmpty = rowValue === null || rowValue === undefined
155
+ return isEmpty === value['$empty']
156
+ }
157
+ case '$eq': {
158
+ return rowValue === value['$eq']
159
+ }
160
+ case '$gt': {
161
+ return rowValue > value['$gt']
162
+ }
163
+ case '$gte': {
164
+ return rowValue >= value['$gte']
165
+ }
166
+ case '$lt': {
167
+ return rowValue < value['$lt']
168
+ }
169
+ case '$lte': {
170
+ return rowValue <= value['$lte']
171
+ }
172
+ case '$in': {
173
+ if (Array.isArray(rowValue)) {
174
+ return !!rowValue.find((e) => (value['$in'].includes(e)))
175
+ }
176
+ if (typeof rowValue !== 'object') {
177
+ return !!value['$in'].includes(rowValue)
178
+ }
179
+ return false
180
+ }
181
+ case '$inValue': {
182
+ const result = getDataByKey(value['$inValue'], data)
183
+ const _value = Array.isArray(result) ? result : []
184
+ if (Array.isArray(rowValue)) {
185
+ return !!rowValue.find((e) => (_value.includes(e)))
186
+ }
187
+ if (typeof rowValue === 'string') {
188
+ return !!_value.includes(rowValue)
189
+ }
190
+ return false
191
+ }
192
+ case '$ne': {
193
+ return rowValue !== value['$ne']
194
+ }
195
+ case '$notIn': {
196
+ if (Array.isArray(rowValue)) {
197
+ return !rowValue.find((e) => (value['$notIn'].includes(e)))
198
+ }
199
+ if (typeof rowValue !== 'object') {
200
+ return !value['$notIn'].includes(rowValue)
201
+ }
202
+ return false
203
+ }
204
+ case '$notInValue': {
205
+ const result = getDataByKey(value['$notInValue'], data)
206
+ const _value = Array.isArray(result) ? result : []
207
+ if (Array.isArray(rowValue)) {
208
+ return !rowValue.find((e) => (_value.includes(e)))
209
+ }
210
+ if (typeof rowValue !== 'object') {
211
+ return !_value.includes(rowValue)
212
+ }
213
+ return false
214
+ }
215
+ case '$range': {
216
+ const [min, max] = value['$range']
217
+ if (typeof min === 'number' && typeof max === 'number' && rowValue >= min && rowValue <= max) {
218
+ return true
219
+ }
220
+ return false
221
+ }
222
+ default:
223
+ return false
224
+ }
225
+ }
226
+
227
+ /* harmony default export */ const getValidation_getValidation = ({
228
+ getValidation
229
+ });
230
+
231
+
232
+ ;// ./lib/helpers/getValidation/index.js
233
+
234
+
235
+ ;// ./lib/helpers/getValueByKeys/getValueByKeys.js
236
+ // keys can be array or string
237
+ function getValueByKeys(keys, data) {
238
+ let _keys = keys
239
+ let _data = data
240
+ if (!Array.isArray(keys)) {
241
+ const { keys: keyArr, obj } = keys
242
+ _keys = keyArr
243
+ _data = obj
244
+ }
245
+ if (_keys.length === 0) {
246
+ return _data
247
+ }
248
+ const firstKey = _keys.shift()
249
+ if (_data && Object.prototype.hasOwnProperty.call(_data, firstKey)) {
250
+ return getValueByKeys(_keys, _data[firstKey])
251
+ }
252
+ if (_data && firstKey) {
253
+ return _data[firstKey]
254
+ }
255
+ return _data
256
+
257
+ }
258
+ /* harmony default export */ const getValueByKeys_getValueByKeys = ({
259
+ getValueByKeys
260
+ });
261
+
262
+
263
+
264
+ ;// ./lib/helpers/getValueByKeys/index.js
265
+
266
+
267
+ ;// ./lib/helpers/jwtHelper/jwtHelper.js
268
+ // 'use strict'
269
+
270
+ /* eslint-disable new-cap */
271
+ /* eslint-disable camelcase */
272
+ /* eslint-disable no-mixed-operators */
273
+ /* eslint-disable no-useless-escape */
274
+ /* eslint-disable no-param-reassign */
275
+
276
+ /* eslint func-names: 0 */
277
+
278
+ // const Buffer = require('buffer/').Buffer
279
+
280
+ const EXPIRY = 3600 // in second
281
+ const ALGORITHM = 'HS256'
282
+ const SECRET = 'ab1234cd'
283
+
284
+ const _hasBuffer = typeof Buffer === 'function'
285
+
286
+ const jwtHelper = {
287
+ create(obj, { secret, algorithm, expiry } = {}) {
288
+ const sAlgorithm = algorithm || ALGORITHM
289
+ const sSecret = secret || SECRET
290
+ const exp = expiry || getTimeInSecond() + EXPIRY
291
+ const payload = {
292
+ ...obj,
293
+ exp
294
+ }
295
+ return encode(payload, sSecret, sAlgorithm)
296
+ },
297
+ createByUser(loginAccount) {
298
+ const exp = getTimeInSecond() + EXPIRY
299
+ const payload = {
300
+ loginAccount,
301
+ exp
302
+ }
303
+ return this.encode(payload)
304
+ },
305
+ encode(payload, algorithm) {
306
+ return encode(payload, SECRET, algorithm)
307
+ },
308
+ decode(token, algorithm) {
309
+ const noVerify = !this.verify(token)
310
+ return decode(token, SECRET, noVerify, algorithm) // if noVerify = true, may skip verification
311
+ },
312
+ getPayload(token) {
313
+ const payload = getPayload(token)
314
+ return {
315
+ payload
316
+ }
317
+ },
318
+ getPayloadIdByKey(token, key) {
319
+ const payload = getPayload(token)
320
+ const id = payload[key] ? payload[key].id : null
321
+ return {
322
+ id,
323
+ jwtToken: token
324
+ }
325
+ },
326
+ resolve(token, secret, algorithm) {
327
+ const sSecret = secret || SECRET
328
+ return decode(token, sSecret, false, algorithm) // need verification
329
+ },
330
+ verify(token) {
331
+ const payload = getPayload(token)
332
+ const today = getTimeInSecond()
333
+ return (payload.exp && (today <= payload.exp)) || false
334
+ }
335
+ }
336
+
337
+ /**
338
+ * Private functions
339
+ */
340
+
341
+ const getPayload = (token) => decode(token, SECRET, true)
342
+
343
+ const getTimeInSecond = () => Math.floor(Date.now() / 1000)
344
+
345
+ /**
346
+ * Private functions, based on jwt-simple 0.2.0
347
+ */
348
+
349
+ const { cryptoHelper } = require('../cryptoHelper')
350
+
351
+ const algorithmMap = {
352
+ HS256: 'sha256',
353
+ HS384: 'sha384',
354
+ HS512: 'sha512',
355
+ RS256: 'RSA-SHA256'
356
+ }
357
+
358
+ const typeMap = {
359
+ HS256: 'hmac',
360
+ HS384: 'hmac',
361
+ HS512: 'hmac',
362
+ RS256: 'sign'
363
+ }
364
+
365
+
366
+ /**
367
+ * Decode jwt
368
+ *
369
+ * @param {Object} token
370
+ * @param {String} key
371
+ * @param {Boolean} noVerify
372
+ * @param {String} algorithm
373
+ * @return {Object} payload
374
+ * @api public
375
+ */
376
+ const decode = function jwt_decode(token, key, noVerify, algorithm) {
377
+ // check token
378
+ if (!token) {
379
+ throw new Error('No token supplied')
380
+ }
381
+ // check segments
382
+ const segments = token.split('.')
383
+ if (segments.length !== 3) {
384
+ throw new Error('Not enough or too many segments')
385
+ }
386
+
387
+ // All segment should be base64
388
+ const headerSeg = segments[0]
389
+ const payloadSeg = segments[1]
390
+ const signatureSeg = segments[2]
391
+
392
+ // base64 decode and parse JSON
393
+ const header = JSON.parse(base64urlDecode(headerSeg))
394
+
395
+ const payload = JSON.parse(base64urlDecode(payloadSeg))
396
+
397
+ if (!noVerify) {
398
+ const signingMethod = algorithmMap[algorithm || header.alg]
399
+ const signingType = typeMap[algorithm || header.alg]
400
+ if (!signingMethod || !signingType) {
401
+ throw new Error('Algorithm not supported')
402
+ }
403
+
404
+ // verify signature. `sign` will return base64 string.
405
+ const signingInput = [headerSeg, payloadSeg].join('.')
406
+ if (!verify(signingInput, key, signingMethod, signingType, signatureSeg)) {
407
+ throw new Error('Signature verification failed')
408
+ }
409
+ }
410
+
411
+ return payload
412
+ }
413
+
414
+
415
+ /**
416
+ * Encode jwt
417
+ *
418
+ * @param {Object} payload
419
+ * @param {String} key
420
+ * @param {String} algorithm
421
+ * @return {String} token
422
+ * @api public
423
+ */
424
+ const encode = function jwt_encode(payload, key, algorithm) {
425
+ // Check key
426
+ if (!key) {
427
+ throw new Error('Require key')
428
+ }
429
+
430
+ // Check algorithm, default is HS256
431
+ if (!algorithm) {
432
+ algorithm = ALGORITHM
433
+ }
434
+
435
+ const signingMethod = algorithmMap[algorithm]
436
+ const signingType = typeMap[algorithm]
437
+ if (!signingMethod || !signingType) {
438
+ throw new Error('Algorithm not supported')
439
+ }
440
+
441
+ // header, typ is fixed value.
442
+ const header = { typ: 'JWT', alg: algorithm }
443
+
444
+ // create segments, all segments should be base64 string
445
+ const segments = []
446
+ segments.push(base64urlEncode(JSON.stringify(header)))
447
+ segments.push(base64urlEncode(JSON.stringify(payload)))
448
+ segments.push(sign(segments.join('.'), key, signingMethod, signingType))
449
+
450
+ return segments.join('.')
451
+ }
452
+
453
+
454
+ /**
455
+ * private util functions
456
+ */
457
+
458
+ function verify(input, key, method, type, signature) {
459
+ if (type === 'hmac') {
460
+ return (signature === sign(input, key, method, type))
461
+ } else if (type === 'sign') {
462
+ try {
463
+ return cryptoHelper.createStringVerify({
464
+ algorithm: method,
465
+ data: input,
466
+ object: key,
467
+ signature: base64urlUnescape(signature),
468
+ signatureEncoding: 'base64'
469
+ })
470
+ } catch (error) {
471
+ throw new Error('createStringVerify failed')
472
+ }
473
+ }
474
+ throw new Error('Algorithm type not recognized')
475
+ }
476
+
477
+ function sign(input, key, method, type) {
478
+ let base64str
479
+ if (type === 'hmac') {
480
+ base64str = cryptoHelper.createStringHmac({
481
+ algorithm: method,
482
+ key,
483
+ data: input,
484
+ outputEncoding: 'base64'
485
+ })
486
+ } else if (type === 'sign') {
487
+ try {
488
+ base64str = cryptoHelper.createSignature({
489
+ algorithm: method,
490
+ data: input,
491
+ privateKey: key,
492
+ outputEncoding: 'base64'
493
+ })
494
+ } catch (error) {
495
+ throw new Error('createSignature failed')
496
+ }
497
+ } else {
498
+ throw new Error('Algorithm type not recognized')
499
+ }
500
+ return base64urlEscape(base64str)
501
+ }
502
+
503
+ function _decode(str) {
504
+ if (_hasBuffer) {
505
+ return Buffer.from(base64urlUnescape(str), 'base64').toString('utf8')
506
+ }
507
+ return atob(base64urlUnescape(str))
508
+ }
509
+
510
+ function _encode(str) {
511
+ if (_hasBuffer) {
512
+ return base64urlEscape(Buffer.from(str, 'utf8').toString('base64'))
513
+ }
514
+ return base64urlEscape(btoa(str))
515
+ }
516
+
517
+ function base64urlDecode(str) {
518
+ // fixed bug if decode string is incorrect
519
+ // return (new Buffer.from(base64urlUnescape(str), 'base64')).toString() || '{}'
520
+ return _decode(str)
521
+ }
522
+
523
+ function base64urlUnescape(str) {
524
+ str += new Array(5 - str.length % 4).join('=')
525
+ return str.replace(/\-/g, '+').replace(/_/g, '/')
526
+ }
527
+
528
+ function base64urlEncode(str) {
529
+ // return base64urlEscape(new Buffer.from((str)).toString('base64'))
530
+ return _encode(str)
531
+ }
532
+
533
+ function base64urlEscape(str) {
534
+ return str.replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '')
535
+ }
536
+
537
+
538
+
539
+ ;// ./lib/helpers/jwtHelper/index.js
540
+
541
+
542
+
543
+
544
+
545
+ ;// ./lib/helpers/padZeros/padZeros.js
546
+ function padZeros(num, minLength = 6) {
547
+ num = num.toString()
548
+ if (num.length < minLength) {
549
+ return padZeros('0' + num, minLength)
550
+ }
551
+ return num
552
+ }
553
+
554
+
555
+
556
+ ;// ./lib/helpers/padZeros/index.js
557
+
558
+
559
+
560
+
561
+ ;// ./lib/helpers/stringFormatter/stringFormatter.js
562
+ function stringFormatter(str) {
563
+ return (str || '').toUpperCase().replace('-', '_').replace(' ', '_')
564
+ }
565
+
566
+
567
+
568
+ ;// ./lib/helpers/stringFormatter/index.js
569
+
570
+
571
+
572
+
573
+ ;// ./lib/helpers/index.js
574
+
575
+
576
+
577
+
578
+
579
+
580
+
581
+
582
+ ;// ./lib/models/apiResponse/apiResponse.js
583
+ class ApiResponse {
584
+ constructor(options = {}) {
585
+ options = options || {}
586
+ this._data = options.data || options._data || []
587
+ this.err = options.err
588
+ this.isNew = options.isNew || false
589
+ this.message = options.message
590
+ this.total = options.total || 0
591
+ this._instanceBuilder = options._instanceBuilder
592
+ }
593
+
594
+ static init(options = {}) {
595
+ if (options instanceof this) {
596
+ return options
597
+ }
598
+ const instance = new this(options)
599
+ return instance
600
+ }
601
+ static get _classname() {
602
+ return 'ApiResponse'
603
+ }
604
+ static get _superclass() {
605
+ return 'ApiResponse'
606
+ }
607
+
608
+ // getters
609
+ get data() {
610
+ if (this._instanceBuilder && (typeof this._instanceBuilder === 'function')) {
611
+ return this._data.map(this._instanceBuilder)
612
+ }
613
+ return this._data
614
+ }
615
+ }
616
+
617
+
618
+
619
+ ;// ./lib/models/apiResponse/makeApiResponse.js
620
+
621
+
622
+ function makeApiResponse({ repo, result }) {
623
+ return ApiResponse.init({
624
+ ...result,
625
+ _instanceBuilder: (i) => {
626
+ return repo.init(i)
627
+ }
628
+ })
629
+ }
630
+
631
+
632
+
633
+ ;// ./lib/models/apiResponse/index.js
634
+
635
+
636
+
637
+
638
+
639
+ ;// ./lib/models/keyValueObject/keyValueObject.js
640
+ class KeyValueObject {
641
+ constructor(options = {}) {
642
+ options = options || {}
643
+ this.key = options.key || null
644
+ this.value = (typeof options.value !== 'undefined') ? options.value : ''
645
+ }
646
+
647
+ // Class methods
648
+ static init(options = {}) {
649
+ if (options instanceof this) {
650
+ return options
651
+ }
652
+ const instance = new this(options)
653
+ return instance.isValid ? instance : null
654
+ }
655
+ static initFromArray(arr = []) {
656
+ if (Array.isArray(arr)) {
657
+ return arr.map((a) => this.init(a))
658
+ }
659
+ return []
660
+ }
661
+ static initOnlyValidFromArray(arr = []) {
662
+ return this.initFromArray(arr).filter((i) => i)
663
+ }
664
+ static get _classname() {
665
+ return 'KeyValueObject'
666
+ }
667
+ static get _superclass() {
668
+ return 'KeyValueObject'
669
+ }
670
+
671
+ static addItem(arr, key, value) {
672
+ arr.push(
673
+ { key, value }
674
+ )
675
+ }
676
+ static addRecord(arr = [], key, value) {
677
+ const self = this
678
+ if (!this.hasKeyValue(arr, key, value)) {
679
+ arr.push(self.init({ key, value }))
680
+ }
681
+ return arr
682
+ }
683
+
684
+ static appendRecord(arr = [], key, value) {
685
+ return arr.map((item) => {
686
+ if (item.key === key) {
687
+ item.value = [...item.value, ...value]
688
+ }
689
+ return item
690
+ })
691
+ }
692
+
693
+ static fromObject(options = {}) {
694
+ const self = this
695
+ return Object.keys(options).reduce((acc, key) => {
696
+ acc.push(self.init({ key, value: options[key] }))
697
+ return acc
698
+ }, [])
699
+ }
700
+
701
+ static removeByKey(arr, key) {
702
+ return arr.reduce((acc, item) => {
703
+ if (item.key !== key) {
704
+ acc.push(item)
705
+ }
706
+ return acc
707
+ }, [])
708
+ }
709
+
710
+ static foundByKey(arr = [], key) {
711
+ const found = arr.find((m) => {
712
+ return m.key === key
713
+ })
714
+ return found || null
715
+ }
716
+
717
+ static foundValueByKey(arr = [], key) {
718
+ const found = this.foundByKey(arr, key)
719
+ return found ? found.value : null
720
+ }
721
+
722
+ static getValueByKey(arr = [], key) {
723
+ const found = arr.find((i) => {
724
+ return i.key === key
725
+ })
726
+ if (found) {
727
+ return found.value
728
+ }
729
+ return null
730
+ }
731
+
732
+ static getValueByKeyFromArray(arr = [], key) {
733
+ if (arr.length === 0) {
734
+ return null
735
+ }
736
+ const firstArr = arr.shift()
737
+ const found = firstArr.find((i) => {
738
+ return i.key === key
739
+ })
740
+ if (found && found.value) {
741
+ return found.value
742
+ }
743
+ return this.getValueByKeyFromArray(arr, key)
744
+ }
745
+
746
+ static getValuesByKey(arr = [], key) {
747
+ return arr.reduce((acc, item) => {
748
+ if (item.key === key) {
749
+ acc.push(item.value)
750
+ }
751
+ return acc
752
+ }, [])
753
+ }
754
+
755
+ static hasKeyValue(arr = [], key, value) {
756
+ if (typeof value === 'undefined') {
757
+ return arr.filter((item) => item.key === key).length > 0
758
+ }
759
+ return arr.filter((item) => (item.key === key && item.value === value)).length > 0
760
+ }
761
+
762
+ static insertOrUpdateRecord(arr = [], key, value) {
763
+ const self = this
764
+ let copy = [...arr]
765
+ if (!self.hasKeyValue(arr, key)) {
766
+ copy.push(self.init({ key, value }))
767
+ } else {
768
+ copy = self.updateRecord(arr, key, value)
769
+ }
770
+ return copy
771
+ }
772
+
773
+ static keys(arr = []) {
774
+ if (Array.isArray(arr)) {
775
+ return arr.reduce((acc, item) => {
776
+ acc.push(item.key)
777
+ return acc
778
+ }, [])
779
+ }
780
+ return []
781
+ }
782
+
783
+ static merge(toArr, fromArr) {
784
+ (fromArr || []).map((from) => {
785
+ const found = toArr.find((to) => {
786
+ return to.key === from.key
787
+ })
788
+ if (found) {
789
+ found.value = (found.value || []).concat(from.value)
790
+ } else {
791
+ toArr.push(from)
792
+ }
793
+ })
794
+ return toArr
795
+ }
796
+
797
+ static toObject(arr = []) {
798
+ if (Array.isArray(arr)) {
799
+ return arr.reduce((acc, item) => {
800
+ acc[item.key] = item.value
801
+ return acc
802
+ }, {})
803
+ }
804
+ return {}
805
+ }
806
+
807
+ static toString(arr = [], delimiter = '; ') {
808
+ if (Array.isArray(arr)) {
809
+ return arr.reduce((acc, item) => {
810
+ acc.push(`${item.key}: ${item.value}`)
811
+ return acc
812
+ }, []).join(delimiter)
813
+ }
814
+ return ''
815
+ }
816
+
817
+ static updateRecord(arr = [], key, value) {
818
+ return arr.map((item) => {
819
+ if (item.key === key) {
820
+ return {
821
+ ...item,
822
+ value
823
+ }
824
+ }
825
+ return item
826
+ })
827
+ }
828
+
829
+ static updateOrInsertRecord(arr = [], key, value) {
830
+ return this.insertOrUpdateRecord(arr, key, value)
831
+ }
832
+
833
+ static updateRecordsFromArray(arr = [], updateArr = []) {
834
+ if (Array.isArray(arr) && Array.isArray(updateArr)) {
835
+ const obj1 = this.toObject(arr)
836
+ const obj2 = this.toObject(updateArr)
837
+ return this.fromObject({
838
+ ...obj1,
839
+ ...obj2
840
+ })
841
+ }
842
+ return []
843
+ }
844
+
845
+ static values(arr = []) {
846
+ if (Array.isArray(arr)) {
847
+ return arr.reduce((acc, item) => {
848
+ acc.push(item.value)
849
+ return acc
850
+ }, [])
851
+ }
852
+ return []
853
+ }
854
+
855
+ // getters
856
+ get isValid() {
857
+ return !!this.key
858
+ }
859
+
860
+ get toObject() {
861
+ const obj = {}
862
+ if (this.isValid) {
863
+ obj[this.key] = this.value
864
+ }
865
+ return obj
866
+ }
867
+ }
868
+
869
+
870
+
871
+ ;// ./lib/models/keyValueObject/index.js
872
+
873
+
874
+
875
+
876
+ ;// ./lib/models/metadata/metadata.js
877
+
878
+
879
+
880
+ class Metadata extends KeyValueObject {
881
+ static init(options = {}) {
882
+ if (options instanceof this) {
883
+ return options
884
+ }
885
+ const instance = new this({
886
+ ...options,
887
+ key: stringFormatter(options.key),
888
+ })
889
+ return instance.isValid ? instance : null
890
+ }
891
+
892
+ static foundByKey(arr = [], key) {
893
+ const found = (arr || []).find((m) => {
894
+ return m.key === stringFormatter(key)
895
+ })
896
+ return found || null
897
+ }
898
+
899
+ static get _classname() {
900
+ return 'Metadata'
901
+ }
902
+ }
903
+
904
+
905
+
906
+ ;// ./lib/models/metadata/index.js
907
+
908
+
909
+
910
+
911
+ ;// ./lib/models/repo/repo.js
912
+ class Repo {
913
+ constructor(options) {
914
+ this.model = options.model
915
+ this.dbTransaction = options.dbTransaction
916
+ }
917
+
918
+ static get _classname() {
919
+ return 'Repo'
920
+ }
921
+ static get _superclass() {
922
+ return 'Repo'
923
+ }
924
+
925
+ init(options) {
926
+ throw new Error('subclass should implement .init(options)')
927
+ }
928
+
929
+ async deleteOne({ id }) {
930
+ try {
931
+ const result = await this.model.deleteOne({ _id: id })
932
+ return {
933
+ ...result, // { message: 'ok', total }
934
+ isNew: false,
935
+ data: []
936
+ }
937
+ } catch (err) {
938
+ throw err
939
+ }
940
+ }
941
+
942
+ findAll({ query }) {
943
+ const options = {}
944
+ return new Promise((resolve, reject) => {
945
+ this.model.findAll(query, options, (err, data, total) => {
946
+ if (err) {
947
+ reject(err)
948
+ } else {
949
+ resolve({
950
+ isNew: false,
951
+ data,
952
+ total: total || data.length
953
+ })
954
+ }
955
+ })
956
+ })
957
+ }
958
+
959
+ findOne({ query }) {
960
+ const options = { session: this.dbTransaction }
961
+ return new Promise((resolve, reject) => {
962
+ this.model.findAll(query, options, (err, data) => {
963
+ if (err) {
964
+ reject(err)
965
+ } else if (data.length === 1) {
966
+ resolve({
967
+ isNew: false,
968
+ data,
969
+ total: 1
970
+ })
971
+ } else if (data.length === 0) {
972
+ reject(new Error('record not found'))
973
+ } else {
974
+ reject(new Error('more than one is found'))
975
+ }
976
+ })
977
+ })
978
+ }
979
+
980
+ saveAll({ docs }) {
981
+ const self = this
982
+ let isNew
983
+ return Promise.all(docs.map(async (doc) => {
984
+ if (doc) {
985
+ const result = await self.saveOne({ doc })
986
+ isNew = result.isNew
987
+ return result.data[0]
988
+ }
989
+ return null
990
+ })).then((savedData) => {
991
+ if (savedData.length !== 1) isNew = null
992
+ return {
993
+ data: savedData,
994
+ isNew,
995
+ total: savedData.length
996
+ }
997
+ })
998
+ }
999
+
1000
+ saveOne({ doc }) {
1001
+ const options = { session: this.dbTransaction }
1002
+ return new Promise((resolve, reject) => {
1003
+ this.model.saveOne(doc, options, (err, result) => {
1004
+ if (err) {
1005
+ reject(err)
1006
+ } else {
1007
+ resolve(result)
1008
+ }
1009
+ })
1010
+ })
1011
+ }
1012
+ }
1013
+
1014
+
1015
+
1016
+ ;// ./lib/models/repo/index.js
1017
+
1018
+
1019
+
1020
+
1021
+ ;// ./lib/models/service/service.js
1022
+
1023
+
1024
+
1025
+ class Service {
1026
+ constructor({ repo }) {
1027
+ this.repo = repo
1028
+ }
1029
+
1030
+ static get _classname() {
1031
+ return 'Service'
1032
+ }
1033
+ static get _superclass() {
1034
+ return 'Service'
1035
+ }
1036
+
1037
+ deleteOne({ id }) {
1038
+ return this.repo.deleteOne({ id })
1039
+ .catch(() => {
1040
+ throw new Error(`Not found for query: ${id}`)
1041
+ })
1042
+ }
1043
+
1044
+ async findAll({ query = {} } = {}) {
1045
+ const result = await this.repo.findAll({ query })
1046
+ return makeApiResponse({
1047
+ repo: this.repo,
1048
+ result
1049
+ })
1050
+ }
1051
+
1052
+ async findOne({ query = {} } = {}) {
1053
+ const result = await this.repo.findOne({ query })
1054
+ return makeApiResponse({
1055
+ repo: this.repo,
1056
+ result
1057
+ })
1058
+ }
1059
+
1060
+ init(options) {
1061
+ return this.repo.init(options)
1062
+ }
1063
+ initFromArray(arr = []) {
1064
+ return arr.map((i) => this.init(i))
1065
+ }
1066
+
1067
+ async saveAll({ docs = [] } = {}) {
1068
+ const copies = docs.map((doc) => {
1069
+ return this.init(doc)
1070
+ })
1071
+ const result = await this.repo.saveAll({ docs: copies })
1072
+ return makeApiResponse({
1073
+ repo: this.repo,
1074
+ result
1075
+ })
1076
+ }
1077
+
1078
+ async saveOne({ doc = {} } = {}) {
1079
+ const copy = this.init(doc)
1080
+ if (copy) {
1081
+ const result = await this.repo.saveOne({ doc: copy })
1082
+ return makeApiResponse({
1083
+ repo: this.repo,
1084
+ result
1085
+ })
1086
+ }
1087
+ return {
1088
+ isNew: null,
1089
+ data: [],
1090
+ err: new Error('doc is not a valid instance')
1091
+ }
1092
+ }
1093
+ }
1094
+
1095
+ function makeService({ repo }) {
1096
+ if (repo === undefined) {
1097
+ throw new Error('repo is required.')
1098
+ }
1099
+ // if (!(repo instanceof Repo)) {
1100
+ // throw new Error('repo is not an instance of Repo.')
1101
+ // }
1102
+ return new Service({ repo })
1103
+ }
1104
+
1105
+
1106
+
1107
+ ;// ./lib/models/service/index.js
1108
+
1109
+
1110
+
1111
+
1112
+ ;// ./lib/models/index.js
1113
+
1114
+
1115
+
1116
+
1117
+
1118
+
1119
+ ;// ./lib/index.js
1120
+
1121
+
1122
+
1123
+ ;// ./index.js
1124
+
1125
+
1126
+ var __webpack_exports__ApiResponse = __webpack_exports__.sh;
1127
+ var __webpack_exports__KeyValueObject = __webpack_exports__.Yc;
1128
+ var __webpack_exports__Metadata = __webpack_exports__.OS;
1129
+ var __webpack_exports__Repo = __webpack_exports__.lc;
1130
+ var __webpack_exports__Service = __webpack_exports__.kl;
1131
+ var __webpack_exports__convertString = __webpack_exports__.l0;
1132
+ var __webpack_exports__formatDate = __webpack_exports__.Yq;
1133
+ var __webpack_exports__getValidation = __webpack_exports__.G8;
1134
+ var __webpack_exports__getValueByKeys = __webpack_exports__.pY;
1135
+ var __webpack_exports__jwtHelper = __webpack_exports__.Q_;
1136
+ var __webpack_exports__makeApiResponse = __webpack_exports__.su;
1137
+ var __webpack_exports__makeService = __webpack_exports__.Q6;
1138
+ var __webpack_exports__padZeros = __webpack_exports__.Lv;
1139
+ var __webpack_exports__stringFormatter = __webpack_exports__.Qy;
1140
+ export { __webpack_exports__ApiResponse as ApiResponse, __webpack_exports__KeyValueObject as KeyValueObject, __webpack_exports__Metadata as Metadata, __webpack_exports__Repo as Repo, __webpack_exports__Service as Service, __webpack_exports__convertString as convertString, __webpack_exports__formatDate as formatDate, __webpack_exports__getValidation as getValidation, __webpack_exports__getValueByKeys as getValueByKeys, __webpack_exports__jwtHelper as jwtHelper, __webpack_exports__makeApiResponse as makeApiResponse, __webpack_exports__makeService as makeService, __webpack_exports__padZeros as padZeros, __webpack_exports__stringFormatter as stringFormatter };