Skip to content

Commit 664d7a7

Browse files
author
Alan Churley
committed
Setting default namespace if one isn't passed rather than throwing an error
1 parent fdf84ac commit 664d7a7

File tree

2 files changed

+11
-10
lines changed

2 files changed

+11
-10
lines changed

packages/metrics/src/Metrics.ts

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import {
1414

1515
const MAX_METRICS_SIZE = 100;
1616
const MAX_DIMENSION_COUNT = 9;
17+
const DEFAULT_NAMESPACE = 'default_namespace';
1718

1819
class Metrics implements MetricsInterface {
1920
private customConfigService?: ConfigServiceInterface;
@@ -111,7 +112,9 @@ class Metrics implements MetricsInterface {
111112
if (metricDefinitions.length === 0 && this.raiseOnEmptyMetrics) {
112113
throw new RangeError('The number of metrics recorded must be higher than zero');
113114
}
114-
if (!this.namespace) throw new Error('Namespace must be defined');
115+
116+
/* TODO: Potentially a logger.warn users here if default namespace should be used? */
117+
/* if (!this.namespace) logger.warn('Namespace should be defined, default used'); */
115118

116119
const metricValues = Object.values(this.storedMetrics).reduce((result: { [key: string]: number }, { name, value }: { name: string; value: number }) => {
117120
result[name] = value;
@@ -126,7 +129,7 @@ class Metrics implements MetricsInterface {
126129
Timestamp: new Date().getTime(),
127130
CloudWatchMetrics: [
128131
{
129-
Namespace: this.namespace,
132+
Namespace: this.namespace || DEFAULT_NAMESPACE,
130133
Dimensions: [dimensionNames],
131134
Metrics: metricDefinitions,
132135
}

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

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import { Metrics, MetricUnits } from '../../src/';
66

77
const MAX_METRICS_SIZE = 100;
88
const MAX_DIMENSION_COUNT = 9;
9+
const DEFAULT_NAMESPACE = 'default_namespace';
910

1011
const consoleSpy = jest.spyOn(console, 'log').mockImplementation();
1112

@@ -343,17 +344,14 @@ describe('Class: Metrics', () => {
343344
});
344345

345346
describe('Feature: Output validation ', () => {
346-
test('Should throw error on serialisation if no namepace is set', () => {
347+
test('Should use default namespace if no namepace is set', () => {
347348
delete process.env.POWERTOOLS_METRICS_NAMESPACE;
348-
expect.assertions(1);
349349
const metrics = new Metrics();
350+
350351
metrics.addMetric('test_name', MetricUnits.Seconds, 10);
351-
try {
352-
metrics.serializeMetrics();
353-
}
354-
catch (e) {
355-
expect(e.message).toBe('Namespace must be defined');
356-
}
352+
const serializedMetrics = metrics.serializeMetrics();
353+
354+
expect(serializedMetrics._aws.CloudWatchMetrics[0].Namespace).toBe(DEFAULT_NAMESPACE);
357355
});
358356
});
359357

0 commit comments

Comments
 (0)