All files / middlewares transaction-logger.ts

82.48% Statements 113/137
70% Branches 14/20
66.66% Functions 2/3
82.48% Lines 113/137

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 1381x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 7x 7x 7x 7x 7x 5x 1x 1x 4x 4x 4x 4x 5x 1x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 24x 24x     4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x               4x 4x 4x 4x 5x 5x 5x 7x 1x 1x                                
import { ElasticLogger } from '../logger'
import { LogTransaction } from '../logger/types'
import { Request, Response, NextFunction } from 'express'
 
// Extend Express Request interface
declare global {
  namespace Express {
    interface Request {
      transactionId?: string
    }
  }
}
 
export const transactionLoggerMiddleware = (
  microservice: string,
  operation: string,
  elasticLogger: ElasticLogger | null
) => {
  return (req: Request, res: Response, next: NextFunction) => {
    if (!elasticLogger) {
      return next()
    }
 
    const startTime = Date.now()
    const transactionId =
      (req.headers['x-transaction-id'] as string) ||
      (req.headers['x-request-id'] as string) ||
      `tx_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
 
    req.transactionId = transactionId
 
    const requestMeta = {
      method: req.method,
      path: req.originalUrl,
      ...(req.ip || req.socket.remoteAddress
        ? { ip: req.ip || req.socket.remoteAddress }
        : {}),
      ...(req.get('User-Agent') ? { userAgent: req.get('User-Agent') } : {}),
    }
 
    const originalSend = res.send
    res.send = function (data: unknown) {
      const duration = Date.now() - startTime
      const status = res.statusCode >= 400 ? 'fail' : 'success'
 
      const context: Record<string, unknown> = {}
 
      if (req.params) {
        Object.assign(context, req.params)
      }
 
      if (req.query) {
        const filteredQuery = { ...req.query }
        delete filteredQuery['token']
        delete filteredQuery['password']
        delete filteredQuery['newPassword']
        delete filteredQuery['secret']
        Object.assign(context, filteredQuery)
      }
 
      if (req.body && typeof req.body === 'object') {
        const filteredBody = { ...req.body }
        delete filteredBody['password']
        delete filteredBody['newPassword']
        delete filteredBody['token']
        delete filteredBody['secret']
        Object.assign(context, filteredBody)
      }
 
      const relevantHeaders = [
        'x-user-id',
        'x-appointment-id',
        'x-platform',
        'authorization',
        'content-type',
        'accept',
      ]
 
      relevantHeaders.forEach((header) => {
        const value = req.get(header)
        if (value) {
          context[header] = header === 'authorization' ? '[REDACTED]' : value
        }
      })
 
      const transactionData: LogTransaction = {
        name: operation,
        microservice,
        transactionId,
        operation,
        status,
        duration,
        context,
        requestMeta,
        responseMeta: {
          statusCode: res.statusCode,
          data: data as unknown,
          responseSize: (data as string)?.length || 0,
        },
      }
 
      setImmediate(async () => {
        try {
          await elasticLogger.logTransaction(transactionData)
        } catch (error) {
          console.error('❌ Erro ao registrar log transacional:', {
            transactionId,
            microservice,
            operation,
            error: error instanceof Error ? error.message : 'Unknown error',
          })
        }
      })
 
      return originalSend.call(this, data)
    }
 
    next()
  }
}
 
export const addTransactionId = (
  req: Request,
  res: Response,
  next: NextFunction
) => {
  if (!req.transactionId) {
    req.transactionId =
      (req.headers['x-transaction-id'] as string) ||
      (req.headers['x-request-id'] as string) ||
      `tx_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
  }

  res.setHeader('X-Transaction-ID', req.transactionId)

  next()
}