playov2-js-utilities 0.3.5 → 0.3.9

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.
package/lib/constants.js CHANGED
@@ -12,7 +12,10 @@ const RATINGS_WEIGHTAGE = Object.freeze({
12
12
  'old': 0.1
13
13
  });
14
14
 
15
+ const DEFAULT_TIME_ZONE = 'Asia/Kolkata';
16
+
15
17
  module.exports = {
16
18
  USER_INDIVIDUAL_RATINGS,
17
- RATINGS_WEIGHTAGE
19
+ RATINGS_WEIGHTAGE,
20
+ DEFAULT_TIME_ZONE
18
21
  }
package/lib/cron.js ADDED
@@ -0,0 +1,43 @@
1
+ /**
2
+ * This file will have all cron related utilities - (e.g. - schedulers etc.).
3
+ * Try to contain service common utilities here.
4
+ */
5
+ const Constants = require('./constants');
6
+ const { CronJob } = require('cron');
7
+ const Utils = require('./util')
8
+
9
+ const cronner = (
10
+ cronTime,
11
+ onTime = Utils.noop,
12
+ onComplete = Utils.noop,
13
+ timeZone = Constants.DEFAULT_TIME_ZONE,
14
+ context = this,
15
+ runOnInit,
16
+ utcOffset,
17
+ ) => {
18
+ const job = new CronJob({
19
+ cronTime,
20
+ // when the time specified by pattern is matched
21
+ onTick: onTime,
22
+ // onComplete
23
+ onComplete,
24
+ // whether the cron should start on constructor invoke (or whether .start() needs to be called)
25
+ start: false,
26
+ // timezone -> defaults to Asia/Kolkata
27
+ timeZone,
28
+ // the context to bind the onTime method to
29
+ context,
30
+ // flat to start cron on invocation of the module
31
+ runOnInit,
32
+ // the utc offset to run the cron at
33
+ utcOffset
34
+ });
35
+ job.start();
36
+ return job;
37
+ };
38
+
39
+ module.exports = {
40
+ cronner
41
+ };
42
+
43
+
package/lib/index.js CHANGED
@@ -1,10 +1,14 @@
1
1
 
2
- //Naming terminology - While exporting constants use PascalCase while exporting functions/methods use camelCase
2
+ /*
3
+ * Naming terminology - While exporting constants use PascalCase while exporting functions/methods use camelCase
4
+ */
3
5
  module.exports = {
4
- ratings : require('./ratings/index'),
5
- Constants : require('./constants'),
6
- playoUtils : require('./util'),
7
- NotificationTemplates : require('./notification-templates'),
6
+ ratings: require('./ratings/index'),
7
+ Constants: require('./constants'),
8
+ playoUtils: require('./util'),
9
+ NotificationTemplates: require('./notification-templates'),
8
10
  NotificationConfig: require('./notification.config'),
9
- httpRequest: require('./request')
11
+ httpRequest: require('./request'),
12
+ Cron: require('./cron'),
13
+ MessagePublisher: require('./message_publisher')
10
14
  };
@@ -0,0 +1,70 @@
1
+
2
+
3
+ const { CloudTasksClient } = require('@google-cloud/tasks');
4
+
5
+ const PLAYO_LOGGER = require("@playo/logger");
6
+ const LOGGER = new PLAYO_LOGGER("playo-message-publisher");
7
+
8
+ // Instantiates a client.
9
+ const client = new CloudTasksClient();
10
+
11
+ const PROJECT = process.env.GCP_PROJECT;
12
+ const LOCATION = process.env.GCP_LOCATION;
13
+
14
+ if (!PROJECT || !LOCATION) {
15
+ console.warn('You need to pass - GCP_PROJECT, GCP_LOCATION in env for message queue to work!');
16
+ }
17
+ /**
18
+ *
19
+ * @param {String} queueId - Name of the queue being targeted
20
+ * @param {Object} payload - {
21
+ * httpMethod: String <POST, GET, PUT>
22
+ * url: String,
23
+ * headers: Object,
24
+ * body: Object, // not needed if GET request
25
+ * ...
26
+ *
27
+ * }
28
+ * @param {Object} messageProcessingProperties - {
29
+ * delay
30
+ * }
31
+ * @param {String} requestId
32
+ */
33
+ async function createHttpTask(queueId, payload, messageProcessingProperties, requestId) {
34
+
35
+ try {
36
+ const project = PROJECT;
37
+ const queue = queueId;
38
+ const location = LOCATION;
39
+
40
+ const { delay = 0 } = messageProcessingProperties
41
+
42
+ const parent = client.queuePath(project, location, queue);
43
+
44
+ const task = { httpRequest: payload };
45
+
46
+ if (payload.body) {
47
+ task.httpRequest.body = Buffer.from(payload.body).toString('base64');
48
+ }
49
+
50
+ if (delay) {
51
+ // The time when the task is scheduled to be attempted.
52
+ task.scheduleTime = {
53
+ seconds: delay + Date.now() / 1000,
54
+ };
55
+ }
56
+
57
+ // Send create task request.
58
+ LOGGER.info(requestId, task, `Sending task to queue ${queueId}}`)
59
+
60
+ const request = { parent: parent, task: task };
61
+ const [response] = await client.createTask(request);
62
+ LOGGER.info(requestId, { name: response.name }, `Added task to queue ${queueId}}`)
63
+ } catch (err) {
64
+ LOGGER.error(requestId, err, err.message)
65
+ }
66
+ };
67
+
68
+ module.exports = {
69
+ createHttpTask
70
+ };
@@ -205,13 +205,17 @@ const host_cancelled_activity = {
205
205
  };
206
206
 
207
207
  /**
208
- *
208
+ * Template for sending activity reminder.
209
+ * Notification is received by all the players of the activity.
210
+ * Text render only
211
+ * @param {String} sport_name
212
+ * @param {String} date
209
213
  */
210
214
  const activity_reminder = {
211
215
  heading: '⏰, Activity reminder!',
212
- text: 'You have a {sport_name}} game coming up on {{date}}. Best of luck!',
216
+ text: 'You have a {{sport_name}} game coming up on {{date}}. Best of luck!',
213
217
  buttons: [],
214
- notificationId: notificationIds.ACTIVITY_REMINDER
218
+ notificationId: notificationIds.ACTIVITY_REMINDER
215
219
  };
216
220
 
217
221
  const host_updated_activity_details = {
@@ -77,7 +77,7 @@ const getUserAverageRatingForASport = (currentAvg, prevAvg) => {
77
77
  let oldAvg = prevAvg ? prevAvg * Constants.RATINGS_WEIGHTAGE.old : 0;
78
78
 
79
79
  // If for any reason any player doesn't have any old rating/ new rating, send back both ratings with 100% weightage (as one of them will be zero)
80
- if (!prevAvg || !currentAvg) {
80
+ if (!prevAvg || !currentAvg) {
81
81
  latest25Avg = currentAvg;
82
82
  oldAvg = prevAvg;
83
83
  }
package/lib/request.js CHANGED
@@ -17,10 +17,14 @@ const playoResponseHandler = (resp, requestId) => {
17
17
  if (status === 200) {
18
18
  const { requestStatus } = data;
19
19
  LOGGER.info(requestId, data, `Api call to url to ${url} succeeded with status ${status}`);
20
- return ({ requestStatus, data });
20
+ if (!requestStatus) {
21
+ data['requestStatus'] = 1; // assume request status of 1 if any service doesn't provide requestStatus.
22
+ }
23
+ return data;
21
24
  } else {
22
25
  LOGGER.error(requestId, data, `Api call to url to ${url} failed with status : ${status}`);
23
- return Promise.reject({ requestStatus: 0, data });
26
+ data['requestStatus'] = 0;
27
+ return Promise.reject(data);
24
28
  }
25
29
  };
26
30
 
package/lib/util.js CHANGED
@@ -1,9 +1,11 @@
1
1
  /**\
2
2
  * This module is not imported in PlayoLib directly as there are already many imports in individual repositories
3
3
  * named util/utils and importing this alongside might cause unforeseen errors or poor readability
4
- * Ideally new repositories should import utils from here only. Todo- look for a workaround
4
+ * Ideally new repositories should import utils from here only. Todo- look for a workaround - named imports
5
5
  */
6
6
 
7
+ const hbs = require('handlebars');
8
+
7
9
  /**
8
10
  * Finds rating given to a user for a sport by playpals <Assumes playpalDocs supplied are already filtered for a user>
9
11
  * @param {Array} playpalDocs
@@ -121,11 +123,30 @@ const getCategoricalBreakUpFromRecentUserRatings = (palRatingDict, levelCategori
121
123
  }
122
124
 
123
125
  return categoricalBreakUp;
124
- }
126
+ };
127
+
128
+ const noop = () => {
129
+ return undefined;
130
+ };
131
+
132
+ /**
133
+ *
134
+ * @param {String} template - Handlebars compatible template
135
+ * @param {Object} data - Data points containing key value pairs of data required in template supplied
136
+ * @returns {String}
137
+ */
138
+ const renderTemplate = (template, data) => {
139
+
140
+ const temp = hbs.compile(template);
141
+
142
+ return temp(data);
143
+ };
125
144
 
126
145
  module.exports = {
127
146
  getRatingsFromPlaypalDocs,
128
147
  findAverage,
129
148
  getRecentRatingDictOfPals,
130
- getCategoricalBreakUpFromRecentUserRatings
131
- }
149
+ getCategoricalBreakUpFromRecentUserRatings,
150
+ noop,
151
+ renderTemplate
152
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "playov2-js-utilities",
3
- "version": "0.3.5",
3
+ "version": "0.3.9",
4
4
  "description": "Private package for JS utility functions",
5
5
  "main": "index.js",
6
6
  "scripts": {
@@ -21,7 +21,10 @@
21
21
  "jest": "^27.1.0"
22
22
  },
23
23
  "dependencies": {
24
+ "@google-cloud/tasks": "^2.5.0",
24
25
  "@playo/logger": "^0.9.18",
25
- "axios": "^0.24.0"
26
+ "axios": "^0.24.0",
27
+ "cron": "^1.8.2",
28
+ "handlebars": "^4.7.7"
26
29
  }
27
30
  }