Skip to content

Instantly share code, notes, and snippets.

@shierro
Created May 8, 2018 00:15
Show Gist options
  • Save shierro/ba3eb5777b2b7d4a3fbe93a9565aec2b to your computer and use it in GitHub Desktop.
Save shierro/ba3eb5777b2b7d4a3fbe93a9565aec2b to your computer and use it in GitHub Desktop.
Example routing using expressJS router
const express = require('express');
const statusMonitor = require('express-status-monitor')({ path: '' });
const healthcheck = require('express-healthcheck');
const versionCheck = require('version-healthcheck');
const swaggerUi = require('swagger-ui-express');
const ErrorController = require('./controllers/ErrorController');
const SfdcController = require('./controllers/SalesforceController');
const swaggerDocument = require('../swagger.json');
const authService = require('./services/authService');
const logger = require('./utils/logger');
const basicAuth = authService.basic();
/* istanbul ignore next */
const registerDevRoutes = (app) => {
/* add route if not on test */
if (process.env.NODE_ENV !== 'test') {
/* Kue UI */
require('kue-ui-express')(app, '/kue/', '/kue-api/');
app.use('/kue-api/', basicAuth, require('kue').app);
}
/* Show these endpoints only on development stages */
if (['development', 'staging'].indexOf(process.env.NODE_ENV) > -1) {
/* Express server status */
app.use(statusMonitor.middleware);
app.get('/status', basicAuth, statusMonitor.pageRoute);
/* Swagger specs definition */
app.use(
'/specs', [
basicAuth,
swaggerUi.serve,
],
swaggerUi.setup(swaggerDocument, true, {
showRequestHeaders: true,
}),
);
}
};
module.exports = (app) => {
registerDevRoutes(app);
/* we register morgan here so it only logs the next routes registered */
app.use(require('morgan')('short', { stream: logger.logStream }));
const leadsRouter = express.Router();
const contactsRouter = express.Router();
/* SFDC APIs */
leadsRouter.post('/', SfdcController.createLeads);
leadsRouter.get('/', SfdcController.getLeads);
leadsRouter.delete('/', SfdcController.deleteLeads);
leadsRouter.patch('/', SfdcController.updateLeads);
contactsRouter.post('/', SfdcController.createLeads);
contactsRouter.get('/', SfdcController.getLeads);
contactsRouter.delete('/', SfdcController.deleteLeads);
contactsRouter.patch('/contacts', SfdcController.updateLeads);
/* APIs */
app.use('/api/leads', authService.bearer, leadsRouter);
app.use('/api/contacts', authService.bearer, contactsRouter);
/* Sanity & version checks */
app.use('/healthcheck', healthcheck());
app.get('/version', versionCheck);
/* Error Handling */
app.use(ErrorController.error404);
app.use(ErrorController.generalError);
};
/* in your index.js */
const app = express();
app.server = http.createServer(app);
/* register routes */
routes(app);
/* istanbul ignore next */
app.server.listen(PORT || 8080, () => {
logger.info(`ENV[${NODE_ENV}] Started on port ${app.server.address().port}`);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment