Skip to content

Instantly share code, notes, and snippets.

@hugmanrique
Last active July 1, 2018 20:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hugmanrique/cc556fcfc17014550e9d6061245ec3a1 to your computer and use it in GitHub Desktop.
Save hugmanrique/cc556fcfc17014550e9d6061245ec3a1 to your computer and use it in GitHub Desktop.
Async Express middleware (for @exception)
import http from 'http';
import express from 'express';
import testMiddleware from './middleware';
const app = express();
const server = http.createServer(app);
app.use(testMiddleware);
app.get('*', (req, res) => {
const { name } = res.locals.user;
res.json({ success: true, name });
});
server.listen(8080);
console.log('Listening on *:8080');
const asyncMiddleware = fn => (req, res, next) => Promise.resolve(fn(req, res, next)).catch(next);
const getUserFromDb = async () => ({
name: 'Test'
});
const testMiddleware = asyncMiddleware(async (req, res, next) => {
try {
const user = await getUserFromDb();
res.locals.user = user;
next();
} catch (err) {
next(err);
}
});
export default testMiddleware;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment