Tuesday, 5 November 2019

Async implementation in Express middleware

I am using a middleware to refactor a bit.Here is the process: every time a request comes, router level middleware takes in and checks if the JWT exists and is not expired, if it exists and is not expired, read the token from Redis server, otherwise request a new token and save it to Redis.I have two questions:The below middleware just gets bypassed, how should I fix this?How to do async/await way of this middleware?Thanks in advance!Middleware:const oAuthClient = require("../client/oAuthClient")const redisClient = require("../client/redis")module.exports = (req, res, next) => {const cid = req.cid;console.log(cid);const existPromise = redisClient.existsAsync(cid)const hgetPromise = redisClient.hgetAsync(cid, "expiration")Promise.all([existPromise, hgetPromise]).then((redisReplies) => {if (redisReplies[0] && (Number(redisReplies[1]) < new Date().getTime())) {redisClient.hgetAsync(cid, "token").then((token) => {req.jwt = token})} else {oAuthClient.credentials.getToken().then((oAuthReplies) => {const jwtToken = oAuthReplies.accessTokenconst expirationIn = oAuthReplies.data.expires_inconst p1 = redisClient.hsetAsync(cid, 'token', jwtToken)const p2 = redisClient.hsetAsync(cid, 'expiration', new Date().getTime() + Number(expirationIn))Promise.all([p1, p2]).then(() => {req.jwt = jwtTokennext()})})}}).catch((err) => {next(err)})}​Route Handler:router.get("/emailBot/:cid", getParams, getOauthToken, async (req, res, next) => {const cid = req.cidconst jwtToken = req.jwttry {const apiUrl = process.env.EMAILBOTAPIconst XToken = process.env.EMAILBOTXTOKENconsole.log(apiUrl, XToken, jwtToken);const apiResponse = await sendMessages.triggerApi(apiUrl, jwtToken, XToken, {invocationContext: {cid: cid}})console.log(apiResponse);} catch (error) {next(error)}res.send({message: "success"}))}

Submitted November 05, 2019 at 08:20AM by PanJohn2019

No comments:

Post a Comment