mardi 13 juin 2017

Develop correct structure and design pattern for my node project

Introduction

First time using Node and appreciate all help and improvements.

I have developed code that

  1. first gets data from a post
  2. secondly authenticates the API connection and gets the key
  3. uses variables from the first and second function and posts to the API

Question

This code is all working and is node so back-end. However I have not built it with MVC in mind, I would like someone to help me clean this and structure it better.

I am brand new to node and wish for my first project to follow a neat MVC structure I can use as A idea on how to structure future products.

What I have

As said before the code works however it is all within index.js on the root, as it is the back-end of my application I would like it to be in a folder called backend then folders or files on from there.

index.js

//---------------------------------- Grab the packages we need and set variables ---------------------------------------
//----------------------------------------------------------------------------------------------------------------------
var express = require('express');
var request = require('request');
var nodePardot = require('node-pardot');
var bodyParser = require('body-parser');
var app = express();
var port = process.env.PORT || 8080;

// Credential's for pardot API
var password = '######';
var userkey = '######';
var emailAdmin = '######';

// 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('Server started! At http://localhost:' + port); // Confirms server start

//---------------------------------- Function to get front end form posted data ----------------------------------------
//----------------------------------------------------------------------------------------------------------------------
var firstFunction = function () {
    var promise = new Promise(function (resolve) { // may be redundant
        setTimeout(function () {
            app.post('/api/data', function (req, res) {
                console.log(req.body);
                // Get varibles from the post form
                var email_user = req.body.email;
                var first_name = req.body.fname;
                var last_name = req.body.lname;

                // res.send(email_user);
                res.send(first_name + ' ' + last_name + ' ' + email_user);

                //resolve when get the response
                resolve({
                    data_email: email_user,
                    data_first_name: first_name,
                    data_last_name: last_name
                });
            });

        }, 2000);
    });
    return promise;
};

//---------------------------------- Function to get API key from Pardot (AUTHENTICATION) ------------------------------
//----------------------------------------------------------------------------------------------------------------------
var secondFunction = function () {
    var promise = 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});
                }
            });

        }, 2000);
    });
    return promise;
};

//---------------------------------- Function to post data to Pardot ---------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------
function thirdFunction(result) {
    var promise = 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 useremail = result[0].data_email;
            var api = result[1].data_api;
            var Fname = result[0].data_first_name;
            var Lname = result[0].data_last_name;
            var options = {
                url: 'http://ift.tt/2rWjniS',
                method: 'POST',
                headers: headers,
                form: {
                    'email': useremail,
                    'user_key': userkey,
                    'api_key': api,
                    'first_name': Fname,
                    'last_name': Lname
                }
            };

// Start the request
            request(options, function (error, response) {
                if (!error && response.statusCode == 200) {
                    console.log("error", error);
                }
                else {
                    console.log("Sent Data successful !");
                    console.log("API Key", api);
                    console.log("user", useremail);
                    console.log("userKey", userkey);
                    console.log("name", Fname);
                    console.log("surname", Lname);
                }
            });
        }, 3000);
    });
    return promise;
}

// sequence of functions
Promise.all([firstFunction(), secondFunction()])
    .then(thirdFunction);

Aucun commentaire:

Enregistrer un commentaire