All files / src/modules/common/database/mongo/shared mongo.utils.ts

77.41% Statements 48/62
81.25% Branches 26/32
78.57% Functions 11/14
74.07% Lines 40/54

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 1331x 1x                                     1x     1x       14x 39x 39x 13x 30x       1x 3x     1x 3x     1x 2x 14x 12x 10x 8x               2x   2x   2x 2x 14x 14x 14x 14x       2x 15x 15x 15x 15x 1x 1x           2x     1x 1x 1x           1x                                 1x                                              
import { Decimal128, ObjectId } from 'bson';
import {
  cloneDeepWith,
  concat,
  dropRight,
  forEach,
  forOwn,
  fromPairs,
  get,
  identity,
  isArray,
  isEqual,
  isFunction,
  isPlainObject,
  isString,
  last,
  set,
  toPath,
  unset,
} from 'lodash';
import { ClientSession, Types } from 'mongoose';
import { IAnyObject, IConvertObjectOptions } from './mongo.interface';
 
export function forOwnRecursive(
  obj: any,
  iteratee: (value: any, path: string[], obj: any) => any = identity,
): any {
  return forOwn(obj, (value: any, key: any) => {
    const path: string[] = [].concat(key.toString());
    if (isPlainObject(value) || isArray(value))
      return forOwnRecursive(value, (v, p) => iteratee(v, path.concat(p), obj));
    return iteratee(value, path, obj);
  });
}
 
export function convertSetToObject<T = any>(value: Set<T>): T[] {
  return Array.from(value.values());
}
 
export function convertMapToPlainObject<T = any>(value: Map<string, T>): { [key: string]: T } {
  return fromPairs(Array.from(value.entries()));
}
 
export function convertObject<T = IAnyObject>(obj: T, options: IConvertObjectOptions = {}): T {
  const defaultReplacer = (value: any) => {
    if (value instanceof ObjectId) return value.toHexString();
    else if (value instanceof Decimal128) return Number(value.toString());
    else if (value instanceof Set) return convertSetToObject(value);
    else if (value instanceof Map) return convertMapToPlainObject(value);
  };
 
  const {
    exclude = ['_v'],
    excludePrefix = '_',
    replacer = defaultReplacer,
    keymap = { _id: 'id' },
  } = options;
 
  const resultObj = cloneDeepWith(obj, replacer);
 
  if (isPlainObject(resultObj) || isArray(resultObj)) {
    forOwnRecursive(resultObj, (value, path) => {
      const key = last(path);
      if (key) {
        const newKey = isFunction(keymap) ? keymap(key) : get(keymap, key);
        if (newKey) set(resultObj, concat(dropRight(path), newKey), value);
      }
    });
 
    forOwnRecursive(resultObj, (_value, path) => {
      if (excludePrefix && last(path)?.startsWith(excludePrefix)) unset(resultObj, path);
      forEach(exclude, (field) => {
        if (isString(field)) field = toPath(field);
        if (isEqual(field, path)) {
          unset(resultObj, path);
          return false;
        }
      });
    });
  }
 
  return resultObj;
}
 
export function getObjectId(value?: string) {
  try {
    return new Types.ObjectId(value);
  } catch (err) {
    return new Types.ObjectId();
  }
}
 
export async function handleSession<T>(
  session: ClientSession,
  asyncFunc: () => Promise<T>,
): Promise<T> {
  let res: any;
 
  try {
    await session.withTransaction(async () => {
      res = await asyncFunc();
    });
 
    return res;
  } finally {
    await session.endSession();
  }
}
 
export function getConnectionString(params: {
  host: string;
  port?: number;
  username?: string;
  password?: string;
  database: string;
}) {
  let uri = 'mongodb://';
 
  Iif (params.username && params.password) {
    uri += `${params.username}:${params.password}@`;
  }
 
  uri += params.host;
 
  Iif (params.port) {
    uri += `:${params.port}`;
  }
 
  uri += `/${params.database}`;
 
  return uri;
}