mirror of
https://github.com/roleypoly/roleypoly.git
synced 2025-04-25 20:09:11 +00:00
feat: add Api and Session contexts
This commit is contained in:
parent
f65779f925
commit
9c2a6a8d61
13 changed files with 340 additions and 7 deletions
|
@ -32,7 +32,7 @@ export const Authed = (props: Props) => {
|
||||||
<MastheadBase>
|
<MastheadBase>
|
||||||
<MastheadAlignment>
|
<MastheadAlignment>
|
||||||
<MastheadLeft>
|
<MastheadLeft>
|
||||||
<MastheadA href="/servers">
|
<MastheadA to="/servers">
|
||||||
<DynamicLogomark height={35} />
|
<DynamicLogomark height={35} />
|
||||||
</MastheadA>
|
</MastheadA>
|
||||||
<InteractionBase
|
<InteractionBase
|
||||||
|
|
|
@ -14,12 +14,12 @@ export const Guest = () => (
|
||||||
<MastheadBase>
|
<MastheadBase>
|
||||||
<MastheadAlignment>
|
<MastheadAlignment>
|
||||||
<MastheadLeft>
|
<MastheadLeft>
|
||||||
<MastheadA href="/">
|
<MastheadA to="/">
|
||||||
<DynamicLogotype height={30} />
|
<DynamicLogotype height={30} />
|
||||||
</MastheadA>
|
</MastheadA>
|
||||||
</MastheadLeft>
|
</MastheadLeft>
|
||||||
<MastheadRight>
|
<MastheadRight>
|
||||||
<MastheadA href="/auth/login">
|
<MastheadA to="/auth/login">
|
||||||
<Button size="small">
|
<Button size="small">
|
||||||
Login{' '}
|
Login{' '}
|
||||||
<FaSignInAlt
|
<FaSignInAlt
|
||||||
|
|
|
@ -1,3 +1,4 @@
|
||||||
|
import { Link } from '@reach/router';
|
||||||
import { onSmallScreen } from '@roleypoly/design-system/atoms/breakpoints';
|
import { onSmallScreen } from '@roleypoly/design-system/atoms/breakpoints';
|
||||||
import { palette } from '@roleypoly/design-system/atoms/colors';
|
import { palette } from '@roleypoly/design-system/atoms/colors';
|
||||||
import { transitions } from '@roleypoly/design-system/atoms/timings';
|
import { transitions } from '@roleypoly/design-system/atoms/timings';
|
||||||
|
@ -66,7 +67,7 @@ export const InteractionBase = styled.div<InteractionBaseProps>`
|
||||||
}
|
}
|
||||||
`;
|
`;
|
||||||
|
|
||||||
export const MastheadA = styled.a`
|
export const MastheadA = styled(Link)`
|
||||||
display: flex;
|
display: flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
justify-content: center;
|
justify-content: center;
|
||||||
|
|
65
packages/web/src/api-context/ApiContext.spec.tsx
Normal file
65
packages/web/src/api-context/ApiContext.spec.tsx
Normal file
|
@ -0,0 +1,65 @@
|
||||||
|
import { render, screen } from '@testing-library/react';
|
||||||
|
import * as React from 'react';
|
||||||
|
import { ApiContextProvider, useApiContext } from './ApiContext';
|
||||||
|
|
||||||
|
const fetchMock = (global.fetch = jest
|
||||||
|
.fn()
|
||||||
|
.mockImplementation(() => ({ json: async () => ({}) })));
|
||||||
|
|
||||||
|
const TestComponent = () => {
|
||||||
|
const context = useApiContext();
|
||||||
|
|
||||||
|
React.useEffect(() => {
|
||||||
|
void context.fetch('/not-a-route');
|
||||||
|
});
|
||||||
|
|
||||||
|
return <>{context.apiUrl}</>;
|
||||||
|
};
|
||||||
|
|
||||||
|
const WrappedTestComponent = () => (
|
||||||
|
<ApiContextProvider>
|
||||||
|
<TestComponent />
|
||||||
|
</ApiContextProvider>
|
||||||
|
);
|
||||||
|
|
||||||
|
it('correctly does fetch url requests', () => {
|
||||||
|
render(<WrappedTestComponent />);
|
||||||
|
|
||||||
|
expect(fetchMock).toBeCalledWith('http://localhost:6609/not-a-route');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('sets up api context when localStorage is set', () => {
|
||||||
|
localStorage.setItem('api_url', 'https://abcde.roleypoly.test');
|
||||||
|
render(<WrappedTestComponent />);
|
||||||
|
|
||||||
|
expect(fetchMock).toBeCalledWith('https://abcde.roleypoly.test/not-a-route');
|
||||||
|
expect(screen.getByText('https://abcde.roleypoly.test').innerHTML).toStrictEqual(
|
||||||
|
'https://abcde.roleypoly.test'
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it.each([
|
||||||
|
['https://next.roleypoly.com/servers', 'https://api-prod.roleypoly.com'],
|
||||||
|
['https://roleypoly.com/servers', 'https://api-prod.roleypoly.com'],
|
||||||
|
['https://notroleypolybutclose.com/servers', 'https://api-prod.roleypoly.com'],
|
||||||
|
['https://myhash.roleypoly.pages.dev/servers', 'https://api-stage.roleypoly.com'],
|
||||||
|
['http://localhost:6601/servers', 'http://localhost:6609'],
|
||||||
|
['http://127.0.0.1:6601/servers', 'http://localhost:6609'],
|
||||||
|
])('sets up api context based on window.location.href = %s', (inputUrl, outputUrl) => {
|
||||||
|
// @ts-ignore
|
||||||
|
delete window.location;
|
||||||
|
window.location = new URL(inputUrl) as any;
|
||||||
|
|
||||||
|
render(<WrappedTestComponent />);
|
||||||
|
|
||||||
|
expect(fetchMock).toBeCalledWith(`${outputUrl}/not-a-route`);
|
||||||
|
expect(screen.getByText(outputUrl).innerHTML).toStrictEqual(outputUrl);
|
||||||
|
});
|
||||||
|
|
||||||
|
const originalWindowLocation = window.location;
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
localStorage.clear();
|
||||||
|
fetchMock.mockClear();
|
||||||
|
window.location = originalWindowLocation;
|
||||||
|
});
|
45
packages/web/src/api-context/ApiContext.tsx
Normal file
45
packages/web/src/api-context/ApiContext.tsx
Normal file
|
@ -0,0 +1,45 @@
|
||||||
|
import * as React from 'react';
|
||||||
|
import { getDefaultApiUrl } from './getDefaultApiUrl';
|
||||||
|
|
||||||
|
type ApiContextData = {
|
||||||
|
apiUrl: string;
|
||||||
|
setApiUrl: (url: string) => void;
|
||||||
|
fetch: (path: string, ...rest: any) => Promise<Response>;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const ApiContext = React.createContext<ApiContextData>({
|
||||||
|
apiUrl: getDefaultApiUrl(),
|
||||||
|
setApiUrl: () => {},
|
||||||
|
fetch: async () => {
|
||||||
|
return new Response();
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
export const useApiContext = () => React.useContext(ApiContext);
|
||||||
|
|
||||||
|
export const ApiContextProvider = (props: { children: React.ReactNode }) => {
|
||||||
|
const [apiUrl, setApiUrl] = React.useState(getDefaultApiUrl());
|
||||||
|
|
||||||
|
const apiContextData: ApiContextData = {
|
||||||
|
apiUrl,
|
||||||
|
setApiUrl,
|
||||||
|
fetch: async (path: string, ...rest: any): Promise<Response> => {
|
||||||
|
return fetch(`${apiUrl}${path}`, ...rest);
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
React.useEffect(() => {
|
||||||
|
const storedApiUrl = localStorage.getItem('api_url');
|
||||||
|
if (storedApiUrl) {
|
||||||
|
setApiUrl(storedApiUrl);
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
React.useEffect(() => {
|
||||||
|
localStorage.setItem('api_url', apiUrl);
|
||||||
|
}, [apiUrl]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ApiContext.Provider value={apiContextData}>{props.children}</ApiContext.Provider>
|
||||||
|
);
|
||||||
|
};
|
14
packages/web/src/api-context/getDefaultApiUrl.spec.ts
Normal file
14
packages/web/src/api-context/getDefaultApiUrl.spec.ts
Normal file
|
@ -0,0 +1,14 @@
|
||||||
|
import { getDefaultApiUrl } from './getDefaultApiUrl';
|
||||||
|
|
||||||
|
it.each([
|
||||||
|
['https://next.roleypoly.com/servers', 'https://api-prod.roleypoly.com'],
|
||||||
|
['https://roleypoly.com/servers', 'https://api-prod.roleypoly.com'],
|
||||||
|
['https://notroleypolybutclose.com/servers', 'https://api-prod.roleypoly.com'],
|
||||||
|
['https://myhash.roleypoly.pages.dev/servers', 'https://api-stage.roleypoly.com'],
|
||||||
|
['http://localhost:6601/servers', 'http://localhost:6609'],
|
||||||
|
['http://127.0.0.1:6601/servers', 'http://localhost:6609'],
|
||||||
|
])('matches %s to %s', (inputUrl, outputUrl) => {
|
||||||
|
const urlHostname = new URL(inputUrl).hostname;
|
||||||
|
|
||||||
|
expect(getDefaultApiUrl(urlHostname)).toStrictEqual(outputUrl);
|
||||||
|
});
|
11
packages/web/src/api-context/getDefaultApiUrl.ts
Normal file
11
packages/web/src/api-context/getDefaultApiUrl.ts
Normal file
|
@ -0,0 +1,11 @@
|
||||||
|
export const getDefaultApiUrl = (host: string = window.location.hostname) => {
|
||||||
|
if (/roleypoly.com$/.test(host)) {
|
||||||
|
return 'https://api-prod.roleypoly.com';
|
||||||
|
} else if (/roleypoly\.pages\.dev$/.test(host)) {
|
||||||
|
return 'https://api-stage.roleypoly.com';
|
||||||
|
} else if (/\blocalhost|127\.0\.0\.1\b/.test(host)) {
|
||||||
|
return 'http://localhost:6609';
|
||||||
|
} else {
|
||||||
|
return 'https://api-prod.roleypoly.com';
|
||||||
|
}
|
||||||
|
};
|
|
@ -2,6 +2,8 @@ import { Router } from '@reach/router';
|
||||||
import * as React from 'react';
|
import * as React from 'react';
|
||||||
|
|
||||||
const LandingPage = React.lazy(() => import('../pages/landing'));
|
const LandingPage = React.lazy(() => import('../pages/landing'));
|
||||||
|
const DevToolsSetApi = React.lazy(() => import('../pages/dev-tools/set-api'));
|
||||||
|
const DevToolsSessionDebug = React.lazy(() => import('../pages/dev-tools/session-debug'));
|
||||||
|
|
||||||
const RouteWrapper = (props: {
|
const RouteWrapper = (props: {
|
||||||
component: React.LazyExoticComponent<React.ComponentType<any>>;
|
component: React.LazyExoticComponent<React.ComponentType<any>>;
|
||||||
|
@ -17,6 +19,11 @@ export const AppRouter = () => {
|
||||||
return (
|
return (
|
||||||
<Router>
|
<Router>
|
||||||
<RouteWrapper component={LandingPage} path="/" />
|
<RouteWrapper component={LandingPage} path="/" />
|
||||||
|
<RouteWrapper component={DevToolsSetApi} path="/x/dev-tools/set-api" />
|
||||||
|
<RouteWrapper
|
||||||
|
component={DevToolsSessionDebug}
|
||||||
|
path="/x/dev-tools/session-debug"
|
||||||
|
/>
|
||||||
</Router>
|
</Router>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
|
@ -1 +0,0 @@
|
||||||
export * from './AppRouter';
|
|
|
@ -1,10 +1,16 @@
|
||||||
import React from 'react';
|
import React from 'react';
|
||||||
import ReactDOM from 'react-dom';
|
import ReactDOM from 'react-dom';
|
||||||
import { AppRouter } from './app-router';
|
import { ApiContextProvider } from './api-context/ApiContext';
|
||||||
|
import { AppRouter } from './app-router/AppRouter';
|
||||||
|
import { SessionContextProvider } from './session-context/SessionContext';
|
||||||
|
|
||||||
ReactDOM.render(
|
ReactDOM.render(
|
||||||
<React.StrictMode>
|
<React.StrictMode>
|
||||||
|
<ApiContextProvider>
|
||||||
|
<SessionContextProvider>
|
||||||
<AppRouter />
|
<AppRouter />
|
||||||
|
</SessionContextProvider>
|
||||||
|
</ApiContextProvider>
|
||||||
</React.StrictMode>,
|
</React.StrictMode>,
|
||||||
document.getElementById('root')
|
document.getElementById('root')
|
||||||
);
|
);
|
||||||
|
|
21
packages/web/src/pages/dev-tools/session-debug.tsx
Normal file
21
packages/web/src/pages/dev-tools/session-debug.tsx
Normal file
|
@ -0,0 +1,21 @@
|
||||||
|
import { useSessionContext } from '../../session-context/SessionContext';
|
||||||
|
|
||||||
|
const SessionDebug = () => {
|
||||||
|
const session = useSessionContext();
|
||||||
|
|
||||||
|
return (
|
||||||
|
<pre>
|
||||||
|
{JSON.stringify(
|
||||||
|
{
|
||||||
|
isAuthenticated: !!session.session?.user,
|
||||||
|
user: session.session?.user || null,
|
||||||
|
guilds: session.session?.guilds || null,
|
||||||
|
},
|
||||||
|
null,
|
||||||
|
' '
|
||||||
|
)}
|
||||||
|
</pre>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default SessionDebug;
|
51
packages/web/src/pages/dev-tools/set-api.tsx
Normal file
51
packages/web/src/pages/dev-tools/set-api.tsx
Normal file
|
@ -0,0 +1,51 @@
|
||||||
|
import { navigate } from '@reach/router';
|
||||||
|
import * as React from 'react';
|
||||||
|
import { useApiContext } from '../../api-context/ApiContext';
|
||||||
|
|
||||||
|
const SetApi = () => {
|
||||||
|
const apiContext = useApiContext();
|
||||||
|
const [apiField, setApiField] = React.useState(apiContext.apiUrl);
|
||||||
|
|
||||||
|
const setApi = () => {
|
||||||
|
// Clear storage to get rid of old API data
|
||||||
|
localStorage.clear();
|
||||||
|
sessionStorage.clear();
|
||||||
|
|
||||||
|
apiContext.setApiUrl(apiField);
|
||||||
|
|
||||||
|
navigate('/');
|
||||||
|
};
|
||||||
|
|
||||||
|
const quickSettingClick = (url: string) => () => {
|
||||||
|
setApiField(url);
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<div>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={apiField}
|
||||||
|
onChange={(ev) => {
|
||||||
|
setApiField(ev.target.value);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<button onClick={setApi}>Set & Go</button>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
Quick Settings:
|
||||||
|
<button onClick={quickSettingClick('https://api-prod.roleypoly.com')}>
|
||||||
|
Production (api-prod)
|
||||||
|
</button>
|
||||||
|
<button onClick={quickSettingClick('https://api-stage.roleypoly.com')}>
|
||||||
|
Staging (api-stage)
|
||||||
|
</button>
|
||||||
|
<button onClick={quickSettingClick('http://localhost:6609')}>
|
||||||
|
Local (:6609)
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default SetApi;
|
113
packages/web/src/session-context/SessionContext.tsx
Normal file
113
packages/web/src/session-context/SessionContext.tsx
Normal file
|
@ -0,0 +1,113 @@
|
||||||
|
import { SessionData } from '@roleypoly/types';
|
||||||
|
import * as React from 'react';
|
||||||
|
import { useApiContext } from '../api-context/ApiContext';
|
||||||
|
|
||||||
|
type SessionContextT = {
|
||||||
|
session?: Omit<Partial<SessionData>, 'tokens'>;
|
||||||
|
setSession: (session?: SessionContextT['session']) => void;
|
||||||
|
authedFetch: (url: string, opts?: RequestInit) => Promise<Response>;
|
||||||
|
};
|
||||||
|
|
||||||
|
const SessionContext = React.createContext<SessionContextT>({
|
||||||
|
setSession: () => {},
|
||||||
|
authedFetch: async () => {
|
||||||
|
return new Response();
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
export const useSessionContext = () => React.useContext(SessionContext);
|
||||||
|
|
||||||
|
export const SessionContextProvider = (props: { children: React.ReactNode }) => {
|
||||||
|
const api = useApiContext();
|
||||||
|
const [session, setSession] = React.useState<SessionContextT['session']>(undefined);
|
||||||
|
|
||||||
|
const sessionContextValue: SessionContextT = React.useMemo(
|
||||||
|
() => ({
|
||||||
|
session,
|
||||||
|
setSession,
|
||||||
|
authedFetch: (url: string, opts?: RequestInit) => {
|
||||||
|
return api.fetch(url, {
|
||||||
|
...opts,
|
||||||
|
headers: {
|
||||||
|
...opts?.headers,
|
||||||
|
authorization: session?.sessionID
|
||||||
|
? `Bearer ${session?.sessionID}`
|
||||||
|
: undefined,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
[session, api]
|
||||||
|
);
|
||||||
|
|
||||||
|
React.useEffect(() => {
|
||||||
|
// No session is set, do we have one available?
|
||||||
|
if (!sessionContextValue.session || !sessionContextValue.session.sessionID) {
|
||||||
|
// We may have the full state in session storage...
|
||||||
|
const storedSessionData = sessionStorage.getItem('rp_session_data');
|
||||||
|
if (storedSessionData) {
|
||||||
|
try {
|
||||||
|
setSession(JSON.parse(storedSessionData));
|
||||||
|
return;
|
||||||
|
} catch (e) {
|
||||||
|
// Oops, this data is wrong.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// But if not, we have the key, maybe?
|
||||||
|
const storedSessionID = localStorage.getItem('rp_session_key');
|
||||||
|
if (storedSessionID && storedSessionID !== '') {
|
||||||
|
setSession({ sessionID: storedSessionID });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// If we hit here, we're definitely not authenticated.
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// If a session is set and it's not stored, set it now.
|
||||||
|
if (
|
||||||
|
localStorage.getItem('rp_session_key') !==
|
||||||
|
sessionContextValue.session.sessionID
|
||||||
|
) {
|
||||||
|
localStorage.setItem(
|
||||||
|
'rp_session_key',
|
||||||
|
sessionContextValue.session.sessionID || ''
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Session is set, but we don't have data. Server sup?
|
||||||
|
if (sessionContextValue.session.sessionID && !sessionContextValue.session.user) {
|
||||||
|
const syncSession = async () => {
|
||||||
|
const response = await sessionContextValue.authedFetch('/get-session');
|
||||||
|
if (response.status !== 200) {
|
||||||
|
console.error('get-session failed', { response });
|
||||||
|
clearSessionData();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const serverSession: SessionContextT['session'] = await response.json();
|
||||||
|
|
||||||
|
setSession(serverSession);
|
||||||
|
sessionStorage.setItem('rp_session_data', JSON.stringify(serverSession));
|
||||||
|
};
|
||||||
|
|
||||||
|
syncSession();
|
||||||
|
}
|
||||||
|
}, [
|
||||||
|
sessionContextValue.session?.user,
|
||||||
|
sessionContextValue.session?.sessionID,
|
||||||
|
sessionContextValue,
|
||||||
|
]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<SessionContext.Provider value={sessionContextValue}>
|
||||||
|
{props.children}
|
||||||
|
</SessionContext.Provider>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
const clearSessionData = () => {
|
||||||
|
sessionStorage.removeItem('rp_session_data');
|
||||||
|
localStorage.removeItem('rp_session_key');
|
||||||
|
};
|
Loading…
Add table
Reference in a new issue