419adea234
* Create middleware and service for pubsub metrics * Use pubsub middleware for all request * Replace isEnabled with isDisabled to avoid negation * Use new headers names * Add acceptance and unit tests * Remove commented log calls * Remove only filters in tests Remove typo * Refactor service to ease integration test * Fix interaction with query controller * Use middleware at api-router and test all controllers * Rename user middleware function * Use sinon latest version * Create middleware and service for pubsub metrics * Use pubsub middleware for all request * Replace isEnabled with isDisabled to avoid negation * Use new headers names * Add acceptance and unit tests * Remove commented log calls * Remove only filters in tests Remove typo * Refactor service to ease integration test * Fix interaction with query controller * Use middleware at api-router and test all controllers * Rename user middleware function * Use sinon latest version * Fix tests * Fix typos * Checks if pubsub config exists to enable the service * Fix typo * Normalize headers values for pubsub * Trim fields when normalizing * Trim fields when normalizing
52 lines
1.3 KiB
JavaScript
52 lines
1.3 KiB
JavaScript
'use strict';
|
|
|
|
const EVENT_VERSION = '1';
|
|
const MAX_LENGTH = 100;
|
|
|
|
function pubSubMetrics (pubSubMetricsService) {
|
|
if (!pubSubMetricsService.isEnabled()) {
|
|
return function pubSubMetricsDisabledMiddleware (req, res, next) { next(); };
|
|
}
|
|
|
|
return function pubSubMetricsMiddleware (req, res, next) {
|
|
const data = getEventData(req, res);
|
|
|
|
if (data.event) {
|
|
pubSubMetricsService.sendEvent(data.event, data.attributes);
|
|
}
|
|
|
|
return next();
|
|
};
|
|
}
|
|
|
|
function getEventData (req, res) {
|
|
const event = normalizedField(req.get('Carto-Event'));
|
|
const eventSource = normalizedField(req.get('Carto-Event-Source'));
|
|
const eventGroupId = normalizedField(req.get('Carto-Event-Group-Id'));
|
|
|
|
if (!event || !eventSource) {
|
|
return [undefined, undefined];
|
|
}
|
|
|
|
const attributes = {
|
|
event_source: eventSource,
|
|
user_id: res.locals.userId,
|
|
response_code: res.statusCode.toString(),
|
|
source_domain: req.hostname,
|
|
event_time: new Date().toISOString(),
|
|
event_version: EVENT_VERSION
|
|
};
|
|
|
|
if (eventGroupId) {
|
|
attributes.event_group_id = eventGroupId;
|
|
}
|
|
|
|
return { event, attributes };
|
|
}
|
|
|
|
function normalizedField (field) {
|
|
return field.toString().trim().substr(0, MAX_LENGTH);
|
|
}
|
|
|
|
module.exports = pubSubMetrics;
|