Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
How to bail on an Express route based on some criteria
// Premise:
// Your app interacts with some data resource.
// There is a route registered per resource type.
// After requesting a resource of a certain type, it's possible for the data to be of another type.
// E.g. You're requesting a category from an API but you are served a member of that category
// instead because there is only one member in the category.
// this route catches all incoming category requests
app.get(
'/category/:category_id',
function getCategory (req, res, next) {
// request the category req.params.category_id from the data source
next();
},
function checkResponse (req, res, next) {
// check if the category was served or if the category member was served
if (responseIsCategoryMember) {
// fetch the member id from the response here
// altering req.url is what allows nexting to an alternate route
req.url = '/category/x/' + fetchedMemberId;
}
next();
}
);
// this route continues a successful category request from the data source
app.get(
'/category/:category_id',
function parseCategoryData (req, res, next) {
// do something with the category data
next();
},
function respond (req, res) {
res.send(appCategoryResponse);
}
);
// this route catches the category member req.url
app.get(
'/category/:category_id/:member_id',
function parseMemberData (req, res, next) {
// do something with the category member data
next();
},
function respond (req, res) {
res.send(appCategoryMemberResponse);
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment