I'm creating an app using Node and Express. However, I can see it'll soon become difficult to manage all the routes that are placed inside app.js
. I have placed all my models in a subdirectory /models
.
Here's my app current structure:
app.js
models
-- products
-- customers
-- ...
public
views
node_modules
In app.js
:
var express = require('express'),
routes = require('./routes'),
user = require('./routes/user'),
http = require('http'),
path = require('path'),
EmployeeProvider = require('./models/employeeprovider').EmployeeProvider,
Products = require('./models/products').Products,
Orders = require('./models/orders').Orders,
Customers = require('./models/customers').Customers,
checkAuth = function(req, res, next) {
if (!req.session.user_id) {
res.send('You are not authorized to view this page');
} else {
next();
}
};
var app = express();
Then some configuration like port
, views
directory, rendering engine, etc.
Further down app.js
I've got the routes:
app.get('/product/edit', auth, function(req, res) {
Products.findAll(function(error, prds) {
res.render('product_edit', {
title: 'New Product',
products: prds
});
});
});
At the top I'm assigning the contents of models/products.js
to a variable, all works fine. However keeping all routes inside app.js
is not ideal. But if I move the routes to routes/product.js
and load the Products
models:
var prod = require('../models/products.js');
I get an error saying that object has no method findAll
.
What am I doing wrong? How can I remove the routes from app.js
?