# @theorchard/lambda-utils

Common utilities for Node based lambdas.

## `staticInit` usage

**Consider using top-level await in new lambdas instead of this util.**

If your lambda has processes that require asynchronous initialization outside the scope of your handler, you can use `staticInit` to wrap your handler:

```ts
export const handler = SentryLambda.wrapHandler(
    staticInit(
        Promise.all([
            kafkaProducer.connect(),
        ]),
        (event) => {
            // Your handler goes here.
        },
    );
);
```

## msk

### `mskHandler` usage

For lambdas that are using MSK trigger, a utility handler is provided that lets you implement a handler for a single record:

```ts
export const handler = SentryLambda.wrapHandler(
    mskHandler({
        recordHandler(record) {
            // Handle each record
        },
    });
);
```

By default, the handler merges all messages on all topics and deduplicates them by key, taking the latest message for each key. It then executes your `recordHandler` in parallel for each record.

If you require only handling records one at a time you can disable parallel processing by specifying `config`. You are required to explicitly state both `deduplicateByKey` and `parallel` in this case to make it very clear what ordering guarantees you are opting in to.

```ts

export const handler = SentryLambda.wrapHandler(
    mskHandler({
        config: {
            deduplicateByKey: true,
            parallel: false,
        },
        recordHandler(record) {
            // Handle each record
        },
    });
);
```

Using `parallel = true` with `deduplicateByKey = false` is heavily discouraged, as you may end up processing two events for the same key simultaneously which may lead to processing bugs.

## `ClientConnector` usage

This is to invoke a real lambda function with specific event data:

```ts
const lambdaConnector = new LambdaConnector('us-east-1');
const { result } = await lambdaConnector.invokeLambda('qa-nr-lambda-validate', {
    some: 'event payload',
});
```
