npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@rpiotti/lambda-micro

v0.0.1

Published

Minimal JavaScript microservices router for AWS Lambda

Downloads

1

Readme

lambda-micro

Build Status Code Coverage npm

Minimal microservices router for AWS Lambda

Concepts

The Lambda Micro router takes two types of arguments: matchers and handlers. The matcher is used to determine if the handlers should be executed for a specific Lambda invocation. The handlers are one or more functions that will be executed for that invocation.

Matchers

The framework includes matchers, but you can also write your own. Here is an example of a matcher for an API Gateway HTTP API (Payload V2):

const matcher = Matcher.HttpApiV2('GET', '/documents(/:id)');

In this case, this matcher is configured to receive an HTTP method (GET in this case) and a URL pattern (using the url-pattern library).

You can also write your own matchers. Matchers receive a request object, and must return either true or false. You can see the entire code for the HTTP API matcher below:

export const matcher = (method, urlPattern) => request => {
  // Is HTTP Context present
  const { event } = request;
  if (!event.requestContext || !event.requestContext.http) {
    return false;
  }
  const httpContext = event.requestContext.http;

  // Does Method match
  const { method: requestMethod, path } = httpContext;
  if (method.toLowerCase() !== requestMethod.toLowerCase()) {
    return false;
  }

  // Does URL Pattern match
  const pattern = new UrlPattern(urlPattern);
  const result = pattern.match(path);

  if (!result) {
    return false;
  }

  // Add path variables to the request object
  request.addRequestData('pathVariables', result);
  // It does match, return true
  return true;
};

You can see in this example that there is a function on the request object, addRequestData that enables the matcher to populate data on the request object that will be passed down to each of the handlers. In this case, this is used to pass down the path variables to the handler functions.

Handlers

Handler functions are executed if the matcher returns true (only the first route that has a matcher that returns true will be executed).

Handler functions receive a request and response object. The request object includes the request data, (including the event and context for the Lambda invocation). The response object includes an output function that provides an easy way to create the required output format (based on the type of router that was configured).

const doSomething = async (request, response) => {
  return response.output({
    message: 'Success'
  }, 200);
};

Examples

API Gateway - HTTP API (Payload V2)

// Create a router
const router = createRouter(RouterType.HTTP_API_V2);

// Call a single function on a route
// The matcher takes the HTTP method and a URL pattern
router.add(Matcher.HttpApiV2('GET', '/service/'), getData);

// Use a path variable, and validate path variables with a JSON schema
router.add(
  Matcher.HttpApiV2('GET', '/service(/:id)'),
  validatePathVariables(pathVariablesSchema),
  getDocument,
);

// Handle a route with multipart form data
// Includes validation of the form data with a JSON schema
router.add(
  Matcher.HttpApiV2('POST', '/service/'),
  parseMultipartFormData,
  validateMultipartFormData(formDataSchema),
  createDocument,
);

// Handle a route that is passed JSON in the body
// Validate the body with a JSON schema
router.add(
  Matcher.HttpApiV2('PATCH', '/service(/:id)'),
  validateBodyJSONVariables(jsonBodySchema),
  updateDocument,
);

// Run the router in the handler function
exports.handler = async (event, context) => {
  return router.run(event, context);
};

Logging

This framework also provides a logger that includes a basic configurable logger for Lambda. Creating a logger is as simple as calling:

// Create a logger by passing in Lambda event and context
const logger = getLogger(event, context);

Once you have a logger, you can log messages at different levels. This includes:

| Function | Log Level | |-------|-------------| | logger.trace | TRACE (10) | | logger.debug | DEBUG (20) | | logger.info | INFO (30) | | logger.warn | WARN (40) | | logger.error | ERROR (50) |

Logging Content

The logger can log three types of values: plain strings, JSON strings (which will be parsed and flattened), and objects (which will be flattened).

Configuring the Logging Level

The logger has a configurable log level. By default, the logger sets the log level at INFO. This means that it will log INFO, WARN, and ERROR messages.

The logger is configurable for the log level. If you specify a value for the LOG_LEVEL environment variable, it will be used. This should be specified as the numeric value:

// Setting the environment variable in the CDK
// Will log DEBUG and above
lambdaFunction.addEnvironment('LOG_LEVEL', '20');

In the above example, it would not also log the DEBUG messages (in addition to INFO, WARN, and ERROR messages).