简体   繁体   中英

node.js exporting methods facade design pattern

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();

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM