import { RouteConfig , VueRouter , Route } from 'vue-router/types/router' ; import RouterMiddlewareConstructorOptions from '../types/RouterMiddlewareConstructorOptions' ; import defaultMiddleWares from './middle/index' ; import { Access } from '../Access' ; import uniq from 'lodash/uniq' ; import Queue from '../class/Queue' ; import QueueTask from '../class/QueueTask' ; import RouterMiddlewarePipeline from './RouterMiddlewarePipeline' ; export default class RouterMiddleware { public static middleWares : Record < string , any > = defaultMiddleWares ; /**
     * global middleWares
     */ protected static globalMiddleWares : string [ ] = [ ] ; /**
     * async router
     */ public routes : RouteConfig [ ] ; /**
     *
     */ private access : Access ; /**
     * validate queue
     */ private queue = new Queue ( ) ; param { Access } access param { RouterMiddlewareConstructorOptions } options public constructor ( access , options ? ) { if ( options && options . routes ) { this . routes = options . routes ; } else { this . routes = [ ] ; } this . access = access ; } public runMiddleware ( options , scope , to , from ? ) { let that = this ; let middleWares = this . getCurrentMiddleWares ( options . middleware ) ; this . queue . addCommand ( new ( class RouterMiddleQueueTask extends QueueTask { public handle ( next ) { new RouterMiddlewarePipeline ( RouterMiddleware . middleWares ) . through ( middleWares , options . terminal || false , [ { router : scope , to : to , from : from , access : that . access , } , ] ) . run ( function ( result ) { options . next ( result ) ; next ( ) ; } ) ; } } ) ( ) ) ; } param middleWares private getCurrentMiddleWares ( middleWares ) { let globalMiddleWares = RouterMiddleware . globalMiddleWares ; let middles = globalMiddleWares . concat ( middleWares ) ; let resultMiddleWares = [ ] ; for ( let i = 0 , current ; ( current = middles [ i ] ) ; i ++ ) { if ( current . substr ( 0 , 1 ) === '-' ) { let realMiddles = current . substr ( 1 ) ; resultMiddleWares = resultMiddleWares . filter ( item => ! ( item === realMiddles || item === realMiddles + '?' ) ) ; continue ; } resultMiddleWares . push ( current ) ; } return uniq ( resultMiddleWares ) ; } param middleWares public static setGlobalMiddleWares ( middleWares ? ) { RouterMiddleware . globalMiddleWares = middleWares || [ ] ; } }