medikoo / aws-lambda-handler

Essential AWS Lambda handler setup

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

*nix build status Windows build status Tests coverage

aws-lambda-handler

Essential AWS Lambda handler setup

When relying directly on basic AWS interface we're immune to handler setup errors which are not transparently reported by AWS:

  • Using callback resolution we may invoke callback twice (and we're not restricted from invoking callback coming from previous invocation). All those superfluous invocations are silently ignored by AWS.
  • Using promise resolution, invocation is resolved immediately after returned promise resolves. This leaves us with no feedback of eventually orphaned async flows (which may be result of typical errors as omitted await or return) and which are eventually executed in next lambda invocation

This handler makes above errors either impossible to make or properly exposed, and additionally:

  • Enforces simple input/output function setup (no matter whether sync or promise returning)
  • Rejects any resolution attemps via context.done or it's affiliates
  • Prevents direct setting of context.callbackWaitsForEmptyEventLoop, as having it false may leak scheduled tasks between lambda invocations.
  • Exposes get-current-context module, which provides out of band access to current invocation context.

Usage

Handler configuration

module.exports = require("aws-lambda-handler")((event, context) => {
    // ...lambda logic
    return result;
});

Above module exports lambda logic on handler property

Out of band context access

some-outer-module-down-the-path.js

const getCurrentContext = require("aws-lambda-handler/get-current-context");

module.exports = (...) => {
  // Retrieve invocation context
  const invocationContext = getCurrentContext();
  if (invocationContext.getRemainingTimeInMillis() > 1000 * 60) {
    // We have time
  } else {
    throw new Error("Not enough time");
  }
}

Tests

npm test

About

Essential AWS Lambda handler setup


Languages

Language:JavaScript 100.0%