Last active
July 1, 2018 20:18
-
-
Save hugmanrique/cc556fcfc17014550e9d6061245ec3a1 to your computer and use it in GitHub Desktop.
Async Express middleware (for @exception)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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'); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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