All files / features/parses-csv-data-response parse-csv-response.js

100% Statements 50/50
100% Branches 10/10
66.66% Functions 2/3
100% Lines 50/50

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 512x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 8x 3x 3x 5x 5x 5x 5x 8x 2x 2x 2x 2x 2x 2x 2x 8x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 19x 19x  
import { parseCSV } from '../../utils/csv-parser.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 parseCSVResponse (response) {
  if (!isCSVResponse(response)) {
    throw Error('Not an CSV response')
  }
 
  const linkHeader = linkHeaderOf(response)
  const hasNextHeader = parseHasMoreHeader(response)
  const data = await Array.fromAsync(parseCSV(toTextStream(response)))
  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 CSV response
 * It checks by checking content type is CSV and the response is a 200 status ok
 *
 * @param {Response} response - response from fetch
 * @returns {boolean} true if is a valid CSV response, false otherwise
 */
export function isCSVResponse (response) {
  return response instanceof Response && response.ok && response.headers.get('Content-Type') === 'text/csv'
}