\$\begingroup\$

I'm working on a project in which I have a backend in nodejs and from there I need to call external APIs, those APIs require authentication token which is valid for 15 minutes. So if response status from external APIs is 401 then I need to generate a new token then call the request.

In my backend, I'm using request-promise package which doesn't provide any interceptor concept like axios, So tried creating my own mechanism, Below code is in typescript

class RequestHandler { private token: any = { promiseCreator: function () { return new Promise((resolve, reject) => { this.rejects.push(reject); this.resolves.push(resolve); }); }, rejects: [], resolves: [], v: null, get value() { return this.v; }, set value(val) { this.v = val; if (val) { this.resolves.forEach((resolve: any) => resolve()); } else { this.rejects.forEach((reject: any) => reject()); } this.resolves = []; this.rejects = []; } }; constructor() { this.authorize(); } // Test Request public async test(reqBody) { const reqOptions = { dataType: "json", headers: { Authorization: `Bearer ${this.token.value}` }, json: reqBody, method: "POST", url: "http://localhost:8080/test-async", }; const { data } = await request(reqOptions); // on success return data if (data.status === "200") { return data; } // if authentication fails generate new token and then request again if (data.status === "401") { return await this.unAuthorizeRequestHandler(this.test.bind(this, reqBody)); } // if status other than 200 and 401 then throw error throw new Error(data.message); } // To Get Authentication Token async authorize() { const reqOptions = { dataType: "json", json: {}, method: "POST", url: "http://localhost:8080/auth", }; const { token } = await request(reqOptions); this.token.value = token; } // handles retry logic async unAuthorizeRequestHandler(requestFunction: any) { if (this.token.value) { this.token.value = null; try { await this.authorize(); } catch (err) { this.token.value = null; throw new Error(err.toString()); } } else { await this.token.promiseCreator(); } return await requestFunction(); } }

In the above code, unAuthorizeRequestHandler handles retry mechanism, it checks first if the token value is not null call authorize function to get the new token and make its value null, so when other requests come they will wait till authorize function sets new token ( it's done by promiseGenerator, it returns pending promise which will get resolve or reject when authorize function set token.value )

Please review my code guys