@questwork/q-utilities 0.1.8 → 0.1.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.min.js CHANGED
@@ -30,7 +30,7 @@ __webpack_require__.d(__webpack_exports__, {
30
30
  Z8: () => (/* reexport */ QMeta),
31
31
  lc: () => (/* reexport */ Repo),
32
32
  kl: () => (/* reexport */ Service),
33
- Bj: () => (/* reexport */ Template),
33
+ Mg: () => (/* reexport */ TemplateCompiler),
34
34
  _x: () => (/* reexport */ UniqueKeyGenerator),
35
35
  l0: () => (/* reexport */ convertString),
36
36
  Yq: () => (/* reexport */ formatDate),
@@ -207,6 +207,16 @@ function getValidation(rule, data, getDataByKey, KeyValueObject) {
207
207
  }
208
208
  return false
209
209
  }
210
+ case '$intervalTimeGt': {
211
+ const now = new Date().getTime()
212
+ const timestamp = new Date(rowValue).getTime()
213
+ return (now - timestamp) > value['$intervalTimeGt']
214
+ }
215
+ case '$intervalTimeLt': {
216
+ const now = new Date().getTime()
217
+ const timestamp = new Date(rowValue).getTime()
218
+ return (now - timestamp) < value['$intervalTimeLt']
219
+ }
210
220
  case '$notInValue': {
211
221
  const result = getDataByKey(value['$notInValue'], data)
212
222
  const _value = Array.isArray(result) ? result : []
@@ -936,11 +946,11 @@ class Repo {
936
946
  reject(new Error('more than one is found'))
937
947
  }
938
948
  })
939
- .catch((err) => {
940
- log({ level: 'warn', output: err.toString() })
941
- throw err
942
- })
943
949
  })
950
+ .catch((err) => {
951
+ log({ level: 'warn', output: err.toString() })
952
+ throw err
953
+ })
944
954
  }
945
955
 
946
956
  saveAll({ docs, systemLog }) {
@@ -954,14 +964,14 @@ class Repo {
954
964
  const promise = typeof this.model.saveAll === 'function'
955
965
  ? this.model.saveAll({ docs })
956
966
  : Promise.all(docs.map(async (doc) => {
957
- if (doc) {
958
- const result = await this.saveOne({ doc })
959
- isNew = result.isNew
960
- const _data = result._data || result.data
961
- return _data[0]
962
- }
963
- return null
964
- }))
967
+ if (doc) {
968
+ const result = await this.saveOne({ doc })
969
+ isNew = result.isNew
970
+ const _data = result._data || result.data
971
+ return _data[0]
972
+ }
973
+ return null
974
+ }))
965
975
  return promise.then((savedData) => {
966
976
  if (savedData.length !== 1) isNew = null
967
977
  const result = {
@@ -1121,10 +1131,31 @@ function makeService({ repo }) {
1121
1131
 
1122
1132
 
1123
1133
 
1124
- ;// ./lib/models/template/constants.js
1134
+ ;// ./lib/models/templateCompiler/templateCompilerException.js
1135
+ const TEMPLATE_COMPILER_EXCEPTION_TYPE = {
1136
+ argumentEmptyException: 'Argument is empty',
1137
+ argumentFormatException: 'Incorrect number or format of argument',
1138
+ invalidFuntionException: 'Function Name is invalid',
1139
+ invalidRegExpException: 'Invalid regular expression',
1140
+ isNotAFunctionException: 'Is not a function',
1141
+ notExistException: 'Key does not exist',
1142
+ resultEmptyException: 'Result is empty',
1143
+ resultMoreThanOneException: 'More than one result'
1144
+ }
1145
+
1146
+ class TemplateCompilerException extends Error {
1147
+ constructor(message) {
1148
+ super(message)
1149
+ this.message = message
1150
+ }
1151
+ }
1152
+
1153
+
1154
+
1155
+ ;// ./lib/models/templateCompiler/constants.js
1125
1156
  const _EMPTY = '_EMPTY'
1126
1157
  const _FN_NAMES = [
1127
- 'get', 'map', 'join', 'concatIf', 'filterOne', 'filterAll', 'formatDate', 'eq', 'neq', 'gt', 'lt', 'gte', 'lte', 'isEmpty', 'isNotEmpty', 'toLowerCase', 'toUpperCase'
1158
+ 'get', 'map', 'join', 'concatIf', 'exec', 'filterOne', 'filterAll', 'formatDate', 'eq', 'neq', 'gt', 'lt', 'gte', 'lte', 'isEmpty', 'isNotEmpty', 'toLowerCase', 'toUpperCase'
1128
1159
  ]
1129
1160
  const _HIDE = '_HIDE'
1130
1161
  const _NOT_EMPTY = '_NOT_EMPTY'
@@ -1134,11 +1165,47 @@ const TAGS_HANDLEBAR = ['{{', '}}']
1134
1165
 
1135
1166
 
1136
1167
 
1137
- ;// ./lib/models/template/helpers/_eq.js
1168
+ ;// ./lib/models/templateCompiler/helpers/_concatIf.js
1169
+
1170
+
1171
+
1172
+
1173
+ function _concatIf(data, args) {
1174
+ if (typeof data !== 'string') {
1175
+ throw new TemplateCompilerException(`_concatIf: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException}: the data must be string :${data.join(', ')}`)
1176
+ }
1177
+ if (args.length !== 3) {
1178
+ throw new TemplateCompilerException(`_concatIf: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException}: ${args.join(', ')}`)
1179
+ }
1180
+ if (data === null || (typeof data === 'undefined')) {
1181
+ return null
1182
+ }
1183
+ const [condition, success, failover] = args
1184
+ const validConditions = [_EMPTY, _NOT_EMPTY]
1185
+ if (validConditions.includes(condition) || success.length !== 2) {
1186
+ throw new TemplateCompilerException(`concatIf: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentEmptyException}: ${condition}, ${success}`)
1187
+ }
1188
+ if (data === '' && failover.includes(_HIDE)) {
1189
+ return ''
1190
+ }
1191
+ if (data !== '' && (data !== null || data !== undefined) && failover.includes(_HIDE)) {
1192
+ return `${success[0]}${data}${success[success.length - 1]}`
1193
+ }
1194
+ return failover
1195
+ }
1196
+
1197
+
1198
+
1199
+ ;// ./lib/models/templateCompiler/helpers/_eq.js
1200
+
1201
+
1138
1202
 
1139
1203
 
1140
1204
  function _eq(data, args) {
1141
- if (data === null || (typeof data === 'undefined') || args.length !== 3) {
1205
+ if (args.length !== 3) {
1206
+ throw new TemplateCompilerException(`eq: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException}: ${args.join(', ')}`)
1207
+ }
1208
+ if (data === null || (typeof data === 'undefined')) {
1142
1209
  return null
1143
1210
  }
1144
1211
  if (args.includes(_SELF)) {
@@ -1152,107 +1219,264 @@ function _eq(data, args) {
1152
1219
 
1153
1220
 
1154
1221
 
1155
- ;// ./lib/models/template/templateException.js
1156
- const TEMPLATE_EXCEPTION_TYPE = {
1157
- argumentEmptyException: 'Argument is empty',
1158
- argumentFormatException: 'Incorrect number or format of argument',
1159
- invalidFuntionException: 'Function Name is invalid',
1160
- invalidRegExpException: 'Invalid regular expression',
1161
- isNotAFunctionException: 'Is not a function',
1162
- notExistException: 'Key does not exist',
1163
- resultEmptyException: 'Result is empty',
1164
- resultMoreThanOneException: 'More than one result'
1165
- }
1166
-
1167
- class TemplateException extends Error {
1168
- constructor(message) {
1169
- super(message)
1170
- this.message = message
1222
+ ;// ./lib/models/templateCompiler/helpers/_exec.js
1223
+ function _exec(data, args) {
1224
+ try {
1225
+ const [methodName, ..._args] = args
1226
+ return data[methodName](..._args)
1227
+ } catch (e) {
1228
+ throw e
1171
1229
  }
1172
1230
  }
1173
1231
 
1174
1232
 
1175
1233
 
1176
- ;// ./lib/models/template/helpers/_filterAll.js
1234
+ ;// ./lib/models/templateCompiler/helpers/_filterAll.js
1235
+
1177
1236
 
1178
1237
 
1179
- const _filterAll_DELIMITER = '~~~'
1238
+ // const DELIMITER = '~~~'
1180
1239
 
1181
1240
  function _filterAll(data, args) {
1182
- if (!Array.isArray(data) || data.length === 0 || !Array.isArray(args) || args.length === 0) {
1241
+ try {
1242
+ if (!Array.isArray(args) || args.length === 0) {
1243
+ throw new TemplateCompilerException(TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentEmptyException)
1244
+ }
1245
+ if (!Array.isArray(data) || data.length === 0) {
1246
+ return []
1247
+ }
1248
+ if (typeof data[0] === 'object') {
1249
+ return _existObject(data, args)
1250
+ }
1251
+ if (typeof data[0] === 'string' || typeof data[0] === 'number') {
1252
+ return _exist(data, args)
1253
+ }
1183
1254
  return []
1255
+ } catch (e) {
1256
+ throw e
1184
1257
  }
1258
+ }
1185
1259
 
1186
- if (typeof data[0] === 'object') {
1187
- return _existObject(data, args)
1188
- }
1260
+ function _exist(data, args) {
1261
+ const _args = args.flat()
1262
+ return data.filter((e) => _args.some((arg) => _performOperation(arg, e)))
1263
+ }
1189
1264
 
1190
- if (typeof data[0] === 'string' || typeof data[0] === 'number') {
1191
- return _exist(data, args)
1265
+ function _existObject(data, args) {
1266
+ if (args.length === 1) {
1267
+ const arg = args[0]
1268
+ return data.filter((e) => {
1269
+ if (arg.includes('.')) {
1270
+ return getValueByKeys(arg.split('.'), e)
1271
+ }
1272
+ return Object.prototype.hasOwnProperty.call(e, arg)
1273
+ })
1192
1274
  }
1193
1275
 
1194
- return []
1195
- }
1276
+ if (args.length > 2) {
1277
+ let res = data
1278
+ for (let i = 0; i < args.length; i += 2) {
1279
+ const group = [args[i], args[i + 1]]
1280
+ res = _existObject(res, group)
1281
+ }
1282
+ return res
1283
+ }
1196
1284
 
1197
- function _exist(data, args) {
1198
- const _str = `${_filterAll_DELIMITER}${args.join(_filterAll_DELIMITER)}${_filterAll_DELIMITER}`
1285
+ const [key, ..._argsArr] = args
1286
+ const _args = _argsArr.flat()
1199
1287
  return data.filter((e) => {
1200
- return _str.includes(`${_filterAll_DELIMITER}${e}${_filterAll_DELIMITER}`) && args.includes(e)
1288
+ const value = key.includes('.') ? getValueByKeys(key.split('.'), e) : e[key]
1289
+ return _args.some((arg) => _performOperation(arg, value))
1201
1290
  })
1202
1291
  }
1203
1292
 
1204
- function _existObject(data, args) {
1205
- if (args.length !== 2) {
1206
- return []
1293
+ function _performOperation(arg, value) {
1294
+ // the arg is undefined
1295
+ if (arg === undefined && value === undefined) return true
1296
+
1297
+ // the arg is null
1298
+ if (arg === null && value === null) return true
1299
+
1300
+ // the arg is boolean
1301
+ if (typeof arg === 'boolean') {
1302
+ return arg === value
1303
+ }
1304
+
1305
+ // the arg is blank or *: Blank => Empty, * => Not Empty
1306
+ if (arg === '' || arg === '*') {
1307
+ // null and undefined are not included in either case
1308
+ if (value === null || value === undefined) {
1309
+ return false
1310
+ }
1311
+ if (typeof value === 'string') {
1312
+ return arg === '' ? value === '' : value !== ''
1313
+ }
1314
+ if (Array.isArray(value)) {
1315
+ return arg === '' ? value.length === 0 : value.length !== 0
1316
+ }
1317
+ return arg !== ''
1318
+ }
1319
+
1320
+ // the arg is alphabetic or number
1321
+ if (_isPureStringOrNumber(arg)) {
1322
+ return arg === value
1323
+ }
1324
+
1325
+ // the arg is array of [] or [*]: [] => Empty, [*] => Not Empty
1326
+ if (arg.startsWith('[') && arg.endsWith(']')) {
1327
+ if (arg === '[]') {
1328
+ return Array.isArray(value) && value.length === 0
1329
+ }
1330
+ if (arg === '[*]') {
1331
+ return Array.isArray(value) && value.length !== 0
1332
+ }
1333
+ return false
1334
+ }
1335
+
1336
+ // the arg is 'operator + string | number'
1337
+ const { operator, value: argValue } = _splitOperator(arg)
1338
+ if (!operator || (argValue !== 0 && !argValue)) {
1339
+ return false
1340
+ }
1341
+ switch (operator) {
1342
+ case '>':
1343
+ return value > argValue
1344
+ case '<':
1345
+ return value < argValue
1346
+ case '!=':
1347
+ return value !== argValue
1348
+ case '>=':
1349
+ return value >= argValue
1350
+ case '<=':
1351
+ return value <= argValue
1352
+ default:
1353
+ return false
1207
1354
  }
1208
- const [key, _args] = args
1209
- return data.filter((e) => {
1210
- return _args.includes(e[key])
1211
- })
1212
1355
  }
1213
1356
 
1357
+ function _isPureStringOrNumber(input) {
1358
+ if (typeof input === 'string') {
1359
+ if (input.startsWith('[') && input.endsWith(']')) {
1360
+ return false
1361
+ }
1362
+ if (/!=|>=|<=|>|</.test(input)) {
1363
+ return false
1364
+ }
1365
+ return true
1366
+ }
1367
+ return !Number.isNaN(input)
1368
+ }
1214
1369
 
1370
+ function _splitOperator(str) {
1371
+ const operators = ['!=', '>=', '<=', '>', '<']
1215
1372
 
1216
- ;// ./lib/models/template/helpers/_filterOne.js
1373
+ const matchedOp = operators.find((op) => str.startsWith(op))
1374
+ if (!matchedOp) return { operator: null, value: null }
1375
+
1376
+ const remaining = str.slice(matchedOp.length)
1377
+
1378
+ // '>Primary' or '<Primary' is invalid
1379
+ if (/^[a-zA-Z]*$/.test(remaining) && matchedOp !== '!=') {
1380
+ return { operator: null, value: null }
1381
+ }
1382
+
1383
+ // if it is a number it is converted to a number
1384
+ const value = (!Number.isNaN(parseFloat(remaining)) && !Number.isNaN(remaining)) ? Number(remaining) : remaining
1385
+
1386
+ return {
1387
+ operator: matchedOp,
1388
+ value
1389
+ }
1390
+ }
1391
+
1392
+
1393
+
1394
+ ;// ./lib/models/templateCompiler/helpers/_filterOne.js
1217
1395
 
1218
1396
 
1219
1397
 
1220
1398
  function _filterOne(data, args) {
1221
- const list = _filterAll(data, args)
1222
- if (list.length > 0) {
1223
- return list[0]
1399
+ try {
1400
+ const list = _filterAll(data, args)
1401
+ if (list.length === 1) {
1402
+ return list[0]
1403
+ }
1404
+ if (list.length === 0) {
1405
+ return null
1406
+ }
1407
+ throw new TemplateCompilerException(TEMPLATE_COMPILER_EXCEPTION_TYPE.resultMoreThanOneException)
1408
+ } catch (e) {
1409
+ throw e
1224
1410
  }
1225
- return null
1226
1411
  }
1227
1412
 
1228
1413
 
1229
1414
 
1230
- ;// ./lib/models/template/helpers/_get.js
1415
+ ;// ./lib/models/templateCompiler/helpers/_formatDate.js
1231
1416
 
1232
1417
 
1233
- function _get(data, key, failover = null) {
1234
- if (data === null || (typeof data === 'undefined') || key === '') {
1418
+ function _formatDate(timestamp, format) {
1419
+ if (format.length === 0) {
1420
+ throw new TemplateCompilerException(`_formateDate: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException}: format parts must be not empty array`)
1421
+ }
1422
+
1423
+ if (timestamp === null || timestamp === undefined) {
1235
1424
  return null
1236
- // throw new TemplateException(TEMPLATE_EXCEPTION_TYPE.argumentEmptyException)
1237
1425
  }
1238
1426
 
1239
- if (key.includes('.')) {
1240
- const parts = key.split('.')
1241
- if (parts.length > 1) {
1242
- const first = parts.shift()
1243
- const remainingKey = parts.join('.')
1244
- if (typeof data[first] !== 'undefined') {
1245
- return _get(data[first], remainingKey, failover)
1246
- }
1247
- return _handleFailover(key, failover)
1248
- }
1427
+ const date = new Date(timestamp)
1428
+
1429
+ const partsMap = {
1430
+ yyyy: String(date.getFullYear()),
1431
+ mm: String(date.getMonth() + 1).padStart(2, '0'),
1432
+ dd: String(date.getDate()).padStart(2, '0')
1249
1433
  }
1250
1434
 
1251
- if (typeof data[key] !== 'undefined') {
1252
- return data[key]
1435
+ // Check for invalid format tokens
1436
+ const validTokens = ['yyyy', 'mm', 'dd']
1437
+ const invalidTokens = format.filter((part) => part.length > 1 && !validTokens.includes(part))
1438
+
1439
+ if (invalidTokens.length > 0) {
1440
+ throw new TemplateCompilerException(
1441
+ `_formateDate: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException}: the format type is not valid: ${format.join(', ')}`
1442
+ )
1253
1443
  }
1254
1444
 
1255
- return _handleFailover(key, failover)
1445
+ // Build the formatted string using reduce
1446
+ return format.reduce((result, part) => result + (partsMap[part] || part), '')
1447
+ }
1448
+
1449
+
1450
+
1451
+ ;// ./lib/models/templateCompiler/helpers/_get.js
1452
+
1453
+
1454
+ function _get(data, key, failover = null) {
1455
+ try {
1456
+ if (key === null || (typeof key === 'undefined') || key === '') {
1457
+ throw new TemplateCompilerException(TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentEmptyException)
1458
+ }
1459
+ if (data === null) {
1460
+ return null
1461
+ }
1462
+ if (key.includes('.')) {
1463
+ const parts = key.split('.')
1464
+ if (parts.length > 1) {
1465
+ const first = parts.shift()
1466
+ const remainingKey = parts.join('.')
1467
+ if (typeof data[first] !== 'undefined') {
1468
+ return _get(data[first], remainingKey, failover)
1469
+ }
1470
+ return _handleFailover(key, failover)
1471
+ }
1472
+ }
1473
+ if (typeof data[key] !== 'undefined') {
1474
+ return data[key]
1475
+ }
1476
+ return _handleFailover(key, failover)
1477
+ } catch (e) {
1478
+ throw e
1479
+ }
1256
1480
  }
1257
1481
 
1258
1482
  function _handleFailover(key, failover) {
@@ -1260,108 +1484,396 @@ function _handleFailover(key, failover) {
1260
1484
  return failover
1261
1485
  }
1262
1486
  return null
1263
- // throw new TemplateException(`Key "${key}" does not exist and no failover`)
1487
+ // throw new TemplateCompilerException(`Key "${key}" does not exist and no failover`)
1488
+ }
1489
+
1490
+
1491
+
1492
+ ;// ./lib/models/templateCompiler/helpers/_gt.js
1493
+
1494
+
1495
+
1496
+
1497
+ function _gt(data, args) {
1498
+ if (args.length !== 3) {
1499
+ throw new TemplateCompilerException(`_gt: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException}: ${args.join(', ')}`)
1500
+ }
1501
+ if (data === null || (typeof data === 'undefined')) {
1502
+ return null
1503
+ }
1504
+ if (args.includes(_SELF)) {
1505
+ args = args.map((arg) => {
1506
+ return (arg === _SELF) ? data : arg
1507
+ })
1508
+ }
1509
+ const expected = args[0]
1510
+ return data > expected ? args[1] : args[2]
1511
+ }
1512
+
1513
+
1514
+
1515
+ ;// ./lib/models/templateCompiler/helpers/_gte.js
1516
+
1517
+
1518
+
1519
+
1520
+ function _gte(data, args) {
1521
+ if (args.length !== 3) {
1522
+ throw new TemplateCompilerException(`_gte: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException}: ${args.join(', ')}`)
1523
+ }
1524
+ if (data === null || (typeof data === 'undefined')) {
1525
+ return null
1526
+ }
1527
+ if (args.includes(_SELF)) {
1528
+ args = args.map((arg) => {
1529
+ return (arg === _SELF) ? data : arg
1530
+ })
1531
+ }
1532
+ const expected = args[0]
1533
+ return data >= expected ? args[1] : args[2]
1534
+ }
1535
+
1536
+
1537
+
1538
+ ;// ./lib/models/templateCompiler/helpers/_isEmpty.js
1539
+
1540
+
1541
+
1542
+
1543
+ function _isEmpty(data, args) {
1544
+ if (args.length !== 2) {
1545
+ throw new TemplateCompilerException(`_isEmpty: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException}: ${args.join(', ')}`)
1546
+ }
1547
+ // if (data === null || (typeof data === 'undefined')) {
1548
+ // return null
1549
+ // }
1550
+ if (args.includes(_SELF)) {
1551
+ args = args.map((arg) => {
1552
+ return (arg === _SELF) ? data : arg
1553
+ })
1554
+ }
1555
+ if (data !== null && typeof data === 'object' && Object.keys(data).length === 0) {
1556
+ return args[0]
1557
+ }
1558
+ return (data === '' || data === null || data === undefined || data.length === 0) ? args[0] : args[1]
1264
1559
  }
1265
1560
 
1266
1561
 
1267
1562
 
1268
- ;// ./lib/models/template/helpers/_join.js
1563
+ ;// ./lib/models/templateCompiler/helpers/_isNotEmpty.js
1564
+
1565
+
1566
+
1567
+
1568
+ function _isNotEmpty(data, args) {
1569
+ if (args.length !== 2) {
1570
+ throw new TemplateCompilerException(`_isNotEmpty: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException}: ${args.join(', ')}`)
1571
+ }
1572
+ // if (data === null || (typeof data === 'undefined')) {
1573
+ // return null
1574
+ // }
1575
+ if (args.includes(_SELF)) {
1576
+ args = args.map((arg) => {
1577
+ return (arg === _SELF) ? data : arg
1578
+ })
1579
+ }
1580
+ if (data !== null && typeof data === 'object' && Object.keys(data).length === 0) {
1581
+ return args[1]
1582
+ }
1583
+ if (Array.isArray(data) && data.length === 0) {
1584
+ return args[1]
1585
+ }
1586
+ if (typeof data === 'string' && data === '') {
1587
+ return args[1]
1588
+ }
1589
+ if (data === null || data === undefined) {
1590
+ return args[1]
1591
+ }
1592
+ return args[0]
1593
+ }
1594
+
1595
+
1596
+ ;// ./lib/models/templateCompiler/helpers/_join.js
1269
1597
  function _join(data, delimiter) {
1270
- return data.join(delimiter)
1598
+ try {
1599
+ if (data.length === 0) return ''
1600
+ if (data.length === 1) return _stringifyObject(data[0])
1601
+ return data.map((item) => _stringifyObject(item)).join(delimiter)
1602
+ } catch (e) {
1603
+ throw e
1604
+ }
1271
1605
  }
1272
1606
 
1607
+ function _stringifyObject(obj) {
1608
+ return JSON.stringify(obj).replace(/"([^"]+)":/g, '$1: ').replace(/"([^"]+)"/g, '$1').replace(/,/g, ', ')
1609
+ }
1273
1610
 
1274
1611
 
1275
- ;// ./lib/models/template/helpers/_map.js
1276
1612
 
1613
+ ;// ./lib/models/templateCompiler/helpers/_lt.js
1277
1614
 
1278
1615
 
1279
- function _map(data, args) {
1280
- if (data === null || (typeof data === 'undefined') || args.length === 0) {
1616
+
1617
+
1618
+ function _lt(data, args) {
1619
+ if (args.length !== 3) {
1620
+ throw new TemplateCompilerException(`_lt: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException}: ${args.join(', ')}`)
1621
+ }
1622
+ if (data === null || (typeof data === 'undefined')) {
1281
1623
  return null
1282
- // throw new TemplateException(TEMPLATE_EXCEPTION_TYPE.argumentEmptyException)
1283
1624
  }
1625
+ if (args.includes(_SELF)) {
1626
+ args = args.map((arg) => {
1627
+ return (arg === _SELF) ? data : arg
1628
+ })
1629
+ }
1630
+ const expected = args[0]
1631
+ return data < expected ? args[1] : args[2]
1632
+ }
1284
1633
 
1285
- const result = data.reduce((acc, item) => {
1286
- if (args.length === 1 && Array.isArray(args[0])) {
1287
- args = args[0]
1288
- acc.hasFormat = true
1634
+
1635
+
1636
+ ;// ./lib/models/templateCompiler/helpers/_lte.js
1637
+
1638
+
1639
+
1640
+
1641
+ function _lte(data, args) {
1642
+ if (args.length !== 3) {
1643
+ throw new TemplateCompilerException(`_lte: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException}: ${args.join(', ')}`)
1644
+ }
1645
+ if (data === null || (typeof data === 'undefined')) {
1646
+ return null
1647
+ }
1648
+ if (args.includes(_SELF)) {
1649
+ args = args.map((arg) => {
1650
+ return (arg === _SELF) ? data : arg
1651
+ })
1652
+ }
1653
+ const expected = args[0]
1654
+ return data <= expected ? args[1] : args[2]
1655
+ }
1656
+
1657
+
1658
+
1659
+ ;// ./lib/models/templateCompiler/helpers/_map.js
1660
+
1661
+
1662
+
1663
+ function _map(data, args) {
1664
+ try {
1665
+ if (args.length === 0) {
1666
+ throw new TemplateCompilerException(TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentEmptyException)
1289
1667
  }
1290
- const list = args.map((key) => {
1291
- if (key.includes('.')) {
1292
- const parts = key.split('.')
1293
- const first = parts[0]
1294
- parts.shift()
1295
- const remainingKey = parts.join('.')
1296
- return _get(item[first], remainingKey)
1668
+ if (data === null || (typeof data === 'undefined')) {
1669
+ return null
1670
+ }
1671
+
1672
+ const result = data.reduce((acc, item) => {
1673
+ if (args.length === 1 && Array.isArray(args[0])) {
1674
+ args = args[0]
1675
+ acc.hasFormat = true
1297
1676
  }
1298
- if (typeof item[key] !== 'undefined') {
1299
- return item[key]
1677
+ const list = args.map((key) => {
1678
+ if (key.includes('.')) {
1679
+ const parts = key.split('.')
1680
+ const first = parts[0]
1681
+ parts.shift()
1682
+ const remainingKey = parts.join('.')
1683
+ return _get(item[first], remainingKey)
1684
+ }
1685
+ if (typeof item[key] !== 'undefined') {
1686
+ return item[key]
1687
+ }
1688
+ return null
1689
+ })
1690
+ if (acc.hasFormat) {
1691
+ acc.content.push(list)
1692
+ } else {
1693
+ acc.content = acc.content.concat(list)
1300
1694
  }
1301
- return null
1302
- // throw new TemplateException('Key "$key" does not exist')
1695
+ return acc
1696
+ }, {
1697
+ content: [],
1698
+ hasFormat: false
1303
1699
  })
1304
- if (acc.hasFormat) {
1305
- acc.content.push(list)
1306
- } else {
1307
- acc.content = acc.content.concat(list)
1308
- }
1309
- return acc
1310
- }, {
1311
- content: [],
1312
- hasFormat: false
1313
- })
1314
- return result.content
1700
+ return result.content
1701
+ } catch (e) {
1702
+ throw e
1703
+ }
1315
1704
  }
1316
1705
 
1317
1706
 
1318
1707
 
1319
- ;// ./lib/models/template/helpers/index.js
1708
+ ;// ./lib/models/templateCompiler/helpers/_neq.js
1320
1709
 
1321
1710
 
1322
1711
 
1323
1712
 
1713
+ function _neq(data, args) {
1714
+ if (args.length !== 3) {
1715
+ throw new TemplateCompilerException(`_neq: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException}: ${args.join(', ')}`)
1716
+ }
1717
+ if (data === null || (typeof data === 'undefined')) {
1718
+ return null
1719
+ }
1720
+ if (args.includes(_SELF)) {
1721
+ args = args.map((arg) => {
1722
+ return (arg === _SELF) ? data : arg
1723
+ })
1724
+ }
1725
+ const expected = args[0]
1726
+ return data !== expected ? args[1] : args[2]
1727
+ }
1728
+
1729
+
1730
+
1731
+ ;// ./lib/models/templateCompiler/helpers/_toLowerCase.js
1732
+
1733
+
1734
+ function _toLowerCase(data, args) {
1735
+ if (args !== undefined) {
1736
+ throw new TemplateCompilerException(`_toLowerCase: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException}: ${args.join(', ')}`)
1737
+ }
1738
+ if (data === null || (typeof data === 'undefined') || typeof data !== 'string') {
1739
+ return null
1740
+ }
1741
+ return String(data).toLowerCase()
1742
+ }
1743
+
1744
+
1745
+
1746
+ ;// ./lib/models/templateCompiler/helpers/_toUpperCase.js
1747
+
1748
+
1749
+ function _toUpperCase(data, args) {
1750
+ if (typeof data !== 'string') {
1751
+ throw new TemplateCompilerException(`_toUpperCase: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException}: the data must be string: ${data}`)
1752
+ }
1753
+ if (args !== undefined) {
1754
+ throw new TemplateCompilerException(`_toUpperCase: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException}: the argument must be empty: ${args.join(', ')}`)
1755
+ }
1756
+ if (data === null || (typeof data === 'undefined') || typeof data !== 'string') {
1757
+ return null
1758
+ }
1759
+ return String(data).toUpperCase()
1760
+ }
1761
+
1324
1762
 
1325
1763
 
1764
+ ;// ./lib/models/templateCompiler/helpers/index.js
1326
1765
 
1327
1766
 
1328
1767
 
1329
- ;// ./lib/models/template/template.js
1330
1768
 
1331
1769
 
1332
1770
 
1333
1771
 
1334
- class Template {
1335
- constructor({ data }) {
1772
+
1773
+
1774
+
1775
+
1776
+
1777
+
1778
+
1779
+
1780
+
1781
+
1782
+
1783
+
1784
+
1785
+
1786
+ ;// ./lib/models/templateCompiler/templateCompiler.js
1787
+
1788
+
1789
+
1790
+
1791
+ class TemplateCompiler {
1792
+ constructor(data) {
1336
1793
  this.data = data
1337
1794
  }
1795
+ static init(options) {
1796
+ return new this(options)
1797
+ }
1798
+ static initFromArray(arr = []) {
1799
+ if (Array.isArray(arr)) {
1800
+ return arr.map((a) => this.init(a))
1801
+ }
1802
+ return []
1803
+ }
1804
+ static initOnlyValidFromArray(arr = []) {
1805
+ return this.initFromArray(arr).filter((i) => i)
1806
+ }
1807
+ static concatIf(data, args) {
1808
+ return _concatIf(data, args)
1809
+ }
1338
1810
  static eq(data, args) {
1339
1811
  return _eq(data, args)
1340
1812
  }
1813
+
1814
+ static filterAll(data, args) {
1815
+ return _filterAll(data, args)
1816
+ }
1817
+
1818
+ static formatDate(data, args) {
1819
+ return _formatDate(data, args)
1820
+ }
1821
+
1341
1822
  static get(data, key, failover = null) {
1342
1823
  return _get(data, key, failover)
1343
1824
  }
1825
+ static gt(data, args) {
1826
+ return _gt(data, args)
1827
+ }
1828
+ static gte(data, args) {
1829
+ return _gte(data, args)
1830
+ }
1831
+ static isEmpty(data, args) {
1832
+ return _isEmpty(data, args)
1833
+ }
1834
+ static isNotEmpty(data, args) {
1835
+ return _isNotEmpty(data, args)
1836
+ }
1344
1837
  static join(data, separator = '') {
1345
1838
  return _join(data, separator)
1346
1839
  }
1840
+ static lt(data, args) {
1841
+ return _lt(data, args)
1842
+ }
1843
+ static lte(data, args) {
1844
+ return _lte(data, args)
1845
+ }
1347
1846
  static map(data, args = []) {
1348
1847
  return _map(data, args)
1349
1848
  }
1849
+ static neq(data, args) {
1850
+ return _neq(data, args)
1851
+ }
1852
+ static toLowerCase(data, args) {
1853
+ return _toLowerCase(data, args)
1854
+ }
1855
+ static toUpperCase(data, args) {
1856
+ return _toUpperCase(data, args)
1857
+ }
1350
1858
  static parseFunction(expression) {
1351
1859
  return _parseFunction(expression, _FN_NAMES)
1352
1860
  }
1353
1861
 
1354
1862
  pipe(expression = '') {
1355
- this.delimiters = expression.substring(0,2) === '<%' ? TAGS_EJS : TAGS_HANDLEBAR
1863
+ this.delimiters = expression.substring(0, 2) === '{{' ? TAGS_HANDLEBAR : TAGS_EJS
1356
1864
  const regex = new RegExp(`${this.delimiters[0]}\\s(.*?)\\s${this.delimiters[1]}`)
1357
1865
  const match = expression.match(regex)
1358
1866
  if (match !== null) {
1359
- const functionList = _parseFunction(match[1], _FN_NAMES)
1360
- return functionList.reduce((acc, fn) => {
1361
- return _callFunction(acc, fn.name, fn.args)
1362
- }, this.data)
1867
+ try {
1868
+ const functionList = _parseFunction(match[1], _FN_NAMES)
1869
+ return functionList.reduce((acc, fn) => {
1870
+ return _callFunction(acc, fn.name, fn.args)
1871
+ }, this.data)
1872
+ } catch (e) {
1873
+ throw new TemplateCompilerException(`TemplateCompiler engine error: ${e.message}`)
1874
+ }
1363
1875
  }
1364
- throw new TemplateException(TEMPLATE_EXCEPTION_TYPE.invalu)
1876
+ throw new TemplateCompilerException(`TemplateCompiler engine error: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.invalidRegExpException}`)
1365
1877
  }
1366
1878
  }
1367
1879
 
@@ -1385,7 +1897,7 @@ function _parseFunction(expression, existFunctionNames) {
1385
1897
  args: paramList
1386
1898
  })
1387
1899
  } else {
1388
- throw new TemplateException(`${functionName} is not a valid function`)
1900
+ throw new TemplateCompilerException(`${functionName} is not a valid function`)
1389
1901
  }
1390
1902
  }
1391
1903
  return acc
@@ -1429,12 +1941,18 @@ function _parseSinglePart(input) {
1429
1941
  return input.substring(1, input.length - 1)
1430
1942
  }
1431
1943
 
1944
+ const _input = _toBasicType(input)
1945
+
1946
+ if (typeof _input !== 'string') {
1947
+ return _input
1948
+ }
1949
+
1432
1950
  // 如果是一个列表形式(例如 ["p", "d"] 或 [p, d])
1433
- if (input.startsWith('[') && input.endsWith(']')) {
1434
- const listContent = input.substring(1, input.length - 1).trim()
1951
+ if (_input.startsWith('[') && _input.endsWith(']')) {
1952
+ const listContent = _input.substring(1, _input.length - 1).trim()
1435
1953
  if (listContent !== '') {
1436
1954
  return listContent.split(',').map((item) => {
1437
- return item.trim().replaceAll('"', '') // 去除可能的双引号
1955
+ return _toBasicType(item.trim())
1438
1956
  })
1439
1957
  }
1440
1958
  return []
@@ -1444,66 +1962,86 @@ function _parseSinglePart(input) {
1444
1962
  return input
1445
1963
  }
1446
1964
 
1965
+ function _toBasicType(input) {
1966
+ if (input.startsWith('"') && input.endsWith('"')) {
1967
+ // 去掉双引号,返回
1968
+ return input.substring(1, input.length - 1)
1969
+ }
1970
+ if (input === 'true') {
1971
+ return true
1972
+ }
1973
+ if (input === 'false') {
1974
+ return false
1975
+ }
1976
+ if (input === 'undefined') {
1977
+ return undefined
1978
+ }
1979
+ if (input === 'null') {
1980
+ return null
1981
+ }
1982
+ if (!Number.isNaN(input) && !Number.isNaN(Number.parseFloat(input))) {
1983
+ return Number(input)
1984
+ }
1985
+ return input
1986
+ }
1987
+
1447
1988
  function _callFunction(data, functionName, parameters) {
1448
- let failover
1449
- switch (functionName) {
1450
- case 'get':
1451
- if (parameters.length > 2) {
1452
- throw new TemplateException(TEMPLATE_EXCEPTION_TYPE.argumentFormatException)
1453
- }
1454
- if (parameters.length === 2) {
1455
- failover = parameters[parameters.length - 1]
1456
- }
1457
- return _get(data, parameters[0], failover)
1458
- case 'map':
1459
- return _map(data, parameters)
1460
- case 'join':
1461
- return _join(data, parameters[0])
1462
- // case 'concatIf':
1463
- // if (parameters.length != 3) {
1464
- // throw const TemplateException(TemplateExceptionType.argumentFormatException);
1465
- // }
1466
- // var condition = parameters.first;
1467
- // var success = parameters[1];
1468
- // var failover = parameters[2];
1469
- // return _concatIf(data, condition, success, failover);
1470
- case 'filterOne':
1471
- return _filterOne(data, parameters)
1472
- case 'filterAll':
1473
- return _filterAll(data, parameters)
1474
- // case 'formatDate':
1475
- // if (parameters is List<String>) {
1476
- // return _formatDate(data, parameters);
1477
- // }
1478
- // throw const TemplateException(TemplateExceptionType.argumentFormatException);
1479
- case 'eq':
1480
- return _eq(data, parameters)
1481
- // case 'neq':
1482
- // return _neq(data, parameters);
1483
- // case 'gt':
1484
- // return _gt(data, parameters);
1485
- // case 'gte':
1486
- // return _gte(data, parameters);
1487
- // case 'lt':
1488
- // return _lt(data, parameters);
1489
- // case 'lte':
1490
- // return _lte(data, parameters);
1491
- // case 'isEmpty':
1492
- // return _isEmpty(data, parameters);
1493
- // case 'isNotEmpty':
1494
- // return _isNotEmpty(data, parameters);
1495
- // case 'toLowerCase':
1496
- // return _toLowerCase(data);
1497
- // case 'toUpperCase':
1498
- // return _toUpperCase(data);
1499
- default:
1500
- throw new Error(`${functionName} is not a valid function`)
1989
+ try {
1990
+ let failover
1991
+ switch (functionName) {
1992
+ case 'exec':
1993
+ return _exec(data, parameters)
1994
+ case 'get':
1995
+ if (parameters.length > 2) {
1996
+ throw new TemplateCompilerException(TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException)
1997
+ }
1998
+ if (parameters.length === 2) {
1999
+ failover = parameters[parameters.length - 1]
2000
+ }
2001
+ return _get(data, parameters[0], failover)
2002
+ case 'join':
2003
+ return _join(data, parameters[0])
2004
+ case 'map':
2005
+ return _map(data, parameters)
2006
+ case 'concatIf':
2007
+ return _concatIf(data, parameters)
2008
+ case 'filterOne':
2009
+ return _filterOne(data, parameters)
2010
+ case 'filterAll':
2011
+ return _filterAll(data, parameters)
2012
+ case 'formatDate':
2013
+ return _formatDate(data, parameters)
2014
+ case 'eq':
2015
+ return _eq(data, parameters)
2016
+ case 'neq':
2017
+ return _neq(data, parameters)
2018
+ case 'gt':
2019
+ return _gt(data, parameters)
2020
+ case 'gte':
2021
+ return _gte(data, parameters)
2022
+ case 'lt':
2023
+ return _lt(data, parameters)
2024
+ case 'lte':
2025
+ return _lte(data, parameters)
2026
+ case 'isEmpty':
2027
+ return _isEmpty(data, parameters)
2028
+ case 'isNotEmpty':
2029
+ return _isNotEmpty(data, parameters)
2030
+ case 'toLowerCase':
2031
+ return _toLowerCase(data)
2032
+ case 'toUpperCase':
2033
+ return _toUpperCase(data)
2034
+ default:
2035
+ throw new Error(`${functionName} is not a valid function`)
2036
+ }
2037
+ } catch (e) {
2038
+ throw e
1501
2039
  }
1502
2040
  }
1503
2041
 
1504
2042
 
1505
2043
 
1506
- ;// ./lib/models/template/index.js
2044
+ ;// ./lib/models/templateCompiler/index.js
1507
2045
 
1508
2046
 
1509
2047
 
@@ -1765,7 +2303,7 @@ var __webpack_exports__Metadata = __webpack_exports__.OS;
1765
2303
  var __webpack_exports__QMeta = __webpack_exports__.Z8;
1766
2304
  var __webpack_exports__Repo = __webpack_exports__.lc;
1767
2305
  var __webpack_exports__Service = __webpack_exports__.kl;
1768
- var __webpack_exports__Template = __webpack_exports__.Bj;
2306
+ var __webpack_exports__TemplateCompiler = __webpack_exports__.Mg;
1769
2307
  var __webpack_exports__UniqueKeyGenerator = __webpack_exports__._x;
1770
2308
  var __webpack_exports__convertString = __webpack_exports__.l0;
1771
2309
  var __webpack_exports__formatDate = __webpack_exports__.Yq;
@@ -1779,4 +2317,4 @@ var __webpack_exports__pReduce = __webpack_exports__.d;
1779
2317
  var __webpack_exports__padZeros = __webpack_exports__.Lv;
1780
2318
  var __webpack_exports__stringFormatter = __webpack_exports__.Qy;
1781
2319
  var __webpack_exports__stringHelper = __webpack_exports__.yO;
1782
- 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__Template as Template, __webpack_exports__UniqueKeyGenerator as UniqueKeyGenerator, __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 };
2320
+ 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__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 };