-1

I am working on an APi using express in node.js.

Controler:

/**
 * @module QuestionController
 */

//1st Action
exports.videoUploaded = function(req,res)
{
//  myCode();
}

//2nd Action
exports.transcribe = function(req, res)
{
var id = req.params.question_id;
//  myCode();
}

Route:

var questionController = require('./../controllers/question');
var apiRouter = express.Router();

apiRouter.route('/questions/:question_id/video_uploaded')
.post(Auth.roleAtLeastPatient,questionController.videoUploaded);

apiRouter.route('/questions/:question_id/transcribe')
.post(Auth.roleAtLeastPatient,questionController.transcribe);

My server file:

var app = require('./srv/express-app');
var webserver = http.createServer(app);

Everything works fine, I can call these, endpoints from the browser and Postman. But, how can I call, transcribe action from inside videoUploaded action, while sending the req params too.

mega6382
  • 9,211
  • 17
  • 48
  • 69
  • In **Controller** If you initiallized a function with a name you can then call it from inside `videoUploaded` function and then do `module.exports = {videoUploaded: "videoUploaded_function", transcribe: "transcribe_function"}` – ArchNoob Oct 06 '17 at 11:39
  • @ArchNoob, actually there are many other actions in the controller too. – mega6382 Oct 06 '17 at 11:40
  • 1
    I still think you can call it from a named function and make separate exports. Oh there's already an answer supporting my point! – ArchNoob Oct 06 '17 at 11:46

1 Answers1

0

How to export

//1st Action
videoUploaded(req,res){
  //  myCode();
}

//2nd Action
transcribe(req, res) {
  //  myCode();

  videoUploaded(...);
}

exports default {
  videoUploaded,
  transcribe,
};

How to use it

   import funcs from 'Questions';

    apiRouter.route('/questions/:question_id/video_uploaded')
      .post(Auth.roleAtLeastPatient, funcs.videoUploaded);

What happens in your case is that you do create functions and store them directly into the module.exports. So there are not available inside the file you did declare it on (videoUploaded is not available in transcribe).

What I do is declaring new functions into the file, so theirs scope is the file (videoUploaded can call transcribe). And then we exports pointer to the functions in the files, so you can call them from outside.


A better soluce would be to use ES6 classes, like :

export default class Controller {

  static videoUploaded() {
    // I can call other methods like :
    Controller.transcribe(...);
  }

  static transcribe() {

  }
}

and then to use it :

   import Controller from 'Controller';

    apiRouter.route('/questions/:question_id/video_uploaded')
      .post(Auth.roleAtLeastPatient, Controller.videoUploaded);
Orelsanpls
  • 22,456
  • 6
  • 42
  • 69