Last active
July 25, 2018 13:56
-
-
Save kouks/1b4c082d38c7ee35d118a97b170bf969 to your computer and use it in GitHub Desktop.
Controller & middleware plugin for VueRouter
This file contains hidden or 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
import router from './router' | |
/** | |
* Intercept each route with a controller call if there is an existing one. | |
*/ | |
router.beforeEach((to, from, next) => { | |
const controller = to.meta.controller | |
const middleware = to.meta.middleware || [] | |
const request = { to, from } | |
// Reduce all the middleware assigned to the route. If a middleware wants to | |
// change the destination, it rejects its own promise. This promise then | |
// bubbles all the way down to the last 'next' call. | |
middleware.reduce((carry, mw) => { | |
return carry.then(mw).then(() => request) | |
}, Promise.resolve(request)) | |
// If there is a controller, call it and resolve the route with the | |
// controller response. | |
.then(request => controller ? Promise.resolve(request) : Promise.reject()) | |
.then(request => new controller[0]()[controller[1]](request)) | |
.then(next, next) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment