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 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 | 42x 39x 14x 14x 12x 12x 12x 12x 12x 12x 12x 12x 12x 2x 11x 11x 2x 11x 2x 2x 2x 1x 1x 1x 1x 11x 9x 1x 1x 11x 7x 7x 1x 6x 6x 3x 6x 2x 6x 12x 12x 12x 12x 12x 12x 11x 10x 10x 9x 4x 5x 12x 12x 12x 5x 5x 2x 2x 3x 3x 7x 1x 1x 15x 15x 14x 14x 15x 15x 15x 15x 15x 2x 13x 12x 5x 7x 8x 7x 7x 7x 7x 7x 7x 7x 7x 10x 10x 10x 10x 10x 20x 20x 10x 1x 9x 10x 10x 10x 5x 5x 2x 3x 1x 1x 1x 1x 8x 1x 7x 7x 1x 6x 5x 5x 5x 6x 6x 6x 6x 6x 6x 4x 4x 4x 2x 2x 6x 6x 7x 7x 7x 7x 7x 3x 2x 2x 7x 7x 6x 6x 1x 6x 5x 6x 2x 2x | /**
* 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.
*/
/**
* Continue the chain: call `next` when the framework passed one (Express, Koa, ...).
* Routers that run middleware without `next` continue on their own.
*
* @private
*/
async function proceed(next) {
if (typeof next === 'function') {
await next();
}
}
/**
* Report an error raised by the middleware itself (not by later handlers) to `next`
* when there is one, else throw it.
*
* @private
*/
function fail(next, _error) {
Eif (typeof next === 'function') {
return next(_error);
}
throw _error;
}
/**
* An error carrying its HTTP status under both names routers read: Express's
* default handler uses `status` (or `statusCode`); the `@coherent.js/api`
* router uses `statusCode`, as its `ApiError` classes do, and answered 500
* for an error that only had `status`.
*
* @private
* @param {string} message - Error message sent to the client
* @param {number} status - 4xx HTTP status
* @returns {Error}
*/
function httpError(message, status) {
const _error = new Error(message);
_error.status = status;
_error.statusCode = status;
// Like `http-errors`: a client error's message is safe to show
_error.expose = true;
return _error;
}
/**
* 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.js/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;
}
} catch (_error) {
// Log database errors
console.error('Database middleware error:', _error);
return fail(next, _error);
}
// Outside the try: an error from a later handler must not call next() a second time
await proceed(next);
};
}
/**
* Finish a transaction when the response ends: commit after a successful response,
* roll back after an error status or when the connection closes first.
*
* @private
*/
function settleWhenResponseEnds(res, settle) {
const listen = res && (typeof res.once === 'function' ? res.once : res.on);
if (typeof listen !== 'function') {
return false;
}
const report = (_error) => console.error('withTransaction: failed to finish the transaction:', _error);
listen.call(res, 'finish', () => {
settle(res.statusCode >= 400).catch(report);
});
listen.call(res, 'close', () => {
settle(true).catch(report);
});
return true;
}
/**
* Transaction middleware for automatic transaction management
*
* The transaction is exposed as `req.tx` and finished:
* - when `next()` returns a promise (async frameworks): after it settles, committing on
* success and rolling back if it rejects;
* - otherwise (Express, whose `next()` returns before an async handler is done, or a
* router that calls middleware without `next`): when the response ends, committing
* on a status below 400 and rolling back on an error status or a closed connection.
*
* A transaction the handler already committed or rolled back is left alone.
*
* @param {DatabaseManager} db - Database manager instance
* @param {Object} [options={}] - Transaction options
* @param {string} [options.isolationLevel] - READ UNCOMMITTED, READ COMMITTED, REPEATABLE READ or SERIALIZABLE
* @param {boolean} [options.readOnly=false] - Start a read-only transaction
* @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;
let settled = false;
const settle = async (failed) => {
if (settled) return;
settled = true;
if (tx.isCommitted || tx.isRolledBack) return;
if (failed) {
await tx.rollback();
} else {
await tx.commit();
}
};
let result;
try {
result = typeof next === 'function' ? next() : undefined;
} catch (_error) {
await settle(true);
throw _error;
}
if (result && typeof result.then === 'function') {
try {
await result;
} catch (_error) {
await settle(true);
throw _error;
}
await settle(false);
return;
}
// The handler may still be running: finish the transaction with the response
if (!settleWhenResponseEnds(res, settle)) {
await settle(true);
throw new Error(
'withTransaction cannot tell when the request ends: next() did not return a promise ' +
'and the response does not emit "finish"/"close". The transaction was rolled back.'
);
}
};
}
/**
* 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) {
// Handle different model types - class vs object
let modelName = requestKey;
if (!modelName) {
if (ModelClass && ModelClass.name) {
modelName = ModelClass.name.toLowerCase();
} else Eif (ModelClass && ModelClass.tableName) {
modelName = ModelClass.tableName.slice(0, -1); // Remove 's' from table name
} else {
modelName = 'model'; // fallback
}
}
const key = modelName;
return async (req, res, next) => {
try {
const paramValue = req.params[paramName];
if (!paramValue) {
throw httpError(`Parameter '${paramName}' is required`, 400);
}
const model = await ModelClass.find(paramValue);
if (!model) {
throw httpError(`${ModelClass.name} not found`, 404);
}
req[key] = model;
} catch (_error) {
return fail(next, _error);
}
await proceed(next);
};
}
/**
* 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 proceed(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) {
throw httpError(`Query parameter '${key}' is required`, 400);
}
continue;
}
// Type coercion
let coercedValue = value;
Eif (config.coerceTypes) {
switch (rules.type) {
case 'number':
coercedValue = Number(value);
if (isNaN(coercedValue)) {
throw httpError(`Query parameter '${key}' must be a number`, 400);
}
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)) {
throw httpError(`Query parameter '${key}' must be one of: ${rules.enum.join(', ')}`, 400);
}
Iif (rules.min !== undefined && coercedValue < rules.min) {
throw httpError(`Query parameter '${key}' must be at least ${rules.min}`, 400);
}
if (rules.max !== undefined && coercedValue > rules.max) {
throw httpError(`Query parameter '${key}' must be at most ${rules.max}`, 400);
}
validatedQuery[key] = coercedValue;
}
// Replace query with the validated (and coerced) version; keep unknown keys
// alongside it when asked, without overwriting the coerced values
req.query = config.stripUnknown ? validatedQuery : { ...req.query, ...validatedQuery };
} catch (_error) {
return fail(next, _error);
}
await proceed(next);
};
}
/**
* 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) => {
let timer;
try {
const startTime = Date.now();
// Test database connection
await Promise.race([
db.query('SELECT 1'),
new Promise((_, reject) => {
timer = 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();
}
} catch (_error) {
req.dbHealth = {
status: 'unhealthy',
error: _error.message,
connected: db.isConnected
};
} finally {
clearTimeout(timer);
}
await proceed(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;
let released = false;
const release = () => {
if (connection && !released) {
released = true;
db.pool.release(connection);
}
};
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', release);
}
await proceed(next);
} catch (_error) {
// Release connection on _error
release();
throw _error;
}
};
}
|