Skip to content

Commit

Permalink
fix(core): check if fetchFile response matches request
Browse files Browse the repository at this point in the history
Throw an error when the Content-Type header of a fetchFile response does 
not match the Accept header of the request.

closes #36
  • Loading branch information
larsgw committed Jun 28, 2019
1 parent 9250844 commit e9f9132
Showing 1 changed file with 36 additions and 1 deletion.
37 changes: 36 additions & 1 deletion packages/core/src/util/fetchFile.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,19 @@ import 'isomorphic-fetch'

import logger from '../logger'

/**
* @access private
* @param {Object} headers
* @return {Object}
*/
function normaliseHeaders (headers) {
const result = {}
for (let header in headers) {
result[header.toLowerCase()] = [].concat(headers[header])
}
return result
}

/**
* @access private
* @param {Object} [opts={}] - Request options
Expand Down Expand Up @@ -31,6 +44,25 @@ function parseOpts (opts = {}) {
return reqOpts
}

/**
* @access private
* @param {Object} request - request headers
* @param {Object} response - response headers
* @return {Boolean}
*/
function sameType (request, response) {
console.log(request, response)
if (!request.accept || !response['content-type']) {
return true
}

const [a, b] = response['content-type'][0].split(';')[0].split('/')
return !!request.accept
.reduce((array, header) => array.concat(header.split(/\s*,\s*/)), [])
.map(type => type.split(';')[0].split('/'))
.find(([c, d]) => (c === a || c === '*') && (d === b || d === '*'))
}

/**
* @access private
* @param {Object} response
Expand All @@ -44,15 +76,18 @@ function parseOpts (opts = {}) {
}

const status = response.status || response.statusCode
const headers = response.headers._headers || response.headers
let error

if (status >= 400) {
error = new Error(`Server responded with status code ${status}`)
} else if (!sameType(normaliseHeaders(opts.headers), normaliseHeaders(headers))) {
error = new Error(`Server responded with content-type ${headers['content-type']}`)
}

if (error) {
error.status = status
error.headers = response.headers
error.headers = headers
error.body = response.body
throw error
}
Expand Down

0 comments on commit e9f9132

Please sign in to comment.