@questwork/q-utilities 0.1.11 → 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.
@@ -1,50 +1,79 @@
1
- /******/ // The require scope
2
- /******/ var __webpack_require__ = {};
3
- /******/
1
+ (function webpackUniversalModuleDefinition(root, factory) {
2
+ if(typeof exports === 'object' && typeof module === 'object')
3
+ module.exports = factory();
4
+ else if(typeof define === 'function' && define.amd)
5
+ define([], factory);
6
+ else if(typeof exports === 'object')
7
+ exports["@questwork/q-utilities"] = factory();
8
+ else
9
+ root["@questwork/q-utilities"] = factory();
10
+ })(this, () => {
11
+ return /******/ (() => { // webpackBootstrap
12
+ /******/ // The require scope
13
+ /******/ var __webpack_require__ = {};
14
+ /******/
4
15
  /************************************************************************/
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] });
16
+ /******/ /* webpack/runtime/define property getters */
17
+ /******/ (() => {
18
+ /******/ // define getter functions for harmony exports
19
+ /******/ __webpack_require__.d = (exports, definition) => {
20
+ /******/ for(var key in definition) {
21
+ /******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
22
+ /******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
23
+ /******/ }
12
24
  /******/ }
13
- /******/ }
14
- /******/ };
15
- /******/ })();
16
- /******/
17
- /******/ /* webpack/runtime/hasOwnProperty shorthand */
18
- /******/ (() => {
19
- /******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
20
- /******/ })();
21
- /******/
25
+ /******/ };
26
+ /******/ })();
27
+ /******/
28
+ /******/ /* webpack/runtime/hasOwnProperty shorthand */
29
+ /******/ (() => {
30
+ /******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
31
+ /******/ })();
32
+ /******/
33
+ /******/ /* webpack/runtime/make namespace object */
34
+ /******/ (() => {
35
+ /******/ // define __esModule on exports
36
+ /******/ __webpack_require__.r = (exports) => {
37
+ /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
38
+ /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
39
+ /******/ }
40
+ /******/ Object.defineProperty(exports, '__esModule', { value: true });
41
+ /******/ };
42
+ /******/ })();
43
+ /******/
22
44
  /************************************************************************/
23
45
  var __webpack_exports__ = {};
46
+ // ESM COMPAT FLAG
47
+ __webpack_require__.r(__webpack_exports__);
24
48
 
25
49
  // EXPORTS
26
50
  __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),
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)
51
+ ApiResponse: () => (/* reexport */ ApiResponse),
52
+ KeyValueObject: () => (/* reexport */ KeyValueObject),
53
+ Metadata: () => (/* reexport */ Metadata),
54
+ QMeta: () => (/* reexport */ QMeta),
55
+ Repo: () => (/* reexport */ Repo),
56
+ Service: () => (/* reexport */ Service),
57
+ TemplateCompiler: () => (/* reexport */ TemplateCompiler),
58
+ TenantAwareEntity: () => (/* reexport */ TenantAwareEntity),
59
+ TrackedEntity: () => (/* reexport */ TrackedEntity),
60
+ UniqueKeyGenerator: () => (/* reexport */ UniqueKeyGenerator),
61
+ concatStringByArray: () => (/* reexport */ concatStringByArray),
62
+ convertString: () => (/* reexport */ convertString),
63
+ formatDate: () => (/* reexport */ formatDate),
64
+ generalPost: () => (/* reexport */ generalPost),
65
+ getValidation: () => (/* reexport */ getValidation),
66
+ getValueByKeys: () => (/* reexport */ getValueByKeys_getValueByKeys),
67
+ init: () => (/* reexport */ init),
68
+ initFromArray: () => (/* reexport */ initFromArray),
69
+ initOnlyValidFromArray: () => (/* reexport */ initOnlyValidFromArray),
70
+ makeApiResponse: () => (/* reexport */ makeApiResponse),
71
+ makeService: () => (/* reexport */ makeService),
72
+ objectHelper: () => (/* reexport */ objectHelper),
73
+ pReduce: () => (/* reexport */ pReduce),
74
+ padZeros: () => (/* reexport */ padZeros),
75
+ stringFormatter: () => (/* reexport */ stringFormatter),
76
+ stringHelper: () => (/* reexport */ stringHelper)
48
77
  });
49
78
 
50
79
  ;// ./lib/helpers/getValidation/getValidation.js
@@ -235,7 +264,7 @@ function padding(m) {
235
264
 
236
265
  ;// ./lib/helpers/getValueByKeys/getValueByKeys.js
237
266
  // keys can be array or object or string
238
- function getValueByKeys(keys, data) {
267
+ function getValueByKeys_getValueByKeys(keys, data) {
239
268
  let _keys = keys
240
269
  let _data = data
241
270
  if (typeof keys === 'string') {
@@ -251,7 +280,7 @@ function getValueByKeys(keys, data) {
251
280
  }
252
281
  const firstKey = _keys.shift()
253
282
  if (_data && Object.prototype.hasOwnProperty.call(_data, firstKey)) {
254
- return getValueByKeys(_keys, _data[firstKey])
283
+ return getValueByKeys_getValueByKeys(_keys, _data[firstKey])
255
284
  }
256
285
  if (_data && firstKey) {
257
286
  return _data[firstKey]
@@ -259,12 +288,11 @@ function getValueByKeys(keys, data) {
259
288
  return _data
260
289
 
261
290
  }
262
- /* harmony default export */ const getValueByKeys_getValueByKeys = ({
263
- getValueByKeys
291
+ /* harmony default export */ const getValueByKeys = ({
292
+ getValueByKeys: getValueByKeys_getValueByKeys
264
293
  });
265
294
 
266
295
 
267
-
268
296
  ;// ./lib/helpers/getValueByKeys/index.js
269
297
 
270
298
 
@@ -292,7 +320,25 @@ class TemplateCompilerException extends Error {
292
320
  ;// ./lib/models/templateCompiler/constants.js
293
321
  const _EMPTY = '_EMPTY'
294
322
  const _FN_NAMES = [
295
- 'get', 'map', 'join', 'concatIf', 'exec', 'filterOne', 'filterAll', 'formatDate', 'eq', 'neq', 'gt', 'lt', 'gte', 'lte', 'isEmpty', 'isNotEmpty', 'toLowerCase', 'toUpperCase'
323
+ 'concatIf',
324
+ 'divide',
325
+ 'eq',
326
+ 'exec',
327
+ 'filterAll',
328
+ 'filterOne',
329
+ 'formatDate',
330
+ 'get',
331
+ 'gt',
332
+ 'gte',
333
+ 'isEmpty',
334
+ 'isNotEmpty',
335
+ 'join',
336
+ 'lt',
337
+ 'lte',
338
+ 'map',
339
+ 'neq',
340
+ 'toLowerCase',
341
+ 'toUpperCase',
296
342
  ]
297
343
  const _HIDE = '_HIDE'
298
344
  const _NOT_EMPTY = '_NOT_EMPTY'
@@ -333,6 +379,20 @@ function _concatIf(data, args) {
333
379
 
334
380
 
335
381
 
382
+ ;// ./lib/models/templateCompiler/helpers/_divide.js
383
+ function _divide(value, divisor) {
384
+ try {
385
+ if (Number.isNaN(value)) {
386
+ return value
387
+ }
388
+ return (value / divisor)
389
+ } catch (e) {
390
+ throw e
391
+ }
392
+ }
393
+
394
+
395
+
336
396
  ;// ./lib/models/templateCompiler/helpers/_eq.js
337
397
 
338
398
 
@@ -404,7 +464,7 @@ function _existObject(data, args) {
404
464
  const arg = args[0]
405
465
  return data.filter((e) => {
406
466
  if (arg.includes('.')) {
407
- return getValueByKeys(arg.split('.'), e)
467
+ return getValueByKeys_getValueByKeys(arg.split('.'), e)
408
468
  }
409
469
  return Object.prototype.hasOwnProperty.call(e, arg)
410
470
  })
@@ -422,7 +482,7 @@ function _existObject(data, args) {
422
482
  const [key, ..._argsArr] = args
423
483
  const _args = _argsArr.flat()
424
484
  return data.filter((e) => {
425
- const value = key.includes('.') ? getValueByKeys(key.split('.'), e) : e[key]
485
+ const value = key.includes('.') ? getValueByKeys_getValueByKeys(key.split('.'), e) : e[key]
426
486
  return _args.some((arg) => _performOperation(arg, value))
427
487
  })
428
488
  }
@@ -918,6 +978,7 @@ function _toUpperCase(data, args) {
918
978
 
919
979
 
920
980
 
981
+
921
982
 
922
983
 
923
984
  ;// ./lib/models/templateCompiler/templateCompiler.js
@@ -944,6 +1005,9 @@ class TemplateCompiler {
944
1005
  static concatIf(data, args) {
945
1006
  return _concatIf(data, args)
946
1007
  }
1008
+ static divide(data, args) {
1009
+ return _divide(data, args)
1010
+ }
947
1011
  static eq(data, args) {
948
1012
  return _eq(data, args)
949
1013
  }
@@ -955,7 +1019,6 @@ class TemplateCompiler {
955
1019
  static formatDate(data, args) {
956
1020
  return _formatDate(data, args)
957
1021
  }
958
-
959
1022
  static get(data, key, failover = null) {
960
1023
  return _get(data, key, failover)
961
1024
  }
@@ -1077,6 +1140,10 @@ function _parseSinglePart(input) {
1077
1140
  // 去掉双引号,返回
1078
1141
  return input.substring(1, input.length - 1)
1079
1142
  }
1143
+ if (input.startsWith("'") && input.endsWith("'")) {
1144
+ // 去掉双引号,返回
1145
+ return input.substring(1, input.length - 1)
1146
+ }
1080
1147
 
1081
1148
  const _input = _toBasicType(input)
1082
1149
 
@@ -1104,6 +1171,10 @@ function _toBasicType(input) {
1104
1171
  // 去掉双引号,返回
1105
1172
  return input.substring(1, input.length - 1)
1106
1173
  }
1174
+ if (input.startsWith("'") && input.endsWith("'")) {
1175
+ // 去掉双引号,返回
1176
+ return input.substring(1, input.length - 1)
1177
+ }
1107
1178
  if (input === 'true') {
1108
1179
  return true
1109
1180
  }
@@ -1126,8 +1197,20 @@ function _callFunction(data, functionName, parameters) {
1126
1197
  try {
1127
1198
  let failover
1128
1199
  switch (functionName) {
1200
+ case 'concatIf':
1201
+ return _concatIf(data, parameters)
1202
+ case 'divide':
1203
+ return _divide(data, parameters)
1204
+ case 'eq':
1205
+ return _eq(data, parameters)
1129
1206
  case 'exec':
1130
1207
  return _exec(data, parameters)
1208
+ case 'filterAll':
1209
+ return _filterAll(data, parameters)
1210
+ case 'filterOne':
1211
+ return _filterOne(data, parameters)
1212
+ case 'formatDate':
1213
+ return _formatDate(data, parameters)
1131
1214
  case 'get':
1132
1215
  if (parameters.length > 2) {
1133
1216
  throw new TemplateCompilerException(TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException)
@@ -1136,34 +1219,24 @@ function _callFunction(data, functionName, parameters) {
1136
1219
  failover = parameters[parameters.length - 1]
1137
1220
  }
1138
1221
  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
1222
  case 'gt':
1156
1223
  return _gt(data, parameters)
1157
1224
  case 'gte':
1158
1225
  return _gte(data, parameters)
1159
- case 'lt':
1160
- return _lt(data, parameters)
1161
- case 'lte':
1162
- return _lte(data, parameters)
1163
1226
  case 'isEmpty':
1164
1227
  return _isEmpty(data, parameters)
1165
1228
  case 'isNotEmpty':
1166
1229
  return _isNotEmpty(data, parameters)
1230
+ case 'join':
1231
+ return _join(data, parameters[0])
1232
+ case 'lt':
1233
+ return _lt(data, parameters)
1234
+ case 'lte':
1235
+ return _lte(data, parameters)
1236
+ case 'map':
1237
+ return _map(data, parameters)
1238
+ case 'neq':
1239
+ return _neq(data, parameters)
1167
1240
  case 'toLowerCase':
1168
1241
  return _toLowerCase(data)
1169
1242
  case 'toUpperCase':
@@ -1194,21 +1267,21 @@ function concatStringByArray(arrTemplate, data) {
1194
1267
  const { type, value = '', restriction, template, format, showMinutes } = item
1195
1268
  switch (type) {
1196
1269
  case('label'): {
1197
- if (getValidation(restriction, data, getValueByKeys)) {
1270
+ if (getValidation(restriction, data, getValueByKeys_getValueByKeys)) {
1198
1271
  acc += (value.toString())
1199
1272
  }
1200
1273
  break
1201
1274
  }
1202
1275
  case('value'): {
1203
- if (getValidation(restriction, data, getValueByKeys)) {
1204
- const _value = getValueByKeys(value.split('.'), data) || ''
1276
+ if (getValidation(restriction, data, getValueByKeys_getValueByKeys)) {
1277
+ const _value = getValueByKeys_getValueByKeys(value.split('.'), data) || ''
1205
1278
  acc += (_value.toString())
1206
1279
  }
1207
1280
  break
1208
1281
  }
1209
1282
  case('array'): {
1210
- if (getValidation(restriction, data, getValueByKeys)) {
1211
- const _value = getValueByKeys(value.split('.'), data) || []
1283
+ if (getValidation(restriction, data, getValueByKeys_getValueByKeys)) {
1284
+ const _value = getValueByKeys_getValueByKeys(value.split('.'), data) || []
1212
1285
  acc += _value.reduce((_acc, item) => {
1213
1286
  return _acc += concatStringByArray(template, item)
1214
1287
  }, '')
@@ -1216,9 +1289,9 @@ function concatStringByArray(arrTemplate, data) {
1216
1289
  break
1217
1290
  }
1218
1291
  case('ellipsis'): {
1219
- if (getValidation(restriction, data, getValueByKeys)) {
1292
+ if (getValidation(restriction, data, getValueByKeys_getValueByKeys)) {
1220
1293
  const { maxLength } = item
1221
- const _value = getValueByKeys(value.split('.'), data) || ''
1294
+ const _value = getValueByKeys_getValueByKeys(value.split('.'), data) || ''
1222
1295
  if (_value.length <= maxLength) {
1223
1296
  acc += (_value.toString())
1224
1297
  } else {
@@ -1228,14 +1301,14 @@ function concatStringByArray(arrTemplate, data) {
1228
1301
  break
1229
1302
  }
1230
1303
  case ('date'): {
1231
- if (getValidation(restriction, data, getValueByKeys)) {
1232
- const _value = getValueByKeys(value.split('.'), data) || ''
1304
+ if (getValidation(restriction, data, getValueByKeys_getValueByKeys)) {
1305
+ const _value = getValueByKeys_getValueByKeys(value.split('.'), data) || ''
1233
1306
  acc += (formatDate(_value, format).toString())
1234
1307
  }
1235
1308
  break
1236
1309
  }
1237
1310
  case ('templateCompiler'): {
1238
- if (getValidation(restriction, data, getValueByKeys)) {
1311
+ if (getValidation(restriction, data, getValueByKeys_getValueByKeys)) {
1239
1312
  const templateCompiler = new TemplateCompiler({ data })
1240
1313
  acc += templateCompiler.pipe(value)
1241
1314
  }
@@ -1255,13 +1328,16 @@ function concatStringByArray(arrTemplate, data) {
1255
1328
 
1256
1329
 
1257
1330
  ;// ./lib/helpers/convertString/convertString.js
1331
+
1332
+
1258
1333
  function convertString(string, patternMatch = /\$\{(.+?)\}/g, value, getValueByKeys) {
1259
- if (!string || typeof getValueByKeys !== 'function') {
1334
+ if (!string) {
1260
1335
  return ''
1261
1336
  }
1337
+ let _getValueByKeys = typeof getValueByKeys !== 'function' ? getValueByKeys : getValueByKeys_getValueByKeys
1262
1338
  const reg = new RegExp(patternMatch, 'g')
1263
1339
  return string.replace(reg, (match, key) => {
1264
- const result = getValueByKeys({ keys: key.split('.'), obj: value })
1340
+ const result = _getValueByKeys({ keys: key.split('.'), obj: value })
1265
1341
  if (result === null || result === undefined) {
1266
1342
  return ''
1267
1343
  }
@@ -1412,282 +1488,468 @@ async function pReduce(iterable, reducer, initialValue) {
1412
1488
 
1413
1489
 
1414
1490
 
1415
- ;// ./lib/models/apiResponse/apiResponse.js
1416
- class ApiResponse {
1417
- constructor(options = {}) {
1491
+ ;// ./lib/models/repo/repo.js
1492
+ class Repo {
1493
+ constructor(options) {
1418
1494
  options = options || {}
1419
- this._data = options.data || options._data || []
1420
- this.err = options.err
1421
- this.isNew = options.isNew || false
1422
- this.message = options.message
1423
- this.total = options.total || 0
1424
- this._instanceBuilder = options._instanceBuilder
1495
+ this.model = options.model
1496
+ this._sharedOptions = options._sharedOptions // { session: this.dbTransaction }
1497
+ this._queryOptions = options._queryOptions
1498
+ this._saveOptions = options._saveOptions
1499
+ this._Class = options._constructor && options._constructor._Class
1500
+ ? options._constructor._Class
1501
+ : null
1425
1502
  }
1426
-
1427
1503
  static init(options = {}) {
1428
1504
  if (options instanceof this) {
1429
1505
  return options
1430
1506
  }
1431
1507
  const instance = new this(options)
1432
- return instance
1508
+ return instance.isValid ? instance : null
1433
1509
  }
1434
1510
  static get _classname() {
1435
- return 'ApiResponse'
1511
+ return 'Repo'
1436
1512
  }
1437
1513
  static get _superclass() {
1438
- return 'ApiResponse'
1514
+ return 'Repo'
1439
1515
  }
1440
1516
 
1441
- // getters
1442
- get data() {
1443
- if (this._instanceBuilder && (typeof this._instanceBuilder === 'function')) {
1444
- return this._data.map(this._instanceBuilder)
1445
- }
1446
- return this._data
1517
+ get _classname() {
1518
+ return 'Repo'
1447
1519
  }
1448
- }
1449
-
1450
1520
 
1521
+ get _superclass() {
1522
+ return 'Repo'
1523
+ }
1451
1524
 
1452
- ;// ./lib/models/apiResponse/makeApiResponse.js
1453
-
1525
+ get isValid() {
1526
+ return this.model
1527
+ && (typeof this.model.deleteOne === 'function')
1528
+ && (typeof this.model.findAll === 'function')
1529
+ && (typeof this.model.saveOne === 'function')
1530
+ }
1454
1531
 
1455
- function makeApiResponse({ repo, result }) {
1456
- return ApiResponse.init({
1457
- ...result,
1458
- _instanceBuilder: (i) => {
1459
- return repo.init(i)
1532
+ get queryOptions() {
1533
+ return {
1534
+ ...this._sharedOptions,
1535
+ ...this._queryOptions,
1460
1536
  }
1461
- })
1462
- }
1463
-
1464
-
1465
-
1466
- ;// ./lib/models/apiResponse/index.js
1467
-
1468
-
1469
-
1470
-
1471
-
1472
- ;// ./lib/models/keyValueObject/keyValueObject.js
1473
- class KeyValueObject {
1474
- constructor(options = {}) {
1475
- options = options || {}
1476
- this.key = options.key || null
1477
- this.value = (typeof options.value !== 'undefined') ? options.value : ''
1478
1537
  }
1479
1538
 
1480
- // Class methods
1481
- static init(options = {}) {
1482
- if (options instanceof this) {
1483
- return options
1539
+ get saveOptions() {
1540
+ return {
1541
+ ...this._sharedOptions,
1542
+ ...this._saveOptions,
1484
1543
  }
1485
- const instance = new this(options)
1486
- return instance.isValid ? instance : null
1487
1544
  }
1488
- static initFromArray(arr = []) {
1489
- if (Array.isArray(arr)) {
1490
- return arr.map((a) => this.init(a))
1545
+
1546
+ init(options) {
1547
+ if (this._Class && typeof this._Class.init === 'function') {
1548
+ return this._Class.init(options)
1491
1549
  }
1492
- return []
1493
- }
1494
- static initOnlyValidFromArray(arr = []) {
1495
- return this.initFromArray(arr).filter((i) => i)
1496
- }
1497
- static get _classname() {
1498
- return 'KeyValueObject'
1499
- }
1500
- static get _superclass() {
1501
- return 'KeyValueObject'
1550
+ return options
1502
1551
  }
1503
1552
 
1504
- static addItem(arr, key, value) {
1505
- arr.push(this.init({ key, value }))
1506
- }
1507
- static addRecord(arr = [], key, value) {
1508
- if (!this.hasKeyValue(arr, key, value)) {
1509
- arr.push(this.init({ key, value }))
1553
+ async deleteOne({ id }) {
1554
+ try {
1555
+ const result = await this.model.deleteOne({ _id: id })
1556
+ return {
1557
+ ...result, // { message: 'ok', total }
1558
+ isNew: false,
1559
+ data: []
1560
+ }
1561
+ } catch (err) {
1562
+ throw err
1510
1563
  }
1511
- return arr
1512
1564
  }
1513
- static appendRecord(arr = [], key, value) {
1514
- return arr.map((item) => {
1515
- if (this.sameKey(item, key)) {
1516
- item.value = [...item.value, ...value]
1517
- }
1518
- return item
1565
+
1566
+ // systemLog is optional
1567
+ findAll({ query, systemLog }) {
1568
+ const log = _makeLog({
1569
+ systemLog,
1570
+ label: 'REPO_READ',
1571
+ message: `fn ${this._classname}.prototype.findAll`,
1572
+ input: [{ query: { ...query }, systemLog: { ...systemLog } }]
1519
1573
  })
1520
- }
1521
- static appendValueArray(arr = [], key, value) {
1522
- return arr.map((item) => {
1523
- if (this.sameKey(item, key)) {
1524
- item.value = [...item.value, ...value]
1525
- }
1526
- return item
1574
+ return new Promise((resolve, reject) => {
1575
+ this.model.findAll(query, this.queryOptions, (err, data, total) => {
1576
+ if (err) {
1577
+ log({ level: 'warn', output: err.toString() })
1578
+ reject(err)
1579
+ } else {
1580
+ const result = {
1581
+ isNew: false,
1582
+ data,
1583
+ total: total || data.length
1584
+ }
1585
+ log({ level: 'info', output: { ...result } })
1586
+ resolve(result)
1587
+ }
1588
+ })
1527
1589
  })
1528
1590
  }
1529
- static foundByKey(arr = [], key) {
1530
- const found = arr.find((m) => {
1531
- return this.sameKey(m, key)
1591
+
1592
+ findOne({ query, systemLog }) {
1593
+ const log = _makeLog({
1594
+ systemLog,
1595
+ label: 'REPO_READ',
1596
+ message: `fn ${this._classname}.prototype.findOne`,
1597
+ input: [{ query: { ...query }, systemLog: { ...systemLog } }]
1532
1598
  })
1533
- return found || null
1534
- }
1535
- static foundValueByKey(arr = [], key) {
1536
- const found = this.foundByKey(arr, key)
1537
- return found ? found.value : null
1599
+ return new Promise((resolve, reject) => {
1600
+ this.model.findAll(query, this.queryOptions, (err, data) => {
1601
+ if (err) {
1602
+ reject(err)
1603
+ } else if (data.length === 1) {
1604
+ const result = {
1605
+ isNew: false,
1606
+ data,
1607
+ total: 1
1608
+ }
1609
+ log({ level: 'info', output: { ...result } })
1610
+ resolve(result)
1611
+ } else if (data.length === 0) {
1612
+ reject(new Error('record not found'))
1613
+ } else {
1614
+ reject(new Error('more than one is found'))
1615
+ }
1616
+ })
1617
+ })
1618
+ .catch((err) => {
1619
+ log({ level: 'warn', output: err.toString() })
1620
+ throw err
1621
+ })
1538
1622
  }
1539
- static fromObject(options = {}) {
1540
- return Object.keys(options).reduce((acc, key) => {
1541
- acc.push(this.init({ key, value: options[key] }))
1542
- return acc
1543
- }, [])
1544
- }
1545
- static getValueByKey(arr = [], key) {
1546
- return this.foundValueByKey(arr, key)
1623
+
1624
+ saveAll({ docs, systemLog }) {
1625
+ let isNew
1626
+ const log = _makeLog({
1627
+ systemLog,
1628
+ label: 'REPO_WRITE',
1629
+ message: `fn ${this._classname}.prototype.saveAll`,
1630
+ input: [{ docs: [...docs], systemLog: { ...systemLog } }]
1631
+ })
1632
+ const promise = typeof this.model.saveAll === 'function'
1633
+ ? this.model.saveAll({ docs })
1634
+ : Promise.all(docs.map(async (doc) => {
1635
+ if (doc) {
1636
+ const result = await this.saveOne({ doc })
1637
+ isNew = result.isNew
1638
+ const _data = result._data || result.data
1639
+ return _data[0]
1640
+ }
1641
+ return null
1642
+ }))
1643
+ return promise.then((savedData) => {
1644
+ if (savedData.length !== 1) isNew = null
1645
+ const result = {
1646
+ data: savedData,
1647
+ isNew,
1648
+ total: savedData.length
1649
+ }
1650
+ log({ level: 'info', output: { ...result } })
1651
+ return result
1652
+ }).catch((err) => {
1653
+ log({ level: 'warn', output: err.toString() })
1654
+ throw err
1655
+ })
1547
1656
  }
1548
- static getValueByKeyFromArray(arr = [], key) {
1549
- if (arr.length === 0) {
1550
- return null
1551
- }
1552
- const firstArr = arr.shift()
1553
- const found = firstArr.find((i) => {
1554
- return this.sameKey(i, key)
1657
+
1658
+ saveOne({ doc, systemLog }) {
1659
+ const log = _makeLog({
1660
+ systemLog,
1661
+ label: 'REPO_WRITE',
1662
+ message: `fn ${this._classname}.prototype.saveOne`,
1663
+ input: [{ doc: { ...doc }, systemLog: { ...systemLog } }]
1555
1664
  })
1556
- if (found && found.value) {
1557
- return found.value
1665
+ return new Promise((resolve, reject) => {
1666
+ this.model.saveOne(doc, this.saveOptions, (err, result) => {
1667
+ if (err) {
1668
+ log({ level: 'warn', output: err.toString() })
1669
+ reject(err)
1670
+ } else {
1671
+ log({ level: 'info', output: { ...result } })
1672
+ resolve(result)
1673
+ }
1674
+ })
1675
+ })
1676
+ }
1677
+ }
1678
+
1679
+ function _makeLog({ systemLog, label, message: message1, input } = {}) {
1680
+ return ({ level, messgae: massage2, output } = {}) => {
1681
+ if (systemLog && systemLog.systemLogHelper) {
1682
+ systemLog.systemLogHelper.log({
1683
+ batchId: systemLog.batchId,
1684
+ label,
1685
+ level,
1686
+ message: massage2 || message1,
1687
+ data: {
1688
+ payload: {
1689
+ input,
1690
+ output
1691
+ }
1692
+ }
1693
+ })
1558
1694
  }
1559
- return this.getValueByKeyFromArray(arr, key)
1560
1695
  }
1561
- static getValuesByKey(arr = [], key) {
1562
- return arr.reduce((acc, item) => {
1563
- if (this.sameKey(item, key)) {
1564
- acc.push(item.value)
1565
- }
1566
- return acc
1567
- }, [])
1696
+ }
1697
+
1698
+
1699
+
1700
+ ;// ./lib/models/apiResponse/apiResponse.js
1701
+ class ApiResponse {
1702
+ constructor(options = {}) {
1703
+ options = options || {}
1704
+ this._data = options.data || options._data || []
1705
+ this.err = options.err
1706
+ this.isNew = options.isNew || false
1707
+ this.message = options.message
1708
+ this.total = options.total || 0
1709
+ this._instanceBuilder = options._instanceBuilder
1568
1710
  }
1569
- static hasKeyValue(arr = [], key, value) {
1570
- if (typeof value === 'undefined') {
1571
- return arr.filter((item) => this.sameKey(item, key)).length > 0
1711
+
1712
+ static init(options = {}) {
1713
+ if (options instanceof this) {
1714
+ return options
1572
1715
  }
1573
- return arr.filter((item) => (this.sameKey(item, key) && _isSame(item.value, value))).length > 0
1716
+ const instance = new this(options)
1717
+ return instance
1574
1718
  }
1575
- static insertOrUpdateRecord(arr = [], key, value) {
1576
- let copy = [...arr]
1577
- if (!this.hasKeyValue(arr, key)) {
1578
- copy.push(this.init({ key, value }))
1579
- } else {
1580
- copy = this.updateRecord(arr, key, value)
1719
+ static get _classname() {
1720
+ return 'ApiResponse'
1721
+ }
1722
+ static get _superclass() {
1723
+ return 'ApiResponse'
1724
+ }
1725
+
1726
+ // getters
1727
+ get data() {
1728
+ if (this._instanceBuilder && (typeof this._instanceBuilder === 'function')) {
1729
+ return this._data.map(this._instanceBuilder)
1581
1730
  }
1582
- return copy
1731
+ return this._data
1583
1732
  }
1584
- static keys(arr = []) {
1585
- if (Array.isArray(arr)) {
1586
- return arr.reduce((acc, item) => {
1587
- acc.push(item.key)
1588
- return acc
1589
- }, [])
1733
+ }
1734
+
1735
+
1736
+
1737
+ ;// ./lib/models/apiResponse/makeApiResponse.js
1738
+
1739
+
1740
+ function makeApiResponse({ repo, result }) {
1741
+ return ApiResponse.init({
1742
+ ...result,
1743
+ _instanceBuilder: (i) => {
1744
+ return repo.init(i)
1590
1745
  }
1591
- return []
1746
+ })
1747
+ }
1748
+
1749
+
1750
+
1751
+ ;// ./lib/models/service/service.js
1752
+
1753
+
1754
+
1755
+ class Service {
1756
+ constructor({ repo }) {
1757
+ this.repo = repo
1592
1758
  }
1593
- static merge(toArr, fromArr) {
1594
- (fromArr || []).map((from) => {
1595
- const found = toArr.find((to) => {
1596
- return to.key === from.key
1759
+
1760
+ static get _classname() {
1761
+ return 'Service'
1762
+ }
1763
+ static get _superclass() {
1764
+ return 'Service'
1765
+ }
1766
+
1767
+ deleteOne({ id }) {
1768
+ return this.repo.deleteOne({ id })
1769
+ .catch(() => {
1770
+ throw new Error(`Not found for query: ${id}`)
1597
1771
  })
1598
- if (found) {
1599
- found.value = (found.value || []).concat(from.value)
1600
- } else {
1601
- toArr.push(from)
1602
- }
1772
+ }
1773
+
1774
+ async findAll({ query = {}, systemLog } = {}) {
1775
+ const result = await this.repo.findAll({ query, systemLog })
1776
+ return makeApiResponse({
1777
+ repo: this.repo,
1778
+ result
1603
1779
  })
1604
- return toArr
1605
1780
  }
1606
- static removeByKey(arr, key) {
1607
- return arr.reduce((acc, item) => {
1608
- if (!this.sameKey(item, key)) {
1609
- acc.push(item)
1610
- }
1611
- return acc
1612
- }, [])
1781
+
1782
+ async findOne({ query = {}, systemLog } = {}) {
1783
+ const result = await this.repo.findOne({ query, systemLog })
1784
+ return makeApiResponse({
1785
+ repo: this.repo,
1786
+ result
1787
+ })
1613
1788
  }
1614
- static sameKey(item, key) {
1615
- return _isSame(item.key, key)
1789
+
1790
+ init(options) {
1791
+ return this.repo.init(options)
1616
1792
  }
1617
- static toObject(arr = []) {
1793
+ initFromArray(arr = []) {
1618
1794
  if (Array.isArray(arr)) {
1619
- return arr.reduce((acc, item) => {
1620
- acc[item.key] = item.value
1621
- return acc
1622
- }, {})
1795
+ return arr.map((a) => this.init(a))
1623
1796
  }
1624
- return {}
1797
+ return []
1625
1798
  }
1626
- static toString(arr = [], delimiter = '; ') {
1627
- if (Array.isArray(arr)) {
1628
- return arr.reduce((acc, item) => {
1629
- acc.push(`${item.key}: ${item.value}`)
1630
- return acc
1631
- }, []).join(delimiter)
1632
- }
1633
- return ''
1799
+ initOnlyValidFromArray(arr = []) {
1800
+ return this.initFromArray(arr).filter((i) => i)
1634
1801
  }
1635
- static updateRecord(arr = [], key, value) {
1636
- return arr.map((item) => {
1637
- if (this.sameKey(item, key)) {
1638
- return {
1639
- ...item,
1640
- value
1641
- }
1642
- }
1643
- return item
1802
+
1803
+ async saveAll({ docs = [], config = {}, systemLog } = {}) {
1804
+ const copies = docs.map((doc) => {
1805
+ return config.skipInit ? doc : this.init(doc)
1806
+ })
1807
+ const result = await this.repo.saveAll({ docs: copies, systemLog })
1808
+ return makeApiResponse({
1809
+ repo: this.repo,
1810
+ result
1644
1811
  })
1645
1812
  }
1646
- static updateOrInsertRecord(arr = [], key, value) {
1647
- return this.insertOrUpdateRecord(arr, key, value)
1648
- }
1649
- static updateRecordsFromArray(arr = [], updateArr = []) {
1650
- if (Array.isArray(arr) && Array.isArray(updateArr)) {
1651
- const obj1 = this.toObject(arr)
1652
- const obj2 = this.toObject(updateArr)
1653
- return this.fromObject({
1654
- ...obj1,
1655
- ...obj2
1813
+
1814
+ // set skipInit to true if we want to use POST for query
1815
+ async saveOne({ doc = {}, config = {}, systemLog } = {}) {
1816
+ const copy = config.skipInit ? doc : this.init(doc)
1817
+ if (copy) {
1818
+ const result = await this.repo.saveOne({ doc: copy, systemLog })
1819
+ return makeApiResponse({
1820
+ repo: this.repo,
1821
+ result
1656
1822
  })
1657
1823
  }
1658
- return []
1659
- }
1660
- static values(arr = []) {
1661
- if (Array.isArray(arr)) {
1662
- return arr.reduce((acc, item) => {
1663
- acc.push(item.value)
1664
- return acc
1665
- }, [])
1824
+ return {
1825
+ isNew: null,
1826
+ data: [],
1827
+ err: new Error('doc is not a valid instance')
1666
1828
  }
1667
- return []
1668
1829
  }
1830
+ }
1669
1831
 
1670
- // getters
1671
- get isValid() {
1672
- return !!this.key
1832
+ function makeService({ repo }) {
1833
+ if (repo === undefined) {
1834
+ throw new Error('repo is required.')
1835
+ }
1836
+ if (repo._superclass !== Repo._superclass) {
1837
+ throw new Error('repo is not an instance of Repo.')
1673
1838
  }
1839
+ return new Service({ repo })
1840
+ }
1674
1841
 
1675
- get toObject() {
1676
- const obj = {}
1677
- if (this.isValid) {
1678
- obj[this.key] = this.value
1679
- }
1680
- return obj
1842
+
1843
+
1844
+ ;// ./lib/helpers/generalPost/generalPost.js
1845
+
1846
+
1847
+
1848
+
1849
+
1850
+ async function generalPost({ body = {}, GeneralModel, UniqueKeyGenerator, resourceInfo }) {
1851
+ const { resources, data, globalShared = {}, shared = {}, relationship = {} } = body
1852
+ const _resourceInfo = resourceInfo || body.resourceInfo
1853
+ _attachShared(data, globalShared, shared)
1854
+ const obj = await pReduce(resources, async (acc, resource) => {
1855
+ const service = _makeService(resource, _resourceInfo, UniqueKeyGenerator, GeneralModel)
1856
+ _createRelationship(data, relationship[resource], acc)
1857
+ const _data = data[resource]
1858
+ const result = await service.saveAll({ docs: [].concat(_data) })
1859
+ acc[resource] = Array.isArray(_data) ? result._data : result._data[0]
1860
+ return acc
1861
+ }, {})
1862
+ return obj
1863
+ }
1864
+
1865
+ function _attachShared(data, globalShared = {}, shared = {}) {
1866
+ Object.keys(shared).forEach((key) => {
1867
+ const _data = data[key]
1868
+ data[key] = objectHelper.merge({}, _data, globalShared, shared[key] || {})
1869
+ })
1870
+ }
1871
+
1872
+ function _createRelationship(data, relationship = {}, object) {
1873
+ Object.keys(relationship).forEach((key) => {
1874
+ const path = relationship[key]
1875
+ const val = objectHelper.get(object, path)
1876
+ objectHelper.set(data, key, val)
1877
+ })
1878
+ }
1879
+
1880
+ function _makeService(resource, resourceInfo, UniqueKeyGenerator, GeneralModel) {
1881
+ const { collectionName, fields } = resourceInfo[resource]
1882
+ const uniqueKeyGenerator = UniqueKeyGenerator.makeGenerator(fields)
1883
+ const model = new GeneralModel({ collectionName, uniqueKeyGenerator })
1884
+ return makeService({
1885
+ repo: new Repo({ model })
1886
+ })
1887
+ }
1888
+
1889
+
1890
+
1891
+ ;// ./lib/helpers/generalPost/index.js
1892
+
1893
+
1894
+
1895
+
1896
+ ;// ./lib/helpers/init/init.js
1897
+ function init(_class, options) {
1898
+ if (options instanceof _class) {
1899
+ return options
1900
+ }
1901
+ try {
1902
+ const instance = new _class(options)
1903
+ return instance.isValid ? instance : null
1904
+ } catch (e) {
1905
+ console.log(`init failed for class: ${_class._classname || 'no _classname'}`, e)
1906
+ return null
1681
1907
  }
1682
1908
  }
1683
1909
 
1684
- function _isSame(key1, key2) {
1685
- return key1 === key2
1910
+ ;// ./lib/helpers/init/index.js
1911
+
1912
+
1913
+ ;// ./lib/helpers/initFromArray/initFromArray.js
1914
+
1915
+
1916
+ function initFromArray(_class, arr) {
1917
+ if (Array.isArray(arr)) {
1918
+ return arr.map((a) => init(_class, a))
1919
+ }
1920
+ return []
1686
1921
  }
1687
1922
 
1923
+ ;// ./lib/helpers/initFromArray/index.js
1688
1924
 
1689
1925
 
1690
- ;// ./lib/models/keyValueObject/index.js
1926
+ ;// ./lib/helpers/initOnlyValidFromArray/initOnlyValidFromArray.js
1927
+
1928
+
1929
+ function initOnlyValidFromArray(_class, arr) {
1930
+ return initFromArray(_class, arr).filter((i) => i)
1931
+ }
1932
+
1933
+ ;// ./lib/helpers/initOnlyValidFromArray/index.js
1934
+
1935
+
1936
+ ;// ./lib/helpers/padZeros/padZeros.js
1937
+ function padZeros(num, minLength = 6) {
1938
+ num = num.toString()
1939
+ if (num.length < minLength) {
1940
+ return padZeros('0' + num, minLength)
1941
+ }
1942
+ return num
1943
+ }
1944
+
1945
+
1946
+
1947
+ ;// ./lib/helpers/padZeros/index.js
1948
+
1949
+
1950
+
1951
+
1952
+ ;// ./lib/helpers/pReduce/index.js
1691
1953
 
1692
1954
 
1693
1955
 
@@ -1706,129 +1968,161 @@ function stringFormatter(str, delimiter = '_') {
1706
1968
 
1707
1969
 
1708
1970
 
1709
- ;// ./lib/models/metadata/metadata.js
1971
+ ;// ./lib/helpers/stringFormatter/index.js
1710
1972
 
1711
1973
 
1712
1974
 
1713
- const DELIMITER = '_'
1714
1975
 
1715
- class Metadata extends KeyValueObject {
1716
- static init(options = {}) {
1717
- if (options instanceof this) {
1718
- return options
1719
- }
1720
- const instance = new this({
1721
- ...options,
1722
- key: stringFormatter(options.key, DELIMITER),
1723
- })
1724
- return instance.isValid ? instance : null
1976
+ ;// ./lib/helpers/stringHelper/stringHelper.js
1977
+ function baseXEncode(num, base = 34) {
1978
+ const charset = getBaseCharset(base)
1979
+ return encode(num, charset)
1980
+ }
1981
+
1982
+ function encode(int, charset) {
1983
+ const { byCode } = charset
1984
+ if (int === 0) {
1985
+ return byCode[0]
1725
1986
  }
1726
- static get _classname() {
1727
- return 'Metadata'
1987
+
1988
+ let res = ''
1989
+ const max = charset.length
1990
+ while (int > 0) {
1991
+ res = byCode[int % max] + res
1992
+ int = Math.floor(int / max)
1728
1993
  }
1994
+ return res
1995
+ }
1729
1996
 
1730
- static merge(toArr, fromArr) {
1731
- (fromArr || []).map((from) => {
1732
- const found = toArr.find((to) => {
1733
- return metadata_isSame(to.key, from.key)
1734
- })
1735
- if (found) {
1736
- found.value = (found.value || []).concat(from.value)
1737
- } else {
1738
- toArr.push(from)
1997
+ function getBaseCharset(base) {
1998
+ let charset = '9876543210ABCDEFGHJKLMNPQRSTUVWXYZ'
1999
+ if (base === 58) {
2000
+ charset = '9876543210ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz'
2001
+ }
2002
+ return indexCharset(charset)
2003
+ }
2004
+
2005
+ function indexCharset(str) {
2006
+ const byCode = {}
2007
+ const byChar = {}
2008
+ const { length } = str
2009
+ let char
2010
+ for (let i = 0; i < length; i++) {
2011
+ char = str[i]
2012
+ byCode[i] = char
2013
+ byChar[char] = i;
2014
+ }
2015
+ return { byCode, byChar, length }
2016
+ }
2017
+
2018
+ function isSame(str1, str2) {
2019
+ if (typeof str1 !== 'string' || typeof str2 !== 'string') {
2020
+ return false
2021
+ }
2022
+ return str1.trim().toUpperCase() === str2.trim().toUpperCase()
2023
+ }
2024
+
2025
+ function randomString({ len = 16, pattern = 'a1' } = {}) {
2026
+ const A = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
2027
+ const a = 'abcdefghijklmnopqrstuvwxyz'
2028
+ const num = '1234567890'
2029
+ const mark = '~!@#$%^&*_+-='
2030
+ let str = ''
2031
+ if (pattern.includes('A')) {
2032
+ str += A
2033
+ }
2034
+ if (pattern.includes('a')) {
2035
+ str += a
2036
+ }
2037
+ if (pattern.includes('1')) {
2038
+ str += num
2039
+ }
2040
+ if (pattern.includes('#')) {
2041
+ str += mark
2042
+ }
2043
+ const chars = [...str]
2044
+ return [...Array(len)].map(i => {
2045
+ return chars[(Math.random() * chars.length) | 0]
2046
+ }).join``
2047
+ }
2048
+
2049
+ function reverse(str) {
2050
+ const _str = (typeof str !== 'string') ? str.toString() : str
2051
+ const splitString = _str.split('')
2052
+ const reverseArray = splitString.reverse()
2053
+ return reverseArray.join('')
2054
+ }
2055
+
2056
+ function setCode(base = 34) {
2057
+ const now = (new Date()).valueOf()
2058
+ const random = randomString({
2059
+ len: 8,
2060
+ pattern: '1'
2061
+ })
2062
+ const str = reverse(`${now}${random}`)
2063
+ // const str = `${now}${random}`
2064
+ return baseXEncode(str, base)
2065
+ }
2066
+
2067
+ function toCamelCase(str) {
2068
+ if (!str) return ''
2069
+ return str
2070
+ .trim()
2071
+ .split(/\s+/)
2072
+ .map((word, index) => {
2073
+ if (!word) return ''
2074
+ if (index === 0) {
2075
+ return word.toLowerCase()
1739
2076
  }
2077
+ return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()
1740
2078
  })
1741
- return toArr
1742
- }
1743
- static sameKey(item, key) {
1744
- return metadata_isSame(item.key, key)
1745
- }
2079
+ .join('')
1746
2080
  }
1747
2081
 
1748
- function metadata_isSame(key1, key2) {
1749
- return stringFormatter(key1, DELIMITER) === stringFormatter(key2, DELIMITER)
2082
+ const stringHelper = {
2083
+ isSame,
2084
+ setCode,
2085
+ toCamelCase,
1750
2086
  }
1751
2087
 
1752
2088
 
1753
2089
 
1754
- ;// ./lib/models/metadata/index.js
2090
+ ;// ./lib/helpers/stringHelper/index.js
1755
2091
 
1756
2092
 
1757
2093
 
1758
2094
 
1759
- ;// ./lib/models/qMeta/qMeta.js
2095
+ ;// ./lib/helpers/index.js
1760
2096
 
1761
2097
 
1762
- const updateAllowedProps = [
1763
- 'attributes',
1764
- 'ref'
1765
- ]
1766
2098
 
1767
- class QMeta {
1768
- constructor(options = {}) {
1769
- options = options || {}
1770
- this.attributes = KeyValueObject.initOnlyValidFromArray(options.attributes)
1771
- this.ref = options.ref || {}
1772
- }
1773
2099
 
1774
- static get _classname() {
1775
- return 'QMeta'
1776
- }
1777
- static get _superclass() {
1778
- return 'QMeta'
1779
- }
1780
2100
 
1781
- // Class methods
1782
- static init(options = {}) {
1783
- if (options instanceof QMeta) {
1784
- return options
1785
- }
1786
- return new QMeta(options)
1787
- }
1788
2101
 
1789
- // instance methods
1790
- addAttribute(obj) {
1791
- const kvObject = KeyValueObject.init(obj)
1792
- if (!kvObject) {
1793
- throw new Error('invalid meta attribute')
1794
- }
1795
- this.attributes.push(kvObject)
1796
- return this
1797
- }
1798
2102
 
1799
- update(obj) {
1800
- Object.keys(obj).forEach((key) => {
1801
- if (updateAllowedProps.includes(key)) {
1802
- if (key === 'attributes') {
1803
- this[key] = KeyValueObject.initOnlyValidFromArray(obj[key])
1804
- } else {
1805
- this[key] = obj[key]
1806
- }
1807
- }
1808
- })
1809
- return this
1810
- }
1811
- }
1812
2103
 
1813
2104
 
1814
2105
 
1815
- ;// ./lib/models/qMeta/index.js
1816
2106
 
1817
2107
 
1818
2108
 
1819
2109
 
1820
- ;// ./lib/models/repo/repo.js
1821
- class Repo {
1822
- constructor(options) {
2110
+
2111
+ ;// ./lib/models/apiResponse/index.js
2112
+
2113
+
2114
+
2115
+
2116
+
2117
+ ;// ./lib/models/keyValueObject/keyValueObject.js
2118
+ class KeyValueObject {
2119
+ constructor(options = {}) {
1823
2120
  options = options || {}
1824
- this.model = options.model
1825
- this._sharedOptions = options._sharedOptions // { session: this.dbTransaction }
1826
- this._queryOptions = options._queryOptions
1827
- this._saveOptions = options._saveOptions
1828
- this._Class = options._constructor && options._constructor._Class
1829
- ? options._constructor._Class
1830
- : null
2121
+ this.key = options.key || null
2122
+ this.value = (typeof options.value !== 'undefined') ? options.value : ''
1831
2123
  }
2124
+
2125
+ // Class methods
1832
2126
  static init(options = {}) {
1833
2127
  if (options instanceof this) {
1834
2128
  return options
@@ -1836,532 +2130,484 @@ class Repo {
1836
2130
  const instance = new this(options)
1837
2131
  return instance.isValid ? instance : null
1838
2132
  }
2133
+ static initFromArray(arr = []) {
2134
+ if (Array.isArray(arr)) {
2135
+ return arr.map((a) => this.init(a))
2136
+ }
2137
+ return []
2138
+ }
2139
+ static initOnlyValidFromArray(arr = []) {
2140
+ return this.initFromArray(arr).filter((i) => i)
2141
+ }
1839
2142
  static get _classname() {
1840
- return 'Repo'
2143
+ return 'KeyValueObject'
1841
2144
  }
1842
2145
  static get _superclass() {
1843
- return 'Repo'
2146
+ return 'KeyValueObject'
1844
2147
  }
1845
2148
 
1846
- get _classname() {
1847
- return 'Repo'
2149
+ static addItem(arr, key, value) {
2150
+ arr.push(this.init({ key, value }))
1848
2151
  }
1849
-
1850
- get _superclass() {
1851
- return 'Repo'
2152
+ static addRecord(arr = [], key, value) {
2153
+ if (!this.hasKeyValue(arr, key, value)) {
2154
+ arr.push(this.init({ key, value }))
2155
+ }
2156
+ return arr
1852
2157
  }
1853
-
1854
- get isValid() {
1855
- return this.model
1856
- && (typeof this.model.deleteOne === 'function')
1857
- && (typeof this.model.findAll === 'function')
1858
- && (typeof this.model.saveOne === 'function')
2158
+ static appendRecord(arr = [], key, value) {
2159
+ return arr.map((item) => {
2160
+ if (this.sameKey(item, key)) {
2161
+ item.value = [...item.value, ...value]
2162
+ }
2163
+ return item
2164
+ })
1859
2165
  }
1860
-
1861
- get queryOptions() {
1862
- return {
1863
- ...this._sharedOptions,
1864
- ...this._queryOptions,
1865
- }
2166
+ static appendValueArray(arr = [], key, value) {
2167
+ return arr.map((item) => {
2168
+ if (this.sameKey(item, key)) {
2169
+ item.value = [...item.value, ...value]
2170
+ }
2171
+ return item
2172
+ })
1866
2173
  }
1867
-
1868
- get saveOptions() {
1869
- return {
1870
- ...this._sharedOptions,
1871
- ...this._saveOptions,
1872
- }
2174
+ static foundByKey(arr = [], key) {
2175
+ const found = arr.find((m) => {
2176
+ return this.sameKey(m, key)
2177
+ })
2178
+ return found || null
1873
2179
  }
1874
-
1875
- init(options) {
1876
- if (this._Class && typeof this._Class.init === 'function') {
1877
- return this._Class.init(options)
2180
+ static foundValueByKey(arr = [], key) {
2181
+ const found = this.foundByKey(arr, key)
2182
+ return found ? found.value : null
2183
+ }
2184
+ static fromObject(options = {}) {
2185
+ return Object.keys(options).reduce((acc, key) => {
2186
+ acc.push(this.init({ key, value: options[key] }))
2187
+ return acc
2188
+ }, [])
2189
+ }
2190
+ static getValueByKey(arr = [], key) {
2191
+ return this.foundValueByKey(arr, key)
2192
+ }
2193
+ static getValueByKeyFromArray(arr = [], key) {
2194
+ if (arr.length === 0) {
2195
+ return null
1878
2196
  }
1879
- return options
2197
+ const firstArr = arr.shift()
2198
+ const found = firstArr.find((i) => {
2199
+ return this.sameKey(i, key)
2200
+ })
2201
+ if (found && found.value) {
2202
+ return found.value
2203
+ }
2204
+ return this.getValueByKeyFromArray(arr, key)
1880
2205
  }
1881
-
1882
- async deleteOne({ id }) {
1883
- try {
1884
- const result = await this.model.deleteOne({ _id: id })
1885
- return {
1886
- ...result, // { message: 'ok', total }
1887
- isNew: false,
1888
- data: []
2206
+ static getValuesByKey(arr = [], key) {
2207
+ return arr.reduce((acc, item) => {
2208
+ if (this.sameKey(item, key)) {
2209
+ acc.push(item.value)
1889
2210
  }
1890
- } catch (err) {
1891
- throw err
2211
+ return acc
2212
+ }, [])
2213
+ }
2214
+ static hasKeyValue(arr = [], key, value) {
2215
+ if (typeof value === 'undefined') {
2216
+ return arr.filter((item) => this.sameKey(item, key)).length > 0
1892
2217
  }
2218
+ return arr.filter((item) => (this.sameKey(item, key) && _isSame(item.value, value))).length > 0
1893
2219
  }
1894
-
1895
- // systemLog is optional
1896
- findAll({ query, systemLog }) {
1897
- const log = _makeLog({
1898
- systemLog,
1899
- label: 'REPO_READ',
1900
- message: `fn ${this._classname}.prototype.findAll`,
1901
- input: [{ query: { ...query }, systemLog: { ...systemLog } }]
1902
- })
1903
- return new Promise((resolve, reject) => {
1904
- this.model.findAll(query, this.queryOptions, (err, data, total) => {
1905
- if (err) {
1906
- log({ level: 'warn', output: err.toString() })
1907
- reject(err)
1908
- } else {
1909
- const result = {
1910
- isNew: false,
1911
- data,
1912
- total: total || data.length
1913
- }
1914
- log({ level: 'info', output: { ...result } })
1915
- resolve(result)
1916
- }
1917
- })
1918
- })
2220
+ static insertOrUpdateRecord(arr = [], key, value) {
2221
+ let copy = [...arr]
2222
+ if (!this.hasKeyValue(arr, key)) {
2223
+ copy.push(this.init({ key, value }))
2224
+ } else {
2225
+ copy = this.updateRecord(arr, key, value)
2226
+ }
2227
+ return copy
1919
2228
  }
1920
-
1921
- findOne({ query, systemLog }) {
1922
- const log = _makeLog({
1923
- systemLog,
1924
- label: 'REPO_READ',
1925
- message: `fn ${this._classname}.prototype.findOne`,
1926
- input: [{ query: { ...query }, systemLog: { ...systemLog } }]
1927
- })
1928
- return new Promise((resolve, reject) => {
1929
- this.model.findAll(query, this.queryOptions, (err, data) => {
1930
- if (err) {
1931
- reject(err)
1932
- } else if (data.length === 1) {
1933
- const result = {
1934
- isNew: false,
1935
- data,
1936
- total: 1
1937
- }
1938
- log({ level: 'info', output: { ...result } })
1939
- resolve(result)
1940
- } else if (data.length === 0) {
1941
- reject(new Error('record not found'))
1942
- } else {
1943
- reject(new Error('more than one is found'))
1944
- }
2229
+ static keys(arr = []) {
2230
+ if (Array.isArray(arr)) {
2231
+ return arr.reduce((acc, item) => {
2232
+ acc.push(item.key)
2233
+ return acc
2234
+ }, [])
2235
+ }
2236
+ return []
2237
+ }
2238
+ static merge(toArr, fromArr) {
2239
+ (fromArr || []).map((from) => {
2240
+ const found = toArr.find((to) => {
2241
+ return to.key === from.key
1945
2242
  })
2243
+ if (found) {
2244
+ found.value = (found.value || []).concat(from.value)
2245
+ } else {
2246
+ toArr.push(from)
2247
+ }
1946
2248
  })
1947
- .catch((err) => {
1948
- log({ level: 'warn', output: err.toString() })
1949
- throw err
1950
- })
2249
+ return toArr
1951
2250
  }
1952
-
1953
- saveAll({ docs, systemLog }) {
1954
- let isNew
1955
- const log = _makeLog({
1956
- systemLog,
1957
- label: 'REPO_WRITE',
1958
- message: `fn ${this._classname}.prototype.saveAll`,
1959
- input: [{ docs: [...docs], systemLog: { ...systemLog } }]
1960
- })
1961
- const promise = typeof this.model.saveAll === 'function'
1962
- ? this.model.saveAll({ docs })
1963
- : Promise.all(docs.map(async (doc) => {
1964
- if (doc) {
1965
- const result = await this.saveOne({ doc })
1966
- isNew = result.isNew
1967
- const _data = result._data || result.data
1968
- return _data[0]
1969
- }
1970
- return null
1971
- }))
1972
- return promise.then((savedData) => {
1973
- if (savedData.length !== 1) isNew = null
1974
- const result = {
1975
- data: savedData,
1976
- isNew,
1977
- total: savedData.length
2251
+ static removeByKey(arr, key) {
2252
+ return arr.reduce((acc, item) => {
2253
+ if (!this.sameKey(item, key)) {
2254
+ acc.push(item)
1978
2255
  }
1979
- log({ level: 'info', output: { ...result } })
1980
- return result
1981
- }).catch((err) => {
1982
- log({ level: 'warn', output: err.toString() })
1983
- throw err
1984
- })
2256
+ return acc
2257
+ }, [])
1985
2258
  }
1986
-
1987
- saveOne({ doc, systemLog }) {
1988
- const log = _makeLog({
1989
- systemLog,
1990
- label: 'REPO_WRITE',
1991
- message: `fn ${this._classname}.prototype.saveOne`,
1992
- input: [{ doc: { ...doc }, systemLog: { ...systemLog } }]
1993
- })
1994
- return new Promise((resolve, reject) => {
1995
- this.model.saveOne(doc, this.saveOptions, (err, result) => {
1996
- if (err) {
1997
- log({ level: 'warn', output: err.toString() })
1998
- reject(err)
1999
- } else {
2000
- log({ level: 'info', output: { ...result } })
2001
- resolve(result)
2259
+ static sameKey(item, key) {
2260
+ return _isSame(item.key, key)
2261
+ }
2262
+ static toObject(arr = []) {
2263
+ if (Array.isArray(arr)) {
2264
+ return arr.reduce((acc, item) => {
2265
+ acc[item.key] = item.value
2266
+ return acc
2267
+ }, {})
2268
+ }
2269
+ return {}
2270
+ }
2271
+ static toString(arr = [], delimiter = '; ') {
2272
+ if (Array.isArray(arr)) {
2273
+ return arr.reduce((acc, item) => {
2274
+ acc.push(`${item.key}: ${item.value}`)
2275
+ return acc
2276
+ }, []).join(delimiter)
2277
+ }
2278
+ return ''
2279
+ }
2280
+ static updateRecord(arr = [], key, value) {
2281
+ return arr.map((item) => {
2282
+ if (this.sameKey(item, key)) {
2283
+ return {
2284
+ ...item,
2285
+ value
2002
2286
  }
2003
- })
2287
+ }
2288
+ return item
2004
2289
  })
2005
2290
  }
2006
- }
2007
-
2008
- function _makeLog({ systemLog, label, message: message1, input } = {}) {
2009
- return ({ level, messgae: massage2, output } = {}) => {
2010
- if (systemLog && systemLog.systemLogHelper) {
2011
- systemLog.systemLogHelper.log({
2012
- batchId: systemLog.batchId,
2013
- label,
2014
- level,
2015
- message: massage2 || message1,
2016
- data: {
2017
- payload: {
2018
- input,
2019
- output
2020
- }
2021
- }
2291
+ static updateOrInsertRecord(arr = [], key, value) {
2292
+ return this.insertOrUpdateRecord(arr, key, value)
2293
+ }
2294
+ static updateRecordsFromArray(arr = [], updateArr = []) {
2295
+ if (Array.isArray(arr) && Array.isArray(updateArr)) {
2296
+ const obj1 = this.toObject(arr)
2297
+ const obj2 = this.toObject(updateArr)
2298
+ return this.fromObject({
2299
+ ...obj1,
2300
+ ...obj2
2022
2301
  })
2023
2302
  }
2303
+ return []
2304
+ }
2305
+ static values(arr = []) {
2306
+ if (Array.isArray(arr)) {
2307
+ return arr.reduce((acc, item) => {
2308
+ acc.push(item.value)
2309
+ return acc
2310
+ }, [])
2311
+ }
2312
+ return []
2024
2313
  }
2025
- }
2026
-
2027
2314
 
2315
+ // getters
2316
+ get isValid() {
2317
+ return !!this.key
2318
+ }
2028
2319
 
2029
- ;// ./lib/models/repo/index.js
2320
+ get toObject() {
2321
+ const obj = {}
2322
+ if (this.isValid) {
2323
+ obj[this.key] = this.value
2324
+ }
2325
+ return obj
2326
+ }
2327
+ }
2030
2328
 
2329
+ function _isSame(key1, key2) {
2330
+ return key1 === key2
2331
+ }
2031
2332
 
2032
2333
 
2033
2334
 
2034
- ;// ./lib/models/service/service.js
2335
+ ;// ./lib/models/keyValueObject/index.js
2035
2336
 
2036
2337
 
2037
2338
 
2038
- class Service {
2039
- constructor({ repo }) {
2040
- this.repo = repo
2041
- }
2042
2339
 
2043
- static get _classname() {
2044
- return 'Service'
2045
- }
2046
- static get _superclass() {
2047
- return 'Service'
2048
- }
2340
+ ;// ./lib/models/metadata/metadata.js
2049
2341
 
2050
- deleteOne({ id }) {
2051
- return this.repo.deleteOne({ id })
2052
- .catch(() => {
2053
- throw new Error(`Not found for query: ${id}`)
2054
- })
2055
- }
2056
2342
 
2057
- async findAll({ query = {}, systemLog } = {}) {
2058
- const result = await this.repo.findAll({ query, systemLog })
2059
- return makeApiResponse({
2060
- repo: this.repo,
2061
- result
2062
- })
2063
- }
2064
2343
 
2065
- async findOne({ query = {}, systemLog } = {}) {
2066
- const result = await this.repo.findOne({ query, systemLog })
2067
- return makeApiResponse({
2068
- repo: this.repo,
2069
- result
2070
- })
2071
- }
2344
+ const DELIMITER = '_'
2072
2345
 
2073
- init(options) {
2074
- return this.repo.init(options)
2075
- }
2076
- initFromArray(arr = []) {
2077
- if (Array.isArray(arr)) {
2078
- return arr.map((a) => this.init(a))
2346
+ class Metadata extends KeyValueObject {
2347
+ static init(options = {}) {
2348
+ if (options instanceof this) {
2349
+ return options
2079
2350
  }
2080
- return []
2351
+ const instance = new this({
2352
+ ...options,
2353
+ key: stringFormatter(options.key, DELIMITER),
2354
+ })
2355
+ return instance.isValid ? instance : null
2081
2356
  }
2082
- initOnlyValidFromArray(arr = []) {
2083
- return this.initFromArray(arr).filter((i) => i)
2357
+ static get _classname() {
2358
+ return 'Metadata'
2084
2359
  }
2085
2360
 
2086
- async saveAll({ docs = [], systemLog } = {}) {
2087
- const copies = docs.map((doc) => {
2088
- return this.init(doc)
2089
- })
2090
- const result = await this.repo.saveAll({ docs: copies, systemLog })
2091
- return makeApiResponse({
2092
- repo: this.repo,
2093
- result
2361
+ static merge(toArr, fromArr) {
2362
+ (fromArr || []).map((from) => {
2363
+ const found = toArr.find((to) => {
2364
+ return metadata_isSame(to.key, from.key)
2365
+ })
2366
+ if (found) {
2367
+ found.value = (found.value || []).concat(from.value)
2368
+ } else {
2369
+ toArr.push(from)
2370
+ }
2094
2371
  })
2372
+ return toArr
2095
2373
  }
2096
-
2097
- async saveOne({ doc = {}, systemLog } = {}) {
2098
- const copy = this.init(doc)
2099
- if (copy) {
2100
- const result = await this.repo.saveOne({ doc: copy, systemLog })
2101
- return makeApiResponse({
2102
- repo: this.repo,
2103
- result
2104
- })
2105
- }
2106
- return {
2107
- isNew: null,
2108
- data: [],
2109
- err: new Error('doc is not a valid instance')
2110
- }
2374
+ static sameKey(item, key) {
2375
+ return metadata_isSame(item.key, key)
2111
2376
  }
2112
2377
  }
2113
2378
 
2114
- function makeService({ repo }) {
2115
- if (repo === undefined) {
2116
- throw new Error('repo is required.')
2117
- }
2118
- if (repo._superclass !== Repo._superclass) {
2119
- throw new Error('repo is not an instance of Repo.')
2120
- }
2121
- return new Service({ repo })
2379
+ function metadata_isSame(key1, key2) {
2380
+ return stringFormatter(key1, DELIMITER) === stringFormatter(key2, DELIMITER)
2122
2381
  }
2123
2382
 
2124
2383
 
2125
2384
 
2126
- ;// ./lib/models/service/index.js
2385
+ ;// ./lib/models/metadata/index.js
2127
2386
 
2128
2387
 
2129
2388
 
2130
2389
 
2131
- ;// ./lib/models/uniqueKeyGenerator/uniqueKeyGenerator.js
2390
+ ;// ./lib/models/qMeta/qMeta.js
2132
2391
 
2133
2392
 
2134
- class UniqueKeyGenerator {
2393
+ const updateAllowedProps = [
2394
+ 'attributes',
2395
+ 'ref'
2396
+ ]
2397
+
2398
+ class QMeta {
2399
+ constructor(options = {}) {
2400
+ options = options || {}
2401
+ this.attributes = KeyValueObject.initOnlyValidFromArray(options.attributes)
2402
+ this.ref = options.ref || {}
2403
+ }
2404
+
2135
2405
  static get _classname() {
2136
- return 'UniqueKeyGenerator'
2406
+ return 'QMeta'
2137
2407
  }
2138
2408
  static get _superclass() {
2139
- return 'UniqueKeyGenerator'
2409
+ return 'QMeta'
2140
2410
  }
2141
- static makeFormatter({ fieldName, format, options }) {
2142
- switch (format) {
2143
- case 'set_code':
2144
- return _makeSetCode(fieldName, options)
2145
- default:
2146
- return _makeSetCode(fieldName, options)
2411
+
2412
+ // Class methods
2413
+ static init(options = {}) {
2414
+ if (options instanceof QMeta) {
2415
+ return options
2147
2416
  }
2417
+ return new QMeta(options)
2148
2418
  }
2149
- static makeGenerator(arr) {
2150
- const fns = arr.map((item) => this.makeFormatter(item))
2151
- return async (obj) => {
2152
- const output = await pReduce(fns, async (acc, fn) => {
2153
- const _obj = await fn(obj)
2154
- return Object.assign(acc, _obj)
2155
- }, obj)
2156
- return output
2419
+
2420
+ // instance methods
2421
+ addAttribute(obj) {
2422
+ const kvObject = KeyValueObject.init(obj)
2423
+ if (!kvObject) {
2424
+ throw new Error('invalid meta attribute')
2157
2425
  }
2426
+ this.attributes.push(kvObject)
2427
+ return this
2158
2428
  }
2159
- }
2160
2429
 
2161
- function _makeSetCode(fieldName, options) {
2162
- return async (obj = {}) => {
2163
- if (obj[fieldName]) {
2164
- return {}
2165
- }
2166
- return {
2167
- [fieldName]: stringHelper.setCode()
2168
- }
2430
+ update(obj) {
2431
+ Object.keys(obj).forEach((key) => {
2432
+ if (updateAllowedProps.includes(key)) {
2433
+ if (key === 'attributes') {
2434
+ this[key] = KeyValueObject.initOnlyValidFromArray(obj[key])
2435
+ } else {
2436
+ this[key] = obj[key]
2437
+ }
2438
+ }
2439
+ })
2440
+ return this
2169
2441
  }
2170
2442
  }
2171
2443
 
2172
2444
 
2173
2445
 
2174
- ;// ./lib/models/uniqueKeyGenerator/index.js
2175
-
2176
-
2177
-
2178
-
2179
- ;// ./lib/models/index.js
2180
-
2181
-
2182
-
2183
-
2446
+ ;// ./lib/models/qMeta/index.js
2184
2447
 
2185
2448
 
2186
2449
 
2187
2450
 
2451
+ ;// ./lib/models/repo/index.js
2188
2452
 
2189
- ;// ./lib/helpers/generalPost/generalPost.js
2190
2453
 
2191
2454
 
2192
2455
 
2456
+ ;// ./lib/models/service/index.js
2193
2457
 
2194
- async function generalPost({ body = {}, GeneralModel, UniqueKeyGenerator, resourceInfo }) {
2195
- const { resources, data, globalShared = {}, shared = {}, relationship = {} } = body
2196
- const _resourceInfo = resourceInfo || body.resourceInfo
2197
- _attachShared(data, globalShared, shared)
2198
- const obj = await pReduce(resources, async (acc, resource) => {
2199
- const service = _makeService(resource, _resourceInfo, UniqueKeyGenerator, GeneralModel)
2200
- _createRelationship(data, relationship[resource], acc)
2201
- const _data = data[resource]
2202
- const result = await service.saveAll({ docs: [].concat(_data) })
2203
- acc[resource] = Array.isArray(_data) ? result._data : result._data[0]
2204
- return acc
2205
- }, {})
2206
- return obj
2207
- }
2208
2458
 
2209
- function _attachShared(data, globalShared = {}, shared = {}) {
2210
- Object.keys(shared).forEach((key) => {
2211
- const _data = data[key]
2212
- data[key] = objectHelper.merge({}, _data, globalShared, shared[key] || {})
2213
- })
2214
- }
2215
2459
 
2216
- function _createRelationship(data, relationship = {}, object) {
2217
- Object.keys(relationship).forEach((key) => {
2218
- const path = relationship[key]
2219
- const val = objectHelper.get(object, path)
2220
- objectHelper.set(data, key, val)
2221
- })
2222
- }
2223
2460
 
2224
- function _makeService(resource, resourceInfo, UniqueKeyGenerator, GeneralModel) {
2225
- const { collectionName, fields } = resourceInfo[resource]
2226
- const uniqueKeyGenerator = UniqueKeyGenerator.makeGenerator(fields)
2227
- const model = new GeneralModel({ collectionName, uniqueKeyGenerator })
2228
- return makeService({
2229
- repo: new Repo({ model })
2230
- })
2231
- }
2461
+ ;// ./lib/models/trackedEntity/trackedEntity.js
2232
2462
 
2233
2463
 
2464
+ class TrackedEntity {
2465
+ constructor(options = {}, { trackFlat = false } = {}) {
2466
+ const timestamp = Date.now()
2467
+ const _tracking = {
2468
+ active: options.active ?? true,
2469
+ created: options.created ?? timestamp,
2470
+ creator: options.creator ?? '',
2471
+ deleted: options.deleted ?? false,
2472
+ modified: options.modified ?? timestamp,
2473
+ owner: options.owner ?? '',
2474
+ }
2234
2475
 
2235
- ;// ./lib/helpers/generalPost/index.js
2476
+ if (trackFlat) {
2477
+ Object.assign(this, _tracking)
2478
+ } else {
2479
+ this.meta = { ..._tracking, ...options.meta }
2480
+ }
2481
+ }
2236
2482
 
2483
+ // Class methods
2484
+ static get _classname() {
2485
+ return 'TrackedEntity'
2486
+ }
2487
+ static get _superclass() {
2488
+ return 'TrackedEntity'
2489
+ }
2237
2490
 
2491
+ static init(options = {}) {
2492
+ return init(this, options)
2493
+ }
2494
+ static initFromArray(arr = []) {
2495
+ return initFromArray(this, arr)
2496
+ }
2497
+ static initOnlyValidFromArray(arr = []) {
2498
+ return initOnlyValidFromArray(this, arr)
2499
+ }
2500
+ static nest(entity) {
2501
+ const { active, created, creator, deleted, modified, owner, ...rest } = entity
2502
+ return { ...rest, meta: { active, created, creator, deleted, modified, owner } }
2503
+ }
2238
2504
 
2505
+ // getters
2506
+ get isValid() {
2507
+ return !!this
2508
+ }
2239
2509
 
2240
- ;// ./lib/helpers/padZeros/padZeros.js
2241
- function padZeros(num, minLength = 6) {
2242
- num = num.toString()
2243
- if (num.length < minLength) {
2244
- return padZeros('0' + num, minLength)
2510
+ setModified() {
2511
+ const timestamp = Date.now()
2512
+ if (this.meta) {
2513
+ this.meta.modified = timestamp
2514
+ } else {
2515
+ this.modified = timestamp
2516
+ }
2245
2517
  }
2246
- return num
2247
2518
  }
2248
2519
 
2520
+ ;// ./lib/models/trackedEntity/index.js
2249
2521
 
2522
+ // Explicit named export (optional)
2250
2523
 
2251
- ;// ./lib/helpers/padZeros/index.js
2252
-
2253
-
2254
-
2255
-
2256
- ;// ./lib/helpers/pReduce/index.js
2257
-
2258
-
2259
-
2260
-
2261
- ;// ./lib/helpers/stringFormatter/index.js
2524
+ ;// ./lib/models/tenantAwareEntity/tenantAwareEntity.js
2262
2525
 
2263
2526
 
2527
+ class TenantAwareEntity extends TrackedEntity {
2528
+ constructor(options = {}) {
2529
+ options = options || {}
2264
2530
 
2531
+ /**
2532
+ * instead of throw error, we choose to implement the isValid checking
2533
+ */
2534
+ // if (!options.tenantCode) {
2535
+ // throw new Error('tenantCode required')
2536
+ // }
2265
2537
 
2266
- ;// ./lib/helpers/stringHelper/stringHelper.js
2267
- function baseXEncode(num, base = 34) {
2268
- const charset = getBaseCharset(base)
2269
- return encode(num, charset)
2270
- }
2538
+ super(options)
2271
2539
 
2272
- function encode(int, charset) {
2273
- let byCode = charset.byCode;
2274
- if (int === 0) {
2275
- return byCode[0];
2540
+ this._tenant = options._tenant
2541
+ this.tenantCode = options.tenantCode // Required for multi-tenancy
2276
2542
  }
2277
2543
 
2278
- var res = "",
2279
- max = charset.length;
2280
- while (int > 0) {
2281
- res = byCode[int % max] + res;
2282
- int = Math.floor(int / max);
2544
+ // Class methods
2545
+ static get _classname() {
2546
+ return 'TenantAwareEntity'
2283
2547
  }
2284
- return res;
2285
- }
2286
-
2287
- function getBaseCharset(base) {
2288
- let charset = '9876543210ABCDEFGHJKLMNPQRSTUVWXYZ'
2289
- if (base === 58) {
2290
- charset = '9876543210ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz'
2548
+ static get _superclass() {
2549
+ return 'TenantAwareEntity'
2291
2550
  }
2292
- return indexCharset(charset)
2293
- }
2294
2551
 
2295
- function indexCharset(str) {
2296
- var byCode = {},
2297
- byChar = {},
2298
- length = str.length,
2299
- i, char;
2300
- for (i = 0; i < length; i++) {
2301
- char = str[i];
2302
- byCode[i] = char;
2303
- byChar[char] = i;
2552
+ // getters
2553
+ get isValid() {
2554
+ return super.isValid && !!this.tenantCode // Required for multi-tenancy
2304
2555
  }
2305
- return { byCode: byCode, byChar: byChar, length: length };
2306
2556
  }
2307
2557
 
2308
- function randomString({ len = 16, pattern = 'a1' } = {}) {
2309
- const A = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
2310
- const a = 'abcdefghijklmnopqrstuvwxyz'
2311
- const num = '1234567890'
2312
- const mark = '~!@#$%^&*_+-='
2313
- let str = ''
2314
- if (pattern.includes('A')) {
2315
- str += A
2558
+ ;// ./lib/models/tenantAwareEntity/index.js
2559
+
2560
+
2561
+
2562
+ ;// ./lib/models/uniqueKeyGenerator/uniqueKeyGenerator.js
2563
+
2564
+
2565
+ class UniqueKeyGenerator {
2566
+ static get _classname() {
2567
+ return 'UniqueKeyGenerator'
2316
2568
  }
2317
- if (pattern.includes('a')) {
2318
- str += a
2569
+ static get _superclass() {
2570
+ return 'UniqueKeyGenerator'
2319
2571
  }
2320
- if (pattern.includes('1')) {
2321
- str += num
2572
+ static makeFormatter({ fieldName, format, options }) {
2573
+ switch (format) {
2574
+ case 'set_code':
2575
+ return _makeSetCode(fieldName, options)
2576
+ default:
2577
+ return _makeSetCode(fieldName, options)
2578
+ }
2322
2579
  }
2323
- if (pattern.includes('#')) {
2324
- str += mark
2580
+ static makeGenerator(arr) {
2581
+ const fns = arr.map((item) => this.makeFormatter(item))
2582
+ return async (obj) => {
2583
+ const output = await pReduce(fns, async (acc, fn) => {
2584
+ const _obj = await fn(obj)
2585
+ return Object.assign(acc, _obj)
2586
+ }, obj)
2587
+ return output
2588
+ }
2325
2589
  }
2326
- const chars = [...str]
2327
- return [...Array(len)].map(i => {
2328
- return chars[(Math.random() * chars.length) | 0]
2329
- }).join``
2330
2590
  }
2331
2591
 
2332
- function reverse(str) {
2333
- if (typeof str !== 'string') {
2334
- str = str.toString()
2592
+ function _makeSetCode(fieldName, options) {
2593
+ return async (obj = {}) => {
2594
+ if (obj[fieldName]) {
2595
+ return {}
2596
+ }
2597
+ return {
2598
+ [fieldName]: stringHelper.setCode()
2599
+ }
2335
2600
  }
2336
- const splitString = str.split('')
2337
- const reverseArray = splitString.reverse()
2338
- return reverseArray.join('')
2339
- }
2340
-
2341
- function setCode(base = 34) {
2342
- const now = (new Date()).valueOf()
2343
- const random = randomString({
2344
- len: 8,
2345
- pattern: '1'
2346
- })
2347
- const str = reverse(`${now}${random}`)
2348
- // const str = `${now}${random}`
2349
- return baseXEncode(str, base)
2350
2601
  }
2351
2602
 
2352
- const stringHelper = {
2353
- setCode
2354
- }
2355
-
2356
-
2357
- ;// ./lib/helpers/stringHelper/index.js
2358
2603
 
2359
2604
 
2605
+ ;// ./lib/models/uniqueKeyGenerator/index.js
2360
2606
 
2361
2607
 
2362
2608
 
2363
- ;// ./lib/helpers/index.js
2364
2609
 
2610
+ ;// ./lib/models/index.js
2365
2611
 
2366
2612
 
2367
2613
 
@@ -2380,25 +2626,7 @@ const stringHelper = {
2380
2626
  ;// ./index.js
2381
2627
 
2382
2628
 
2383
- var __webpack_exports__ApiResponse = __webpack_exports__.sh;
2384
- var __webpack_exports__KeyValueObject = __webpack_exports__.Yc;
2385
- var __webpack_exports__Metadata = __webpack_exports__.OS;
2386
- var __webpack_exports__QMeta = __webpack_exports__.Z8;
2387
- var __webpack_exports__Repo = __webpack_exports__.lc;
2388
- var __webpack_exports__Service = __webpack_exports__.kl;
2389
- var __webpack_exports__TemplateCompiler = __webpack_exports__.Mg;
2390
- var __webpack_exports__UniqueKeyGenerator = __webpack_exports__._x;
2391
- var __webpack_exports__concatStringByArray = __webpack_exports__.yl;
2392
- var __webpack_exports__convertString = __webpack_exports__.l0;
2393
- var __webpack_exports__formatDate = __webpack_exports__.Yq;
2394
- var __webpack_exports__generalPost = __webpack_exports__.zn;
2395
- var __webpack_exports__getValidation = __webpack_exports__.G8;
2396
- var __webpack_exports__getValueByKeys = __webpack_exports__.pY;
2397
- var __webpack_exports__makeApiResponse = __webpack_exports__.su;
2398
- var __webpack_exports__makeService = __webpack_exports__.Q6;
2399
- var __webpack_exports__objectHelper = __webpack_exports__.UI;
2400
- var __webpack_exports__pReduce = __webpack_exports__.d;
2401
- var __webpack_exports__padZeros = __webpack_exports__.Lv;
2402
- var __webpack_exports__stringFormatter = __webpack_exports__.Qy;
2403
- var __webpack_exports__stringHelper = __webpack_exports__.yO;
2404
- 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 };
2629
+ /******/ return __webpack_exports__;
2630
+ /******/ })()
2631
+ ;
2632
+ });