@autofleet/node-common 1.1.64 → 1.1.65

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/events/index.js +38 -9
  2. package/package.json +1 -1
package/events/index.js CHANGED
@@ -1,21 +1,52 @@
1
1
  const PubSub = require('@google-cloud/pubsub');
2
2
  const logger = require('../logger/index')();
3
3
 
4
- // EventType - 'vehicle'/'stop_point' etc.
5
- const publish = (eventType, eventObj, debug = false) => {
4
+ let Client;
5
+ let Publisher;
6
+
7
+ const getPubsubPublisher = async () => {
8
+ if (Publisher) {
9
+ return Publisher;
10
+ }
11
+
6
12
  const envv = process.env.NODE_ENV || 'development';
7
13
  const projectId = process.env.PROJECT;
8
14
  const topic = process.env.TOPIC;
9
15
 
10
16
  if (!topic || !projectId) {
11
- return 'Missing project/topic';
17
+ return {
18
+ debug: 'Missing project/topic',
19
+ };
12
20
  }
13
21
 
14
- if ((envv === 'development' || envv === 'test') && !debug) {
15
- return 'Not publishing in dev/test';
22
+ if ((envv === 'development' || envv === 'test')) {
23
+ return {
24
+ debug: 'Not publishing in dev/test',
25
+ };
16
26
  }
17
27
 
18
- const pubsubClient = new PubSub({ projectId });
28
+ Client = new PubSub({ projectId });
29
+ Publisher = Client.topic(topic).publisher();
30
+
31
+ return {
32
+ client: Client,
33
+ publisher: Publisher,
34
+ topic,
35
+ envv,
36
+ };
37
+ };
38
+
39
+ // EventType - 'vehicle'/'stop_point' etc.
40
+ const publish = (eventType, eventObj) => {
41
+ const {
42
+ debug,
43
+ publisher,
44
+ envv,
45
+ } = getPubsubPublisher();
46
+
47
+ if (debug) {
48
+ return debug;
49
+ }
19
50
 
20
51
  const msg = {
21
52
  type: eventType,
@@ -26,9 +57,7 @@ const publish = (eventType, eventObj, debug = false) => {
26
57
  const data = JSON.stringify(msg);
27
58
  const dataBuffer = Buffer.from(data);
28
59
 
29
- return pubsubClient
30
- .topic(topic)
31
- .publisher()
60
+ return publisher
32
61
  .publish(dataBuffer)
33
62
  .then((messageId) => {
34
63
  logger.info(`Message ${messageId} published to google pubsub`);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@autofleet/node-common",
3
- "version": "1.1.64",
3
+ "version": "1.1.65",
4
4
  "description": "",
5
5
  "scripts": {
6
6
  "coverage": "jest --coverage --forceExit --runInBand",