Ad

NodeJS - Converting Event.headers To Lowercase For Use With AWS

Is there any way by which I can convert the event.headers to lowercase?

I came across this thread but I can't get it to work correctly..

index.js

// I have tried 2 different attempts, one is my own and most probably wrong, 
// the other is from the link I posted above.

// My obviously flawed attempt
function makeLower(headers) {
    for(const key in headers) {
      event.headers[key] = key.toLowerCase();
    }
  }

  // console.log('Distribution Audit Create Invoked');

  const headers = makeLower(event.headers);

  // Convert headers to lower case so AWS doesn't kick off
  // Source: https://github.com/serverless/serverless/issues/2765
  // const headers = {};
  // for (const key in event.headers) {
  //   headers[key.toLowerCase()] = event.headers[key];
  // }
  // event.headers = headers;

  console.log('HEADERS: ' + headers['content-type']);

index.test.js (testing isn't my strongest suit :-/)

it('should still return 202, with uppercase headers > 
     converting them to lower', done => {

    // Isn't working when sending in CAPS - Does work with non-caps
    event.headers = {'content-type': 'SOME HEADERS'};

    lambda.handler(event, null, (err, request) => {
      should.not.exist(err);
      should.exist(request);
      done();
    });
  })
Ad

Answer

Shouldn't your function convert both the keys and the values to lowercase?

function makeLower(headers) {
  let head = {}

  for(const key in headers) {
    if (headers.hasOwnProperty(key)) {
      head[key.toLowerCase()] = headers[key].toLowerCase()
    }
  }

  return head
}

And not use the original object to store the lowercase values? Otherwise you end up with both the lowercase and original version in your object.

Ad
source: stackoverflow.com
Ad