|
| 1 | +const User = require('../models/User') |
| 2 | +const redis = require('../../config/redis') |
| 3 | + |
| 4 | +const activity = async (req, res, next) => { |
| 5 | + var redisClient = redis.redisClient |
| 6 | + var route = req.originalUrl.replace(/\?.*$/, '') |
| 7 | + var method = req.method |
| 8 | + var userID = req.user.id.toString() |
| 9 | + console.log('req.body ', req.body) |
| 10 | + console.log('res.locals.data ', res.locals.data) |
| 11 | + console.log('route ', route) |
| 12 | + console.log('methods ', method) |
| 13 | + |
| 14 | + if (route === '/user/logout') { |
| 15 | + var activityData = await redisClient.lrange(userID, 0, -1) |
| 16 | + const data = await User.findOne({ |
| 17 | + _id: userID |
| 18 | + }) |
| 19 | + var activityElement = { |
| 20 | + route: '', |
| 21 | + method: '', |
| 22 | + collectionType: '', |
| 23 | + id: '', |
| 24 | + timestamp: '' |
| 25 | + } |
| 26 | + for (let index = 0; index < activityData.length; index++) { |
| 27 | + var activityDataElement = activityData[index].split(',') |
| 28 | + activityElement.route = activityDataElement[0] |
| 29 | + activityElement.method = activityDataElement[1] |
| 30 | + activityElement.collectionType = activityDataElement[2] |
| 31 | + activityElement.id = activityDataElement[3] |
| 32 | + activityElement.timestamp = activityDataElement[4] |
| 33 | + data.activity.unshift(activityElement) |
| 34 | + } |
| 35 | + await data.update() |
| 36 | + console.log('DATA') |
| 37 | + console.log(data) |
| 38 | + // clear data from redis |
| 39 | + await redisClient.del(userID) |
| 40 | + } else if (method !== 'GET') { |
| 41 | + var objectID = res.locals.data._id |
| 42 | + userID = objectID |
| 43 | + var timeStamp = Date() |
| 44 | + var collectionType = res.locals.collectionType |
| 45 | + if (typeof res.locals.data.userId !== 'undefined') { |
| 46 | + userID = res.locals.data.userId |
| 47 | + } |
| 48 | + // example /auth/login,POST,user,5ed09e9d446f2b1c208b6ba8,Thu Jul 23 2020 20:28:29 GMT+0530 (India Standard Time) |
| 49 | + activityElement = route.concat(',', method, ',', collectionType, ',', objectID, ',', timeStamp) |
| 50 | + // userID => [(route, collection, method, objectID), (route,method, collection, objectID) ...] |
| 51 | + await redisClient.rpush(userID, activityElement) |
| 52 | + next() |
| 53 | + } |
| 54 | +} |
| 55 | + |
| 56 | +module.exports = activity |
0 commit comments