Reputation: 7032
At server.js I've got the following:
app.use( require( './server/rest-api/v1/products' ) );
app.use( require( './server/rest-api/v1/product-categories' ) );
app.use( require( './server/rest-api/v1/measuring-units' ) );
app.use( require( './server/rest-api/v1/inventory' ) );
app.use( require( './server/rest-api/v1/suppliers' ) );
...
What I want is to make of /server/rest-api/v1
a module, that means that it needs an index.js
, but what would it contain so that I'll only have to do the following at server.js
:
app.use( require( './server/rest-api/v1');
Here's one of the folders as modules I have if is necessary to understand what I ask:
/server/rest-api/v1/products/index.js
module.exports = (function () {
var express = require( 'express' ),
router = express.Router(),
create_product = require( './create-product.controller.js' ),
list_product = require( './list-product.controller.js' ),
detail_product = require( './detail-product.controller.js' ),
update_product = require( './update-product.controller.js' );
router.route( '/api/v1/purchases/products/new' )
.post( create_product.post );
router.route( '/api/v1/purchases/products/list' )
.get( list_product.get );
router.route( '/api/v1/purchases/products/detail/:id' )
.get( detail_product.get );
router.route( '/api/v1/purchases/products/update' )
.put( update_product.put );
return router;
})();
Upvotes: 1
Views: 479
Reputation: 493
You want /server/rest-api/v1/index.js
to expose a unique Router
that uses sub-routers, each corresponding to one of your folders (products, product_categories, etc.)
/server/rest-api/v1/index.js
var express = require('express'),
router = express.Router(),
product_router = require('./products'),
product_categories_router = require('./product_categories');
router.use(product_router);
router.use(product_categories_router);
// etc.
module.exports = router;
On a side note, if you are dealing with many routes this way, it may be handier for you to define your API entry point once ('/api/v1'
), when mounting the router. This way your "business" routers don't need to know the entry path themselves (and it should not matter to them), which is convenient if you ever need to change that path one day.
Then again this is up to you and how you want to design your server :)
Example :
server.js
app.use('/api/v1', require('./server/rest-api/v1'));
/server/rest-api/v1/index.js
var express = require('express'),
router = express.Router(),
product_router = require('./products');
router.use('/purchases/products', product_router);
module.exports = router;
/server/rest-api/v1/products/index.js
var express = require('express'),
router = express.Router(),
create_product = require('./create-product.controller');
router.route('/new').post(create_product.post);
module.exports = router;
Upvotes: 2