mirror of
https://github.com/roleypoly/roleypoly.git
synced 2025-06-17 09:59:10 +00:00
feat(UI): add role picker, auth helpers, refactor for viability
This commit is contained in:
parent
3fe3cfc21f
commit
e4e4bb9024
32 changed files with 408 additions and 136 deletions
56
src/common/utils/isomorphicFetch.ts
Normal file
56
src/common/utils/isomorphicFetch.ts
Normal file
|
@ -0,0 +1,56 @@
|
|||
import { NextPageContext } from 'next';
|
||||
import getConfig from 'next/config';
|
||||
import nookies from 'nookies';
|
||||
import useSWR from 'swr';
|
||||
|
||||
export const getPublicURI = (context?: NextPageContext) => {
|
||||
if (context?.req) {
|
||||
const { publicRuntimeConfig } = getConfig();
|
||||
return publicRuntimeConfig.apiPublicURI;
|
||||
} else {
|
||||
return typeof localStorage !== 'undefined' && localStorage.getItem('api_uri');
|
||||
}
|
||||
};
|
||||
|
||||
export const getSessionKey = (context?: NextPageContext) => {
|
||||
if (context?.req) {
|
||||
return nookies.get(context)['rp_session_key'];
|
||||
} else {
|
||||
return (
|
||||
typeof sessionStorage !== 'undefined' && sessionStorage.getItem('session_key')
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
export const apiFetch = async <T>(
|
||||
path: string,
|
||||
init?: RequestInit,
|
||||
context?: NextPageContext
|
||||
): Promise<T | null> => {
|
||||
const sessionKey = getSessionKey(context);
|
||||
if (!sessionKey) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const authorizedInit: RequestInit = {
|
||||
...(init || {}),
|
||||
headers: {
|
||||
...(init?.headers || {}),
|
||||
authorization: `Bearer ${sessionKey}`,
|
||||
},
|
||||
};
|
||||
|
||||
const response = await fetch(`${getPublicURI(context)}${path}`, authorizedInit);
|
||||
|
||||
if (response.status >= 400) {
|
||||
const reason = (await response.json())['error'];
|
||||
throw new Error(`Fetch failed: ${reason}`);
|
||||
}
|
||||
|
||||
return response.json() as Promise<T>;
|
||||
};
|
||||
|
||||
export const swrFetch = <T>(path: string, context?: NextPageContext) =>
|
||||
useSWR<T>(path, (url: string): Promise<any> => apiFetch<T>(url, undefined, context), {
|
||||
revalidateOnFocus: false,
|
||||
});
|
|
@ -1,7 +1,7 @@
|
|||
export const sortBy = <T>(
|
||||
export const sortBy = <T, Key extends keyof T>(
|
||||
array: T[],
|
||||
key: keyof T,
|
||||
predicate?: (a: T[keyof T], b: T[keyof T]) => number
|
||||
key: Key,
|
||||
predicate?: (a: T[typeof key], b: T[typeof key]) => number
|
||||
) => {
|
||||
return array.sort((a, b) => {
|
||||
if (predicate) {
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue