Created
March 20, 2018 08:50
-
-
Save lephyrus/a493982612cfed8a877df3171ad4bc3e to your computer and use it in GitHub Desktop.
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 { ActivatedRouteSnapshot, Route } from '@angular/router'; | |
const GET_FAIL_ROUTE = Symbol('getFailRoute'); | |
export function getRedirectOnFailTarget( | |
guardInstance: any, | |
routeSnapshot: ActivatedRouteSnapshot | |
): string[] | undefined { | |
return isGetFailRouteAvailable(routeSnapshot.data) | |
? routeSnapshot.data[GET_FAIL_ROUTE](guardInstance) | |
: undefined; | |
} | |
export function processActivateOrRedirectRoute( | |
inputRoute: ActivateOrRedirectRoute | |
): Route { | |
// separate `activateOrRedirect` property | |
const { activateOrRedirect, ...route } = inputRoute; | |
// construct canActivate array | |
const canActivate = activateOrRedirect.map( | |
({ canActivate: _canActivate }) => _canActivate | |
); | |
// prepare redirection lookup function and "hide" it in data under our symbol | |
const getFailRoute = createGetFailRouteFn(activateOrRedirect); | |
const data = { | |
...route.data, | |
[GET_FAIL_ROUTE]: getFailRoute | |
}; | |
// this ends up being a standard `Route` object | |
return { ...route, canActivate, data }; | |
} | |
function createGetFailRouteFn( | |
activateOrRedirectDefs: ActivateOrRedirectDef[] | |
): GetFailRouteFn { | |
return guardInstance => { | |
// get matching redirection targets | |
const targetRoute = activateOrRedirectDefs | |
.filter(({ canActivate }) => guardInstance instanceof canActivate) | |
.map(({ redirectTo }) => redirectTo); | |
// return first match | |
return targetRoute[0]; | |
}; | |
} | |
// note that the type used in this type guard needs Typescript >= v2.7 | |
function isGetFailRouteAvailable(data: { | |
[name: string]: any; | |
}): data is { [name: string]: any; [GET_FAIL_ROUTE]: GetFailRouteFn } { | |
return !!data[GET_FAIL_ROUTE]; | |
} | |
interface ActivateOrRedirectDef { | |
canActivate: any; // class of CanActivate guard | |
redirectTo: string[]; | |
} | |
type ActivateOrRedirectRoute = Route & { | |
activateOrRedirect: ActivateOrRedirectDef[]; | |
}; | |
type GetFailRouteFn = (guardInstance: any) => string[] | undefined; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment