Wednesday 17 May 2017

What is the best way to separate your code in a Node.js application?

I'm working on a MEAN (Mongo Express.js Angular Node.js) CRUD application. I have it working but everything is in one .js file. The single source code file is quite large. I want to refactor the code so CRUD functionality is in different source code files. Reading through other posts, I've got a working model but am not sure it is the right way in Node using Mongo to get it done.

Here's the code so far:

<pre>

var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var path = require('path');
var db;
var connect = 'mongodb://<<mddbconnect string>>;
const MongoClient = require('mongodb').MongoClient;
var ObjectID = require("mongodb").ObjectID;

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.use(express.static(__dirname + '/'));

// viewed at http://localhost:<<port referecnes in app.listen>>
app.get('/', (req, res) => {
    res.sendFile(path.join(__dirname + '/index.html'));
});

MongoClient.connect(connect, (err, database) => {
    if (err) return console.log(err)
    db = database
    app.listen(3000, () => {
        console.log('listening on 3000' + Date() );

    // Here's the require for the search function in another source code file.
    var searchroute = require('./serverSearch')(app, db);

    })
})

//Handlers
The rest of the CRUD application functions with app.post, app.get.  These are other functions I want to move into different source code files, like serverSearch.js.
</pre>

The code I separated right now is the search functionality which is inside of the MongoClient.connection function. This function has to successfully execute to make sure the variable 'db' is valid before passing both variables 'app' and 'db' to the the search function built out in the source code file serverSearch.js.

I could now build out my other CRUD functions in separate files in put them in the same area as 'var searchroute = require('./serverSearch)(app,db);

Is this the best way to separate code in a MEAN application where the main app and db vars need to be instantiated then passed to functions in other source code files?



via Jef

No comments:

Post a Comment