Cleanest way to add middlewares to a single route Js ExpressWhat is Node.js' Connect, Express and “middleware”?How to include route handlers in multiple files in Express?How to get all registered routes in Express?Proper way to return JSON using node or ExpressUnit testing promise based code in node.js express route/controllerExiting from post route if middleware condition fails and not continue to execute the functionHot reloading with express and chokidar causes a http headers sent error when using multiple routesI got an empty array in sub document array saving using mongoose ( MEAN stack)Why express.Router() while separating routesUnit test express-validator middleware
Partial sums of primes
Teaching indefinite integrals that require special-casing
In Star Trek IV, why did the Bounty go back to a time when whales were already rare?
Who must act to prevent Brexit on March 29th?
Why are all the doors on Ferenginar (the Ferengi home world) far shorter than the average Ferengi?
Simulating a probability of 1 of 2^N with less than N random bits
Would it be legal for a US State to ban exports of a natural resource?
Could solar power be utilized and substitute coal in the 19th century?
Why are on-board computers allowed to change controls without notifying the pilots?
Hostile work environment after whistle-blowing on coworker and our boss. What do I do?
How can I raise concerns with a new DM about XP splitting?
How to check participants in at events?
Identify a stage play about a VR experience in which participants are encouraged to simulate performing horrific activities
Taylor series of product of two functions
What does the "3am" section means in manpages?
Is there an wasy way to program in Tikz something like the one in the image?
Female=gender counterpart?
Giant Toughroad SLR 2 for 200 miles in two days, will it make it?
Was the picture area of a CRT a parallelogram (instead of a true rectangle)?
Meta programming: Declare a new struct on the fly
Pronouncing Homer as in modern Greek
Science Fiction story where a man invents a machine that can help him watch history unfold
Lightning Web Component - do I need to track changes for every single input field in a form
A known event to a history junkie
Cleanest way to add middlewares to a single route Js Express
What is Node.js' Connect, Express and “middleware”?How to include route handlers in multiple files in Express?How to get all registered routes in Express?Proper way to return JSON using node or ExpressUnit testing promise based code in node.js express route/controllerExiting from post route if middleware condition fails and not continue to execute the functionHot reloading with express and chokidar causes a http headers sent error when using multiple routesI got an empty array in sub document array saving using mongoose ( MEAN stack)Why express.Router() while separating routesUnit test express-validator middleware
I'm wondering if I'm doing thing the cleanest way. Here's my setup:
Files
- app.js
- routes.js
- controllers
- wallet.js
routes.js
const router = require('express').Router()
const wallet = require('./controllers/wallet')
router.post('/wallet/generate', wallet.generate)
router.get('/wallet/address', wallet.address)
router.get('/wallet/balance', wallet.balance)
router.post('/wallet/transfer', wallet.transfer)
module.exports = router
controllers/wallet.js
const generate = async (req, res) =>
// ...
const address = async (req, res) =>
// ...
const balance = async (req, res) =>
// ...
const _transfer = async (req, res) =>
// ...
const transfer = [
// I put my subroute specific middlewares here
handleInvalidAddress,
handleInvalidAmount,
handleInvalidTokenName,
_transfer
]
module.exports = transfer, generate, address, balance
Is this an acceptable way to do it? I couldn't find any good examples of open source express apps I could model. It seems to me that declaring my small middlewares only specific to one route in the routes.js
file would be wrong. All the logic is in the controllers folder and the middlewares are logic.
edit: the transfer middlewares
They are unlikely to be reused anywhere else than the wallet transfer route. In real life they are bigger and shouldn't clutter the transfer route function
const handleInvalidAddress = (req, res, next) =>
if (req.body.address)
return next()
res.status(400).send('invalid address')
const handleInvalidAmount = (req, res, next) =>
if (req.body.amount)
return next()
res.status(400).send('invalid amount')
const handleInvalidTokenName = (req, res, next) =>
if (req.body.tokenName)
return next()
res.status(400).send('invalid token name')
node.js express
add a comment |
I'm wondering if I'm doing thing the cleanest way. Here's my setup:
Files
- app.js
- routes.js
- controllers
- wallet.js
routes.js
const router = require('express').Router()
const wallet = require('./controllers/wallet')
router.post('/wallet/generate', wallet.generate)
router.get('/wallet/address', wallet.address)
router.get('/wallet/balance', wallet.balance)
router.post('/wallet/transfer', wallet.transfer)
module.exports = router
controllers/wallet.js
const generate = async (req, res) =>
// ...
const address = async (req, res) =>
// ...
const balance = async (req, res) =>
// ...
const _transfer = async (req, res) =>
// ...
const transfer = [
// I put my subroute specific middlewares here
handleInvalidAddress,
handleInvalidAmount,
handleInvalidTokenName,
_transfer
]
module.exports = transfer, generate, address, balance
Is this an acceptable way to do it? I couldn't find any good examples of open source express apps I could model. It seems to me that declaring my small middlewares only specific to one route in the routes.js
file would be wrong. All the logic is in the controllers folder and the middlewares are logic.
edit: the transfer middlewares
They are unlikely to be reused anywhere else than the wallet transfer route. In real life they are bigger and shouldn't clutter the transfer route function
const handleInvalidAddress = (req, res, next) =>
if (req.body.address)
return next()
res.status(400).send('invalid address')
const handleInvalidAmount = (req, res, next) =>
if (req.body.amount)
return next()
res.status(400).send('invalid amount')
const handleInvalidTokenName = (req, res, next) =>
if (req.body.tokenName)
return next()
res.status(400).send('invalid token name')
node.js express
Are these 'controllers' reusable? Should they really be declared in separate module?
– estus
Mar 7 at 10:41
@estus I wouldn't say they're reusable. They're made specifically for that one route.
– Dave
Mar 7 at 10:51
add a comment |
I'm wondering if I'm doing thing the cleanest way. Here's my setup:
Files
- app.js
- routes.js
- controllers
- wallet.js
routes.js
const router = require('express').Router()
const wallet = require('./controllers/wallet')
router.post('/wallet/generate', wallet.generate)
router.get('/wallet/address', wallet.address)
router.get('/wallet/balance', wallet.balance)
router.post('/wallet/transfer', wallet.transfer)
module.exports = router
controllers/wallet.js
const generate = async (req, res) =>
// ...
const address = async (req, res) =>
// ...
const balance = async (req, res) =>
// ...
const _transfer = async (req, res) =>
// ...
const transfer = [
// I put my subroute specific middlewares here
handleInvalidAddress,
handleInvalidAmount,
handleInvalidTokenName,
_transfer
]
module.exports = transfer, generate, address, balance
Is this an acceptable way to do it? I couldn't find any good examples of open source express apps I could model. It seems to me that declaring my small middlewares only specific to one route in the routes.js
file would be wrong. All the logic is in the controllers folder and the middlewares are logic.
edit: the transfer middlewares
They are unlikely to be reused anywhere else than the wallet transfer route. In real life they are bigger and shouldn't clutter the transfer route function
const handleInvalidAddress = (req, res, next) =>
if (req.body.address)
return next()
res.status(400).send('invalid address')
const handleInvalidAmount = (req, res, next) =>
if (req.body.amount)
return next()
res.status(400).send('invalid amount')
const handleInvalidTokenName = (req, res, next) =>
if (req.body.tokenName)
return next()
res.status(400).send('invalid token name')
node.js express
I'm wondering if I'm doing thing the cleanest way. Here's my setup:
Files
- app.js
- routes.js
- controllers
- wallet.js
routes.js
const router = require('express').Router()
const wallet = require('./controllers/wallet')
router.post('/wallet/generate', wallet.generate)
router.get('/wallet/address', wallet.address)
router.get('/wallet/balance', wallet.balance)
router.post('/wallet/transfer', wallet.transfer)
module.exports = router
controllers/wallet.js
const generate = async (req, res) =>
// ...
const address = async (req, res) =>
// ...
const balance = async (req, res) =>
// ...
const _transfer = async (req, res) =>
// ...
const transfer = [
// I put my subroute specific middlewares here
handleInvalidAddress,
handleInvalidAmount,
handleInvalidTokenName,
_transfer
]
module.exports = transfer, generate, address, balance
Is this an acceptable way to do it? I couldn't find any good examples of open source express apps I could model. It seems to me that declaring my small middlewares only specific to one route in the routes.js
file would be wrong. All the logic is in the controllers folder and the middlewares are logic.
edit: the transfer middlewares
They are unlikely to be reused anywhere else than the wallet transfer route. In real life they are bigger and shouldn't clutter the transfer route function
const handleInvalidAddress = (req, res, next) =>
if (req.body.address)
return next()
res.status(400).send('invalid address')
const handleInvalidAmount = (req, res, next) =>
if (req.body.amount)
return next()
res.status(400).send('invalid amount')
const handleInvalidTokenName = (req, res, next) =>
if (req.body.tokenName)
return next()
res.status(400).send('invalid token name')
node.js express
node.js express
edited Mar 7 at 11:26
Dave
asked Mar 7 at 10:28
DaveDave
123
123
Are these 'controllers' reusable? Should they really be declared in separate module?
– estus
Mar 7 at 10:41
@estus I wouldn't say they're reusable. They're made specifically for that one route.
– Dave
Mar 7 at 10:51
add a comment |
Are these 'controllers' reusable? Should they really be declared in separate module?
– estus
Mar 7 at 10:41
@estus I wouldn't say they're reusable. They're made specifically for that one route.
– Dave
Mar 7 at 10:51
Are these 'controllers' reusable? Should they really be declared in separate module?
– estus
Mar 7 at 10:41
Are these 'controllers' reusable? Should they really be declared in separate module?
– estus
Mar 7 at 10:41
@estus I wouldn't say they're reusable. They're made specifically for that one route.
– Dave
Mar 7 at 10:51
@estus I wouldn't say they're reusable. They're made specifically for that one route.
– Dave
Mar 7 at 10:51
add a comment |
1 Answer
1
active
oldest
votes
It's a good recipe to define new router like shown above. In case middleware and route handler functions aren't reused, they can be used in-place. It doesn't need to be aware of wallet
part because it's common to all routes:
const router = require('express').Router()
router.post('/generate', async (req, res) => ...)
router.get('/address', async (req, res) => ...)
router.get('/balance', async (req, res) => ...)
router.use('/transfer', function handleInvalidAddress(req, res, next) ...)
router.post('/transfer', async (req, res) => ...)
module.exports = router;
And mount it like:
const walletRouter = require('./routes/wallet')
appRouter.use('/wallet', walletRouter);
In case wallet
routes need to be distributed between several modules for some reason (e.g. plugin system), it may be beneficial to use dependency injection:
module.exports = router =>
router.post('/generate', async (req, res) => ...)
router.get('/address', async (req, res) => ...)
router.get('/balance', async (req, res) => ...)
router.use('/transfer', function handleInvalidAddress(req, res, next) ...)
router.post('/transfer', async (req, res) => ...)
;
And mount it like:
const walletRouter = Router();
require('./routes/wallet')(walletRouter);
appRouter.use('/wallet', walletRouter);
so how would you add the handleInvalidAddress middleware to the wallet transfer route using this method?
– Dave
Mar 7 at 11:12
This depends on what handleInvalidAddress is and how it's supposed to work. Is it a middleware or route handler? In case it's route handler, what route should it be available at? Please update the question with stackoverflow.com/help/mcve to be more specific.
– estus
Mar 7 at 11:15
ok I added them
– Dave
Mar 7 at 11:27
I updated the post. Since they aren't reused and they clearly belong to single /transfer route (that they use req.body suggests that they would be useless for other /transfer routes like GET, even if they existed), it may be unreasonable to keep them as separate middlewares, they could be merged into route handler.
– estus
Mar 7 at 11:40
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55041528%2fcleanest-way-to-add-middlewares-to-a-single-route-js-express%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
It's a good recipe to define new router like shown above. In case middleware and route handler functions aren't reused, they can be used in-place. It doesn't need to be aware of wallet
part because it's common to all routes:
const router = require('express').Router()
router.post('/generate', async (req, res) => ...)
router.get('/address', async (req, res) => ...)
router.get('/balance', async (req, res) => ...)
router.use('/transfer', function handleInvalidAddress(req, res, next) ...)
router.post('/transfer', async (req, res) => ...)
module.exports = router;
And mount it like:
const walletRouter = require('./routes/wallet')
appRouter.use('/wallet', walletRouter);
In case wallet
routes need to be distributed between several modules for some reason (e.g. plugin system), it may be beneficial to use dependency injection:
module.exports = router =>
router.post('/generate', async (req, res) => ...)
router.get('/address', async (req, res) => ...)
router.get('/balance', async (req, res) => ...)
router.use('/transfer', function handleInvalidAddress(req, res, next) ...)
router.post('/transfer', async (req, res) => ...)
;
And mount it like:
const walletRouter = Router();
require('./routes/wallet')(walletRouter);
appRouter.use('/wallet', walletRouter);
so how would you add the handleInvalidAddress middleware to the wallet transfer route using this method?
– Dave
Mar 7 at 11:12
This depends on what handleInvalidAddress is and how it's supposed to work. Is it a middleware or route handler? In case it's route handler, what route should it be available at? Please update the question with stackoverflow.com/help/mcve to be more specific.
– estus
Mar 7 at 11:15
ok I added them
– Dave
Mar 7 at 11:27
I updated the post. Since they aren't reused and they clearly belong to single /transfer route (that they use req.body suggests that they would be useless for other /transfer routes like GET, even if they existed), it may be unreasonable to keep them as separate middlewares, they could be merged into route handler.
– estus
Mar 7 at 11:40
add a comment |
It's a good recipe to define new router like shown above. In case middleware and route handler functions aren't reused, they can be used in-place. It doesn't need to be aware of wallet
part because it's common to all routes:
const router = require('express').Router()
router.post('/generate', async (req, res) => ...)
router.get('/address', async (req, res) => ...)
router.get('/balance', async (req, res) => ...)
router.use('/transfer', function handleInvalidAddress(req, res, next) ...)
router.post('/transfer', async (req, res) => ...)
module.exports = router;
And mount it like:
const walletRouter = require('./routes/wallet')
appRouter.use('/wallet', walletRouter);
In case wallet
routes need to be distributed between several modules for some reason (e.g. plugin system), it may be beneficial to use dependency injection:
module.exports = router =>
router.post('/generate', async (req, res) => ...)
router.get('/address', async (req, res) => ...)
router.get('/balance', async (req, res) => ...)
router.use('/transfer', function handleInvalidAddress(req, res, next) ...)
router.post('/transfer', async (req, res) => ...)
;
And mount it like:
const walletRouter = Router();
require('./routes/wallet')(walletRouter);
appRouter.use('/wallet', walletRouter);
so how would you add the handleInvalidAddress middleware to the wallet transfer route using this method?
– Dave
Mar 7 at 11:12
This depends on what handleInvalidAddress is and how it's supposed to work. Is it a middleware or route handler? In case it's route handler, what route should it be available at? Please update the question with stackoverflow.com/help/mcve to be more specific.
– estus
Mar 7 at 11:15
ok I added them
– Dave
Mar 7 at 11:27
I updated the post. Since they aren't reused and they clearly belong to single /transfer route (that they use req.body suggests that they would be useless for other /transfer routes like GET, even if they existed), it may be unreasonable to keep them as separate middlewares, they could be merged into route handler.
– estus
Mar 7 at 11:40
add a comment |
It's a good recipe to define new router like shown above. In case middleware and route handler functions aren't reused, they can be used in-place. It doesn't need to be aware of wallet
part because it's common to all routes:
const router = require('express').Router()
router.post('/generate', async (req, res) => ...)
router.get('/address', async (req, res) => ...)
router.get('/balance', async (req, res) => ...)
router.use('/transfer', function handleInvalidAddress(req, res, next) ...)
router.post('/transfer', async (req, res) => ...)
module.exports = router;
And mount it like:
const walletRouter = require('./routes/wallet')
appRouter.use('/wallet', walletRouter);
In case wallet
routes need to be distributed between several modules for some reason (e.g. plugin system), it may be beneficial to use dependency injection:
module.exports = router =>
router.post('/generate', async (req, res) => ...)
router.get('/address', async (req, res) => ...)
router.get('/balance', async (req, res) => ...)
router.use('/transfer', function handleInvalidAddress(req, res, next) ...)
router.post('/transfer', async (req, res) => ...)
;
And mount it like:
const walletRouter = Router();
require('./routes/wallet')(walletRouter);
appRouter.use('/wallet', walletRouter);
It's a good recipe to define new router like shown above. In case middleware and route handler functions aren't reused, they can be used in-place. It doesn't need to be aware of wallet
part because it's common to all routes:
const router = require('express').Router()
router.post('/generate', async (req, res) => ...)
router.get('/address', async (req, res) => ...)
router.get('/balance', async (req, res) => ...)
router.use('/transfer', function handleInvalidAddress(req, res, next) ...)
router.post('/transfer', async (req, res) => ...)
module.exports = router;
And mount it like:
const walletRouter = require('./routes/wallet')
appRouter.use('/wallet', walletRouter);
In case wallet
routes need to be distributed between several modules for some reason (e.g. plugin system), it may be beneficial to use dependency injection:
module.exports = router =>
router.post('/generate', async (req, res) => ...)
router.get('/address', async (req, res) => ...)
router.get('/balance', async (req, res) => ...)
router.use('/transfer', function handleInvalidAddress(req, res, next) ...)
router.post('/transfer', async (req, res) => ...)
;
And mount it like:
const walletRouter = Router();
require('./routes/wallet')(walletRouter);
appRouter.use('/wallet', walletRouter);
edited Mar 7 at 11:37
answered Mar 7 at 11:01
estusestus
77.2k23114234
77.2k23114234
so how would you add the handleInvalidAddress middleware to the wallet transfer route using this method?
– Dave
Mar 7 at 11:12
This depends on what handleInvalidAddress is and how it's supposed to work. Is it a middleware or route handler? In case it's route handler, what route should it be available at? Please update the question with stackoverflow.com/help/mcve to be more specific.
– estus
Mar 7 at 11:15
ok I added them
– Dave
Mar 7 at 11:27
I updated the post. Since they aren't reused and they clearly belong to single /transfer route (that they use req.body suggests that they would be useless for other /transfer routes like GET, even if they existed), it may be unreasonable to keep them as separate middlewares, they could be merged into route handler.
– estus
Mar 7 at 11:40
add a comment |
so how would you add the handleInvalidAddress middleware to the wallet transfer route using this method?
– Dave
Mar 7 at 11:12
This depends on what handleInvalidAddress is and how it's supposed to work. Is it a middleware or route handler? In case it's route handler, what route should it be available at? Please update the question with stackoverflow.com/help/mcve to be more specific.
– estus
Mar 7 at 11:15
ok I added them
– Dave
Mar 7 at 11:27
I updated the post. Since they aren't reused and they clearly belong to single /transfer route (that they use req.body suggests that they would be useless for other /transfer routes like GET, even if they existed), it may be unreasonable to keep them as separate middlewares, they could be merged into route handler.
– estus
Mar 7 at 11:40
so how would you add the handleInvalidAddress middleware to the wallet transfer route using this method?
– Dave
Mar 7 at 11:12
so how would you add the handleInvalidAddress middleware to the wallet transfer route using this method?
– Dave
Mar 7 at 11:12
This depends on what handleInvalidAddress is and how it's supposed to work. Is it a middleware or route handler? In case it's route handler, what route should it be available at? Please update the question with stackoverflow.com/help/mcve to be more specific.
– estus
Mar 7 at 11:15
This depends on what handleInvalidAddress is and how it's supposed to work. Is it a middleware or route handler? In case it's route handler, what route should it be available at? Please update the question with stackoverflow.com/help/mcve to be more specific.
– estus
Mar 7 at 11:15
ok I added them
– Dave
Mar 7 at 11:27
ok I added them
– Dave
Mar 7 at 11:27
I updated the post. Since they aren't reused and they clearly belong to single /transfer route (that they use req.body suggests that they would be useless for other /transfer routes like GET, even if they existed), it may be unreasonable to keep them as separate middlewares, they could be merged into route handler.
– estus
Mar 7 at 11:40
I updated the post. Since they aren't reused and they clearly belong to single /transfer route (that they use req.body suggests that they would be useless for other /transfer routes like GET, even if they existed), it may be unreasonable to keep them as separate middlewares, they could be merged into route handler.
– estus
Mar 7 at 11:40
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55041528%2fcleanest-way-to-add-middlewares-to-a-single-route-js-express%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Are these 'controllers' reusable? Should they really be declared in separate module?
– estus
Mar 7 at 10:41
@estus I wouldn't say they're reusable. They're made specifically for that one route.
– Dave
Mar 7 at 10:51