Boss machine bonus, problems with nested router and parameters

Currently working on the Boss Machine project. I’m trying to challenge myself to make something that works as well as something that is well organized. Things are finally working okay, and making some progress, but there is one thing I can’t quite figure out.

I have a router set up and functioning. This router in turn uses an additional router. All is working so far. Now I am trying to run router.param() to preform some logic in the child router using the parameter that comes from the parent router. I have included {mergeParams: true} when creating the child router.

I would like to run additional logic using the parameter for all http methods in the child router, but don’t seem to be able to. Can I not use router.param() for this purpose? I also seem to not have access to req.minion in the child router (which was attached using router.param() in the parent).

Alternatively is there a way to carry over logic from the router.param() in the parent router to the child router?

Parent router

const {getFromDatabaseById, getAllFromDatabase} = require('./db');

const express = require('express');
const workRouter = require('./workRouter.js');

const minionsRouter = express.Router();
minionsRouter.use('/:minionID/work', workRouter);

minionsRouter.param('minionId', (req, res, next, minionId) => {
    const minion = getFromDatabaseById('minions', minionId);
    if(minion){
        req.minion = minion;
        next();
    }else{
        res.status(404).send();
    }
});

minionsRouter.get('/', (req, res, next) => {
    res.send(getAllFromDatabase('minions'));
});

minionsRouter.get('/:minionId', (req, res, next) => {
    res.send(req.minion);
});

//Some additional http methods here

module.exports = minionsRouter;

Child router

const {getAllFromDatabase} = require('./db');

const express = require('express');
const workRouter = express.Router({mergeParams: true});

workRouter.param('minionId', (req, res, next, minionId) => {
    const allWork = getAllFromDatabase('work');
    const minionWork = allWork.filter(work => work.minionId === minionId);
    console.log(minionWork);
    if(minionWork){
        req.minionWork = minionWork;
        next();
    }else{
        res.status(404).send();
    }
});

workRouter.get('/', (req, res, next) => {
    res.send(req.minionWork);
});

//Some additional http methods here

module.exports = workRouter;

The get methods in the parent router work perfectly, and the get method in the child router works if I move the logic in the router.param() call to it, but as is it does not seem to attach minionWork to req. If router.param() won’t work for this, how can I avoid repeating that code for all http methods in the child router? Thanks!

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.