Skip to content

Commit 571edab

Browse files
Refactor Token in API calls
1 parent 8109cb2 commit 571edab

23 files changed

+287
-164
lines changed

.circleci/config.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ jobs:
2828
- attach_workspace:
2929
at: .
3030
- run: echo "//registry.npmjs.org/:_authToken=$NPM_TOKEN" >> ~/.npmrc
31-
- run: npm publish
31+
- run: npm publish --tag test-release
3232
# dont change anything
3333
workflows:
3434
version: 2

__tests__/services/api.js

Lines changed: 20 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -78,44 +78,48 @@ describe('Test api', () => {
7878
}
7979

8080
let api;
81-
test('API v2 service works without auth token', () => {
82-
api = getApi('V2');
81+
test('API v2 service works without auth token', async () => {
82+
api = await getApi('V2');
8383
return testApi(api, config.API.V2);
8484
});
8585

86-
test('API v2 service works with auth token', () => {
87-
api = getApi('V2', 'TOKEN');
86+
test('API v2 service works with auth token', async () => {
87+
api = await getApi('V2', 'TOKEN');
8888
return testApi(api, config.API.V2, 'TOKEN');
8989
});
9090

9191
test(
92-
'API v2 service from the previous call is re-used, if token is the same',
93-
() => expect(getApi('V2', 'TOKEN')).toBe(api),
92+
'API v2 service from the previous call is re-used, if token is the same', async () => {
93+
const api2 = await getApi('V2', 'TOKEN');
94+
expect(api2).toBe(api);
95+
},
9496
);
9597

96-
test('New API v2 service is created if token is new', () => {
97-
const api2 = getApi('V2', 'TOKEN2');
98+
test('New API v2 service is created if token is new', async () => {
99+
const api2 = await getApi('V2', 'TOKEN2');
98100
expect(api2).not.toBe(api);
99101
return testApi(api2, config.API.V2, 'TOKEN2');
100102
});
101103

102-
test('API v3 service works without auth token', () => {
103-
api = getApi('V3');
104+
test('API v3 service works without auth token', async () => {
105+
api = await getApi('V3');
104106
return testApi(api, config.API.V3);
105107
});
106108

107-
test('API v3 service works with auth token', () => {
108-
api = getApi('V3', 'TOKEN');
109+
test('API v3 service works with auth token', async () => {
110+
api = await getApi('V3', 'TOKEN');
109111
return testApi(api, config.API.V3, 'TOKEN');
110112
});
111113

112114
test(
113-
'API v3 service from the previous call is re-used, if token is the same',
114-
() => expect(getApi('V3', 'TOKEN')).toBe(api),
115+
'API v3 service from the previous call is re-used, if token is the same', async () => {
116+
const api2 = await getApi('V3', 'TOKEN');
117+
return expect(api2).toBe(api);
118+
},
115119
);
116120

117-
test('New API v3 service is created if token is new', () => {
118-
const api2 = getApi('V3', 'TOKEN2');
121+
test('New API v3 service is created if token is new', async () => {
122+
const api2 = await getApi('V3', 'TOKEN2');
119123
expect(api2).not.toBe(api);
120124
return testApi(api2, config.API.V3, 'TOKEN2');
121125
});

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@
3131
"lint:js": "./node_modules/.bin/eslint --ext .js,.jsx .",
3232
"test": "npm run lint && npm run jest"
3333
},
34-
"version": "1.1.1",
34+
"version": "1000.25.3",
3535
"dependencies": {
3636
"auth0-js": "^6.8.4",
3737
"config": "^3.2.0",

src/actions/auth.js

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -37,11 +37,11 @@ async function checkErrorV5(res) {
3737
* @param {String} userTokenV3 v3 authentication token.
3838
* @return {Action}
3939
*/
40-
function loadProfileDone(userTokenV3) {
40+
async function loadProfileDone(userTokenV3) {
4141
if (!userTokenV3) return Promise.resolve(null);
4242
const user = decodeToken(userTokenV3);
43-
const apiV3 = getApiV3(userTokenV3);
44-
const apiV5 = getApiV5(userTokenV3);
43+
const apiV3 = await getApiV3(userTokenV3);
44+
const apiV5 = await getApiV5(userTokenV3);
4545
return Promise.all([
4646
apiV3.get(`/members/${user.handle}`)
4747
.then(res => res.json()).then(res => (res.result.status === 200 ? res.result.content : {})),

src/actions/smp.js

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,8 +21,9 @@ function deleteSubmissionInit() {}
2121
* @param {Number|String} submissionId Submission ID.
2222
* @return {Action}
2323
*/
24-
function deleteSubmissionDone(tokenV3, submissionId) {
25-
return getApi('V5', tokenV3).delete(`/submissions/${submissionId}`)
24+
async function deleteSubmissionDone(tokenV3, submissionId) {
25+
const apiV5 = await getApi('V5', tokenV3);
26+
return apiV5.delete(`/submissions/${submissionId}`)
2627
.then(() => submissionId);
2728
}
2829

src/services/__mocks__/challenges.js

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -253,11 +253,12 @@ class ChallengesService {
253253
* Gets possible challenge types.
254254
* @return {Promise} Resolves to the array of challenge type names.
255255
*/
256-
getChallengeTypes() {
256+
async getChallengeTypes() {
257+
const apiV2 = await this.private.apiV2;
257258
return Promise.all([
258-
this.private.apiV2.get('/design/challengetypes')
259+
apiV2.get('/design/challengetypes')
259260
.then(res => (res.ok ? res.json() : new Error(res.statusText))),
260-
this.private.apiV2.get('/develop/challengetypes')
261+
apiV2.get('/develop/challengetypes')
261262
.then(res => (res.ok ? res.json() : new Error(res.statusText))),
262263
]).then(([a, b]) => a.concat(b));
263264
}
@@ -266,8 +267,9 @@ class ChallengesService {
266267
* Gets possible challenge tags (technologies).
267268
* @return {Promise} Resolves to the array of tag strings.
268269
*/
269-
getChallengeTags() {
270-
return this.private.api.get('/technologies')
270+
async getChallengeTags() {
271+
const api = await this.private.api;
272+
return api.get('/technologies')
271273
.then(res => (res.ok ? res.json() : new Error(res.statusText)))
272274
.then(res => (
273275
res.result.status === 200
@@ -311,9 +313,10 @@ class ChallengesService {
311313
* @param {String} challengeId
312314
* @return {Promise}
313315
*/
314-
register(challengeId) {
316+
async register(challengeId) {
317+
const apiV2 = await this.private.apiV2;
315318
const endpoint = `/challenges/${challengeId}/register`;
316-
return this.private.apiV2.postJson(endpoint)
319+
return apiV2.postJson(endpoint)
317320
.then(res => (res.ok ? res.json() : new Error(res.statusText)));
318321
}
319322

@@ -322,9 +325,10 @@ class ChallengesService {
322325
* @param {String} challengeId
323326
* @return {Promise}
324327
*/
325-
unregister(challengeId) {
328+
async unregister(challengeId) {
329+
const apiV2 = await this.private.apiV2;
326330
const endpoint = `/challenges/${challengeId}/unregister`;
327-
return this.private.apiV2.post(endpoint)
331+
return apiV2.post(endpoint)
328332
.then(res => (res.ok ? res.json() : new Error(res.statusText)));
329333
}
330334

src/services/__mocks__/groups.js

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -184,8 +184,9 @@ class GroupService {
184184
* @param {String} membershipType
185185
* @return {Promise}
186186
*/
187-
addMember(groupId, memberId, membershipType) {
188-
return this.private.api.postJson(`/groups/${groupId}/members`, {
187+
async addMember(groupId, memberId, membershipType) {
188+
const api = await this.private.api;
189+
return api.postJson(`/groups/${groupId}/members`, {
189190
param: { memberId, membershipType },
190191
}).then(handleApiResponse);
191192
}
@@ -202,12 +203,13 @@ class GroupService {
202203
* whether the response should information about sub-groups, if any.
203204
* @return {Promise} On success resolves to the group data object.
204205
*/
205-
getGroup(groupId, withSubGroups = true) {
206+
async getGroup(groupId, withSubGroups = true) {
207+
const api = await this.private.api;
206208
let url = `/groups/${groupId}`;
207209
if (withSubGroups) {
208210
url = `${url}/getSubGroups?includeSubGroups=true&oneLevel=false`;
209211
}
210-
return this.private.api.get(url).then(handleApiResponse);
212+
return api.get(url).then(handleApiResponse);
211213
}
212214

213215
/**
@@ -255,8 +257,9 @@ class GroupService {
255257
* @return {Promise} On sucess resolves to the array of member objects,
256258
* which include user IDs, membership time, and some bookkeeping data.
257259
*/
258-
getMembers(groupId) {
259-
return this.private.api.get(`/groups/${groupId}/members`)
260+
async getMembers(groupId) {
261+
const api = await this.private.api;
262+
return api.get(`/groups/${groupId}/members`)
260263
.then(handleApiResponse);
261264
}
262265

src/services/api.js

Lines changed: 21 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
import _ from 'lodash';
77
import fetch from 'isomorphic-fetch';
88
import { config, isomorphy } from 'topcoder-react-utils';
9+
import { isTokenExpired, getFreshToken, configureConnector } from '@topcoder-platform/tc-auth-lib';
910
import { auth } from 'tc-core-library-js';
1011
import { delay } from '../utils/time';
1112
import {
@@ -251,12 +252,25 @@ const lastApiInstances = {};
251252
* @param {String} token Optional. Auth token for Topcoder API.
252253
* @return {Api} API service object.
253254
*/
254-
export function getApi(version, token) {
255+
export async function getApi(version, token) {
256+
let nToken = token;
257+
if (isomorphy.isClientSide() && nToken && isTokenExpired(nToken)) {
258+
configureConnector({
259+
connectorUrl: config.URL.ACCOUNTS_APP_CONNECTOR,
260+
frameId: 'tc-accounts-iframe',
261+
frameTitle: 'Accounts authentication window',
262+
});
263+
console.log('currently Token: ', nToken);
264+
console.log('token expired, getting new one...');
265+
nToken = await getFreshToken();
266+
console.log('newToken: ', nToken);
267+
}
268+
255269
if (!version || !config.API[version]) {
256270
throw new Error(`${version} is not a valid API version`);
257271
}
258-
if (!lastApiInstances[version] || lastApiInstances[version].private.token !== token) {
259-
lastApiInstances[version] = new Api(config.API[version], token);
272+
if (!lastApiInstances[version] || lastApiInstances[version].private.token !== nToken) {
273+
lastApiInstances[version] = new Api(config.API[version], nToken);
260274
}
261275
return lastApiInstances[version];
262276
}
@@ -266,10 +280,10 @@ export function getApi(version, token) {
266280
* DO NOT USE THEM FOR NEW IMPLEMENTATIONS.
267281
* USE THE getApi(version, token) FACTORY.
268282
*/
269-
export const getApiV2 = token => getApi('V2', token);
270-
export const getApiV3 = token => getApi('V3', token);
271-
export const getApiV4 = token => getApi('V4', token);
272-
export const getApiV5 = token => getApi('V5', token);
283+
export const getApiV2 = async token => getApi('V2', token);
284+
export const getApiV3 = async token => getApi('V3', token);
285+
export const getApiV4 = async token => getApi('V4', token);
286+
export const getApiV5 = async token => getApi('V5', token);
273287

274288
/**
275289
* Gets a valid TC M2M token, either requesting one from TC Auth0 API, or

src/services/billing.js

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,8 +30,9 @@ class Billing {
3030
* Gets billing accounts accessible to service user.
3131
* @return {Promise} Resolves to the list of billing account objects.
3232
*/
33-
getUserBillingAccounts() {
34-
return this.private.api.fetch();
33+
async getUserBillingAccounts() {
34+
const api = await this.private.api;
35+
return api.fetch();
3536
}
3637
}
3738

0 commit comments

Comments
 (0)