All files / src/packages/logger/shared utils.ts

21.42% Statements 6/28
0% Branches 0/14
0% Functions 0/4
23.07% Lines 6/26

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 501x 1x     1x       1x                                                         1x       1x                
import * as httpContext from 'express-http-context';
import { isNil, isPlainObject } from 'lodash';
import { ILogInput } from './interface';
 
export function getUserId(): string | undefined {
  return httpContext.get('user')?.id;
}
 
export function serializedError(error: ILogInput) {
  const errorKeys = ['error', 'err'];
 
  Iif (error instanceof Error) {
    const obj: ILogInput = {};
    for (const key of Object.getOwnPropertyNames(error)) {
      const value = (error as any)[key];
      Iif (!isNil(value)) {
        if (errorKeys.includes(key)) obj.reason = serializedError(value);
        else obj[key] = serializedError(value);
      }
    }
    return Object.keys(obj).length ? obj : undefined;
  }
 
  Iif (isPlainObject(error)) {
    const obj: ILogInput = {};
    for (const key of Object.keys(error)) {
      Iif (!isNil(error[key])) {
        if (errorKeys.includes(key)) obj.reason = serializedError(error[key]);
        else obj[key] = serializedError(error[key]);
      }
    }
    return Object.keys(obj).length ? obj : undefined;
  }
 
  return error;
}
 
export function formatResBodyString(body: string) {
  return body.replace(/\\"/g, '');
}
 
export function getCommonData(data?: ILogInput) {
  return data
    ? {
        env: process.env.NODE_ENV,
        ...serializedError(data),
      }
    : undefined;
}