Skip to content

Commit f430195

Browse files
committed
test(metrics): add array input for middleware
1 parent 9c1644d commit f430195

File tree

3 files changed

+75
-15
lines changed

3 files changed

+75
-15
lines changed

packages/metrics/src/middleware/middy.ts

Lines changed: 20 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -2,23 +2,30 @@ import type { Metrics } from '../Metrics';
22
import middy from '@middy/core';
33
import { ExtraOptions } from '../types';
44

5-
const logMetrics = (metrics: Metrics, options: ExtraOptions = {}): middy.MiddlewareObj => {
5+
const logMetrics = (target: Metrics | Metrics[], options: ExtraOptions = {}): middy.MiddlewareObj => {
6+
const metricsInstances = target instanceof Array ? target : [target];
7+
68
const logMetricsBefore = async (request: middy.Request): Promise<void> => {
7-
metrics.setFunctionName(request.context.functionName);
8-
const { raiseOnEmptyMetrics, defaultDimensions, captureColdStartMetric } = options;
9-
if (raiseOnEmptyMetrics !== undefined) {
10-
metrics.raiseOnEmptyMetrics();
11-
}
12-
if (defaultDimensions !== undefined) {
13-
metrics.setDefaultDimensions(defaultDimensions);
14-
}
15-
if (captureColdStartMetric !== undefined) {
16-
metrics.captureColdStartMetric();
17-
}
9+
metricsInstances.forEach((metrics: Metrics) => {
10+
metrics.setFunctionName(request.context.functionName);
11+
const { raiseOnEmptyMetrics, defaultDimensions, captureColdStartMetric } = options;
12+
if (raiseOnEmptyMetrics !== undefined) {
13+
metrics.raiseOnEmptyMetrics();
14+
}
15+
if (defaultDimensions !== undefined) {
16+
metrics.setDefaultDimensions(defaultDimensions);
17+
}
18+
if (captureColdStartMetric !== undefined) {
19+
metrics.captureColdStartMetric();
20+
}
21+
});
22+
1823
};
1924

2025
const logMetricsAfter = async (): Promise<void> => {
21-
metrics.purgeStoredMetrics();
26+
metricsInstances.forEach((metrics: Metrics) => {
27+
metrics.purgeStoredMetrics();
28+
});
2229
};
2330

2431
return {

packages/metrics/tests/unit/Metrics.test.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -229,7 +229,7 @@ describe('Class: Metrics', () => {
229229
test('Cold start metric should only be written out once and flushed automatically', async () => {
230230
const metrics = new Metrics({ namespace: 'test' });
231231

232-
const handler = async (_event, _context): Promise<void> => {
232+
const handler = async (_event: unknown, _context: unknown): Promise<void> => {
233233
// Should generate only one log
234234
metrics.captureColdStartMetric();
235235
};
@@ -363,7 +363,7 @@ describe('Class: Metrics', () => {
363363
expect.assertions(1);
364364

365365
const metrics = new Metrics({ namespace: 'test' });
366-
const handler = async (_event, _context): Promise<void> => {
366+
const handler = async (_event: unknown, _context: unknown): Promise<void> => {
367367
metrics.raiseOnEmptyMetrics();
368368
// Logic goes here
369369
metrics.purgeStoredMetrics();

packages/metrics/tests/unit/middleware/middy.test.ts

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -142,6 +142,59 @@ describe('Middy middleware', () => {
142142

143143
});
144144

145+
test('when an array of Metrics instances is passed, it prints the metrics in the stdout', async () => {
146+
147+
// Prepare
148+
const metrics = new Metrics({ namespace:'serverlessAirline', service:'orders' });
149+
150+
const lambdaHandler = (): void => {
151+
metrics.addMetric('successfulBooking', MetricUnits.Count, 1);
152+
metrics.addMetric('successfulBooking', MetricUnits.Count, 1);
153+
};
154+
const metricsOptions: ExtraOptions = {
155+
raiseOnEmptyMetrics: true
156+
};
157+
const handler = middy(lambdaHandler).use(logMetrics([metrics], metricsOptions));
158+
const event = { foo: 'bar' };
159+
const getRandomInt = (): number => Math.floor(Math.random() * 1000000000);
160+
161+
const awsRequestId = getRandomInt().toString();
162+
const context = {
163+
callbackWaitsForEmptyEventLoop: true,
164+
functionVersion: '$LATEST',
165+
functionName: 'foo-bar-function',
166+
memoryLimitInMB: '128',
167+
logGroupName: '/aws/lambda/foo-bar-function',
168+
logStreamName: '2021/03/09/[$LATEST]abcdef123456abcdef123456abcdef123456',
169+
invokedFunctionArn: 'arn:aws:lambda:eu-central-1:123456789012:function:foo-bar-function',
170+
awsRequestId: awsRequestId,
171+
getRemainingTimeInMillis: () => 1234,
172+
done: () => console.log('Done!'),
173+
fail: () => console.log('Failed!'),
174+
succeed: () => console.log('Succeeded!'),
175+
};
176+
177+
// Act
178+
await handler(event, context, () => console.log('Lambda invoked!'));
179+
180+
// Assess
181+
expect(console.log).toHaveBeenNthCalledWith(1, JSON.stringify({
182+
'_aws': {
183+
'Timestamp': 1466424490000,
184+
'CloudWatchMetrics': [{
185+
'Namespace': 'serverlessAirline',
186+
'Dimensions': [
187+
['service']
188+
],
189+
'Metrics': [{ 'Name': 'successfulBooking', 'Unit': 'Count' }],
190+
}],
191+
},
192+
'service': 'orders',
193+
'successfulBooking': 1,
194+
}));
195+
196+
});
197+
145198
});
146199

147200
});

0 commit comments

Comments
 (0)