Let to the caller to choose how to handle the call to a method

This commit is contained in:
Daniel García Aubert 2020-04-27 13:27:05 +02:00
parent e90c196598
commit 1bbde4f5e3
2 changed files with 6 additions and 10 deletions

View File

@ -3,7 +3,7 @@
const EVENT_VERSION = '1'; const EVENT_VERSION = '1';
const MAX_LENGTH = 100; const MAX_LENGTH = 100;
function pubSubMetrics ({ enabled, metricsBackend }) { function pubSubMetrics ({ enabled, metricsBackend, logger }) {
if (!enabled) { if (!enabled) {
return function pubSubMetricsDisabledMiddleware (req, res, next) { return function pubSubMetricsDisabledMiddleware (req, res, next) {
next(); next();
@ -15,7 +15,9 @@ function pubSubMetrics ({ enabled, metricsBackend }) {
const { event, attributes } = getEventData(req, res); const { event, attributes } = getEventData(req, res);
if (event) { if (event) {
metricsBackend.send(event, attributes); metricsBackend.send(event, attributes)
.then(() => logger.debug(`PubSubTracker: event '${event}' published succesfully`))
.catch((error) => logger.error(`ERROR: pubsub middleware failed to publish event '${event}': ${error.message}`));
} }
}); });

View File

@ -5,19 +5,13 @@ const { PubSub } = require('@google-cloud/pubsub');
module.exports = class PubSubMetricsBackend { module.exports = class PubSubMetricsBackend {
constructor (options = {}) { constructor (options = {}) {
const { project_id: projectId, credentials: keyFilename, topic } = options; const { project_id: projectId, credentials: keyFilename, topic } = options;
this._pubsub = new PubSub({ projectId, keyFilename }); this._pubsub = new PubSub({ projectId, keyFilename });
this._topicName = topic; this._topicName = topic;
} }
send (event, attributes) { send (event, attributes) {
const data = Buffer.from(event); const data = Buffer.from(event);
return this._pubsub.topic(this._topicName).publish(data, attributes);
this._pubsub.topic(this._topicName).publish(data, attributes)
.then(() => {
console.log(`PubSubTracker: event '${event}' published to '${this._topicName}'`);
})
.catch((error) => {
console.error(`ERROR: pubsub middleware failed to publish event '${event}': ${error.message}`);
});
} }
}; };