-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathGuard.tsx
More file actions
196 lines (177 loc) · 6.06 KB
/
Guard.tsx
File metadata and controls
196 lines (177 loc) · 6.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
import React, { useCallback, useContext, useEffect, useMemo } from 'react';
import { __RouterContext as RouterContext } from 'react-router';
import { matchPath, Redirect, Route } from 'react-router-dom';
import {
ErrorPageContext,
FromRouteContext,
GuardContext,
LoadingPageContext,
RawErrorContext,
} from './contexts';
import { usePrevious, useStateRef, useStateWhenMounted } from './hooks';
import renderPage from './renderPage';
import {
GuardFunction,
GuardProps,
GuardType,
GuardTypes,
Next,
NextAction,
NextPropsPayload,
NextRedirectPayload,
} from './types';
type PageProps = NextPropsPayload;
type RouteError = string | Record<string, any> | null;
type RouteRedirect = NextRedirectPayload | null;
interface GuardsResolve {
props: PageProps;
redirect: RouteRedirect;
}
const Guard: React.FunctionComponent<GuardProps> = ({ children, component, meta, render }) => {
const routeProps = useContext(RouterContext);
const routePrevProps = usePrevious(routeProps);
const hasPathChanged = useMemo(
() => routeProps.location.pathname !== routePrevProps.location.pathname,
[routePrevProps, routeProps],
);
const fromRouteProps = useContext(FromRouteContext);
const guards = useContext(GuardContext);
const LoadingPage = useContext(LoadingPageContext);
const ErrorPage = useContext(ErrorPageContext);
const useRawErrors = useContext(RawErrorContext);
const hasGuards = useMemo(() => !!(guards && guards.length > 0), [guards]);
const [validationsRequested, setValidationsRequested] = useStateRef<number>(0);
const [routeValidated, setRouteValidated] = useStateRef<boolean>(!hasGuards);
const [routeError, setRouteError] = useStateWhenMounted<RouteError>(null);
const [routeRedirect, setRouteRedirect] = useStateWhenMounted<RouteRedirect>(null);
const [pageProps, setPageProps] = useStateWhenMounted<PageProps>({});
/**
* Memoized callback to get the current number of validations requested.
* This is used in order to see if new validations were requested in the
* middle of a validation execution.
*/
const getValidationsRequested = useCallback(() => validationsRequested.current, [
validationsRequested,
]);
/**
* Memoized callback to get the next callback function used in guards.
* Assigns the `props` and `redirect` functions to callback.
*/
const getNextFn = useCallback((resolve: Function): Next => {
const getResolveFn = (type: GuardType) => (payload: NextPropsPayload | NextRedirectPayload) =>
resolve({ type, payload });
const next = () => resolve({ type: GuardTypes.CONTINUE });
return Object.assign(next, {
props: getResolveFn(GuardTypes.PROPS),
redirect: getResolveFn(GuardTypes.REDIRECT),
});
}, []);
/**
* Runs through a single guard, passing it the current route's props,
* the previous route's props, and the next callback function. If an
* error occurs, it will be thrown by the Promise.
*
* @param guard the guard function
* @returns a Promise returning the guard payload
*/
const runGuard = (guard: GuardFunction): Promise<NextAction> =>
new Promise(async (resolve, reject) => {
try {
const to = {
...routeProps,
meta: meta || {},
};
await guard(to, fromRouteProps, getNextFn(resolve));
} catch (error) {
reject(error);
}
});
/**
* Loops through all guards in context. If the guard adds new props
* to the page or causes a redirect, these are tracked in the state
* constants defined above.
*/
const resolveAllGuards = async (): Promise<GuardsResolve> => {
let index = 0;
let props = {};
let redirect = null;
if (guards) {
while (!redirect && index < guards.length) {
const { type, payload } = await runGuard(guards[index]);
if (payload) {
if (type === GuardTypes.REDIRECT) {
redirect = payload;
} else if (type === GuardTypes.PROPS) {
props = Object.assign(props, payload);
}
}
index += 1;
}
}
return {
props,
redirect,
};
};
/**
* Validates the route using the guards. If an error occurs, it
* will toggle the route error state.
*/
const validateRoute = async (useRawErrors: boolean | null | undefined): Promise<void> => {
const currentRequests = validationsRequested.current;
let pageProps: PageProps = {};
let routeError: RouteError = null;
let routeRedirect: RouteRedirect = null;
try {
const { props, redirect } = await resolveAllGuards();
pageProps = props;
routeRedirect = redirect;
} catch (error) {
routeError = useRawErrors ? error : error.message || 'Not found.';
}
if (currentRequests === getValidationsRequested()) {
setPageProps(pageProps);
setRouteError(routeError);
setRouteRedirect(routeRedirect);
setRouteValidated(true);
}
};
useEffect(() => {
validateRoute(useRawErrors);
}, [useRawErrors]);
useEffect(() => {
if (hasPathChanged) {
setValidationsRequested(requests => requests + 1);
setRouteError(null);
setRouteRedirect(null);
setRouteValidated(!hasGuards);
if (hasGuards) {
validateRoute(useRawErrors);
}
}
}, [hasPathChanged, useRawErrors]);
if (hasPathChanged) {
if (hasGuards) {
return renderPage(LoadingPage, routeProps);
}
return null;
} else if (!routeValidated.current) {
return renderPage(LoadingPage, routeProps);
} else if (routeError) {
return renderPage(ErrorPage, { ...routeProps, error: routeError });
} else if (routeRedirect) {
const pathToMatch = typeof routeRedirect === 'string' ? routeRedirect : routeRedirect.pathname;
const { path, isExact: exact } = routeProps.match;
if (pathToMatch && !matchPath(pathToMatch, { path, exact })) {
return <Redirect to={routeRedirect} />;
}
}
return (
<RouterContext.Provider value={{ ...routeProps, ...pageProps }}>
<Route component={component} render={render}>
{children}
</Route>
</RouterContext.Provider>
);
};
export default Guard;