Idiomatic Query string parameter parsing in nodejs on AWS Lambda

Viewed 1697

Consider the following a nodeJS function running on AWS Lambda, serving http requests:

module.exports.fetchLogLines = (event, context, callback) => {

  // Parse the 'token' param string argument
  let token = null;
  if ((event.queryStringParameters !== null) && 
      ('nextForwardToken' in event.queryStringParameters)) {
    token = event.queryStringParameters.nextForwardToken;
  }

  // Parse the 'tailf' param string argument
  let startFromHead = true;
  if ((event.queryStringParameters !== null) && 
      ('tailf' in event.queryStringParameters) &&
      (event.queryStringParameters.tailf === 'true')) {
    startFromHead = false;
  }

  // Parse the logStreamName param string argument
  const logStreamName = event.queryStringParameters.logStreamName;
  ...

This seems to be a cumbersome way to parse the query string arguments:

  • 7 LOC for validation and parsing
  • Mo obvious way to specify which arguments are required and which are optional
  • No obvious way to define expected types (Integer, number, etc.) and cast the values
  • No true value assertion - for example, tailf is checked for === 'true', ignoring True, yes, 1, on and other texts meaning true in API conventions

There ought to be a library that does that.

Is there an idiomatic way to parse query string arguments in nodeJS, define their types, and specify which arguments are required and which ones are optional?

0 Answers
Related