Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
const express = require('express');
const Promise = require('bluebird');
const app = express();
const logger = console.log;
const tracking = console.log;
const exceptionCatcher = console.error;
const getDataById = () => new Promise((resolve, reject) => {
resolve({data: 'I am response'});
});
const dataFilterService = () => new Promise((resolve, reject) => {
resolve({data: 'I am filtered'});
});;
app.param('entry_id', (req, res, next, entry_id) => {
getDataById(entry_id)
.then((data) => {
req.metadata = {
info: 'data is received',
event: 'data.received'
};
req.result = data;
next();
})
.catch(next);
});
app.get('/data/:entry_id', (req, res, next) => {
next();
});
app.get('/data/:entry_id/filtered', (req, res, next) => {
dataFilterService(req.result)
.then((apiResult) => {
req.metadata = {
info: 'data is filtered',
event: 'api.result.received'
}
req.result = apiResult;
next();
})
.catch(next);
});
app.use((req, res, next) => {
if (req.metadata.event) {
tracking(req.metadata.event);
next();
}
});
app.use('/data', (req, res, next) => {
if (req.metadata.info) {
logger(req.metadata.info);
next();
}
});
app.use((req, res, next) => {
if (req.result) {
res.json(req.result);
} else {
next(new Error('Result not found'));
}
});
app.use((err, req, res, next) => {
logger('[ERROR] ', err.message);
exceptionCatcher(err);
res.status(500).json({
error: 'Something went wrong'
});
});
app.listen(3000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment