Standardize ExpressJS JSON responses
Run npm i -S express-presenter
- Import the package
const expressPresenter = require('express-presenter')
- Instantiate
express-presenter(it takes an optionalapiVersionparameter)const presenter = expressPresenter('v1')
- Use it as a middleware (see the examples below)
As any ExpressJS middleware, you can either use it globally:
// See: examples/simple-express-app.js
const express = require('express');
const bodyParser = require('body-parser');
const expressPresenter = require('express-presenter');
const app = express();
const presenter = expressPresenter();
app.use(bodyParser.json());
app.use(presenter); // This must be before declaring your routes
app.use('/ok', (req, res) => {
res.ok({
message: 'Take my mhajeb',
data: { name: 'Mhajeb', isHot: true },
});
});
app.use('/created', (req, res) => {
res.created({
message: 'A new mhajeb is created',
data: { name: 'Mhajeb', isHot: true },
});
});Or in your routes file:
// See: examples/express-routes-file.js
const express = require('express');
const expressPresenter = require('../src');
const router = express.Router();
const presenter = expressPresenter('v1'); // Here you can set your API version
router.get('/api/v1/get', presenter, (req, res) => {
res.ok({
message: 'Take my mhajeb',
data: { name: 'Mhajeb', isHot: true },
});
});
router.post('/api/v1/create', presenter, (req, res) => {
// ... Creating mhajeb
res.created({
message: 'A new mhajeb is created',
data: { name: 'Mhajeb', isHot: true },
});
});
router.get('/api/v1/start-task', presenter, (req, res) => {
res.accepted({
message: 'I will start cooking Mhajeb',
});
});
router.get('/api/v1/finished-eating', presenter, (req, res) => {
res.noContent();
});
module.exports = router;Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.
Please make sure to update tests as appropriate.
This project is licensed under the MIT License - see the LICENSE file for details