Skip to content

Commit

Permalink
feat: add metric service
Browse files Browse the repository at this point in the history
  • Loading branch information
FutureDuck authored and lfilho committed Jun 14, 2020
1 parent 41cf7f7 commit a681db8
Show file tree
Hide file tree
Showing 3 changed files with 66 additions and 0 deletions.
10 changes: 10 additions & 0 deletions __tests__/src/shared/metric_service.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import MetricService from '../../../src/shared/metric_service.js';

describe('Metric Service', () => {
it('should throw if trying to emit an non-Metric', async () => {
await expect(async () => {
await MetricService.emit('my-made-up-metric');
}).rejects.toThrow(/Invalid metric/);
//TODO https://github.com/lfilho/ddg-test-project/issues/46
});
});
51 changes: 51 additions & 0 deletions src/shared/metric_service.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import Metric from './model/metric.js';
import fetch from './util/fake_fetch.js';

export default class MetricService {
static async emit(metric) {
if (!(metric instanceof Metric)) {
throw new Error('Invalid metric.');
}

const metricPayload = getMetricPayload(metric);
const metricJson = getMetricJson(metricPayload);
const metricString = getMetricString(metricPayload);

// Here we would make a `fetch` request to our metric service
// For now, let's just log mimic an async request
return fetch(metricJson)
.then((response) => {
console.log(`Metric sent! Server returned status: ${response.status}`);
console.info(metricString);
})
.catch((error) => {
console.error(
'Error while sending metric. Did you pay your internet bill?',
error
);
});
}
}

// when are private fields and methods coming? :-(
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Private_class_fields

function getMetricPayload(metric) {
const timestamp = new Date().toISOString();

const payload = {
timestamp,
dimension: metric.dimension,
value: metric.value,
};

return payload;
}

function getMetricJson(payload) {
return JSON.stringify(payload);
}

function getMetricString(payload) {
return `INFO ${payload.timestamp} ${payload.dimension}=${payload.value}`;
}
5 changes: 5 additions & 0 deletions src/shared/util/fake_fetch.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
// A simple `fetch` mock so we can unit test via node without extra dependencies

export default async function fetch() {
return Promise.resolve({ status: 200 });
}

0 comments on commit a681db8

Please sign in to comment.