0

I am trying to follow the facade design pattern in a node.js application where I have on object that is used with the rest of the application called controller.js as the facade. The controller controls calls to objects user.js, animal.js, and house.js which are all separate files.

In controller.js I do

var housecontroller = require("./controllers/housecontroller");
...

I want to call something like controller.getHouse() in another file (client). How do I make it so that I can do that and not have to call housecontroller.getHouse()?

Each of my controllers are formatted as follows

module.exports = {
    getHouse:function(){...},
    ...
}

I'm a bit confused on how to properly export things in order to get this to work. I import/export the controllers and their methods in controller.js as follows

module.exports = {
    getHouse : housecontroller.getHouse,
    ...
};    

I use only the house in the examples but it's implied I do the same for user and animal which all have several methods. In the client, I just import controller.js and use its methods.

var controller = require("./controller");
controller.getHouse();
cavs
  • 367
  • 1
  • 3
  • 14

1 Answers1

3

According to your code/naming you could have a file controller.js in controllers folder with something like this

var housecontroller = require('./housecontroller');
var carcontroller = require('./carcontroller');

module.exports = {
  getHouse: housecontroller.controller,
  getCar: carcontroller.controller
};

The client code could be:

var controller = require('./controllers/controller');
controller.getHouse();

I added carcontroller as example of extension.

If you only have one function to offer from each controller you can change your code and these examples to:

//housecontroller.js
module.exports = getHouse;

//controller.js
var housecontroller = require('./housecontroller');
var carcontroller = require('./carcontroller');

module.exports = {
  getHouse: housecontroller,
  getCar: carcontroller
};

Although I don't recommend it because you are reducing the opportunity to offer more functions from that module in the future

eduardods
  • 56
  • 3
  • Thanks for the response. I tried what you suggested but I think I'm now having trouble with how parameters are getting passed in those methods that are being exported in controller.js – cavs Dec 16 '15 at 00:35
  • 2
    Keep in mind each method is assigning/passing the function that you developed originally in housecontroller, so that function is the one where you have to change the signature to add parameters and play with them. Is that what you mean? – eduardods Dec 16 '15 at 00:53