Skip to content

Fastify plugin to use AWS Lambda Powertools for Typescript

License

Notifications You must be signed in to change notification settings

jorgevrgs/fastify-aws-powertools

Repository files navigation

fastify-aws-powertools

NPM Version CI

Introduction

Implementation of a Fastify plugin of AWS Lambda Powertools for Typescript to take advantage of Logger, Metrics, and Tracer services for AWS Lambda. Inspired by Middy middleware created by AWS Lambda Powertools team.

Getting Started

Install the dependency:

npm i fastify-aws-powertools

Add peer dependencies (if there are not installed yet):

npm i fastify @fastify/aws-lambda

Configure the plugin:

import fastifyAwsPowertool from 'fastify-aws-powertools';
import type { FastifyAwsPowertoolsOptions } from 'fastify-aws-powertools';
import type { FastifyASyncPlugin } from 'fastify';

export const plugin: FastifyASyncPlugin = async (fastify) => {
  const options: FastifyAwsPowertoolsOptions = {
    loggerOptions: {
      logEvent: true,
      clearState: true,
    },
    metricsOptions: {
      captureColdStartMetric: true,
    },
    tracerOptions: {
      captureResponse: true,
    },
  };
  fastify.register(fastifyAwsPowertool, options);
};

Also, available each plugin separately:

import { fastifyAwsPowertoolsLogger } from 'fastify-aws-powertools';
import type { FastifyAwsPowertoolsOptions } from 'fastify-aws-powertools';
import type { FastifyASyncPlugin } from 'fastify';

export const plugin: FastifyASyncPlugin = async (fastify) => {
  const options: FastifyAwsPowertoolsOptions = {
    loggerOptions: {
      logEvent: true,
      clearState: true,
    }
  };
  fastify.register(fastifyAwsPowertoolsLogger, options);
};

Dependencies

Install and configure @fastify/aws-lambda to use this plugin. See @fastify/aws-lambda.

Options

Logger, Metrics, and Tracer instances will be automatically provided if either (logger|metrics|tracer) or (logger|metrics|tracer)InstanceOptions are provided.

Logger Plugin

Property Description Default
logger Logger instance, otherwise provide loggerInstanceOptions undefined
loggerOptions {logEvent?: boolean; resetKeys?: boolean;} undefined
loggerInstanceOptions See ConstructorOptions undefined

Metrics Plugin

Property Description Default
metrics Metrics instance, otherwise provide metricsInstanceOptions undefined
metricsOptions {throwOnEmptyMetrics?: boolean; defaultDimensions?: Record<[key: string]: string>; captureColdStartMetric?: boolean;} undefined
metricsInstanceOptions See MetricsOptions undefined

Tracer Plugin

Property Description Default
tracer Tracer instance, otherwise provide tracerInstanceOptions undefined
tracerOptions {captureResponse?: boolean;} undefined
tracerInstanceOptions See TracerOptions undefined

PowerTools Plugin

Use fastifyAwsPowertoolsPlugin if you want to use all the plugins.

Example

Simple example using all the plugins:

// index.ts
import fastify from 'fastify';
import awsLambdaFastify from '@fastify/aws-lambda';
import { MetricUnits } from '@aws-lambda-powertools/metrics';
import fastifyAwsPowertool, {
  type FastifyAwsPowertoolsOptions,
} from 'fastify-aws-powertools';

const server = fastify({
  logger: false,
});

server.register(fastifyAwsPowertool);

server.get('/', async (request, reply) => {
  request.tracer.putAnnotation('successfulBooking', true);
  request.logger.info('This is a log with an extra variable', {
    foo: 'bar',
  });
  request.metrics.addMetric('successfulBooking', MetricUnits.Count, 1);
  request.metrics.addMetadata(
    'bookingId',
    '7051cd10-6283-11ec-90d6-0242ac120003',
  );
  request.metrics.publishStoredMetrics();

  return 'Hello world!';
});

const proxy = awsLambdaFastify(server);

export const handler = async (event: any, context: any) =>
  proxy(event, context);

Additional examples can be found in the examples folder.

import fastifyAwsPowertoolsPlugin, { type FastifyAwsPowertoolsOptions, Logger as FastifyLogger } from 'fastify-aws-powertools';
import { Logger } from '@aws-lambda-powertools/logger';
import { Metrics } from '@aws-lambda-powertools/metrics';
import { Tracer } from '@aws-lambda-powertools/tracer';
import { Fastify, type FastifyASyncPlugin } from 'fastify';


const serviceName = 'my-service';

const logger = new Logger({
    serviceName,
  });

const metrics = new Metrics({
  serviceName,
  namespace: serviceName,
});

const tracer = new Tracer({
  serviceName,
  captureHTTPsRequests: true,
});

tracer.provider.setLogger(logger);

export const myPlugin: FastifyASyncPlugin = async (fastify) => {

  const options: FastifyAwsPowertoolsOptions = {
    logger,
    metrics,
    tracer,
    loggerOptions: {
      logEvent: true,
      clearState: true,
    },
    metricsOptions: {
      captureColdStartMetric: true,
    },
    tracerOptions: {
      captureResponse: true,
    },
  };
  fastify.register(fastifyAwsPowertoolsPlugin, options);
};

const logger = new FastifyLogger({
  serviceName
});

const app = Fastify({ logger });