@areumtecnologia/mysql-db-handler 1.0.13 → 1.0.14

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.
Files changed (2) hide show
  1. package/README.md +159 -14
  2. package/package.json +1 -1
package/README.md CHANGED
@@ -25,7 +25,14 @@ A powerful, robust, and production-ready MySQL wrapper for Node.js. It features
25
25
  * [Inserting Records (`insert`)](#inserting-records-insert)
26
26
  * [Updating Records (`update`)](#updating-records-update)
27
27
  * [Deleting Records (`delete`)](#deleting-records-delete)
28
- * [jQuery DataTables Server-Side Support](#jquery-datatables-server-side-support)
28
+ * [jQuery DataTables Server-Side Support (`selectToDatatable`)](#jquery-datatables-server-side-support-selecttodatatable)
29
+ * [Key Features & Performance](#key-features--performance-optimizations)
30
+ * [Method Signature](#method-signature)
31
+ * [Basic Express.js Example](#basic-expressjs-example)
32
+ * [Enforcing Backend Security (`strictCondition`)](#enforcing-backend-security-strictcondition)
33
+ * [Using JOINs and Custom Expressions](#using-joins-and-custom-expressions)
34
+ * [Frontend jQuery DataTables Setup](#frontend-jquery-datatables-setup)
35
+ * [Response Structure & Error Handling](#response-structure--error-handling)
29
36
  * [Transaction Support (ACID & Transparent)](#transaction-support-acid--transparent)
30
37
  * [1. Explicit Block (`db.transaction`)](#1-explicit-block-dbtransaction)
31
38
  * [2. Singleton Compatibility with `AsyncLocalStorage`](#2-singleton-compatibility-with-asynclocalstorage)
@@ -316,30 +323,168 @@ console.log('Deleted rows:', result.affectedRows);
316
323
 
317
324
  ---
318
325
 
319
- ## jQuery DataTables Server-Side Support
326
+ ## jQuery DataTables Server-Side Support (`selectToDatatable`)
320
327
 
321
- The `selectToDatatable` method processes the complex nested payloads sent by jQuery DataTables server-side scripts and returns the required format.
328
+ The `selectToDatatable` method provides seamless, high-performance integration with [jQuery DataTables](https://datatables.net/) server-side processing. It automatically handles pagination, search (global and column-based), multi-column ordering, regex filters, total/filtered counts, and backend security constraints.
329
+
330
+ ### Key Features & Performance Optimizations
331
+
332
+ * **Smart Single `COUNT(*)`:** When no client-side search filter is active (the default state in standard page loads and 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
+ * **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
+ * **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
+ * **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
+ * **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
+ * **Prototype Pollution Protection (CWE-1321):** Deeply sanitizes incoming request keys, blocking injections targeting `__proto__`, `constructor`, or `prototype`.
338
+
339
+ ---
340
+
341
+ ### Method Signature
322
342
 
323
343
  ```javascript
324
- // Express.js Route Example
325
- app.post('/api/users/dt', async (req, res) => {
326
- // req.body contains the DataTables standard payload:
327
- // { draw: 1, start: 0, length: 10, search: { value: 'John', regex: false }, columns: [...] }
328
-
329
- // You can enforce strict conditions that the client cannot bypass (e.g., tenant containment)
344
+ await handler.selectToDatatable(rawDtQuery, strictCondition = [])
345
+ ```
346
+
347
+ | Parameter | Type | Description |
348
+ | :--- | :--- | :--- |
349
+ | `rawDtQuery` | `Object` | The request payload sent by jQuery DataTables (`req.body` or `req.query`). Supports both flat bracketed keys and nested objects. |
350
+ | `strictCondition` | `Array` *(Optional)* | Backend conditions that the client cannot view or modify (e.g. multi-tenant isolation, user scoping, active-only filters). |
351
+
352
+ ---
353
+
354
+ ### Basic Express.js Example
355
+
356
+ ```javascript
357
+ const express = require('express');
358
+ const { db, usersHandler } = require('./databaseController');
359
+
360
+ const app = express();
361
+ app.use(express.json());
362
+ app.use(express.urlencoded({ extended: true }));
363
+
364
+ app.post('/api/users/datatable', async (req, res) => {
365
+ // req.body contains: { draw, start, length, search, order, columns }
366
+ const result = await usersHandler.selectToDatatable(req.body);
367
+ res.json(result);
368
+ });
369
+ ```
370
+
371
+ ---
372
+
373
+ ### Enforcing Backend Security (`strictCondition`)
374
+
375
+ Never rely on the client to enforce data access 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
+
377
+ ```javascript
378
+ app.post('/api/orders/datatable', async (req, res) => {
379
+ // Client-side parameters cannot bypass these conditions:
330
380
  const strictConditions = [
331
381
  { tenant_id: req.user.tenantId },
332
382
  'AND',
333
- { status: 'deleted', operator: '!=' }
383
+ { status: 'deleted', operator: '!=' },
384
+ 'AND',
385
+ { store_id: [101, 102, 105] } // Automatically mapped to: `store_id` IN (?, ?, ?)
334
386
  ];
335
387
 
336
- const datatableResult = await usersHandler.selectToDatatable(req.body, strictConditions);
337
-
338
- // Returns: { draw: 1, recordsTotal: 100, recordsFiltered: 12, data: [...] }
339
- res.json(datatableResult);
388
+ const result = await ordersHandler.selectToDatatable(req.body, strictConditions);
389
+ res.json(result);
340
390
  });
341
391
  ```
342
392
 
393
+ ---
394
+
395
+ ### Using JOINs and Custom Expressions
396
+
397
+ If your table requires JOINs or computed fields, initialize the `DataBaseHandler` with an expression parameter:
398
+
399
+ ```javascript
400
+ // Table: 'sales s'
401
+ // Expression: JOIN with customers and users, selecting extra fields
402
+ const salesHandler = new DataBaseHandler(
403
+ db,
404
+ 'customers_sales s',
405
+ ', c.name AS customer_name, u.name AS user_name ' +
406
+ 'LEFT JOIN customers c ON c.id = s.customer ' +
407
+ 'LEFT JOIN users u ON u.id = s.user'
408
+ );
409
+
410
+ app.post('/api/sales/datatable', async (req, res) => {
411
+ // DataTables columns can now search and sort by qualified identifiers:
412
+ // e.g. columns: [{ data: 's.id' }, { data: 'c.name' }, { data: 's.amount' }]
413
+ const result = await salesHandler.selectToDatatable(req.body, [
414
+ { 's.deleted_at': null, operator: 'IS' }
415
+ ]);
416
+ res.json(result);
417
+ });
418
+ ```
419
+
420
+ ---
421
+
422
+ ### Frontend jQuery DataTables Setup
423
+
424
+ Configure your frontend DataTables instance with `serverSide: true`:
425
+
426
+ ```javascript
427
+ $('#usersTable').DataTable({
428
+ processing: true,
429
+ serverSide: true,
430
+ ajax: {
431
+ url: '/api/users/datatable',
432
+ type: 'POST',
433
+ contentType: 'application/json',
434
+ data: function (d) {
435
+ return JSON.stringify(d);
436
+ }
437
+ },
438
+ columns: [
439
+ { data: 'id', name: 'id' },
440
+ { data: 'name', name: 'name' },
441
+ { data: 'email', name: 'email' },
442
+ { data: 'role', name: 'role' },
443
+ {
444
+ data: null,
445
+ orderable: false,
446
+ searchable: false,
447
+ render: function (data, type, row) {
448
+ return `<button onclick="editUser(${row.id})">Edit</button>`;
449
+ }
450
+ }
451
+ ],
452
+ order: [[0, 'desc']]
453
+ });
454
+ ```
455
+
456
+ ---
457
+
458
+ ### Response Structure & Error Handling
459
+
460
+ The method always returns the standard JSON response expected by DataTables:
461
+
462
+ #### Success Response
463
+ ```json
464
+ {
465
+ "draw": 1,
466
+ "recordsTotal": 1250,
467
+ "recordsFiltered": 45,
468
+ "data": [
469
+ { "id": 42, "name": "John Doe", "email": "john@example.com", "role": "admin" },
470
+ { "id": 43, "name": "Jane Smith", "email": "jane@example.com", "role": "editor" }
471
+ ]
472
+ }
473
+ ```
474
+
475
+ #### Safe Error Handling
476
+ If an underlying database error occurs, `selectToDatatable` catches it safely, notifies your `onError` handler (if configured), and returns a structured response with the error message so the client table does not hang indefinitely:
477
+
478
+ ```json
479
+ {
480
+ "draw": 1,
481
+ "recordsTotal": 0,
482
+ "recordsFiltered": 0,
483
+ "data": [],
484
+ "error": "ER_NO_SUCH_TABLE: Table 'my_app_db.invalid_table' doesn't exist"
485
+ }
486
+ ```
487
+
343
488
 
344
489
  ---
345
490
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@areumtecnologia/mysql-db-handler",
3
- "version": "1.0.13",
3
+ "version": "1.0.14",
4
4
  "description": "A powerful MySQL wrapper with connection pooling, singleton support, and advanced query handling for Node.js.",
5
5
  "main": "index.js",
6
6
  "scripts": {