All files / src/database middleware.js

97.54% Statements 397/407
92.77% Branches 77/83
100% Functions 10/10
97.54% Lines 397/407

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 4421x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1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 7x 7x 7x   7x 7x 7x 7x 7x 7x 6x 6x 6x 6x 6x 6x 1x 6x   6x 7x 5x 1x 1x 1x 5x 5x   6x 5x 7x 2x 2x 1x 1x 2x 2x 2x 7x 7x  
/**
 * Database Middleware for Coherent.js Router Integration
 * 
 * @fileoverview Provides middleware for seamless database integration with the router,
 * including connection management, transaction handling, and query helpers.
 */
 
/**
 * Database middleware for router integration
 * 
 * @param {DatabaseManager} db - Database manager instance
 * @param {Object} [options={}] - Middleware options
 * @returns {Function} Middleware function
 * 
 * @example
 * import { withDatabase } from '@coherent/database';
 * 
 * const router = new SimpleRouter();
 * router.use(withDatabase(db));
 * 
 * router.get('/users', async (req, res) => {
 *   const users = await req.db.query('SELECT * FROM users');
 *   res.json(users.rows);
 * });
 */
export function withDatabase(db, options = {}) {
  const config = {
    autoConnect: true,
    attachModels: true,
    transactionKey: 'tx',
    ...options
  };
 
  return async (req, res, next) => {
    try {
      // Ensure database is connected
      if (config.autoConnect && !db.isConnected) {
        await db.connect();
      }
 
      // Attach database to request
      req.db = db;
 
      // Attach query helper (preserve original req.query)
      req.dbQuery = async (sql, params, queryOptions) => {
        return await db.query(sql, params, queryOptions);
      };
 
      // Attach transaction helper
      req.transaction = async (callback) => {
        const tx = await db.transaction();
        
        try {
          const result = await callback(tx);
          await tx.commit();
          return result;
        } catch (error) {
          await tx.rollback();
          throw error;
        }
      };
 
      // Attach models if configured
      if (config.attachModels && db.models) {
        req.models = db.models;
      }
 
      await next();
 
    } catch (error) {
      // Log database errors
      console.error('Database middleware error:', error);
      
      // Pass error to error handler
      if (typeof next === 'function') {
        next(error);
      } else {
        throw error;
      }
    }
  };
}
 
/**
 * Transaction middleware for automatic transaction management
 * 
 * @param {DatabaseManager} db - Database manager instance
 * @param {Object} [options={}] - Transaction options
 * @returns {Function} Middleware function
 * 
 * @example
 * router.post('/transfer', withTransaction(db), async (req, res) => {
 *   // All database operations in this handler will be wrapped in a transaction
 *   await req.tx.query('UPDATE accounts SET balance = balance - ? WHERE id = ?', [amount, fromId]);
 *   await req.tx.query('UPDATE accounts SET balance = balance + ? WHERE id = ?', [amount, toId]);
 *   // Transaction is automatically committed on success or rolled back on error
 * });
 */
export function withTransaction(db, options = {}) {
  const config = {
    isolationLevel: null,
    readOnly: false,
    ...options
  };
 
  return async (req, res, next) => {
    const tx = await db.transaction(config);
    req.tx = tx;
 
    try {
      await next();
      
      // Commit transaction if not already committed
      if (!tx.isCommitted && !tx.isRolledBack) {
        await tx.commit();
      }
      
    } catch (error) {
      // Rollback transaction if not already rolled back
      if (!tx.isRolledBack && !tx.isCommitted) {
        await tx.rollback();
      }
      
      throw error;
    }
  };
}
 
/**
 * Model binding middleware
 * 
 * @param {Function} ModelClass - Model class to bind
 * @param {string} [paramName='id'] - Route parameter name
 * @param {string} [requestKey] - Request key to attach model (defaults to model name)
 * @returns {Function} Middleware function
 * 
 * @example
 * router.get('/users/:id', withModel(User), async (req, res) => {
 *   // req.user contains the loaded User model
 *   res.json(req.user.toJSON());
 * });
 * 
 * router.get('/posts/:postId', withModel(Post, 'postId', 'post'), async (req, res) => {
 *   // req.post contains the loaded Post model
 *   res.json(req.post.toJSON());
 * });
 */
export function withModel(ModelClass, paramName = 'id', requestKey = null) {
  const key = requestKey || ModelClass.name.toLowerCase();
  
  return async (req, res, next) => {
    try {
      const paramValue = req.params[paramName];
      
      if (!paramValue) {
        const error = new Error(`Parameter '${paramName}' is required`);
        error.status = 400;
        throw error;
      }
 
      const model = await ModelClass.find(paramValue);
      
      if (!model) {
        const error = new Error(`${ModelClass.name} not found`);
        error.status = 404;
        throw error;
      }
 
      req[key] = model;
      await next();
      
    } catch (error) {
      if (typeof next === 'function') {
        next(error);
      } else {
        throw error;
      }
    }
  };
}
 
/**
 * Pagination middleware
 * 
 * @param {Object} [options={}] - Pagination options
 * @returns {Function} Middleware function
 * 
 * @example
 * router.get('/users', withPagination(), async (req, res) => {
 *   const users = await User.query()
 *     .limit(req.pagination.limit)
 *     .offset(req.pagination.offset)
 *     .execute();
 *   
 *   res.json({
 *     data: users.rows,
 *     pagination: req.pagination
 *   });
 * });
 */
export function withPagination(options = {}) {
  const config = {
    defaultLimit: 20,
    maxLimit: 100,
    pageParam: 'page',
    limitParam: 'limit',
    ...options
  };
 
  return async (req, res, next) => {
    const page = Math.max(1, parseInt(req.query[config.pageParam]) || 1);
    const limit = Math.min(
      config.maxLimit,
      Math.max(1, parseInt(req.query[config.limitParam]) || config.defaultLimit)
    );
    const offset = (page - 1) * limit;
 
    req.pagination = {
      page,
      limit,
      offset,
      hasNext: null, // To be set by the handler
      hasPrev: page > 1,
      totalPages: null, // To be set by the handler
      totalCount: null // To be set by the handler
    };
 
    await next();
  };
}
 
/**
 * Query validation middleware
 * 
 * @param {Object} schema - Validation schema
 * @param {Object} [options={}] - Validation options
 * @returns {Function} Middleware function
 * 
 * @example
 * router.get('/users', withQueryValidation({
 *   status: { type: 'string', enum: ['active', 'inactive'] },
 *   age: { type: 'number', min: 0, max: 120 }
 * }), async (req, res) => {
 *   // req.query is validated and sanitized
 * });
 */
export function withQueryValidation(schema, options = {}) {
  const config = {
    stripUnknown: true,
    coerceTypes: true,
    ...options
  };
 
  return async (req, res, next) => {
    try {
      const validatedQuery = {};
      
      for (const [key, rules] of Object.entries(schema)) {
        const value = req.query[key];
        
        // Skip if not provided and not required
        if (value === undefined || value === null || value === '') {
          if (rules.required) {
            const error = new Error(`Query parameter '${key}' is required`);
            error.status = 400;
            throw error;
          }
          continue;
        }
 
        // Type coercion
        let coercedValue = value;
        if (config.coerceTypes) {
          switch (rules.type) {
            case 'number':
              coercedValue = Number(value);
              if (isNaN(coercedValue)) {
                const error = new Error(`Query parameter '${key}' must be a number`);
                error.status = 400;
                throw error;
              }
              break;
            case 'boolean':
              coercedValue = value === 'true' || value === '1';
              break;
            case 'array':
              coercedValue = Array.isArray(value) ? value : [value];
              break;
          }
        }
 
        // Validation
        if (rules.enum && !rules.enum.includes(coercedValue)) {
          const error = new Error(`Query parameter '${key}' must be one of: ${rules.enum.join(', ')}`);
          error.status = 400;
          throw error;
        }
 
        if (rules.min !== undefined && coercedValue < rules.min) {
          const error = new Error(`Query parameter '${key}' must be at least ${rules.min}`);
          error.status = 400;
          throw error;
        }
 
        if (rules.max !== undefined && coercedValue > rules.max) {
          const error = new Error(`Query parameter '${key}' must be at most ${rules.max}`);
          error.status = 400;
          throw error;
        }
 
        validatedQuery[key] = coercedValue;
      }
 
      // Replace query with validated version
      if (!config.stripUnknown) {
        Object.assign(validatedQuery, req.query);
      }
      
      req.query = validatedQuery;
      await next();
      
    } catch (error) {
      if (typeof next === 'function') {
        next(error);
      } else {
        throw error;
      }
    }
  };
}
 
/**
 * Database health check middleware
 * 
 * @param {DatabaseManager} db - Database manager instance
 * @param {Object} [options={}] - Health check options
 * @returns {Function} Middleware function
 * 
 * @example
 * router.get('/health', withHealthCheck(db), (req, res) => {
 *   res.json({ status: 'healthy', database: req.dbHealth });
 * });
 */
export function withHealthCheck(db, options = {}) {
  const config = {
    timeout: 5000,
    includeStats: true,
    ...options
  };
 
  return async (req, res, next) => {
    try {
      const startTime = Date.now();
      
      // Test database connection
      await Promise.race([
        db.query('SELECT 1'),
        new Promise((_, reject) => 
          setTimeout(() => reject(new Error('Health check timeout')), config.timeout)
        )
      ]);
      
      const responseTime = Date.now() - startTime;
      
      req.dbHealth = {
        status: 'healthy',
        responseTime,
        connected: db.isConnected
      };
 
      if (config.includeStats) {
        req.dbHealth.stats = db.getStats();
      }
 
      await next();
      
    } catch (error) {
      req.dbHealth = {
        status: 'unhealthy',
        error: error.message,
        connected: db.isConnected
      };
      
      await next();
    }
  };
}
 
/**
 * Connection pooling middleware for request-scoped connections
 * 
 * @param {DatabaseManager} db - Database manager instance
 * @param {Object} [options={}] - Pool options
 * @returns {Function} Middleware function
 * 
 * @example
 * router.use(withConnectionPool(db, { acquireTimeout: 10000 }));
 */
export function withConnectionPool(db, options = {}) {
  const config = {
    acquireTimeout: 30000,
    releaseOnResponse: true,
    ...options
  };
 
  return async (req, res, next) => {
    let connection = null;
    
    try {
      // Acquire connection from pool
      connection = await db.pool.acquire(config.acquireTimeout);
      
      // Attach connection to request
      req.dbConnection = connection;
      
      // Attach query helper to use this connection
      req.dbQuery = async (sql, params, queryOptions) => {
        return await db.adapter.query(connection, sql, params, queryOptions);
      };
 
      // Release connection when response finishes
      if (config.releaseOnResponse) {
        res.on('finish', () => {
          if (connection) {
            db.pool.release(connection);
          }
        });
      }
 
      await next();
      
    } catch (error) {
      // Release connection on error
      if (connection) {
        db.pool.release(connection);
      }
      
      throw error;
    }
  };
}