raptor
raptor

Reputation: 760

Function parameter overwritten

The following node.js module logs ModelA two times and ModelB two times during initialization, as expected. Then the model parameter is somehow overwritten and when I attempt to use the routes, it always logs ModelA.

module.exports = (model) => {
  console.log(model.modelName);
  return (db) => {
    console.log(model.modelName);

    router.post('/', (req, res, next) => {
      console.log(model.modelName);
      model.insertMany(req.body, (err, docs) => {
        if(err) return next(err);
        res.json(docs);
      });
    });

    return router;
  };
};

The module is used like this:

const express = require('express');
const router = express.Router();

const plural = require('./plural.js');

module.exports = (db) => {
  router.use('/a', plural(db.ModelA)(db));
  router.use('/b', plural(db.ModelB)(db));

  return router;
};

Upvotes: 0

Views: 50

Answers (1)

mscdex
mscdex

Reputation: 106726

Assuming you are only creating a new Router instance at the top of plural.js, then you need to instead create the Router instance inside the function that adds the route handler (router.post(...)), otherwise you're returning the same Router instance both times and the second call to plural() is just appending to the same Router. Because of that, the ModelA-based route handler will always execute first and respond to the request (unless it calls next()). For example:

const Router = require('express').Router;
// const router = new Router();  // <--- move this line ...
module.exports = (model) => {
  return (db) => {
    const router = new Router(); // <--- ... to here

    router.post('/', (req, res, next) => {
      console.log(model.modelName);
      model.insertMany(req.body, (err, docs) => {
        if(err) return next(err);
        res.json(docs);
      });
    });

    return router;
  };
};

Upvotes: 1

Related Questions