All files / features/parses-json-lines-object-array-data-response parse-json-lines-response.js

40.38% Statements 21/52
100% Branches 0/0
0% Functions 0/3
40.38% Lines 21/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 532x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x                                                           2x 2x 2x 2x 2x 2x 2x 2x 2x      
import { parseJsonLines } from '../../utils/json-lines-parser.js'
import { isPlainObject } from '../../utils/object.js'
import { linkHeaderOf, toTextStream, parseHasMoreHeader } from '../../utils/response.js'
/** @import {ParsedResponse} from '../data-loading/fetch-data' */
/**
 * Checks if response is a valid CSV response
 * It checks by checking content type is CSV
 *
 * @param {Response} response - response from fetch
 * @returns {Promise<ParsedResponse>} parsed response
 */
export async function parseJsonLinesResponse (response) {
  if (!isJsonLinesResponse(response)) {
    throw Error('Not an CSV response')
  }

  const linkHeader = linkHeaderOf(response)
  const hasNextHeader = parseHasMoreHeader(response)
  const data = (await Array.fromAsync(parseJsonLines(toTextStream(response)))).filter(isPlainObject)

  if (linkHeader.byRel.next) {
    return {
      hasMore: true,
      navigationMode: 'link',
      href: linkHeader.byRel.next[0].url,
      data,
    }
  }
  if (hasNextHeader) {
    return {
      hasMore: true,
      navigationMode: 'after_value',
      data,
    }
  }

  return {
    hasMore: false,
    data,
  }
}
 
/**
 * Checks if response is a valid JSON Lines response
 * It checks by checking content type is JSON Lines and the response is a 200 status ok
 *
 * @param {Response} response - response from fetch
 * @returns {boolean} true if is a valid JSON Lines response, false otherwise
 */
export function isJsonLinesResponse (response) {
  return response.ok && response.headers.get('Content-Type') === 'application/jsonl'
}