Code coverage report for node/src/integrations/express.ts

Statements: 80% (12 / 15)      Branches: 68.18% (15 / 22)      Functions: 100% (2 / 2)      Lines: 80% (12 / 15)      Ignored: none     

All files » node/src/integrations/ » express.ts
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  1 1                             1   1       1         1 1             1 1   1   1                             1            
import * as Express from 'express';
import {ACCESS_TEMPLATE} from './access-logger';
import {
  LogConfig,
  LogLevel,
  LogOptions,
  logProvider,
  MessageContext,
  templateString,
} from '@btilford/ts-base-core';
 
 
export type AccessLogOptions = LogOptions & {
  useLevel: LogLevel;
  name?: string;
}
 
export function accessLogMiddleware(options: AccessLogOptions): Express.RequestHandler {
  let config: LogConfig;
  const configDefaults = {
    messageTemplate: templateString(ACCESS_TEMPLATE),
  };
 
  Iif (options.parent && options.config) {
    config = options.parent.config.extend({
      ...options.config,
      ...configDefaults
    }, true);
  } else Eif (options.parent) {
    config = options.parent.config.extend(configDefaults, true);
  } else {
    config = LogConfig.create({
      ...options.config,
      ...configDefaults
    });
  }
  const logger = (options?.parent || logProvider()).extend(options.name || 'access', config)
  return function accessLog(req: Express.Request, res: Express.Response, next: Express.NextFunction): any {
 
    next();
 
    const errored = logger.write(options.useLevel, new MessageContext('', {
      timestamp: new Date().toISOString(),
      pid: process.env.pid,
      req: {
        url: req.originalUrl,
        method: req.method,
        ip: (req.header('x-fowarded-for') || '').split(',')[0].trim() || '',
        userAgent: req.header('user-agent')
      },
      res: {
        status: res.statusCode,
        length: res.getHeader('content-length') || 0,
      }
    }));
 
    Iif (errored) {
      process.stderr.write(`ERROR writing access log! ${errored.message} ${errored.stack}`);
    }
  }
}