Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bootzooka frontend - the more functional way #540

Open
wants to merge 8 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion backend-start.sh
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
#!/bin/bash

sbt "~backend/reStart"
sbt "~backend/reStart" -mem 3000
3 changes: 3 additions & 0 deletions ui/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,10 @@
"axios": "^0.20.0",
"bootstrap": "^4.5.2",
"formik": "^2.2.0",
"fp-ts": "^2.9.5",
"immer": "^7.0.9",
"io-ts": "^2.2.14",
"io-ts-reporters": "^1.2.2",
"jest-environment-jsdom-sixteen": "^1.0.3",
"noop-ts": "^1.0.3",
"react": "^16.13.1",
Expand Down
26 changes: 18 additions & 8 deletions ui/src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,24 @@
import React from "react";
import { BrowserRouter } from "react-router-dom";
import Main from "./main/Main/Main";
import { UserContextProvider } from "./contexts/UserContext/UserContext";
import {initialUserState, UserReducer, UserContext, matchUserState} from "./contexts/UserContext/UserContext";
import {some} from "fp-ts/Option";

const App: React.FC = () => (
<BrowserRouter>
<UserContextProvider>
<Main />
</UserContextProvider>
</BrowserRouter>
);
const App: React.FC = () => {
const [state, dispatch] = React.useReducer(UserReducer, initialUserState);

return (
<BrowserRouter>
{matchUserState({
LoggedIn: userLoggedIn => (<UserContext.Provider value={ {user: some(userLoggedIn), dispatch }}>
<Main />
</UserContext.Provider>),
LoggedOut: () => <h1>logged out</h1>,
Unknown: () => <h1>unknown</h1>,
Initial: () => <h1>initial</h1>
})}
</BrowserRouter>
);
}

export default App;
101 changes: 67 additions & 34 deletions ui/src/contexts/UserContext/UserContext.tsx
Original file line number Diff line number Diff line change
@@ -1,66 +1,99 @@
import React from "react";
import immer from "immer";
import noop from "noop-ts";
import { ApiKey, UserDetails } from "../../services/UserService/UserServiceFP";
import { none, Option } from "fp-ts/es6/Option";
import {some} from "fp-ts/Option";

export interface UserDetails {
createdOn: string;
email: string;
login: string;
type LoginState = "logged_in" | "logged_out" | "unknown" | "initial";

interface UserLoginState<T extends LoginState> {
tag: T;
}

interface UserLoggedIn extends UserLoginState<"logged_in"> {
apiKey: ApiKey;
user: UserDetails;
}

interface UserLoginStateUnknown extends UserLoginState<"unknown">{
apiKey: ApiKey;
}

export interface UserState {
apiKey: string | null;
user: UserDetails | null;
loggedIn: boolean | null;
type UserLoggedOut = UserLoginState<"logged_out">;

type InitialLoginState = UserLoginState<"initial">;

export type UserState = UserLoggedIn | UserLoggedOut | UserLoginStateUnknown | InitialLoginState;

const isUserLoggedIn = (state: UserState): state is UserLoggedIn => "apiKey" in state && "user" in state;
const isUserLoginStateUnknown = (state: UserState): state is UserLoginStateUnknown => "apiKey" in state && state.tag === "unknown";
const isUserLoggedOut = (state: UserState): state is UserLoggedOut => "tag" in state && state.tag === "logged_out";
const isUserLoginStateInitial = (state: UserState): state is InitialLoginState => "tag" in state && state.tag === "initial";

interface UserStateMatcher<T> {
LoggedIn: (state: UserLoggedIn) => T;
LoggedOut: (state: UserLoggedOut) => T;
Unknown: (state: UserLoginStateUnknown) => T;
Initial: (state: InitialLoginState) => T;
}

export const initialUserState: UserState = {
apiKey: null,
user: null,
loggedIn: null,
export const matchUserState = <T extends any>(matcher: UserStateMatcher<T>) => (state: UserState): T => {
if(isUserLoggedIn(state)) {
return matcher.LoggedIn(state);
}
if(isUserLoginStateUnknown(state)) {
return matcher.Unknown(state);
}
if(isUserLoginStateInitial(state)) {
return matcher.Initial(state);
}
return matcher.LoggedOut(state);
};


export const initialUserState: UserState = { tag: "initial" };

export type UserAction =
| { type: "SET_API_KEY"; apiKey: string | null }
| { type: "SET_LOGIN_STATUS_UNKNOWN"; apiKey: ApiKey }
| { type: "UPDATE_USER_DATA"; user: Partial<UserDetails> }
| { type: "LOG_IN"; user: UserDetails }
| { type: "LOG_IN"; payload: UserLoggedIn }
| { type: "LOG_OUT" };

const UserReducer = (state: UserState, action: UserAction): UserState => {
export const UserReducer = (state: UserState, action: UserAction): UserState => {
switch (action.type) {
case "SET_API_KEY":
return immer(state, (draftState) => {
draftState.apiKey = action.apiKey;
case "SET_LOGIN_STATUS_UNKNOWN":
return immer(state, () => {
const userState: UserState = { tag: "unknown", apiKey: action.apiKey };
return userState;
});
case "UPDATE_USER_DATA":
return immer(state, (draftState) => {
if (!draftState.user) return;
draftState.user = { ...draftState.user, ...action.user };
if (isUserLoggedIn(draftState)) {
return ({ ...draftState, user: {
...draftState.user,
...action.user
}})
} else {
return state;
}
});
case "LOG_IN":
return immer(state, (draftState) => {
draftState.user = action.user;
draftState.loggedIn = true;
return { user: action.payload.user, apiKey: action.payload.apiKey, tag: "logged_in" };
});
case "LOG_OUT":
return immer(state, (draftState) => {
draftState.apiKey = null;
draftState.user = null;
draftState.loggedIn = false;
return { tag: "logged_out"};
});
}
};

type UserContextData = Omit<UserLoggedIn, "tag">;
export const UserContext = React.createContext<{
state: UserState;
dispatch: React.Dispatch<UserAction>;
user: Option<UserContextData>;
dispatch: React.Dispatch<UserAction>,
}>({
state: initialUserState,
user: none,
dispatch: noop,
});

export const UserContextProvider: React.FC = ({ children }) => {
const [state, dispatch] = React.useReducer(UserReducer, initialUserState);

return <UserContext.Provider value={{ state, dispatch }}>{children}</UserContext.Provider>;
};
23 changes: 8 additions & 15 deletions ui/src/main/Main/Main.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,32 +3,25 @@ import Footer from "../Footer/Footer";
import Top from "../Top/Top";
import ForkMe from "../ForkMe/ForkMe";
import { UserContext } from "../../contexts/UserContext/UserContext";
import Loader from "../Loader/Loader";
import Routes from "../Routes/Routes";
import useLoginOnApiKey from "./useLoginOnApiKey";
import useLocalStoragedApiKey from "./useLocalStoragedApiKey";

const Main: React.FC = () => {
const {
state: { loggedIn },
user,
} = React.useContext(UserContext);

useLocalStoragedApiKey();
useLoginOnApiKey();

if (loggedIn === null) {
return <Loader />;
}

return (
<>
<Top />
<ForkMe>
<Routes />
</ForkMe>
<Footer />
</>
);
return <>
<Top />
<ForkMe>
<Routes />
</ForkMe>
<Footer />
</>
};

export default Main;
42 changes: 20 additions & 22 deletions ui/src/main/Main/useLocalStoragedApiKey.tsx
Original file line number Diff line number Diff line change
@@ -1,37 +1,35 @@
import React from "react";
import { UserContext } from "../../contexts/UserContext/UserContext";
import {fold, fromNullable, map, some} from "fp-ts/Option";
import { pipe } from "fp-ts/pipeable";

const useLocalStoragedApiKey = () => {
const useLocalStorageApiKey = () => {
const {
dispatch,
state: { apiKey, loggedIn },
user,
} = React.useContext(UserContext);

const apiKeyRef = React.useRef(apiKey);

React.useEffect(() => {
apiKeyRef.current = apiKey;
}, [apiKey, dispatch]);
pipe(
user,
map(({ apiKey }) => apiKey),
fold(
() => localStorage.removeItem('apiKey'),
key => localStorage.setItem('apiKey', key),
)
)
}, [user]);

React.useEffect(() => {
const storedApiKey = localStorage.getItem("apiKey");

if (!storedApiKey) return dispatch({ type: "LOG_OUT" });

dispatch({ type: "SET_API_KEY", apiKey: storedApiKey });
pipe(
fromNullable(localStorage.getItem("apiKey")),
fold(
() => dispatch({ type: 'LOG_OUT' }),
apiKey => dispatch({ type: 'SET_LOGIN_STATUS_UNKNOWN', apiKey })
)
);
}, [dispatch]);

React.useEffect(() => {
switch (loggedIn) {
case true:
return localStorage.setItem("apiKey", apiKeyRef.current || "");
case false:
return localStorage.removeItem("apiKey");
case null:
default:
return;
}
}, [loggedIn]);
};

export default useLocalStoragedApiKey;
22 changes: 15 additions & 7 deletions ui/src/main/Main/useLoginOnApiKey.tsx
Original file line number Diff line number Diff line change
@@ -1,21 +1,29 @@
import React from "react";
import { UserContext } from "../../contexts/UserContext/UserContext";
import userService from "../../services/UserService/UserService";
import { pipe } from "fp-ts/pipeable";
import { map, some } from "fp-ts/Option";

const useLoginOnApiKey = () => {
const {
dispatch,
state: { apiKey },
user,
} = React.useContext(UserContext);

React.useEffect(() => {
if (!apiKey) return;
console.log('useLoginOnApiKey');
pipe(
user,
map(({ apiKey }) => {
userService
.getCurrentUser(apiKey)
.then((user) => dispatch({ type: "LOG_IN", payload: { apiKey, tag: "logged_in", user: user } }))
.catch(() => dispatch({ type: "LOG_OUT" }));
})
)

userService
.getCurrentUser(apiKey)
.then((user) => dispatch({ type: "LOG_IN", user }))
.catch(() => dispatch({ type: "LOG_OUT" }));
}, [apiKey, dispatch]);

}, [user, dispatch]);
};

export default useLoginOnApiKey;
14 changes: 10 additions & 4 deletions ui/src/main/Routes/ProtectedRoute.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,21 @@ import React from "react";
import { Route, RouteProps } from "react-router-dom";
import { UserContext } from "../../contexts/UserContext/UserContext";
import Login from "../../pages/Login/Login";
import { fold } from "fp-ts/Option";
import { pipe } from "fp-ts/pipeable";

const ProtectedRoute: React.FC<RouteProps> = ({ children, ...props }) => {
const {
state: { loggedIn },
state: { user },
} = React.useContext(UserContext);

if (!loggedIn) return <Route {...props} component={Login} />;

return <Route {...props}>{children}</Route>;
return pipe(
user,
fold(
() => <Route {...props} component={Login} />,
_ => <Route {...props}>{children}</Route>
)
);
};

export default ProtectedRoute;
Loading