From e608cca7c1a66dfc3379ca1065585fa89df736ad Mon Sep 17 00:00:00 2001 From: malteish Date: Wed, 11 Sep 2024 10:29:21 +0200 Subject: [PATCH] output csv instead of json on metrics endpoint --- packages/delivery-service/src/metrics.ts | 27 ++++++++++++++++++++++-- 1 file changed, 25 insertions(+), 2 deletions(-) diff --git a/packages/delivery-service/src/metrics.ts b/packages/delivery-service/src/metrics.ts index 4a415f39e..9fa2705d2 100644 --- a/packages/delivery-service/src/metrics.ts +++ b/packages/delivery-service/src/metrics.ts @@ -1,6 +1,8 @@ import { DeliveryServiceProperties } from '@dm3-org/dm3-lib-delivery'; import express from 'express'; import { IDatabase } from './persistence/getDatabase'; +import { IntervalMetric } from './persistence/metrics/metricTypes'; + /** * The metrics endpoint returns the metrics of the delivery service. * These can include the number of messages received, the cumulative size of messages received, etc., @@ -13,9 +15,30 @@ export default ( ) => { const router = express.Router(); router.get('', async (req, res) => { - const metrics = await db.getMetrics(deliveryServiceProperties); + const metrics: IntervalMetric[] = await db.getMetrics( + deliveryServiceProperties, + ); + + if (metrics.length === 0) { + return res.status(204).send('No metrics data available'); + } + + // Convert metrics to CSV format + const headers = Object.keys(metrics[0]); + const csvRows = metrics.map((metric) => + headers + .map((header) => metric[header as keyof IntervalMetric]) + .join(','), + ); + + const csvData = [headers.join(','), ...csvRows].join('\n'); - return res.status(200).send(JSON.stringify(metrics)); + res.setHeader('Content-Type', 'text/csv'); + res.setHeader( + 'Content-Disposition', + 'attachment; filename=metrics.csv', + ); + return res.status(200).send(csvData); }); return router;