mirror of
https://github.com/apricote/Listory.git
synced 2026-01-13 21:21:02 +00:00
feat(frontend): redo setup with ts+tailwind and implement auth+header
This commit is contained in:
parent
f2065d3f1f
commit
05f230a7ce
32 changed files with 5927 additions and 2749 deletions
40
frontend/src/api/api.ts
Normal file
40
frontend/src/api/api.ts
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
import { User } from "./user";
|
||||
|
||||
export class UnauthenticatedError extends Error {}
|
||||
|
||||
const getToken = (): string => {
|
||||
const cookieValue = document.cookie.replace(
|
||||
/(?:(?:^|.*;\s*)listory_access_token\s*=\s*([^;]*).*$)|^.*$/,
|
||||
"$1"
|
||||
);
|
||||
|
||||
return cookieValue;
|
||||
};
|
||||
|
||||
const getDefaultHeaders = (): Headers => {
|
||||
const headers = new Headers();
|
||||
|
||||
headers.append("Content-Type", "application/json");
|
||||
headers.append("Authorization", `Bearer ${getToken()}`);
|
||||
|
||||
return headers;
|
||||
};
|
||||
|
||||
export const getUsersMe = async (): Promise<User> => {
|
||||
const res = await fetch(`api/v1/users/me`, { headers: getDefaultHeaders() });
|
||||
|
||||
switch (res.status) {
|
||||
case 200: {
|
||||
break;
|
||||
}
|
||||
case 401: {
|
||||
throw new UnauthenticatedError(`No token or token expired`);
|
||||
}
|
||||
default: {
|
||||
throw new Error(`Unable to getUsersMe: ${res.status}`);
|
||||
}
|
||||
}
|
||||
|
||||
const user: User = await res.json();
|
||||
return user;
|
||||
};
|
||||
Loading…
Add table
Add a link
Reference in a new issue