# All files serializer.ts

92.3% Statements 48/52
85.71% Branches 12/14
100% Functions 1/1
92.3% Lines 48/52

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
    531x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    4x
    4x
    4x
    4x
    1x
    324x
    324x
    324x
    324x
    324x
    324x
    324x
    4x
    324x

    320x
    320x
    324x
    1902x
    1902x
    1902x
    74x
    1902x
    4x
    4x
    4x
    4x
    4x
    4x

    4x
    4x
    1828x
    1824x
    1824x
    1902x
    320x
    320x
     /* eslint-disable @typescript-eslint/no-unsafe-return */
    /* eslint-disable @typescript-eslint/no-explicit-any */
    /* eslint-disable @typescript-eslint/no-unsafe-call */
    /* eslint-disable @typescript-eslint/no-unsafe-member-access */
    /* eslint-disable @typescript-eslint/no-unsafe-assignment */
    // eslint-disable-next-line @typescript-eslint/ban-types
    export interface ISerializable extends Object {
      toJSON(): object
      toBSON(): object
      [index: string]: any
    }

    export enum SerializationStrategy {
      JSON = 'toJSON',
      BSON = 'toBSON',
    }

    export function Serialize(
      strategy: SerializationStrategy,
      document: ISerializable,
      keys?: string[]
    ): object {
      const strategyFunc = strategy.toString()
      if (!keys && document && typeof document[strategyFunc] === 'function') {
        return document[strategyFunc]()
      } else if (!keys) {
        return {}
      }
      keys = Array.from(new Set(keys))
      const serializationTarget: { [index: string]: any } = {}
      for (const key of keys) {
        const child = document[key]

        if (child && typeof child[strategyFunc] === 'function') {
          serializationTarget[key] = child[strategyFunc]()
        } else if (Array.isArray(child)) {
          if (child.length > 0) {
            serializationTarget[key] = []
            for (const cc of child) {
              if (typeof cc === 'object') {
                serializationTarget[key].push(Serialize(strategy, cc as ISerializable))
              } else {
                serializationTarget[key].push(cc)
              }
            }
          }
        } else {
          serializationTarget[key] = child
        }
      }
      return serializationTarget
    }