@areumtecnologia/mysql-db-handler 2.0.3 → 2.1.0
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/README.md +37 -13
- package/index.d.ts +1 -1
- package/lib/databaseHandler.js +64 -19
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -522,9 +522,11 @@ app.post('/api/users/datatable', async (req, res) => {
|
|
|
522
522
|
|
|
523
523
|
---
|
|
524
524
|
|
|
525
|
-
### Enforcing Backend Security (`strictCondition`)
|
|
525
|
+
### Enforcing Backend Security & Custom Filters (`strictCondition`)
|
|
526
526
|
|
|
527
|
-
Never rely on
|
|
527
|
+
Never rely solely on client frontend parameters to enforce data boundaries or custom business filters. Pass `strictCondition` to apply non-bypassable constraints.
|
|
528
|
+
|
|
529
|
+
`strictCondition` supports both **Array syntax** (with custom operators, arrays mapped to `IN`, and explicit `'AND'`/`'OR'`) and **Plain Object syntax** (multiple properties are automatically combined with `AND`):
|
|
528
530
|
|
|
529
531
|
```javascript
|
|
530
532
|
app.post('/api/orders/datatable', async (req, res) => {
|
|
@@ -542,17 +544,39 @@ app.post('/api/orders/datatable', async (req, res) => {
|
|
|
542
544
|
});
|
|
543
545
|
```
|
|
544
546
|
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
547
|
+
---
|
|
548
|
+
|
|
549
|
+
### Handling Custom Frontend Filters (e.g., Status, Dates, Categories)
|
|
550
|
+
|
|
551
|
+
When users apply custom UI filters (dropdowns, datepickers, checkboxes) alongside DataTables, capture them in your controller and pass them into `strictCondition`:
|
|
552
|
+
|
|
553
|
+
```javascript
|
|
554
|
+
app.post('/api/clientes/datatable', async (req, res) => {
|
|
555
|
+
const filters = [];
|
|
556
|
+
|
|
557
|
+
// Map UI filter (e.g. 'HABILITADO') to database column ('active' = 1 / 0)
|
|
558
|
+
if (req.body.status) {
|
|
559
|
+
filters.push({ active: req.body.status === 'HABILITADO' ? 1 : 0 });
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
if (req.body.created_after) {
|
|
563
|
+
if (filters.length > 0) filters.push('AND');
|
|
564
|
+
filters.push({ created_at: req.body.created_after, operator: '>=' });
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
// Pass request body + backend-mapped filters
|
|
568
|
+
const result = await clientesHandler.selectToDatatable(req.body, filters);
|
|
569
|
+
res.json(result);
|
|
570
|
+
});
|
|
571
|
+
```
|
|
572
|
+
|
|
573
|
+
> [!TIP]
|
|
574
|
+
> **DataTables Modern Protocol Support (v1.10, v2.x, v3.x):**
|
|
575
|
+
> `selectToDatatable` automatically normalizes:
|
|
576
|
+
> - **Search**: supports standard `{ value: '...', regex: false }`, direct strings (`search: '...'`), and query fallbacks (`q`).
|
|
577
|
+
> - **Columns**: accepts both standard `Array` and index-keyed objects (`{ '0': {...}, '1': {...} }`).
|
|
578
|
+
> - **Ordering**: supports ordering by column index (`order: [{ column: 0, dir: 'asc' }]`) and by column name (`order: [{ name: 'col_name', dir: 'desc' }]`).
|
|
579
|
+
> - **Payload collision**: prevents bracketed keys (`search[value]`) from being corrupted by flat parameters.
|
|
556
580
|
|
|
557
581
|
---
|
|
558
582
|
|
package/index.d.ts
CHANGED
|
@@ -184,7 +184,7 @@ export class DataBaseHandler<T = RowDataPacket> {
|
|
|
184
184
|
|
|
185
185
|
// Core Operations
|
|
186
186
|
paginate(options?: PaginateOptions): Promise<PaginatedResult<T>>;
|
|
187
|
-
selectToDatatable(rawDtQuery: Record<string, any>, strictCondition?: any[]): Promise<{
|
|
187
|
+
selectToDatatable(rawDtQuery: Record<string, any>, strictCondition?: any[] | Record<string, any>): Promise<{
|
|
188
188
|
draw: number;
|
|
189
189
|
recordsTotal: number;
|
|
190
190
|
recordsFiltered: number;
|
package/lib/databaseHandler.js
CHANGED
|
@@ -670,7 +670,15 @@ class DatabaseHandler {
|
|
|
670
670
|
for (const key of Object.keys(flatObject)) {
|
|
671
671
|
if (!key.includes('[')) {
|
|
672
672
|
if (key !== '__proto__' && key !== 'constructor' && key !== 'prototype') {
|
|
673
|
-
|
|
673
|
+
const existing = result[key];
|
|
674
|
+
const incoming = flatObject[key];
|
|
675
|
+
if (existing && typeof existing === 'object' && (!incoming || typeof incoming !== 'object')) {
|
|
676
|
+
// Não sobrescreve um objeto já estruturado (ex: search vindo de search[value]) com valor primitivo
|
|
677
|
+
} else if (existing && typeof existing === 'object' && incoming && typeof incoming === 'object') {
|
|
678
|
+
result[key] = { ...existing, ...incoming };
|
|
679
|
+
} else {
|
|
680
|
+
result[key] = incoming;
|
|
681
|
+
}
|
|
674
682
|
}
|
|
675
683
|
continue;
|
|
676
684
|
}
|
|
@@ -684,7 +692,7 @@ class DatabaseHandler {
|
|
|
684
692
|
for (let i = 0; i < keys.length - 1; i++) {
|
|
685
693
|
const k = keys[i];
|
|
686
694
|
const nextKey = keys[i + 1];
|
|
687
|
-
if (current[k] === undefined) {
|
|
695
|
+
if (current[k] === undefined || current[k] === null || typeof current[k] !== 'object') {
|
|
688
696
|
current[k] = !isNaN(nextKey) ? [] : {};
|
|
689
697
|
}
|
|
690
698
|
current = current[k];
|
|
@@ -954,7 +962,18 @@ class DatabaseHandler {
|
|
|
954
962
|
const parsedDraw = parseInt(draw, 10) || 0;
|
|
955
963
|
|
|
956
964
|
try {
|
|
957
|
-
|
|
965
|
+
let finalStrict = [];
|
|
966
|
+
if (Array.isArray(strictCondition)) {
|
|
967
|
+
finalStrict = [...strictCondition];
|
|
968
|
+
} else if (strictCondition && typeof strictCondition === 'object') {
|
|
969
|
+
const entries = Object.entries(strictCondition);
|
|
970
|
+
for (let i = 0; i < entries.length; i++) {
|
|
971
|
+
const [k, v] = entries[i];
|
|
972
|
+
if (i > 0) finalStrict.push('AND');
|
|
973
|
+
finalStrict.push({ [k]: v });
|
|
974
|
+
}
|
|
975
|
+
}
|
|
976
|
+
|
|
958
977
|
const softCol = this._getSoftDeleteColumn();
|
|
959
978
|
if (softCol && !this._qb.withTrashed) {
|
|
960
979
|
if (finalStrict.length > 0) finalStrict.push('AND');
|
|
@@ -969,14 +988,25 @@ class DatabaseHandler {
|
|
|
969
988
|
const finalBindings = [...baseWhere.bindings];
|
|
970
989
|
const finalWhereClauses = baseWhere.sql ? [baseWhere.sql] : [];
|
|
971
990
|
|
|
991
|
+
// Normaliza columns para suportar tanto Array quanto Objeto indexado ({ '0': {...}, '1': {...} })
|
|
992
|
+
const colsArray = Array.isArray(columns)
|
|
993
|
+
? columns
|
|
994
|
+
: (columns && typeof columns === 'object' ? Object.values(columns) : []);
|
|
995
|
+
|
|
972
996
|
const dtSearchClauses = [];
|
|
973
|
-
if (
|
|
974
|
-
|
|
975
|
-
|
|
997
|
+
if (colsArray.length > 0) {
|
|
998
|
+
// Normaliza o termo de busca global (suporta search.value, string direta ou fallback q)
|
|
999
|
+
const rawSearchVal = typeof search === 'string'
|
|
1000
|
+
? search
|
|
1001
|
+
: (search && search.value != null ? search.value : (dtQuery.q != null ? dtQuery.q : ''));
|
|
1002
|
+
const globalSearchTerm = String(rawSearchVal ?? '').trim();
|
|
1003
|
+
|
|
1004
|
+
if (globalSearchTerm !== '') {
|
|
1005
|
+
const searchableCols = colsArray.filter(c => c && c.data && isTrue(c.searchable));
|
|
976
1006
|
if (searchableCols.length > 0) {
|
|
977
|
-
const isRegex = isTrue(search.regex);
|
|
1007
|
+
const isRegex = (typeof search === 'object' && search !== null) ? isTrue(search.regex) : false;
|
|
978
1008
|
const operator = isRegex ? 'REGEXP' : 'LIKE';
|
|
979
|
-
const term = isRegex ?
|
|
1009
|
+
const term = isRegex ? globalSearchTerm : `%${globalSearchTerm}%`;
|
|
980
1010
|
|
|
981
1011
|
const orClauses = searchableCols.map(c => `${safeColumn(c.data)} ${operator} ?`);
|
|
982
1012
|
dtSearchClauses.push(`(${orClauses.join(' OR ')})`);
|
|
@@ -986,14 +1016,23 @@ class DatabaseHandler {
|
|
|
986
1016
|
}
|
|
987
1017
|
}
|
|
988
1018
|
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
const
|
|
993
|
-
const
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
1019
|
+
// Busca individual por coluna
|
|
1020
|
+
for (const col of colsArray) {
|
|
1021
|
+
if (col && col.data && isTrue(col.searchable)) {
|
|
1022
|
+
const colSearch = col.search;
|
|
1023
|
+
const colVal = typeof colSearch === 'string'
|
|
1024
|
+
? colSearch
|
|
1025
|
+
: (colSearch && colSearch.value != null ? colSearch.value : '');
|
|
1026
|
+
const colSearchTerm = String(colVal ?? '').trim();
|
|
1027
|
+
|
|
1028
|
+
if (colSearchTerm !== '') {
|
|
1029
|
+
const isRegex = (typeof colSearch === 'object' && colSearch !== null) ? isTrue(colSearch.regex) : false;
|
|
1030
|
+
const operator = isRegex ? 'REGEXP' : 'LIKE';
|
|
1031
|
+
const term = isRegex ? colSearchTerm : `%${colSearchTerm}%`;
|
|
1032
|
+
|
|
1033
|
+
dtSearchClauses.push(`${safeColumn(col.data)} ${operator} ?`);
|
|
1034
|
+
finalBindings.push(term);
|
|
1035
|
+
}
|
|
997
1036
|
}
|
|
998
1037
|
}
|
|
999
1038
|
}
|
|
@@ -1008,12 +1047,18 @@ class DatabaseHandler {
|
|
|
1008
1047
|
const joinClause = this._buildJoinClauses(this._qb.joins);
|
|
1009
1048
|
|
|
1010
1049
|
let orderSql = '';
|
|
1011
|
-
if (order &&
|
|
1050
|
+
if (order && colsArray.length > 0) {
|
|
1012
1051
|
const orderArray = Array.isArray(order) ? order : Object.values(order);
|
|
1013
1052
|
const orderParts = [];
|
|
1014
1053
|
for (const ord of orderArray) {
|
|
1015
|
-
if (!ord
|
|
1016
|
-
|
|
1054
|
+
if (!ord) continue;
|
|
1055
|
+
let colDef = null;
|
|
1056
|
+
if (ord.column !== undefined && ord.column !== null && ord.column !== '') {
|
|
1057
|
+
colDef = colsArray[parseInt(ord.column, 10)];
|
|
1058
|
+
} else if (ord.name || ord.data) {
|
|
1059
|
+
const targetName = ord.name || ord.data;
|
|
1060
|
+
colDef = colsArray.find(c => c && (c.name === targetName || c.data === targetName));
|
|
1061
|
+
}
|
|
1017
1062
|
if (colDef && isTrue(colDef.orderable) && colDef.data) {
|
|
1018
1063
|
const orderDir = ord.dir && String(ord.dir).toUpperCase() === 'ASC' ? 'ASC' : 'DESC';
|
|
1019
1064
|
orderParts.push(`${safeColumn(colDef.data)} ${orderDir}`);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@areumtecnologia/mysql-db-handler",
|
|
3
|
-
"version": "2.0
|
|
3
|
+
"version": "2.1.0",
|
|
4
4
|
"description": "High-scale enterprise Micro-ORM and MySQL Data Mapper with connection pooling, read/write splitting, eager loading, keyset pagination, soft deletes, and fluent query builder for Node.js.",
|
|
5
5
|
"main": "index.js",
|
|
6
6
|
"types": "index.d.ts",
|