From a681db83a5dea5b9b4e502180c71f53dfb070c7d Mon Sep 17 00:00:00 2001 From: FutureDuck Date: Sat, 13 Jun 2020 20:55:50 -0700 Subject: [PATCH] feat: add metric service --- __tests__/src/shared/metric_service.spec.js | 10 ++++ src/shared/metric_service.js | 51 +++++++++++++++++++++ src/shared/util/fake_fetch.js | 5 ++ 3 files changed, 66 insertions(+) create mode 100644 __tests__/src/shared/metric_service.spec.js create mode 100644 src/shared/metric_service.js create mode 100644 src/shared/util/fake_fetch.js diff --git a/__tests__/src/shared/metric_service.spec.js b/__tests__/src/shared/metric_service.spec.js new file mode 100644 index 0000000..ff6647a --- /dev/null +++ b/__tests__/src/shared/metric_service.spec.js @@ -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 + }); +}); diff --git a/src/shared/metric_service.js b/src/shared/metric_service.js new file mode 100644 index 0000000..48c5b77 --- /dev/null +++ b/src/shared/metric_service.js @@ -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}`; +} diff --git a/src/shared/util/fake_fetch.js b/src/shared/util/fake_fetch.js new file mode 100644 index 0000000..516d2d5 --- /dev/null +++ b/src/shared/util/fake_fetch.js @@ -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 }); +}