Express TypeScript LogCall Decorator

JS
S
JavaScript

Decorator for logging calls

1import logService from '../services/log';
2
3export function LogCall() {
4  return function validator(target: any, key: any, descriptor: any) {
5    const fn = descriptor.value;
6    descriptor.value = function (...args: any) {
7      try {
8        if (args.length > 0) {
9          let parsedArgs = {};
10          const requestObj = args[0];
11          if (!requestObj) {
12            return fn.apply(this, args);
13          }
14          const argsAreRequest = requestObj.hasOwnProperty('_readableState');
15          if (argsAreRequest) {
16            if (requestObj.body.type === 'text/csv') {
17              parsedArgs = { headers: requestObj.headers, params: requestObj.params, query: requestObj.query, type: requestObj.type };
18            } else {
19              parsedArgs = { headers: requestObj.headers, body: requestObj.body, params: requestObj.params, query: requestObj.query, type: requestObj.type };
20            }
21          }
22          logService.log('info', `Function call: ${key}();`, parsedArgs);
23        }
24        return fn.apply(this, args);
25      } catch (err) {
26        logService.log('error', `LogCall has a problem`, err);
27        return fn.apply(this, args);
28      }
29    };
30  };
31}
32
33
34// Middleware
35const routesLogging = (req: Request, res: Response, next: NextFunction) => {
36  if (req.body && req.body.type === 'text/csv') {
37    logService.log('info', `${req.method} ${req.originalUrl}`, {
38      body: 'Large bodies are not traced',
39      type: req.body.type,
40      ip: req.ip,
41      headers: req.headers
42    });
43  } else {
44    logService.log('info', `${req.method} ${req.originalUrl}`, {
45      body: req.body,
46      query: req.query,
47      ip: req.ip,
48      headers: req.headers
49    });
50  }
51  next();
52};
53
54    // Logging, Audit Trail
55    this.app.use(routesLogging);
56

Created on 6/18/2021