AdamFune / capstone-project-2-expresso

Capstone project from Codecademy's intensive program.
0 stars 0 forks source link

Server.js Recommendation #2

Open jordanwillis opened 6 years ago

jordanwillis commented 6 years ago

Your express middleware and router setup looks great! One recommendation that I would make it to consider adding an API level router abstraction to prevent having to continually add routers in your server.js file. There are of course a hundred different ways to structure an express application, but at least for me, I've come to enjoy letting my server.js primarily contain standard express setup boilerplate code and create an extra file that contains the main API router setup. Here is an example of what I mean.

server.js

const bodyParser = require('body-parser');
const cors = require('cors');
const errorhandler = require('errorhandler');
const express = require('express');
const apiRouter = require('./api/index.js');
const app = express();

const PORT = process.env.PORT || 4000;

app.use(bodyParser.json());
app.use(cors());
app.use('/api', apiRouter);
app.use(errorhandler());

app.listen(PORT, () => {
  console.log('Listening on port: ' + PORT);
});

module.exports = app;

./api/index.js

const express = require('express');
const apiRouter = express.Router();
const employeesRouter = require('./employees.js');
const menusRouter = require('./menus.js');

apiRouter.use('/employees', employeesRouter);
apiRouter.use('/menus', menusRouter); 

module.exports = apiRouter;

Now as my API grows over time I can leave my server.js alone and just modify ./api/index.js.

Again, this is not necessarily a best practice but rather just a recommendation based upon how I like to do things in case this resonates with you.

AdamFune commented 6 years ago

This is great advice that I will implement in the future.