Skip to content

Instantly share code, notes, and snippets.

@jasonmit
Last active April 10, 2019 03:22
Show Gist options
  • Save jasonmit/9c5c1891cc7f808644fd067d24f1993d to your computer and use it in GitHub Desktop.
Save jasonmit/9c5c1891cc7f808644fd067d24f1993d to your computer and use it in GitHub Desktop.
intecept prevent propagation + once() allows for tighter control over ordering request handlers
// Currently there is a gap in the API for supporting
// intecepting requests by specific order. An intercept()
// will call all intercept handlers registered against a route, in order.
// In some cases, you may want them to be order-specific. i.e.,
// fire an intercept, when the next time the route is hit fire another.
// It can be achieved today with the current API, but it requires
// a bit of boilerplate and isn't trivial for those who don't understand
// the inner-workings of the API (it trolled Alex, and I didn't know immediately what
// the stacking behavior would be without looking through the docs/implementation).
//
// Here is one proposal for an API that tries to solve this:
//
server.get('/person/1')
.intercept((req, res, e) => {
// will prevent the next interceptor for get('/person/1')
// from being called (line 20). And since we used `once`, the
// next handler called the next time `/person/1` is hit is the interceptor on line 20.
e.stopPropagation();
res.status(200).json({
id: 1,
name: 'Tom'
});
})
.times(1);
server.delete('/person/1')
.intercept((req, res) => res.status(200));
server.get('/person/1')
.intercept((req, res) => res.status(404))
.times(1);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment