Search code examples
javascriptexpressrabbitmqmicroservicesamqp

Passing Javascript amqplib Channel To Route Middleware In ExpressJS


I am attempting to create an amqplib connection / channel when my express server starts up and pass that to routes so that they may declare queues, publish messages, etc. I have tried middleware but each time you go to a route and the middleware is invoked, a new connection is built.

I have my route middleware separated out of my index.js file so keep things tidy so I can't just define the amqp queue / publishing logic inside of index.js.

For example ...

// index.js
// ...
const amqplibConnection = // create amqp connection;
const channel = amqplibConnection.createChannel();

const app = express();
const fooRoutes = require('./routes/foo')
// how can I pass channel to ./routes/foo ???
app.use('/api/v1/foo', fooRoutes);

// routes/foo.js
const router = express.Router();
router.get('/', (req, res) => {
    // declare queue, publish message, etc ...
});

Solution

  • You could find mark1 in the following code.
    mark1: create new middleware and assign channel to req.channel then call next(), and you could use req.channel in your foo.js.

    // index.js
    // ...
    const amqplibConnection = // create amqp connection;
    const channel = amqplibConnection.createChannel();
    
    const app = express();
    const fooRoutes = require('./routes/foo')
    // ================= mark1 =================
    app.use('/api/v1/foo', (req, res, next) => {
        req.channel = channel;
        next();
    }, fooRoutes);
    
    // routes/foo.js
    const router = express.Router();
    router.get('/', (req, res) => {
        // declare queue, publish message, etc ...
        req.channel... // do something
    });