2020-02-20 18:48:32 +08:00
|
|
|
'use strict';
|
|
|
|
|
|
|
|
const { PubSub } = require('@google-cloud/pubsub');
|
|
|
|
|
2020-04-27 17:59:36 +08:00
|
|
|
module.exports = class PubSubMetricsBackend {
|
2020-04-27 18:46:27 +08:00
|
|
|
constructor (options = {}) {
|
|
|
|
const { project_id: projectId, credentials: keyFilename, topic } = options;
|
|
|
|
this._pubsub = new PubSub({ projectId, keyFilename });
|
|
|
|
this._topicName = topic;
|
2020-02-20 18:48:32 +08:00
|
|
|
}
|
|
|
|
|
2020-04-27 18:46:27 +08:00
|
|
|
send (event, attributes) {
|
2020-02-20 18:48:32 +08:00
|
|
|
const data = Buffer.from(event);
|
|
|
|
|
2020-04-27 18:46:27 +08:00
|
|
|
this._pubsub.topic(this._topicName).publish(data, attributes)
|
2020-02-20 18:48:32 +08:00
|
|
|
.then(() => {
|
2020-04-27 18:46:27 +08:00
|
|
|
console.log(`PubSubTracker: event '${event}' published to '${this._topicName}'`);
|
2020-02-20 18:48:32 +08:00
|
|
|
})
|
|
|
|
.catch((error) => {
|
|
|
|
console.error(`ERROR: pubsub middleware failed to publish event '${event}': ${error.message}`);
|
|
|
|
});
|
|
|
|
}
|
2020-04-27 18:13:54 +08:00
|
|
|
};
|