@areumtecnologia/mysql-db-handler 2.0.0 → 2.0.1
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 +126 -10
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -325,16 +325,70 @@ console.log('Deleted rows:', result.affectedRows);
|
|
|
325
325
|
|
|
326
326
|
## jQuery DataTables Server-Side Support (`selectToDatatable`)
|
|
327
327
|
|
|
328
|
-
The `selectToDatatable` method provides seamless, high-performance integration with [jQuery DataTables](https://datatables.net/) server-side processing. It automatically
|
|
328
|
+
The `selectToDatatable` method provides seamless, enterprise-grade, high-performance integration with [jQuery DataTables](https://datatables.net/) server-side processing. It eliminates manual SQL pagination boilerplate, automatically handling pagination, search (global and column-specific), multi-column ordering, regex filters, dual-count latency optimizations, backend security constraints, Soft Deletes, and sensitive field masking.
|
|
329
|
+
|
|
330
|
+
---
|
|
331
|
+
|
|
332
|
+
### Step-by-Step Execution Lifecycle (Under the Hood)
|
|
333
|
+
|
|
334
|
+
Whenever `selectToDatatable(rawDtQuery, strictCondition)` is invoked, it executes the following optimized workflow:
|
|
335
|
+
|
|
336
|
+
```
|
|
337
|
+
[Incoming Request] (req.body or req.query)
|
|
338
|
+
│
|
|
339
|
+
▼
|
|
340
|
+
1. Hydration & Security Filter
|
|
341
|
+
• Flattens or parses bracketed keys (e.g. columns[0][data] -> { columns: [{ data: ... }] })
|
|
342
|
+
• Prototype Pollution Guard: Sanitizes __proto__, constructor, and prototype (CWE-1321)
|
|
343
|
+
• Sanitizes integers (draw, start, length) preventing NaN injections
|
|
344
|
+
│
|
|
345
|
+
▼
|
|
346
|
+
2. Backend Security & Tenant Scoping (strictCondition)
|
|
347
|
+
• Injects non-bypassable backend filters (tenant_id, account_id, branch, etc.)
|
|
348
|
+
• [v2.0.0] Injects Soft Delete filter (deletado_em IS NULL) automatically unless withTrashed() is active
|
|
349
|
+
│
|
|
350
|
+
▼
|
|
351
|
+
3. Search Clause Generation
|
|
352
|
+
• Global Search (search.value): Checks all columns where searchable == true -> (col1 LIKE ? OR col2 LIKE ?)
|
|
353
|
+
• Column-Specific Search (columns[i].search.value): Checks individual columns -> AND colN LIKE ?
|
|
354
|
+
• Regex Toggle: If regex == true, switches operator from LIKE %term% to REGEXP term
|
|
355
|
+
• Parameterized bindings: All terms use prepared statement placeholders (?) to block SQL injection
|
|
356
|
+
│
|
|
357
|
+
▼
|
|
358
|
+
4. Dual-COUNT Latency Optimization
|
|
359
|
+
• No Active Search Filter: Only 1 COUNT(*) query is executed. recordsFiltered is instantly set to recordsTotal (up to 50% database I/O reduction).
|
|
360
|
+
• Active Search Filter: Executes total COUNT(*) and filtered COUNT(*) concurrently via Promise.all().
|
|
361
|
+
│
|
|
362
|
+
▼
|
|
363
|
+
5. Short-Circuit Check
|
|
364
|
+
• If recordsFiltered === 0: The data SELECT query is skipped entirely. Returns data: [] immediately, avoiding expensive filesort and buffer allocations.
|
|
365
|
+
│
|
|
366
|
+
▼
|
|
367
|
+
6. Multi-Column Ordering & Keyset Limitation
|
|
368
|
+
• Parses all order directives (order[0], order[1], etc.)
|
|
369
|
+
• Maps column index to sanitized column name (e.g. `col1` ASC, `col2` DESC)
|
|
370
|
+
• Generates LIMIT start, length safely
|
|
371
|
+
│
|
|
372
|
+
▼
|
|
373
|
+
7. Data Retrieval & Sensitive Field Masking
|
|
374
|
+
• Executes SELECT <columns> FROM <table> [JOINS] [WHERE] [ORDER BY] [LIMIT]
|
|
375
|
+
• [v2.0.0] Strips any fields declared in hiddenFields (e.g. senha_hash, token) before output
|
|
376
|
+
│
|
|
377
|
+
▼
|
|
378
|
+
[Standard JSON Response to DataTables]
|
|
379
|
+
```
|
|
380
|
+
|
|
381
|
+
---
|
|
329
382
|
|
|
330
383
|
### Key Features & Performance Optimizations
|
|
331
384
|
|
|
332
|
-
* **Smart Single `COUNT(*)`:** When no client-side search filter is active (the default state
|
|
385
|
+
* **Smart Single `COUNT(*)`:** When no client-side search filter is active (the default state during initial page load, sorting, and standard pagination), `recordsFiltered` is automatically set to `recordsTotal`. The method skips the redundant second `COUNT(*)` query, **reducing database count latency and I/O by up to 50%**.
|
|
333
386
|
* **Short-Circuit on Zero Results:** If search criteria yield zero records (`recordsFiltered === 0`), the data retrieval query (`SELECT ... LIMIT`) is skipped entirely, returning an empty array `data: []` instantly without triggering expensive `filesort` or index scans.
|
|
334
387
|
* **Format & Content-Type Agnostic:** Fully supports both `application/json` (with native JavaScript boolean values `true`/`false`) and `application/x-www-form-urlencoded` (nested or bracket-flattened parameters like `columns[0][data]`).
|
|
335
388
|
* **Multi-Column Sorting:** Seamlessly parses multiple order directives (e.g. holding Shift or configuring `order: [[0, 'asc'], [1, 'desc']]`), producing `ORDER BY \`col1\` ASC, \`col2\` DESC`.
|
|
336
389
|
* **Safe Qualified Column Identifiers:** Automatically splits table/alias qualified column names (e.g. `u.name`, `p.title`) and escapes each component separately (`` `u`.`name` ``), avoiding MySQL `ER_BAD_FIELD_ERROR` issues when using JOINs.
|
|
337
390
|
* **Prototype Pollution Protection (CWE-1321):** Deeply sanitizes incoming request keys, blocking injections targeting `__proto__`, `constructor`, or `prototype`.
|
|
391
|
+
* **[v2.0.0] Soft Delete & Hidden Fields Aware:** Automatically excludes soft-deleted records (`deletado_em IS NULL`) and strips sensitive columns (`hiddenFields`) from the returned JSON.
|
|
338
392
|
|
|
339
393
|
---
|
|
340
394
|
|
|
@@ -344,10 +398,24 @@ The `selectToDatatable` method provides seamless, high-performance integration w
|
|
|
344
398
|
await handler.selectToDatatable(rawDtQuery, strictCondition = [])
|
|
345
399
|
```
|
|
346
400
|
|
|
347
|
-
|
|
401
|
+
#### Parameters
|
|
402
|
+
|
|
403
|
+
| Parameter | Type | Required | Description |
|
|
404
|
+
| :--- | :--- | :---: | :--- |
|
|
405
|
+
| `rawDtQuery` | `Object` | **Yes** | The request payload sent by jQuery DataTables (`req.body` in POST or `req.query` in GET). Supports both bracket-flattened keys and nested JSON. |
|
|
406
|
+
| `strictCondition` | `Array` \| `Object` | No | Backend constraints that the client cannot view or modify (e.g. multi-tenant isolation, user scoping, active-only filters). |
|
|
407
|
+
|
|
408
|
+
#### DataTables Payload Schema (`rawDtQuery`)
|
|
409
|
+
|
|
410
|
+
| Field | Type | Description |
|
|
348
411
|
| :--- | :--- | :--- |
|
|
349
|
-
| `
|
|
350
|
-
| `
|
|
412
|
+
| `draw` | `number` \| `string` | Draw counter echoed back to the client to ensure response synchronization. |
|
|
413
|
+
| `start` | `number` \| `string` | Zero-based paging first record indicator (`OFFSET`). Defaults to `0`. |
|
|
414
|
+
| `length` | `number` \| `string` | Number of records to return (`LIMIT`). |
|
|
415
|
+
| `search.value` | `string` | Global search value applied across all columns with `searchable: true`. |
|
|
416
|
+
| `search.regex` | `boolean` \| `string` | If `true` or `'true'`, uses MySQL `REGEXP` instead of `LIKE %value%`. |
|
|
417
|
+
| `order` | `Array<Object>` | Array of order objects: `{ column: 0, dir: 'asc' \| 'desc' }`. |
|
|
418
|
+
| `columns` | `Array<Object>` | Array of column definitions: `{ data: 'col_name', searchable: true, orderable: true, search: { value: '', regex: false } }`. |
|
|
351
419
|
|
|
352
420
|
---
|
|
353
421
|
|
|
@@ -372,7 +440,7 @@ app.post('/api/users/datatable', async (req, res) => {
|
|
|
372
440
|
|
|
373
441
|
### Enforcing Backend Security (`strictCondition`)
|
|
374
442
|
|
|
375
|
-
Never rely on the client to enforce data
|
|
443
|
+
Never rely on the client frontend to enforce data boundaries. Pass a `strictCondition` array to apply non-bypassable constraints. It shares the same query-building syntax as `select()`, supporting custom operators, arrays (`IN`), and `AND`/`OR` conjunctions:
|
|
376
444
|
|
|
377
445
|
```javascript
|
|
378
446
|
app.post('/api/orders/datatable', async (req, res) => {
|
|
@@ -392,9 +460,33 @@ app.post('/api/orders/datatable', async (req, res) => {
|
|
|
392
460
|
|
|
393
461
|
---
|
|
394
462
|
|
|
395
|
-
### Using JOINs
|
|
463
|
+
### Using JOINs with DataTables
|
|
464
|
+
|
|
465
|
+
#### Option A: Modern Fluent Query Builder Joins (Recommended in v2.0.0)
|
|
466
|
+
Chain `.selectFields()` and `.leftJoin()` / `.join()` directly with `.selectToDatatable()`:
|
|
467
|
+
|
|
468
|
+
```javascript
|
|
469
|
+
app.post('/api/pedidos/datatable', async (req, res) => {
|
|
470
|
+
const result = await pedidosHandler
|
|
471
|
+
.selectFields([
|
|
472
|
+
'pedidos.id',
|
|
473
|
+
'pedidos.valor',
|
|
474
|
+
'pedidos.criado_em',
|
|
475
|
+
{ column: 'c.nome', as: 'cliente_nome' },
|
|
476
|
+
{ column: 'v.nome', as: 'vendedor_nome' }
|
|
477
|
+
])
|
|
478
|
+
.leftJoin('clientes c', 'pedidos.cliente_id', '=', 'c.id')
|
|
479
|
+
.leftJoin('vendedores v', 'pedidos.vendedor_id', '=', 'v.id')
|
|
480
|
+
.selectToDatatable(req.body, [
|
|
481
|
+
{ 'pedidos.empresa_id': req.user.empresaId }
|
|
482
|
+
]);
|
|
483
|
+
|
|
484
|
+
res.json(result);
|
|
485
|
+
});
|
|
486
|
+
```
|
|
396
487
|
|
|
397
|
-
|
|
488
|
+
#### Option B: Legacy Expression Parameter
|
|
489
|
+
You can also initialize the handler with a SQL expression containing the JOINs and selected columns:
|
|
398
490
|
|
|
399
491
|
```javascript
|
|
400
492
|
// Table: 'sales s'
|
|
@@ -408,8 +500,7 @@ const salesHandler = new DataBaseHandler(
|
|
|
408
500
|
);
|
|
409
501
|
|
|
410
502
|
app.post('/api/sales/datatable', async (req, res) => {
|
|
411
|
-
// DataTables columns can
|
|
412
|
-
// e.g. columns: [{ data: 's.id' }, { data: 'c.name' }, { data: 's.amount' }]
|
|
503
|
+
// DataTables columns can search and sort by qualified identifiers (e.g. 'c.name')
|
|
413
504
|
const result = await salesHandler.selectToDatatable(req.body, [
|
|
414
505
|
{ 's.deleted_at': null, operator: 'IS' }
|
|
415
506
|
]);
|
|
@@ -419,6 +510,31 @@ app.post('/api/sales/datatable', async (req, res) => {
|
|
|
419
510
|
|
|
420
511
|
---
|
|
421
512
|
|
|
513
|
+
### Soft Deletes & Sensitive Fields in DataTables (v2.0.0)
|
|
514
|
+
|
|
515
|
+
When configuring business rules on the handler, `selectToDatatable` automatically complies without requiring manual filters:
|
|
516
|
+
|
|
517
|
+
```javascript
|
|
518
|
+
const clientesHandler = new DatabaseHandler(db, 'clientes', {
|
|
519
|
+
softDelete: 'deletado_em', // Injeta 'AND deletado_em IS NULL' automaticamente
|
|
520
|
+
hiddenFields: ['senha_hash', 'token_recuperacao'] // Remove do retorno mesmo se 'SELECT *' for usado
|
|
521
|
+
});
|
|
522
|
+
|
|
523
|
+
// A consulta abaixo já ignora excluídos e nunca expõe senha_hash
|
|
524
|
+
app.post('/api/clientes/datatable', async (req, res) => {
|
|
525
|
+
const result = await clientesHandler.selectToDatatable(req.body);
|
|
526
|
+
res.json(result);
|
|
527
|
+
});
|
|
528
|
+
|
|
529
|
+
// Para consultar registos da lixeira (soft-deleted):
|
|
530
|
+
app.post('/api/clientes/trash/datatable', async (req, res) => {
|
|
531
|
+
const result = await clientesHandler.onlyTrashed().selectToDatatable(req.body);
|
|
532
|
+
res.json(result);
|
|
533
|
+
});
|
|
534
|
+
```
|
|
535
|
+
|
|
536
|
+
---
|
|
537
|
+
|
|
422
538
|
### Frontend jQuery DataTables Setup
|
|
423
539
|
|
|
424
540
|
Configure your frontend DataTables instance with `serverSide: true`:
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@areumtecnologia/mysql-db-handler",
|
|
3
|
-
"version": "2.0.
|
|
3
|
+
"version": "2.0.1",
|
|
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",
|