Created
March 25, 2022 18:48
-
-
Save 0ex-d/171e9ad0a7103b65bb8c4261e9175a04 to your computer and use it in GitHub Desktop.
Quick verbose middleware in Node.js frameworks (Koa & Express)
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
app.get("/check", middleWare, (_, res) => { | |
res.send("Hello boi"); | |
}); |
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
// usage | |
router.get("/health", middleWare, (ctx) => { | |
ctx.body = { msg: "All systems is are a go!" }; | |
}); |
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
// you may use dependencies as you deem fit | |
const middleWare = async (req, _, next) => { | |
const { body, url, headers, params, method, statusCode } = req; | |
console.log( | |
`${chalk.white.bgRed.bold(method)} - ${chalk.blue.underline(url)}` | |
); | |
console.log({ ...headers }); // this logs header to console | |
try { | |
const token = headers?.authorization?.slice(7); | |
if (token) { | |
console.log(token); | |
// do something with Auth header | |
} | |
return await next(); | |
} catch (error) { | |
console.error(error?.message); | |
return res.status(500).json({ status: 500, message: msg }); | |
} | |
}; |
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
// you may use dependencies as you deem fit | |
const middleWare = async (ctx, next) => { | |
const { request, response, params } = ctx; | |
const { method, url, header } = request; | |
log(`${chalk.white.bgRed.bold(method)} - ${chalk.blue.underline(url)}`); | |
log({ ...header }); // this logs header to console | |
log(params); | |
try { | |
const token = header?.authorization?.slice(7); | |
if (token) { | |
console.log(token); | |
// do something with Auth header | |
} | |
return await next(); | |
} catch (error) { | |
console.error(error?.message); | |
return res.status(500).json({ status: 500, message: msg }); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment