This commit is contained in:
Hayden 2022-08-30 18:11:36 -08:00
parent 682774c9ce
commit 630fe83de5
5 changed files with 184 additions and 146 deletions

View file

@ -1,9 +1,10 @@
{
"arrowParens": "avoid",
"semi": true,
"tabWidth": 4,
"useTabs": true,
"tabWidth": 2,
"useTabs": false,
"vueIndentScriptAndStyle": true,
"singleQuote": true,
"trailingComma": "es5"
"trailingComma": "es5",
"printWidth": 120
}

View file

@ -1,18 +1,22 @@
import { BaseAPI, UrlBuilder } from './base';
export type Result<T> = {
item: T;
item: T;
};
export type User = {
name: string;
email: string;
isSuperuser: boolean;
id: number;
name: string;
email: string;
isSuperuser: boolean;
id: number;
};
export class UserApi extends BaseAPI {
public self() {
return this.http.get<Result<User>>(UrlBuilder('/users/self'));
}
public self() {
return this.http.get<Result<User>>(UrlBuilder('/users/self'));
}
public logout() {
return this.http.post<object, void>(UrlBuilder('/users/logout'), {});
}
}

View file

@ -1,95 +1,97 @@
export enum Method {
GET = 'GET',
POST = 'POST',
PUT = 'PUT',
DELETE = 'DELETE',
GET = 'GET',
POST = 'POST',
PUT = 'PUT',
DELETE = 'DELETE',
}
export interface TResponse<T> {
status: number;
error: boolean;
data: T;
response: Response;
status: number;
error: boolean;
data: T;
response: Response;
}
export class Requests {
private baseUrl: string;
private token: () => string;
private headers: Record<string, string> = {};
private logger?: (response: Response) => void;
private baseUrl: string;
private token: () => string;
private headers: Record<string, string> = {};
private logger?: (response: Response) => void;
private url(rest: string): string {
return this.baseUrl + rest;
}
private url(rest: string): string {
return this.baseUrl + rest;
}
constructor(
baseUrl: string,
token: string | (() => string) = '',
headers: Record<string, string> = {},
logger?: (response: Response) => void
) {
this.baseUrl = baseUrl;
this.token = typeof token === 'string' ? () => token : token;
this.headers = headers;
this.logger = logger;
}
constructor(
baseUrl: string,
token: string | (() => string) = '',
headers: Record<string, string> = {},
logger?: (response: Response) => void
) {
this.baseUrl = baseUrl;
this.token = typeof token === 'string' ? () => token : token;
this.headers = headers;
this.logger = logger;
}
public get<T>(url: string): Promise<TResponse<T>> {
return this.do<T>(Method.GET, url);
}
public get<T>(url: string): Promise<TResponse<T>> {
return this.do<T>(Method.GET, url);
}
public post<T, U>(url: string, payload: T): Promise<TResponse<U>> {
return this.do<U>(Method.POST, url, payload);
}
public post<T, U>(url: string, payload: T): Promise<TResponse<U>> {
return this.do<U>(Method.POST, url, payload);
}
public put<T, U>(url: string, payload: T): Promise<TResponse<U>> {
return this.do<U>(Method.PUT, url, payload);
}
public put<T, U>(url: string, payload: T): Promise<TResponse<U>> {
return this.do<U>(Method.PUT, url, payload);
}
public delete<T>(url: string): Promise<TResponse<T>> {
return this.do<T>(Method.DELETE, url);
}
public delete<T>(url: string): Promise<TResponse<T>> {
return this.do<T>(Method.DELETE, url);
}
private methodSupportsBody(method: Method): boolean {
return method === Method.POST || method === Method.PUT;
}
private methodSupportsBody(method: Method): boolean {
return method === Method.POST || method === Method.PUT;
}
private async do<T>(
method: Method,
url: string,
payload: Object = {}
): Promise<TResponse<T>> {
const args: RequestInit = {
method,
headers: {
'Content-Type': 'application/json',
...this.headers,
},
};
private async do<T>(method: Method, url: string, payload: Object = {}): Promise<TResponse<T>> {
const args: RequestInit = {
method,
headers: {
'Content-Type': 'application/json',
...this.headers,
},
};
const token = this.token();
if (token !== '' && args.headers !== undefined) {
// @ts-expect-error -- headers is always defined at this point
args.headers['Authorization'] = token;
}
const token = this.token();
if (token !== '' && args.headers !== undefined) {
// @ts-expect-error -- headers is always defined at this point
args.headers['Authorization'] = token;
}
if (this.methodSupportsBody(method)) {
args.body = JSON.stringify(payload);
}
if (this.methodSupportsBody(method)) {
args.body = JSON.stringify(payload);
}
const response = await fetch(this.url(url), args);
const response = await fetch(this.url(url), args);
if (this.logger) {
this.logger(response);
}
if (this.logger) {
this.logger(response);
}
const data = await response.json();
const data: T = await (async () => {
try {
return await response.json();
} catch (e) {
return {} as T;
}
})();
return {
status: response.status,
error: !response.ok,
data,
response,
};
}
return {
status: response.status,
error: !response.ok,
data,
response,
};
}
}

View file

@ -1,57 +1,73 @@
<script setup lang="ts">
import { useUserApi } from '@/composables/use-api';
useHead({
title: 'Homebox | Home',
});
import { useUserApi } from '@/composables/use-api';
import { useAuthStore } from '@/store/auth';
useHead({
title: 'Homebox | Home',
});
const links = [
{
name: 'Home',
href: '/home',
},
{
name: 'Logout',
href: '/logout',
last: true,
},
];
const api = useUserApi();
const api = useUserApi();
const user = ref({});
const user = ref({});
onMounted(async () => {
const { data } = await api.self();
onMounted(async () => {
const { data } = await api.self();
if (data) {
user.value = data.item;
}
});
if (data) {
user.value = data.item;
}
});
const authStore = useAuthStore();
const router = useRouter();
async function logout() {
const { error } = await authStore.logout(api);
if (error) {
console.error(error);
return;
}
router.push('/');
}
const links = [
{
name: 'Home',
href: '/home',
},
{
name: 'Logout',
action: logout,
last: true,
},
];
</script>
<template>
<section class="max-w-7xl mx-auto">
<header class="sm:px-6 py-2 lg:p-14 sm:py-6">
<h2
class="mt-1 text-4xl font-bold tracking-tight text-gray-200 sm:text-5xl lg:text-6xl"
>
Homebox
</h2>
<div class="ml-1 text-lg text-gray-400 space-x-2 italic">
<template v-for="link in links">
<router-link
class="hover:text-base-content transition-color duration-200"
:to="link.href"
>
{{ link.name }}
</router-link>
<span v-if="!link.last"> / </span>
</template>
</div>
</header>
</section>
<section class="max-w-7xl mx-auto sm:px-6 lg:px-14">
{{ user }}
</section>
<section class="max-w-7xl mx-auto">
<header class="sm:px-6 py-2 lg:p-14 sm:py-6">
<h2 class="mt-1 text-4xl font-bold tracking-tight text-gray-200 sm:text-5xl lg:text-6xl">Homebox</h2>
<div class="ml-1 text-lg text-gray-400 space-x-2">
<template v-for="link in links">
<router-link
v-if="!link.action"
class="hover:text-base-content transition-color duration-200 italic"
:to="link.href"
>
{{ link.name }}
</router-link>
<button v-else @click="link.action" class="hover:text-base-content transition-color duration-200 italic">
{{ link.name }}
</button>
<span v-if="!link.last"> / </span>
</template>
</div>
</header>
</section>
<section class="max-w-7xl mx-auto sm:px-6 lg:px-14">
{{ user }}
</section>
</template>
<route lang="yaml">

View file

@ -1,21 +1,36 @@
import { UserApi } from '@/api/user';
import { defineStore } from 'pinia';
export const useAuthStore = defineStore('auth', {
state: () => ({
token: useLocalStorage('pinia/auth/token', ''),
expires: useLocalStorage('pinia/auth/expires', ''),
}),
getters: {
isTokenExpired: state => {
if (!state.expires) {
return true;
}
state: () => ({
token: useLocalStorage('pinia/auth/token', ''),
expires: useLocalStorage('pinia/auth/expires', ''),
}),
getters: {
isTokenExpired: state => {
if (!state.expires) {
return true;
}
if (typeof state.expires === 'string') {
return new Date(state.expires) < new Date();
}
if (typeof state.expires === 'string') {
return new Date(state.expires) < new Date();
}
return state.expires < new Date();
},
},
return state.expires < new Date();
},
},
actions: {
async logout(api: UserApi) {
const result = await api.logout();
if (result.error) {
return result;
}
this.token = '';
this.expires = '';
return result;
},
},
});