Skip to content

Commit 127aad4

Browse files
flochazFlorian Chazal
and
Florian Chazal
authored
fix: captureColdStartMetric and throwOnEmptyMetrics when set to false was interpreted as true (#1090)
Co-authored-by: Florian Chazal <[email protected]>
1 parent 133ed3c commit 127aad4

File tree

3 files changed

+269
-95
lines changed

3 files changed

+269
-95
lines changed

Diff for: packages/metrics/src/middleware/middy.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -9,13 +9,13 @@ const logMetrics = (target: Metrics | Metrics[], options: ExtraOptions = {}): mi
99
metricsInstances.forEach((metrics: Metrics) => {
1010
metrics.setFunctionName(request.context.functionName);
1111
const { throwOnEmptyMetrics, defaultDimensions, captureColdStartMetric } = options;
12-
if (throwOnEmptyMetrics !== undefined) {
12+
if (throwOnEmptyMetrics) {
1313
metrics.throwOnEmptyMetrics();
1414
}
1515
if (defaultDimensions !== undefined) {
1616
metrics.setDefaultDimensions(defaultDimensions);
1717
}
18-
if (captureColdStartMetric !== undefined) {
18+
if (captureColdStartMetric) {
1919
metrics.captureColdStartMetric();
2020
}
2121
});

Diff for: packages/metrics/tests/unit/Metrics.test.ts

+26
Original file line numberDiff line numberDiff line change
@@ -371,6 +371,32 @@ describe('Class: Metrics', () => {
371371
}
372372
});
373373

374+
test('Error should not be thrown on empty metrics if throwOnEmptyMetrics is set to false', async () => {
375+
expect.assertions(1);
376+
377+
const metrics = new Metrics({ namespace: 'test' });
378+
class LambdaFunction implements LambdaInterface {
379+
@metrics.logMetrics({ throwOnEmptyMetrics: false })
380+
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
381+
// @ts-ignore
382+
public handler<TEvent, TResult>(
383+
_event: TEvent,
384+
_context: Context,
385+
_callback: Callback<TResult>,
386+
): void | Promise<TResult> {
387+
return;
388+
}
389+
}
390+
391+
try {
392+
await new LambdaFunction().handler(dummyEvent, dummyContext.helloworldContext, () => console.log('Lambda invoked!'));
393+
} catch (e) {
394+
fail(`Should not throw but got the following Error: ${e}`);
395+
}
396+
const loggedData = JSON.parse(consoleSpy.mock.calls[0][0]);
397+
expect(loggedData._aws.CloudWatchMetrics[0].Metrics.length).toBe(0);
398+
});
399+
374400
test('Error should be thrown on empty metrics when throwOnEmptyMetrics() is called', async () => {
375401
expect.assertions(1);
376402

0 commit comments

Comments
 (0)