A lot of "express routers" in a single Bookshelf transaction - node.js

Bookshelf transaction is working only in callback function. How i can do it?
var express = require('express');
var router = express.Router();
router.post('/', (req, res, next) => {
Bookshelf.transaction((trx) => {
req.trx = trx;
next();
});
});
router.post('/', (req, res, next) => {
// use req.trx
});
router.post('/', (req, res, next) => {
// use req.trx
});
router.post('/', (req, res, next) => {
req.trx.commit();
});

Related

How to ignore the prefix api route in express for any action?

index.js
app.use('', routes);
routes.js
app.get('/comments', (req, res) => {
});
app.get('/posts/:id/comments', (req, res) => {
});
app.post('/comments', (req, res) => {
});
app.delete('/comments/:id', (req, res) => {
});
app.put('/comments/:id', (req, res) => {
});
I want to prefix all routes with '/comments/' except the one with the following full path: '/posts/:id/comments'. Is this possible to do without creating a new set of routes? I don't want to make another file with the name "routes2.js". I would like to use app.use('/comments/', routes); without having to create another set of routes so I can avoid repeating myself.
you can try this in your
index.js
routes=require('path/to/routes.js')
//move this route out of routes.js
app.get('/posts/:id/comments', (req, res) => {
});
app.use('/comments', routes);
and in your
routes.js
router=require('express').Router
router.get('/', (req, res) => {
});
router.post('/', (req, res) => {
});
router.delete('/', (req, res) => {
});
router.put('/', (req, res) => {
});
exports.module=router

Express router bypasses middleware

I am trying to create middleware to handle the response that are next()ed from the routes, but it bypasses route.use and throws 404
const router = require('express').Router();
const { errorResponse, successResponse, redirectResponse } = require('./test');
const errorResponse = (err, req, res, next) => {
next(Boom.notFound());
};
const successResponse = (err, req, res, next) => {
res.locals.res = {
data: {
hello: 'world'
}
};
next();
};
const redirectResponse = (err, req, res, next) => {
res.locals.res = {
meta: {
redirect: true
}
};
next();
};
module.exports = (app) => {
/**
* Test Routes
*/
router.get('/successTest', successResponse);
router.get('/errorTest', errorResponse);
router.get('/redirectTest', redirectResponse);
router
.use((err, req, res, next) => {
console.log('successHandler');
next();
})
.use((err, req, res, next) => {
console.log('redirectHandler');
next();
})
.use((err, req, res, next) => {
console.log('errorHandler');
res.status(200).json({});
});
// does not go to any of the middlewares and gives out 404
// from digging in i found that err param is not err but is req
app.use('/v1', router);
};
Thanks for helping
Take a look at Express.js Error-handling middleware documentation.
Basically it says that middleware with 4 arguments like
app.use(function (err, req, res, next) {
console.error(err.stack)
res.status(500).send('Something broke!')
})
interpreted as middleware to handle errors.
It means that it won't act like regular middleware.
For example:
app.get('/1',
(err, req, res, next) => {
// will not be outputted in console
console.log('got here');
next();
},
(req, res) => {
res.send('Hello World!');
});
app.get('/2',
(req, res, next) => {
console.log('got here');
next();
},
(req, res) => {
res.send('Hello World!');
});

Switch between routers Express

I want to display a website completely different in function of an arbitrary value.
Let's say I have two routers
const express = require('express');
const app = express();
const router1 = express.Router();
router1.get('/', (req, res, next) => res.json({message: 'I am the router1'}))
const router2 = express.Router();
router2.get('/', (req, res, next) => res.json({message: 'I am the router2'}))
app.use((req, res, next) => {
if(Math.random() > 0.5) {
// Use router1
} else {
// Use router2
}
})
I have no idea how I can do that. I will have a lots of routes (router.get, router.post) I don't want to check that on each route
Thanks
Just return a call to the router:
app.use((req, res, next) => {
if(Math.random() > 0.5) {
return router1(req, res, next)
} else {
return router2(req, res, next)
}
})
This can also be done by usage of .next('router') method.
Here is an example:
const router1 = express.Router();
router1.use((req, res, next) => {
console.log("This gets called everytime!");
if(Math.random() > 0.5)
next('router');//skip to next router object
else
next();//continue with current router
});
router1.get('/',(req, res, next) => {
console.log("Continuing with current router");
res.send("Continuing with current router");
});
const router2 = express.Router();
router2.get('/', (req, res, next) => {
console.log("Skipped Router 1, continuing with router 2");
res.send("Skipped Router 1, continuing with router 2");
});
//binding both routers here
app.use("*", router1, router2);
.next('router') basically skips to next router object, which has been mentioned in the app.use line, if only next() is used then it continues with current router methods.
Why not just?
if(Math.random() > 0.5) {
app.use(router1);
} else {
app.use(router2);
}

Module route separation

When I use http://tes.com/routes, it will route to the api=>get('/'), instead of web=>get('/'). Why?
app.js:
var api = require('./app/routes/routes').api;
var transaction_web = require('./app/routes/routes').web;
app.use('/api/routes', transaction_api);
app.use('/routes', transaction_web);
routes.js:
var api = (function () {
router.get('/', function (req, res, next) {
...
});
return router;
})();
var web = (function () {
router.get('/', function (req, res, next) {
...
});
return router;
})();
module.exports = {
api: api,
web: web
};
The reason is because that's the order in which you're adding the routes.
This:
var api = (function () {
router.get('/', function (req, res, next) {
...
});
return router;
})();
is the same as:
router.get('/', function (req, res, next) {
...
});
var api = router;
The same thing happens with the other block where you assign web, so you end up with:
router.get('/', function (req, res, next) {
// api route
});
var api = router;
router.get('/', function (req, res, next) {
// web route
});
var web = router;
The solution would be to create separate Router instances. For example:
var api = new express.Router();
api.get('/', function (req, res, next) {
// web route
});
var web = new express.Router();
web.get('/', function (req, res, next) {
// web route
});

node express.Router().route() vs express.route()

What should I use:
express.Router().route()
or
express.route()
?
Is it true express.Router().route() is someway deprecated?
For the current version of Express, you should use express.Router().route(). See the express documentation for confirmation. express.Router().route() is not depreciated.
For example:
var router = express.Router();
router.param('user_id', function(req, res, next, id) {
// sample user, would actually fetch from DB, etc...
req.user = {
id: id,
name: 'TJ'
};
next();
});
router.route('/users/:user_id')
.all(function(req, res, next) {
// runs for all HTTP verbs first
// think of it as route specific middleware!
next();
})
.get(function(req, res, next) {
res.json(req.user);
})
.put(function(req, res, next) {
// just an example of maybe updating the user
req.user.name = req.params.name;
// save user ... etc
res.json(req.user);
})
.post(function(req, res, next) {
next(new Error('not implemented'));
})
.delete(function(req, res, next) {
next(new Error('not implemented'));
})
Router.route() can use for chainable routes.
Meaning: You have one API for all the METHODS, you can write that in .route().
var app = express.Router();
app.route('/test')
.get(function (req, res) {
//code
})
.post(function (req, res) {
//code
})
.put(function (req, res) {
//code
})

Resources