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

@buildist/lambda-lib

v1.0.0

Published

Builders and tools for creating AWS Lambda function handlers that provides automation for things such as logging, instrumentation and parameters propagation

Downloads

3

Readme

lambda-lib

This library is a toolbox for creating AWS Lambda handlers that provides tooling and automation for:

  • structured logging and serialization of both incoming events and responses;
  • exception handling;
  • remote calls to other lambda APIs (via HTTP, SNS or Kinesis), with automated -- Correlation id propagation -- Request and response logging -- AWS X-Ray instrumentation

Usage

Lambda Handler Builder

Supose you have a business logic module (myServiceModule in the example below) and must give an http endpoint to it, like so:

Sequence Diagram

In such case, you might use LambdaEndpoint:

exports.myLambdaHandler = new LambdaEndpoint()
	.withHandler(myServiceModule.someBusinessHandler)
	.withStaticParams('myParam1', myParam2)
	.build();

This will return a lambda handler similar to the following:

exports.myLambdaHandler = async (event, context, callback) => {
	try {
		//... do some logging and event pre-processing
		let result = myServiceModule.someBusinessHandler('myParam2', myParam2);
		//... do some logging and success post-processing
		callback(null, result);
	} catch(e) {
		//... do some logging and error post-processing
		callback(errorResult);
	}
}

Lambda Handler Wrapper

An alternative way to achieve the same goal is to use the Labda Wrapper notation:

exports.myLambdaHandler = LambdaEndpoint.Wrap(async (event, context, callback) => {
		let myParam = event.queryStringParameters.myParam;
		return myServiceModule.someBusinessHandler('myParam2', myParam);
});

Using either Wrapper or Builder form, event will be pre-processed, so for instance, in the above example event.queryStringParameters will never be undefined.

Also, the error or success callback will be handled by the wrapper, all you have to do is return the data (or throw the proper exception).

Event parsing

Most of the times, you may not have static parameters to your inner service call. You may get such values from the incoming event like such:

exports.myLambdaHandler = new LambdaEndpoint()
	.withHandler(myServiceModule.someBusinessHandler)
	.withEventParams(e => [e.body.some, e.queryStringParams.someOther])
	.build();

This would be similar to:

exports.myLambdaHandler = async (event, context, callback) => {
	try {
		let param1 = JSON.parse(event.body).some;
		let param2 = event.querystringParams.someOther
		let result = myServiceModule.someBusinessHandler(param1, param2);
		callback(null, result);
	} catch(e) {
		//...
	}
}

Note that event.body is automatically parsed, but only if it's headers include content-type=application/json

Error handling

Handled Business Exceptions

TODO

Unhandled Business Exception

TODO

Provided Clients: cascading function calls

Now let's assume your lambda or business logic may need to access some other lambda. Using the provided clients ensures these calls will be logged in a standard and structured manner, and that will propagate logging settings and correlation id's.

Sequence Diagram - Cascade

  • HTTP
const { httpClient, RemoteException } = require('@buildist/lambda-lib').Clients;

try {
	let response = await httpClient.makeRequest('GET', 'https://my.service/foo');
} catch(e) {
	if(e instanceof RemoteException) {
		let {statusCode, errorCode, message} = e;
	}
}
  • SNS
//TODO
  • Kinesis
//TODO

Log

You must set the log level in lambda's environment variable process.env.LOG_LEVEL, and it must be either DEBUG, INFO, WARN or ERROR. The default value is DEBUG.

Using the service builder and client libraries, it will be automatically logged:

  • ERROR
    • Errors with attached invocation event)
  • INFO
    • Incoming Events
    • Outgoing service responses (callback)
  • DEBUG
    • Outgoing HTTP, SNS and Kinesis events
    • Incoming HTTP responses
//example log output for the cascading function calls scenario: 
{"message":"LAMBDA EVENT RECEIVED","level":"INFO","awsRegion":"us-west-2","awsRequestId":"myAwsRequestId","x-correlation-id":"myAwsRequestId","Debug-Log-Enabled":"true","httpMethod":"GET","headers":{}}
{"message":"HTTP REQUEST","level":"DEBUG","awsRegion":"us-west-2","x-correlation-id":"myAwsRequestId","x-correlation-myKey":"myVal","hostname":"my.host","path":"/foo","port":null,"method":"GET","headers":{"x-correlation-id":"myCorrelationId","x-correlation-myKey":"myVal"}}
{"message":"HTTP RESPONSE","level":"DEBUG","awsRegion":"us-west-2","x-correlation-id":"myAwsRequestId","x-correlation-myKey":"myVal","statusCode":200,"body":"{}","headers":{"content-type":"application/json"}}
{"message":"LAMBDA RESPONSE","level":"INFO","awsRegion":"us-west-2","awsRequestId":"myAwsRequestId","x-correlation-id":"myAwsRequestId","Debug-Log-Enabled":"true","statusCode":200,"headers":{"Content-Type":"application/json","Access-Control-Allow-Credentials":true}}

Correlation IDs

If the remote lambda is build using this lambda-builder, they will log the same correlation ID in the incoming event, and you will be able to track a long-living business event in the logs of every function involved.