Skip to content

Commit

Permalink
Merge branch 'error_management' into sql_error_management
Browse files Browse the repository at this point in the history
  • Loading branch information
oded leiba committed Aug 2, 2016
2 parents 82efce0 + 6d88336 commit 7366e8b
Show file tree
Hide file tree
Showing 3 changed files with 110 additions and 26 deletions.
127 changes: 105 additions & 22 deletions lib/router.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,12 @@

var express = require('express')
var merge = require('merge')
var clone = require('clone')
var jf = require('jsonfile')
var fs = require('fs')
var path = require('path')

var ROOT_VERSION = 'root'

function build_rest_path (path, params) {
if (params) {
Expand Down Expand Up @@ -43,40 +49,47 @@ function parse_error_msg (err) {

function get_params_from_request (request, params_template, mandatory, callback) {
var params = {}
var errors
params_template = params_template || []
for (var index = 0; index < params_template.length; index++) {
var param_name = params_template[index]
var param
if (request.check) {
if (mandatory) request.assert(param_name, 'Missing param: ' + param_name).notEmpty()
var errors = request.validationErrors()
if (errors) {
if (!Array.isArray(errors)) errors = [errors]
var msgs = errors.map(function (err) {
return parse_error_msg(err)
})
var msg = msgs.join('\n')
// console.error(msg)
var err = {
message: msg,
status: 400
}
return callback(err)
}
param = extract_param(request, param_name)
errors = request.validationErrors()
} else {
param = extract_param(request, param_name)
}
if (!(typeof param === 'undefined')) params[param_name] = param
}

if (request.check) {
errors = request.validationErrors()
if (errors) {
if (!Array.isArray(errors)) errors = [errors]
var explanations = errors.map(function (err) {
return parse_error_msg(err)
})
var explanation = explanations.join('\n')
console.error(explanation)
var err = {
message: 'Validation error',
explanation: explanation,
status: 400
}
return callback(err)
}
}

callback(null, params)
}

function build_function_call (controllers_path, path_element) {
var function_name_array = path_element.function_name.split('.')
var cFile = controllers_path + function_name_array[0] + '.js'
var cFunction = function_name_array[1]
var version = function_name_array.length === 3 ? function_name_array[0] : ''
var file_name = function_name_array[function_name_array.length - 2]
var cFile = path.join(controllers_path, version, file_name + '.js')
var cFunction = function_name_array[function_name_array.length - 1]
return function (request, response, next) {
return require(cFile)[cFunction](request, response, next)
}
Expand All @@ -99,7 +112,7 @@ function build_request_params (path_element) {
}
}

function connect_paths (router, method, controllers_path, auth, routes, private_area, custom_middlewares) {
function connect_paths (router, version, method, controllers_path, auth, routes, private_area, custom_middlewares) {
for (var path in routes) {
var middlewares = []
var path_element = routes[path]
Expand All @@ -126,16 +139,86 @@ function connect_paths (router, method, controllers_path, auth, routes, private_

var handler = build_function_call(controllers_path, path_element)
middlewares.push(handler)

path = (version === ROOT_VERSION) ? path : '/' + version + path
rest_path = (version === ROOT_VERSION) ? path : '/' + version + rest_path
router[method](path, middlewares)
router[method](rest_path, middlewares)
}
}

module.exports = function (routes, controllers_path, auth, router, custom_middlewares) {
var build_routes = function (routes_path) {
var routes = {}
var GET_public = {}
var GET_private = {}
var POST_public = {}
var POST_private = {}
var PUT_public = {}
var PUT_private = {}
var DELETE_public = {}
var DELETE_private = {}

var version_folders = [ROOT_VERSION]
var files = fs.readdirSync(routes_path)
files.forEach(function (file_name) {
var file_path = path.join(routes_path, file_name)
if (fs.lstatSync(file_path).isDirectory()) {
if (file_name[0] !== 'v' || isNaN(file_name.substring(1, file_name.length))) {
throw new Error('version folders under routes path must be of format "v"<number>')
}
version_folders.push(file_name)
}
})
version_folders.sort(function (folder1, folder2) {
return parseInt(folder1.substring(1, folder1.length), 10) - parseInt(folder2.substring(1, folder2.length), 10)
})

version_folders.forEach(function (version) {
merge_route(GET_public, 'GET-public.json')
merge_route(GET_private, 'GET-private.json')
merge_route(POST_public, 'POST-public.json')
merge_route(POST_private, 'POST-private.json')
merge_route(PUT_public, 'PUT-public.json')
merge_route(PUT_private, 'PUT-private.json')
merge_route(DELETE_public, 'DELETE-public.json')
merge_route(DELETE_private, 'DELETE-private.json')

routes[version] = {
// Routing settings
GET: { Public: clone(GET_public), Private: clone(GET_private) },
POST: { Public: clone(POST_public), Private: clone(POST_private) },
PUT: { Public: clone(PUT_public), Private: clone(PUT_private) },
DELETE: { Public: clone(DELETE_public), Private: clone(DELETE_private) }
}

function merge_route (route, file_name) {
console.log('version = ', version)
var versioned_routes_path = version === ROOT_VERSION ? routes_path : path.join(routes_path, version)
console.log('versioned_routes_path = ', versioned_routes_path)
var route_path = path.join(versioned_routes_path, file_name)
try {
var json = jf.readFileSync(route_path)
Object.keys(json).forEach(function (path) {
json[path].function_name = version === ROOT_VERSION ? json[path].function_name : (version + '.' + json[path].function_name)
})
merge(route, json)
} catch (e) {
// file does not exist - do nothing
}
}
})

return routes
}

module.exports = function (routes_path, controllers_path, auth, router, custom_middlewares) {
var routes = build_routes(routes_path)
router = router || express.Router()
for (var method in routes) {
connect_paths(router, method.toLowerCase(), controllers_path, auth, routes[method].Public, false, custom_middlewares)
connect_paths(router, method.toLowerCase(), controllers_path, auth, routes[method].Private, true, custom_middlewares)
for (var version in routes) {
for (var method in routes[version]) {
connect_paths(router, version, method.toLowerCase(), controllers_path, auth, routes[version][method].Public, false, custom_middlewares)
connect_paths(router, version, method.toLowerCase(), controllers_path, auth, routes[version][method].Private, true, custom_middlewares)
}
}
console.log('----------------------------------------------------------------------------------')
console.log('------------------------------- Created Routes -------------------------------')
Expand Down
6 changes: 3 additions & 3 deletions lib/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ module.exports = function (properties) {
var static_folder = properties.engine && properties.engine.static_folder
var admin_users = properties.basic && properties.basic.admin_users
var realm = properties.basic && properties.basic.realm
var validator = { customValidators: properties.modules && properties.modules.validator }
var validator = properties.modules && properties.modules.validator
var router = properties.modules && properties.modules.router
var error = properties.modules && properties.modules.error
var logger = properties.modules && properties.modules.logger
Expand Down Expand Up @@ -115,11 +115,11 @@ module.exports = function (properties) {
app.use(favicon(faviconDir)) // Fast fav icon middleware
app.use(cors()) // Allowing CORS comunication
app.use(bodyParser.json()) // Support for JSON-encoded bodies
app.use(bodyParser.urlencoded({ extended: true })) // Support for URL-encoded bodies
app.use(bodyParser.urlencoded({ extended: true })) // Support for URL-encoded bodies
app.engine(file_extantion, consolidate[engine_type]) // assign the template engine to the file extantion
app.set('view engine', file_extantion) // set file extantion as the default extension
app.set('views', views_folder) // Changing default view folder
app.use(expressValidator(validator)) // Parameter validation middleware
app.use(validator || expressValidator()) // Parameter validation middleware
router && app.use(router) // Load the router to the server
static_folder && app.use(express.static(static_folder)) // Optional HTTP static server middleware
logger && app.use(expressWinston.errorLogger({ // Adds optional express error logging to winston logger
Expand Down
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@
"http-auth": "^2.2.8",
"iniparser": "^1.0.5",
"jade": "^1.11.0",
"jsonfile": "^2.2.1",
"jsonfile": "^2.3.1",
"jwt-simple": "^0.3.1",
"le_node": "^1.1.0",
"lodash": "^3.10.1",
Expand All @@ -77,6 +77,7 @@
"qs": "^5.0.0",
"redis": "^2.4.2",
"request": "^2.61.0",
"sequelize": "3.22.0",
"serve-favicon": "^2.3.0",
"socket.io": "git+https://github.com/tal-beja/socket.io.git",
"socket.io-client": "git+https://github.com/tal-beja/socket.io-redis.git",
Expand Down

0 comments on commit 7366e8b

Please sign in to comment.