All files / deserializers json.js

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 641x       800x 800x   800x 400x 400x 400x   400x     400x 400x 400x 400x   400x             400x   400x   400x 362x   324x 2077x 324x     400x       800x 800x 800x   800x 2903x   2903x 2903x 646x   2257x 2257x 2257x 2257x       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}) {
  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 msg  =               {msg:  e.message}
        const line = verbose > 0 ? {line: lines[index]} : {}
        const info = verbose > 1 ? {info: chunk}        : {}
        err.push(Object.assign(msg, line, info))
      }
    }
  
    return {err, jsons}
  }
}