# lambda-http-interceptor

> This library enables you intercept and mock HTTP call made by an AWS Lambda. It's useful for integration testing.

Latest version **0.1.1** (published 2023-10-27) · 0 weekly downloads

## Install

```sh
npm install lambda-http-interceptor
pnpm add lambda-http-interceptor
yarn add lambda-http-interceptor
bun add lambda-http-interceptor
```

## Health

**Score 20/100 (F)** — status: abandoned.

Positive: has types; no vulnerabilities.

Warnings: low downloads; no esm support; pre 1.0.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 0.1.1 |
| Published | 2023-10-27 |
| First published | 2023-06-02 |
| Weekly downloads | 0 |
| TypeScript types | bundled |
| Module format | CommonJS |
| Dependencies | 7 |
| Unpacked size | 6.9 MB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| Maintainers | maxoomv |

## Links

- npm: https://www.npmjs.com/package/lambda-http-interceptor
- npm.io page: https://npm.io/package/lambda-http-interceptor

## Dependencies (7)

- [msw](https://npm.io/package/msw.md) ^1.2.3
- [ulid](https://npm.io/package/ulid.md) ^2.3.0
- [debug](https://npm.io/package/debug.md) ^4.3.4
- [dynamodb-toolbox](https://npm.io/package/dynamodb-toolbox.md) 1.0.0-beta.0
- [@aws-sdk/lib-dynamodb](https://npm.io/package/@aws-sdk/lib-dynamodb.md) ^3.365.0
- [@aws-sdk/client-dynamodb](https://npm.io/package/@aws-sdk/client-dynamodb.md) ^3.363.0
- [@swarmion/serverless-helpers](https://npm.io/package/@swarmion/serverless-helpers.md) ^0.28.2

## Recent versions

- 0.1.1 (latest) — 2023-10-27
- 0.1.0 — 2023-10-27
- 0.0.7 — 2023-09-15
- 0.0.6 — 2023-09-15
- 0.0.5 — 2023-06-30
- 0.0.4 — 2023-06-16
- 0.0.3 — 2023-06-16
- 0.0.2 — 2023-06-02
- 0.0.1 — 2023-06-02

## README

# HTTP Lambda Interceptor

This library enables you intercept and mock HTTP call made by an AWS Lambda. It's useful for integration testing.

Performing integration tests on deployed resources allows testing applications in the best prod alike environment. Thanks to the interceptor, lambda can be tested without interacting with costly external endpoints or non preprod external endpoints for example.

## Getting started

This library is made of a CDK Construct to instantiate in your stack and a sdk to tool the integration tests.

The HttpInterceptor construct needs to be instantiated in the stack, or inside another Construct.

```ts
import { Stack, StackProps } from "aws-cdk-lib";

import { Construct } from "constructs";
import { HttpInterceptor, applyHttpInterceptor } from "http-lambda-interceptor";
import { NodejsFunction } from "aws-cdk-lib/aws-lambda-nodejs";
import { Runtime } from "aws-cdk-lib/aws-lambda";

export class MyStack extends Stack {
  constructor(scope: Construct, id: string, props?: StackProps) {
    super(scope, id, props);

    const interceptor = new HttpInterceptor(this, "HttpInterceptor");

    const myLambdaFunctionThatMakesExternalCalls = new NodejsFunction(
      this,
      "MakeExternalCalls",
      {
        runtime: Runtime.NODEJS_18_X,
        handler: "index.handler",
        entry: './handler.ts',
      },
    );

    applyHttpInterceptor(myLambdaFunctionThatDoesExternalCalls, interceptor);
  }
}
```

After Deploying that part, everything is setup on the stack to perform integration tests.

```typescript
import fetch from "node-fetch";
import { expect, describe, it } from "vitest";

process.env.HTTP_INTERCEPTOR_TABLE_NAME = '<table-name-from-construct>'

import { setupLambdaHttpInterceptorConfig } from "http-lambda-interceptor";

import { triggerMyLambdaFunctionThatMakesExternalCalls } from './utils';

describe("hello function", () => {
  it("returns a 200", async () => {
    await setupLambdaHttpInterceptorConfig({
      lambdaName: '<myLambdaFunctionThatMakesExternalCalls-name>',
      mockConfigs: [
        {
          url: "https://api-1/*",
          response: {
            status: 404,
            body: JSON.stringify({
              errorMessage: "Not found",
            }),
          },
        },
        {
          url: "https://api-2/path",
          response: {
            passThrough: true,
          },
        },
      ],
    });
    const response = await triggerMyLambdaFunctionThatMakesExternalCalls();
    expect(response.status).toBe(200);
  });
});
```

>To resolve <table-name-from-construct> and <myLambdaFunctionThatMakesExternalCalls-name> easily, we recommend the usage of [@swarmion/integration-tests](https://www.swarmion.dev/docs/how-to-guides/use-integration-tests/)

## How it works

### The CDK Construct

The `HttpInterceptor` needs to be instantiated inside a stack. It contains what is necessary to mock calls:
- an extension 

Then the method `applyHttpInterceptor` needs to be used to link any Lambda to the extension that has been set.
This method can be called with any construct and it will attach the extension to every NodejsFunction Construct nested inside it. Therefore, it can also be called with `this` in the constructor of the stack like the following.

```ts
import { Stack, StackProps } from "aws-cdk-lib";

import { Construct } from "constructs";
import { HttpInterceptor, applyHttpInterceptor } from "http-lambda-interceptor";
import { NodejsFunction } from "aws-cdk-lib/aws-lambda-nodejs";
import { Runtime } from "aws-cdk-lib/aws-lambda";

export class MyStack extends Stack {
  constructor(scope: Construct, id: string, props?: StackProps) {
    super(scope, id, props);

    const interceptor = new HttpInterceptor(this, "HttpInterceptor");

    const myLambdaFunctionThatMakesExternalCalls = new NodejsFunction(
      this,
      "MakeExternalCalls",
      {
        runtime: Runtime.NODEJS_18_X,
        handler: "index.handler",
        entry: './handler.ts',
      },
    );

    applyHttpInterceptor(this, interceptor);
  }
}
```

The construct exposes the name of the DynamoDB table that is used to perform under the hood the configuration of all mocks.
This variable needs to be instantiated to the test environment in which the integration tests are performed.

You can also specify the name of this table yourself in the configuration of the HttpInterceptor construct.

The other part of the library sits in the sdk used to perform the mocking part. Because with only this part, lambda work the same way they did before attaching the extension to it.

### The SDK to use in integration tests

The SDK part is the tooling used to configure the calls that need to be intercepted.

The extension also uses the SDK for fetching the configuration that are set in the tests.

#### How to setup the calls configuration

A method named `setupLambdaHttpInterceptorConfig` is used to set up the configuration that will be used by the lambda to handle the interception of the calls.

The only requirement for the lambda calls to be intercepted is that this setup needs to be done synchronously before the call of the lambda. You can trigger the lambda synchronously or asynchronously, but the setup of the config needs to be done before that.

This is the type of object you need to pass as argument to create the configuration

```typescript
type LambdaHttpInterceptorConfigInput = {
  lambdaName: string;
  mockConfigs: {
    url?: string;
    method?: string;
    body?: string;
    headers?: {
      [x: string]: string;
    };
    response:
      | {
          passThrough: true;
        }
      | {
          status: number;
          body?: string;
          headers?: {
            [x: string]: string;
          };
          passThrough?: false;
        };
    created?: string;
    modified?: string;
    queryParams?:
      | {
          [x: string]: string | undefined;
        }
      | undefined;
  }[];
};
```

This is how to use the `setupLambdaHttpInterceptorConfig` method.

```typescript
import fetch from "node-fetch";
import { expect, describe, it } from "vitest";

process.env.HTTP_INTERCEPTOR_TABLE_NAME = '<table-name-from-construct>'

import { setupLambdaHttpInterceptorConfig } from "http-lambda-interceptor";

import { triggerMyLambdaFunctionThatMakesExternalCalls } from './utils';

describe("hello function", () => {
  it("returns a 200", async () => {
    await setupLambdaHttpInterceptorConfig({
      lambdaName: '<myLambdaFunctionThatMakesExternalCalls-name>',
      mockConfigs: [
        {
          url: "https://api-1/*",
          response: {
            status: 404,
            body: JSON.stringify({
              errorMessage: "Not found",
            }),
          },
        },
        {
          url: "https://api-2/path",
          response: {
            passThrough: true,
          },
        },
      ],
    });
    const response = await triggerMyLambdaFunctionThatMakesExternalCalls();
    expect(response.status).toBe(200);
  });
});
```

The url matching process works by 2 possible ways:
- an exact match of the whole url (ex: `https://api-2/path-1/path-2`)
- an exact match on part of the url. Every url beginning with the same path until the `*`, is matched (ex: `https://api-1/path/*` matches `https://api-1/path` and `https://api-1/path/path-3`)

The method to be given in the method prop needs to be one the [standard HTTP request methods name](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods).

The response status to be given in the params needs to be one the [standard HTTP response status codes](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status).


### Multiple lambda triggers into a testing suite or across testing suites

A `beforeEach` for setup and a `afterEach` with the cleaning method are required in order to make assertions independently between each test of a suite.

For avoiding collisions between testing suites, if the cleaning method is not called in a test for a specific reason, the method needs to be called in a `afterAll`.

And all tests dealing with the same lambda need to be performed in band, they can't be performed in parallel.

PUT EXAMPLE CODE OF THE TEST FILE

### Making expects on the intercepted calls

The method waitForNumberOfInterceptedCalls is used to wait for all intercepted calls when they have been done. It needs configuration about the maximum time to wait before throwing because all supposed intercepted calls have been intercepted.

```typescript
import fetch from "node-fetch";
import { expect, describe, it } from "vitest";

process.env.HTTP_INTERCEPTOR_TABLE_NAME = '<table-name-from-construct>'

import { setupLambdaHttpInterceptorConfig } from "http-lambda-interceptor";

import { triggerMyLambdaFunctionThatMakesExternalCalls } from './utils';

describe("hello function", () => {
  it("returns a 200", async () => {
    await setupLambdaHttpInterceptorConfig({
      lambdaName: '<myLambdaFunctionThatMakesExternalCalls-name>',
      mockConfigs: [
        {
          url: "https://api-1/*",
          response: {
            status: 404,
            body: JSON.stringify({
              errorMessage: "Not found",
            }),
          },
        },
        {
          url: "https://api-2/path",
          response: {
            passThrough: true,
          },
        },
      ],
    });
    const response = await triggerMyLambdaFunctionThatMakesExternalCalls();
    expect(response.status).toBe(200);
  });
  afterEach(async () => {
    await cleanInterceptedCalls('<myLambdaFunctionThatMakesExternalCalls-name>');
  });
  it('returns 200 and catches 2 requests', async () => {
    const response = await fetch(
      `${TEST_ENV_VARS.API_URL}/make-external-call`,
      {
        method: 'post',
      },
    );

    const resp = await waitForNumberOfInterceptedCalls(
      '<myLambdaFunctionThatMakesExternalCalls-name>',
      2,
      5000,
    );
    expect(response.status).toBe(200);
    expect(resp.length).toBe(2);
  });
  it('returns also 200 and catches also 2 requests', async () => {
    const response = await fetch(
      `${TEST_ENV_VARS.API_URL}/make-external-call`,
      {
        method: 'post',
      },
    );

    const resp = await waitForNumberOfInterceptedCalls(
      '<myLambdaFunctionThatMakesExternalCalls-name>',
      2,
      5000,
    );

    expect(response.status).toBe(200);
    expect(resp.length).toBe(2);
    // resp contains all information about the calls made to to external API endpoints mocked
    // Expects can be made on the content of the calls made once received
  });
});
```

## Coming next

Having a class to instantiate in each test suite that will allow independent testing across all tests suites even on the same lambda.

---
_Source: https://npm.io/package/lambda-http-interceptor · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
