Skip to content

Commit e742329

Browse files
authored
Feature/roles cache (#91)
* fetch roles from api and cache * deploy feature branch * remove feature branch from deployment
1 parent 060c33c commit e742329

File tree

4 files changed

+78
-48
lines changed

4 files changed

+78
-48
lines changed

connect/config.js

Lines changed: 0 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -8,15 +8,6 @@ module.exports = {
88
TC_API_V4_BASE_URL: process.env.TC_API_V4_BASE_URL || 'https://api.topcoder-dev.com/v4',
99
MESSAGE_API_BASE_URL: process.env.MESSAGE_API_BASE_URL || 'https://api.topcoder-dev.com/v5',
1010

11-
// Probably temporary variables for TopCoder role ids for 'Connect Manager', 'Connect Copilot' and 'administrator'
12-
// These are values for development backend. For production backend they may be different.
13-
// These variables are currently being used to retrieve above role members using API V3 `/roles` endpoint.
14-
// As soon as this endpoint is replaced with more suitable one, these variables has to be removed if no need anymore.
15-
CONNECT_MANAGER_ROLE_ID: 8,
16-
CONNECT_COPILOT_MANAGER_ROLE_ID: 113,
17-
CONNECT_ACCOUNT_MANAGER_ROLE_ID: 114,
18-
CONNECT_COPILOT_ROLE_ID: 4,
19-
ADMINISTRATOR_ROLE_ID: 1,
2011
// id of the BOT user which creates post with various events in discussions
2112
TCWEBSERVICE_ID: process.env.TCWEBSERVICE_ID || '22838965',
2213
CODERBOT_USER_ID: process.env.CODERBOT_USER_ID || 'CoderBot',

connect/connectNotificationServer.js

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@ const _ = require('lodash');
1111
const service = require('./service');
1212
const { BUS_API_EVENT } = require('./constants');
1313
const EVENTS = require('./events-config').EVENTS;
14-
const TOPCODER_ROLE_RULES = require('./events-config').TOPCODER_ROLE_RULES;
1514
const PROJECT_ROLE_RULES = require('./events-config').PROJECT_ROLE_RULES;
1615
const PROJECT_ROLE_OWNER = require('./events-config').PROJECT_ROLE_OWNER;
1716
const emailNotificationServiceHandler = require('./notificationServices/email').handler;
@@ -30,7 +29,7 @@ const getTopCoderMembersNotifications = (eventConfig) => {
3029
}
3130

3231
const getRoleMembersPromises = eventConfig.topcoderRoles.map(topcoderRole => (
33-
service.getRoleMembers(TOPCODER_ROLE_RULES[topcoderRole].id)
32+
service.getRoleMembers(topcoderRole)
3433
));
3534

3635
return Promise.all(getRoleMembersPromises).then((membersPerRole) => {
@@ -351,8 +350,10 @@ const handler = (topic, message, logger, callback) => {
351350
)).then((notifications) => {
352351
allNotifications = _.filter(notifications, notification => notification.userId !== `${message.initiatorUserId}`);
353352

354-
if (eventConfig.includeUsers && message[eventConfig.includeUsers] && message[eventConfig.includeUsers].length > 0) {
355-
allNotifications = _.filter(allNotifications, notification => message[eventConfig.includeUsers].includes(notification.userId));
353+
if (eventConfig.includeUsers && message[eventConfig.includeUsers] &&
354+
message[eventConfig.includeUsers].length > 0) {
355+
allNotifications = _.filter(allNotifications,
356+
notification => message[eventConfig.includeUsers].includes(notification.userId));
356357
}
357358
logger.debug('filtered notifications: ', allNotifications);
358359
// now let's retrieve some additional data

connect/events-config.js

Lines changed: 0 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
/**
22
* Configuration of connect events
33
*/
4-
const config = require('./config');
54
const { BUS_API_EVENT } = require('./constants');
65

76
// project member role names
@@ -27,15 +26,6 @@ const ROLE_CONNECT_COPILOT_MANAGER = 'Connect Copilot Manager';
2726
const ROLE_CONNECT_ACCOUNT_MANAGER = 'Connect Account Manager';
2827
const ROLE_ADMINISTRATOR = 'administrator';
2928

30-
// TopCoder role rules
31-
const TOPCODER_ROLE_RULES = {
32-
[ROLE_CONNECT_COPILOT]: { id: config.CONNECT_COPILOT_ROLE_ID },
33-
[ROLE_CONNECT_MANAGER]: { id: config.CONNECT_MANAGER_ROLE_ID },
34-
[ROLE_CONNECT_COPILOT_MANAGER]: { id: config.CONNECT_COPILOT_MANAGER_ROLE_ID },
35-
[ROLE_CONNECT_ACCOUNT_MANAGER]: { id: config.CONNECT_ACCOUNT_MANAGER_ROLE_ID },
36-
[ROLE_ADMINISTRATOR]: { id: config.ADMINISTRATOR_ROLE_ID },
37-
};
38-
3929
/**
4030
* Supported events configuration
4131
*
@@ -313,7 +303,6 @@ const EVENT_BUNDLES = {
313303

314304
module.exports = {
315305
PROJECT_ROLE_RULES,
316-
TOPCODER_ROLE_RULES,
317306
EVENTS,
318307
EVENT_BUNDLES,
319308

connect/service.js

Lines changed: 73 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -6,17 +6,19 @@ const request = require('superagent');
66
const config = require('./config');
77
const _ = require('lodash');
88

9+
let rolesCache = null;
10+
911
/**
1012
* Get project details
1113
*
1214
* @param {String} projectId project id
1315
*
1416
* @return {Promise} promise resolved to project details
1517
*/
16-
const getProject = (projectId) => {
17-
return M2m.getMachineToken(config.AUTH0_CLIENT_ID, config.AUTH0_CLIENT_SECRET)
18-
.then((token) => {
19-
return request
18+
const getProject = (projectId) => (
19+
M2m.getMachineToken(config.AUTH0_CLIENT_ID, config.AUTH0_CLIENT_SECRET)
20+
.then((token) => (
21+
request
2022
.get(`${config.TC_API_V4_BASE_URL}/projects/${projectId}`)
2123
.set('accept', 'application/json')
2224
.set('authorization', `Bearer ${token}`)
@@ -32,24 +34,68 @@ const getProject = (projectId) => {
3234
`Failed to get project details of project id: ${projectId}.` +
3335
(errorDetails ? ' Server response: ' + errorDetails : '')
3436
);
35-
});
37+
})
38+
))
39+
.catch((err) => {
40+
err.message = 'Error generating m2m token: ' + err.message;
41+
throw err;
3642
})
43+
);
44+
45+
/**
46+
* Get role id
47+
*
48+
* @param {String} role role
49+
*
50+
* @return {Promise} promise resolved to role members ids list
51+
*/
52+
const getRoleId = (role) => {
53+
if (rolesCache) {
54+
const cachedRole = _.find(rolesCache, { roleName: role });
55+
if (cachedRole) {
56+
return Promise.resolve(cachedRole.id);
57+
}
58+
}
59+
return M2m.getMachineToken(config.AUTH0_CLIENT_ID, config.AUTH0_CLIENT_SECRET)
60+
.then((token) => (
61+
request
62+
.get(`${config.TC_API_V3_BASE_URL}/roles`)
63+
.set('accept', 'application/json')
64+
.set('authorization', `Bearer ${token}`)
65+
.then((res) => {
66+
if (!_.get(res, 'body.result.success')) {
67+
throw new Error('Failed to get roles list');
68+
}
69+
const roles = _.get(res, 'body.result.content');
70+
rolesCache = roles;
71+
return _.find(roles, { roleName: role }).id;
72+
}).catch((err) => {
73+
const errorDetails = _.get(err, 'response.body.result.content.message');
74+
throw new Error(
75+
`Failed to get role id for role ${role}.` +
76+
(errorDetails ? ' Server response: ' + errorDetails : '')
77+
);
78+
})
79+
))
3780
.catch((err) => {
3881
err.message = 'Error generating m2m token: ' + err.message;
3982
throw err;
4083
});
4184
};
85+
4286
/**
4387
* Get role members
4488
*
45-
* @param {String} roleId role id
89+
* @param {String} role role
4690
*
4791
* @return {Promise} promise resolved to role members ids list
4892
*/
49-
const getRoleMembers = (roleId) => {
50-
return M2m.getMachineToken(config.AUTH0_CLIENT_ID, config.AUTH0_CLIENT_SECRET)
51-
.then((token) => {
52-
return request
93+
const getRoleMembers = (role) => (
94+
M2m.getMachineToken(config.AUTH0_CLIENT_ID, config.AUTH0_CLIENT_SECRET)
95+
.then((token) => (
96+
getRoleId(role)
97+
.then(roleId => (
98+
request
5399
.get(`${config.TC_API_V3_BASE_URL}/roles/${roleId}?fields=subjects`)
54100
.set('accept', 'application/json')
55101
.set('authorization', `Bearer ${token}`)
@@ -65,13 +111,14 @@ const getRoleMembers = (roleId) => {
65111
`Failed to get role membrs of role id: ${roleId}.` +
66112
(errorDetails ? ' Server response: ' + errorDetails : '')
67113
);
68-
});
69-
})
114+
})
115+
))
116+
))
70117
.catch((err) => {
71118
err.message = 'Error generating m2m token: ' + err.message;
72119
throw err;
73-
});
74-
};
120+
})
121+
);
75122

76123
/**
77124
* Get users details by ids
@@ -88,8 +135,9 @@ const getUsersById = (ids) => {
88135
throw err;
89136
})
90137
.then((token) => {
138+
const fields = 'fields=userId,email,handle,firstName,lastName,photoURL,status';
91139
return request
92-
.get(`${config.TC_API_V3_BASE_URL}/members/_search?fields=userId,email,handle,firstName,lastName,photoURL,status&query=${query}`)
140+
.get(`${config.TC_API_V3_BASE_URL}/members/_search?${fields}&query=${query}`)
93141
.set('accept', 'application/json')
94142
.set('authorization', `Bearer ${token}`)
95143
.then((res) => {
@@ -125,8 +173,9 @@ const getUsersByHandle = (handles) => {
125173
throw err;
126174
})
127175
.then((token) => {
176+
const fields = 'fields=userId,handle,firstName,lastName,photoURL';
128177
return request
129-
.get(`${config.TC_API_V3_BASE_URL}/members/_search?fields=userId,handle,firstName,lastName,photoURL&query=${query}`)
178+
.get(`${config.TC_API_V3_BASE_URL}/members/_search?${fields}&query=${query}`)
130179
.set('accept', 'application/json')
131180
.set('authorization', `Bearer ${token}`)
132181
.then((res) => {
@@ -154,10 +203,10 @@ const getUsersByHandle = (handles) => {
154203
*
155204
* @return {Promise} promise resolved to topic details
156205
*/
157-
const getTopic = (topicId, logger) => {
158-
return M2m.getMachineToken(config.AUTH0_CLIENT_ID, config.AUTH0_CLIENT_SECRET)
159-
.then((token) => {
160-
return request
206+
const getTopic = (topicId, logger) => (
207+
M2m.getMachineToken(config.AUTH0_CLIENT_ID, config.AUTH0_CLIENT_SECRET)
208+
.then((token) => (
209+
request
161210
.get(`${config.MESSAGE_API_BASE_URL}/topics/${topicId}/read`)
162211
.set('accept', 'application/json')
163212
.set('authorization', `Bearer ${token}`)
@@ -175,13 +224,13 @@ const getTopic = (topicId, logger) => {
175224
`Failed to get topic details of topic id: ${topicId}.` +
176225
(errorDetails ? ' Server response: ' + errorDetails : '')
177226
);
178-
});
179-
})
227+
})
228+
))
180229
.catch((err) => {
181230
err.message = 'Error generating m2m token: ' + err.message;
182231
throw err;
183-
});
184-
};
232+
})
233+
);
185234

186235
module.exports = {
187236
getProject,

0 commit comments

Comments
 (0)