Client - add URL interceptors to simplify routes definition

This commit is contained in:
Sam 2020-01-31 12:46:38 +01:00
parent 34614d5a6c
commit b862a77344
3 changed files with 34 additions and 38 deletions

View File

@ -1,5 +1,5 @@
import React from 'react'
import { Redirect, Route, Switch } from 'react-router-dom'
import { Route, Switch } from 'react-router-dom'
import './App.css'
// import Admin from './Admin'
@ -14,7 +14,6 @@ import Profile from './User/Profile'
import ProfileEdit from './User/ProfileEdit'
import Statistics from './Statistics'
import UserForm from './User/UserForm'
import { isLoggedIn } from '../utils'
export default class App extends React.Component {
constructor(props) {
@ -27,50 +26,20 @@ export default class App extends React.Component {
<div className="App">
<NavBar />
<Switch>
<Route
exact
path="/"
render={() =>
isLoggedIn() ? <Dashboard /> : <Redirect to="/login" />
}
/>
<Route exact path="/" component={Dashboard} />
<Route
exact
path="/register"
render={() =>
isLoggedIn() ? (
<Redirect to="/" />
) : (
<UserForm formType={'register'} />
)
}
render={() => <UserForm formType={'register'} />}
/>
<Route
exact
path="/login"
render={() =>
isLoggedIn() ? (
<Redirect to="/" />
) : (
<UserForm formType={'login'} />
)
}
render={() => <UserForm formType={'login'} />}
/>
<Route exact path="/logout" component={Logout} />
<Route
exact
path="/profile/edit"
render={() =>
isLoggedIn() ? <ProfileEdit /> : <UserForm formType={'login'} />
}
/>
<Route
exact
path="/profile"
render={() =>
isLoggedIn() ? <Profile /> : <UserForm formType={'login'} />
}
/>
<Route exact path="/profile/edit" component={ProfileEdit} />
<Route exact path="/profile" component={Profile} />
<Route exact path="/activities/history" component={Activities} />
<Route exact path="/activities/statistics" component={Statistics} />
<Route path="/activities" component={Activity} />

View File

@ -13,8 +13,9 @@ import Root from './components/Root'
import registerServiceWorker from './registerServiceWorker'
import createRootReducer from './reducers'
import { loadProfile } from './actions/user'
import { historyEnhancer } from './utils/history'
export const history = createBrowserHistory()
export const history = historyEnhancer(createBrowserHistory())
history.listen(() => {
window.scrollTo(0, 0)

View File

@ -0,0 +1,26 @@
const pathInterceptor = toPath => {
if (
!window.localStorage.authToken &&
!['/login', '/register'].includes(toPath.pathname)
) {
toPath.pathname = '/login'
}
if (
window.localStorage.authToken &&
['/login', '/register'].includes(toPath.pathname)
) {
toPath.pathname = '/'
}
return toPath
}
export const historyEnhancer = originalHistory => {
originalHistory.location = pathInterceptor(originalHistory.location)
return {
...originalHistory,
push: (path, ...args) =>
originalHistory.push(pathInterceptor(path), ...args),
replace: (path, ...args) =>
originalHistory.replace(pathInterceptor(path), ...args),
}
}