Skip to content

Commit

Permalink
Added statistics for every user per endpoint
Browse files Browse the repository at this point in the history
  • Loading branch information
kyrea committed Jul 18, 2024
1 parent d01dbf1 commit 404a6bb
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
30 changes: 30 additions & 0 deletions src/middlewares/authorize.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ const authorize = requiredRole => async (req, res, next) => {
* Determine the endpoint based on the request URL.
*/
const endpoint = getEndpointFromUrl(req.originalUrl);

/**
* Check if the requested endpoint is disabled.
*/
Expand Down Expand Up @@ -111,6 +112,11 @@ const authorize = requiredRole => async (req, res, next) => {
return next(createError(403, 'Insufficient privileges to access this endpoint.'));
}

/**
* Log the user request.
*/
await logUserRequest(userData._id, endpoint);

/**
* Increment system stats for successful requests.
*/
Expand Down Expand Up @@ -184,4 +190,28 @@ const incrementSystemStats = async stats => {
await Stats.findByIdAndUpdate({ _id: 'systemstats' }, { $inc: stats });
};

/**
* Log the number of requests made by a user to a specific endpoint.
*
* @param {string} userId - The ID of the user.
* @param {string} endpoint - The endpoint being accessed.
* @returns {Promise<void>} - Resolves when the log is updated.
*/
const logUserRequest = async (userId, endpoint) => {
try {
// Find the user and update the request count for the specific endpoint
await Users.findByIdAndUpdate(
userId,
{
$inc: {
[`statistics.requests.${endpoint}`]: 1,
},
},
{ new: true, upsert: true }, // Create a new document if it doesn't exist
);
} catch (error) {
console.error('Error logging user request:', error);
}
};

export default authorize;
12 changes: 12 additions & 0 deletions src/models/schemas/User.js
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,18 @@ const UserSchema = new mongoose.Schema({
* @type {object}
*/
subscriptionMetadata: { type: Object },

/**
* Object to store the count of requests made to each endpoint by the user.
* @type {Object}
*/
statistics: {
requests: {
type: Map,
of: Number,
default: {},
},
},
});

/**
Expand Down

0 comments on commit 404a6bb

Please sign in to comment.