alykoshin / express-queue

Express middleware to limit a number of simultaneously processing requests using queue
MIT License
45 stars 12 forks source link

[FeatureRequest] different queue per URL #11

Open maxaug999 opened 7 months ago

maxaug999 commented 7 months ago

Hello, I have been trying to make a custom queue to allow queues to be 'grouped' by a common URL. It is because, for my case, a group of users could be using the same route, but another group could not. (depending on the :id param) Ex.: router.route('/moveto/:id').put(customQueue, moveTo); Since the middleware is global, no matter the case, it currently runs the queue even for a group "/moveto/1234" that has no interraction whatsoever with another group of users "/moveto/6789"

router.route('/moveto/1234').put(customQueue, moveTo); router.route('/moveto/6789').put(customQueue, moveTo); Same route, but two different dynamic entities

So far, it is not working very well. Any possibility it could be added as a feature ?

const queue = require('express-queue');
// Object to store queues for different dynamic IDs
const dynamicQueues = {};

// Custom middleware function to handle queuing based on dynamic IDs
function customQueue(req, res, next) {
  const dynamicID = extractDynamicID(req.url);
  if (!dynamicID)
    return next(new ErrorResponse('Queue error', 401));

  if (!dynamicQueues[dynamicID]) {
    // Create a new queue if it doesn't exist for this dynamic ID
    dynamicQueues[dynamicID] = queue({ activeLimit: 1, queuedLimit: -1 });
  }

  // Use the queue associated with the dynamic ID
  dynamicQueues[dynamicID](req, res, next);
}

// Function to extract the dynamic ID from the URL
function extractDynamicID(url) {
  const segments = url.split('/').slice(0, 3);
  return segments.join('/'); // Join segments to form dynamic ID
}