A simple framework for MVC web applications and RESTful APIs.
A simple framework for MVC web applications and RESTful APIs.
mkdir test-app
cd test-app
npm init
npm install mvc-webapp --save
mkdir -p application/models
mkdir -p application/controllers
mkdir -p application/views
mkdir -p application/public
At some point this will be automated by a script, for now, it will involve some keystrokes.
#!/usr/bin/env node
'use strict'
const webapp = require('mvc-webapp')
webapp.run({
applicationRoot: process.env.PWD,
listenPort: process.env.PORT || '3000',
sessionRedisUrl: process.env.REDISCLOUD_URL || undefined,
sessionSecret: process.env.SESSION_SECRET || 'NOT_SO_SECRET',
redirectSecure: true,
errorMiddleware: (err, req, res, _) => {
res.json({
status: err.status,
message: err.message,
stack: req.app.get('env') === 'development' ? err.stack : ''
})
}
})
The error handling can be customized to return plain JSON, HTTP codes or an EJS rendered page, your choice.
'use strict'
const express = require('express')
const router = new express.Router()
router.get('/', (req, res, _) => {
res.json({
status: 'OK',
data: null
})
})
module.exports = router
This should be familiar to any Express user. A special exception is made for the index.js controller file, this is mapped to the root / folder. Additionally, any routes inside that controller, get appended as a method.
In order to render the EJS view, invoke the view (file)name in the res.render call:
res.render('index', {
title: 'Homepage',
user: 'octopie'
})
Add the following file to the root folder and docker build:
FROM node:latest
WORKDIR /app
ADD . /app
RUN npm install
CMD ["npm","start"]