All files / deserializers json.js

100% Statements 40/40
100% Branches 19/19
100% Functions 6/6
100% Lines 35/35

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 651x       800x 800x   800x 400x 400x 400x   400x     400x 400x 400x 400x   400x             400x   400x   400x 361x   307x 1961x 307x     400x       800x 800x 800x   800x 2836x   2836x 2836x 625x   2211x 2211x 2211x 2211x 2211x       800x    
module.exports = {
  name: 'json',
  desc: 'deserializes each chunk into JSON, but fails all chunks if an error is thrown:\n\n--no-bulk, -B [boolean]\nDeactivates bulk deserializing, which is much slower, but fails only those chunks that throw an error.\n',
  func: ({B, noBulk, verbose}) => {
    const _noBulk           = noBulk || B || false
    const deserializeChunks = chunksDeserializer({verbose})
  
    if (_noBulk) {
      return (chunks, lines) => {
        const _lines       = verbose > 0 ? lines : []
        const {jsons, err} = deserializeChunks(chunks, _lines)
  
        return {jsons, err}
      }
    } else {
      return (chunks, lines) => {
        const _lines       = verbose > 0 ? lines : []
        const {jsons, err} = deserializeChunks(concatChunks(chunks), _lines)
        const jsons2       = typeof jsons[0] !== 'undefined' ? jsons[0] : []
 
        return {jsons: jsons2, err}
      }
    }
  }
}
 
function concatChunks (chunks) {
  let str = '['
 
  const chunksLen = chunks.length
 
  if (chunksLen === 0) str += ']'
  else if (chunksLen === 1) str += chunks[0] + ']'
  else {
    str += chunks[0]
    for (let index = 1; index < chunksLen; index++) str += ',' + chunks[index]
    str += ']'
  }
 
  return [str]
}
 
function chunksDeserializer ({verbose, chunker}) {
  return (chunks, lines) => {
    const jsons = []
    const err   = []
  
    for (let index = 0; index < chunks.length; index++) {
      const chunk = chunks[index]
  
      try {
        const obj = JSON.parse(chunk)
        jsons.push(obj)
      } catch (e) {
        const hint = '(if the JSON is formatted over several lines, try using the jsonObj chunker)'
        const msg  =               {msg:  e.message + ' ' + hint}
        const line = verbose > 0 ? {line: lines[index]} : {}
        const info = verbose > 1 ? {info: chunk}        : {}
        err.push(Object.assign(msg, line, info))
      }
    }
  
    return {err, jsons}
  }
}