dougmoscrop/serverless-http

View on GitHub
lib/provider/aws/is-binary.js

Summary

Maintainability
C
1 day
Test Coverage
'use strict';

const BINARY_ENCODINGS = ['gzip', 'deflate', 'br'];
const BINARY_CONTENT_TYPES = (process.env.BINARY_CONTENT_TYPES || '').split(',');

function isBinaryEncoding(headers) {
  const contentEncoding = headers['content-encoding'];

  if (typeof contentEncoding === 'string') {
    return contentEncoding.split(',').some(value =>
      BINARY_ENCODINGS.some(binaryEncoding => value.indexOf(binaryEncoding) !== -1)
    );
  }
}

function isBinaryContent(headers, options) {
  const contentTypes = [].concat(options.binary
    ? options.binary
    : BINARY_CONTENT_TYPES
  ).map(candidate =>
    new RegExp(`^${candidate.replace(/\*/g, '.*')}$`)
  );

  const contentType = (headers['content-type'] || '').split(';')[0];
  return !!contentType && contentTypes.some(candidate => candidate.test(contentType));
}

module.exports = function isBinary(headers, options) {
  if (options.binary === false) {
    return false;
  }

  if (options.binary === true) {
    return true
  }

  if (typeof options.binary === 'function') {
    return options.binary(headers);
  }

  return isBinaryEncoding(headers) || isBinaryContent(headers, options);
};