2

I'm using locomotivejs to build an api and I wanted to know if there was a way to access a controller method from within another controller?

clueless
  • 839
  • 1
  • 10
  • 24

1 Answers1

2

The only possibility is to request another Controller. In our locomotive Project, we use Service to execute same code between different Controllers like this :

Controller :

'use strict';

var Controller          = require('../../../libs/v1.2/controller'),
    codes               = require('../../../config/app/codes'),
    MediaService        = require('../../services/v1.2/media_service');

var AlbumsController = new Controller();

AlbumsController.index = function() {
    var service  = new MediaService(),
        exampleParam  = this.param('exampleParam');

    service.findAllAlbums(exampleParam, function(err, result){
        if(err){
            this.res.status(codes.http.success).json([]);
            return;
        }
        this.res.status(codes.http.success).json(result);
    }.bind(this));
};

In this example, I call directly a service method to get all my albums and, if I want, I call this method in another Controller. I think is the best method to use same action in differents Controller's actions.

throrin19
  • 17,796
  • 4
  • 32
  • 52