Skip to content

Commit

Permalink
fix: captureColdStartMetric and throwOnEmptyMetrics when set to false…
Browse files Browse the repository at this point in the history
… was interpreted as true (#1090)

Co-authored-by: Florian Chazal <chazalf@amazon.com>
  • Loading branch information
flochaz and Florian Chazal committed Sep 29, 2022
1 parent 133ed3c commit 127aad4
Show file tree
Hide file tree
Showing 3 changed files with 269 additions and 95 deletions.
4 changes: 2 additions & 2 deletions packages/metrics/src/middleware/middy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,13 @@ const logMetrics = (target: Metrics | Metrics[], options: ExtraOptions = {}): mi
metricsInstances.forEach((metrics: Metrics) => {
metrics.setFunctionName(request.context.functionName);
const { throwOnEmptyMetrics, defaultDimensions, captureColdStartMetric } = options;
if (throwOnEmptyMetrics !== undefined) {
if (throwOnEmptyMetrics) {
metrics.throwOnEmptyMetrics();
}
if (defaultDimensions !== undefined) {
metrics.setDefaultDimensions(defaultDimensions);
}
if (captureColdStartMetric !== undefined) {
if (captureColdStartMetric) {
metrics.captureColdStartMetric();
}
});
Expand Down
26 changes: 26 additions & 0 deletions packages/metrics/tests/unit/Metrics.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -371,6 +371,32 @@ describe('Class: Metrics', () => {
}
});

test('Error should not be thrown on empty metrics if throwOnEmptyMetrics is set to false', async () => {
expect.assertions(1);

const metrics = new Metrics({ namespace: 'test' });
class LambdaFunction implements LambdaInterface {
@metrics.logMetrics({ throwOnEmptyMetrics: false })
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
public handler<TEvent, TResult>(
_event: TEvent,
_context: Context,
_callback: Callback<TResult>,
): void | Promise<TResult> {
return;
}
}

try {
await new LambdaFunction().handler(dummyEvent, dummyContext.helloworldContext, () => console.log('Lambda invoked!'));
} catch (e) {
fail(`Should not throw but got the following Error: ${e}`);
}
const loggedData = JSON.parse(consoleSpy.mock.calls[0][0]);
expect(loggedData._aws.CloudWatchMetrics[0].Metrics.length).toBe(0);
});

test('Error should be thrown on empty metrics when throwOnEmptyMetrics() is called', async () => {
expect.assertions(1);

Expand Down
Loading

0 comments on commit 127aad4

Please sign in to comment.