Beep
Beep

Reputation: 2823

How to use MVC and include files in my node app

I Have a Node app, I have three files and am trying to structure my node in a MVC pattern.

I want a way to put all my requires and variables in my server.js all the routes in my routes.js and my functions in my controller.js.

My router is fine and works. How do I include the functions from controller in my server file

I have:

var configure = require('./router');
var express = require('express');
var app = express();
var port = process.env.PORT || 8080;

// get an instance of router
var router = express.Router();
configure(router);

var request = require('request');
var nodePardot = require('node-pardot');
var bodyParser = require('body-parser');
var rp = require('request-promise');

// Start the server
app.listen(port);
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({extended: true})); // support encoded bodies
console.log('Test server started! At http://localhost:' + port); // Confirms server start
//
// // START THE SERVER
// // ==============================================
app.listen(port);
console.log('Server has started!! ' + port);

// apply the routes to our application
app.use('/', router);

  module.exports = function (router) {
    
            // route middleware that will happen on every request
            router.use(function (req, res, next) {
        
                // log each request to the console
                console.log(req.method, req.url);
        
                // continue doing what we were doing and go to the route
                next();
            });
        
        // home page route (http://localhost:8080)
            router.get('/', function (req, res) {
                res.send('im the home page!');
            });
    
 

    router.get('/login', function (req, res) {
                res.send('this is the login form');
            })
    
            // process the form (POST http://localhost:8080/login)
            .post('/login', function (req, res) {
                console.log('processing'); // shows on console when post is made
                res.send('processing the login form!'); // output on postman
            });
    };

    var password = 'gf.09';
    var userkey = 'dfgg';
    var emailAdmin = '[email protected]';
    
    // Start the server
    app.listen(port);
    app.use(bodyParser.json()); // support json encoded bodies
    app.use(bodyParser.urlencoded({extended: true})); // support encoded bodies
    console.log('Test server started! At http://localhost:' + port); // Confirms server start
    
    var firstFunction = function () {
        return new Promise (function (resolve) {
            setTimeout(function () {
                app.post('/back-end/test', function (req, res) {
                    console.log(req.body);
                    var login = req.body.LoginEmail;
                    res.send(login);
                    resolve({
                        data_login_email: login
                    });
                });
                console.error("First done");
            }, 2000);
        });
    };
    
    var secondFunction = function () {
        return new Promise (function (resolve) {
            setTimeout(function () {
                nodePardot.PardotAPI({
                    userKey: userkey,
                    email: emailAdmin,
                    password: password,
                    DEBUG: false
                }, function (err, client) {
                    if (err) {
                        // Authentication failed
                        console.error("Authentication Failed", err);
                    } else {
                        // Authentication successful
                        var api_key = client.apiKey;
                        console.log("Authentication successful !", api_key);
                        resolve({data_api: api_key});
                    }
                });
                console.error("Second done");
            }, 2000);
        });
    };
    
    
    function thirdFunction(result) {
        return new Promise (function () {
            setTimeout(function () {
                var headers = {
                    'User-Agent': 'Super Agent/0.0.1',
                    'Content-Type': 'application/x-www-form-urlencoded'
                };
    // Configure the request
                var api = result[1].data_api;
                var login_email = result[0].data_login_email;
                var options = {
                    url: 'https://pi.pardot.com/api/prospect/version/4/do/read',
                    method: 'POST',
                    headers: headers,
                    form: {
                        'email': login_email,
                        'user_key': userkey,
                        'api_key': api
                    },
                    json: true // Automatically stringifies the body to JSON
                };
    
    // Start the request
                rp(options)
                    .then(function (parsedBody) {
                        console.error(login_email, "Is a user, login pass!");
    
                    })
                    .catch(function (err) {
                        console.error("fail no such user");
                        // res.status(400).send()
    
                    });
                console.error("Third done");
            }, 3000);
        }
        );
    }
    
    // sequence of functions
    Promise.all([firstFunction(), secondFunction()])
        .then(thirdFunction);

What I have tried

var routers = require('./router');
var controller = require('./test');
// var controller = require('./test.js','./router' );
var express = require('express');
var request = require('request');
var nodePardot = require('node-pardot');
var bodyParser = require('body-parser');
var rp = require('request-promise');
var app = express();
var port = process.env.PORT || 8080;
var router = express.Router();

routers(router);
controller(Promise);

and

module.exports = function (Promise) {  

all functions 

}

Problem is some of the variables are not available to controller.js so i get errors such as :

app.post('/back-end/controller', function (req, res) {

            ^

Upvotes: 1

Views: 213

Answers (1)

Arpit Solanki
Arpit Solanki

Reputation: 9931

This is dead simple use same logic as you applied in your router.js.

Use something like below in controller.js:

exports.function_name = function(params, ...){
. . .
}

Then access these function by importing the controller.js

var controller = require('./controller.js');
controller.function_name(param..)   # execute with required params and callback

If you want to return an object then you can do module.exports

module.exports = Promise.all([firstFunction(), secondFunction()]) .then(thirdFunction);

The controller object contain a promise now so

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

controller object directly can be used as a promise no need to call a function now.

A better alternative is to export all the functions from controller.js and then in app.js you can use them with promise.

Promise.all([controller.firstFunction(), controller.secondFunction()]) .then(controller.thirdFunction);

Upvotes: 1

Related Questions