-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
48 lines (40 loc) · 2.03 KB
/
Copy pathapp.js
File metadata and controls
48 lines (40 loc) · 2.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/**
* It would be our main entry js file and server will start from it
*/
//===========LOAD ALL REQUIRED MODULE=====================================
var express = require('express'); //load express module to crate instance of app
var cookieParser = require('cookie-parser'); //Parse Cookie header and populate req.cookies.
//body parsing middleware, does not support multi-part, you have to use other module for multi-part parsing.
var bodyParser = require('body-parser');
//express-validation is a middleware that validates the body, params, query,
// headers and cookies of a request and returns a response with errors;
//we have used it for contact request parameters validation with JOI.
var validate = require('express-validation');
//Mongoose is a MongoDB object modeling tool designed to work in an asynchronous environment.
var mongoose = require('mongoose');
//Create a instance of express application.
var app = express();
//load config module to get configuration parameters about database.
var config = require('./app/config');
var db_url = 'mongodb://' + config.host + ':' + config.db_port + '/' + config.db_name;
//connect with mongo db.
mongoose.connect(db_url);
//Get route index so request can be redirect according to route.
var routes = require('./app/routes');
//==============USE MIDDLEWARE===========================================================================
//parse body in json format.
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());
//Call route's index /app/routes.js
app.use('/', routes);
//error handler, if request parameters do not fulfill validations a error message would be sent back as response.
app.use(function (err, req, res, next) {
// specific for validation errors
if (err instanceof validate.ValidationError) {
return res.json({status: err.status, errorMessage: err});
}
});
//Start listing application on defined port in configuration file.
app.listen(config.app_port);
console.log('Express server listening on port ' + config.app_port);