Skip to content

A continuation of HomeBox the inventory and organization system built for the Home User

cleanup

Hayden630fe83de5b4
diff --git a/frontend/.prettierrc b/frontend/.prettierrc
index 4b090754..b12bbd41 100644
--- a/frontend/.prettierrc
+++ b/frontend/.prettierrc
@@ -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
+}
\ No newline at end of file
diff --git a/frontend/src/api/user.ts b/frontend/src/api/user.ts
index a4687370..fb93a078 100644
--- a/frontend/src/api/user.ts
+++ b/frontend/src/api/user.ts
@@ -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'), {});
+ }
}
diff --git a/frontend/src/lib/requests/requests.ts b/frontend/src/lib/requests/requests.ts
index c0c83be3..7ee3f71e 100644
--- a/frontend/src/lib/requests/requests.ts
+++ b/frontend/src/lib/requests/requests.ts
@@ -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 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;
- }
-
- 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 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);
- }
-
- 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,
- },
- };
-
- 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);
- }
-
- const response = await fetch(this.url(url), args);
-
- if (this.logger) {
- this.logger(response);
- }
-
- const data = await response.json();
-
- return {
- status: response.status,
- error: !response.ok,
- data,
- response,
- };
- }
+ 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;
+ }
+
+ 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 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 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 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;
+ }
+
+ if (this.methodSupportsBody(method)) {
+ args.body = JSON.stringify(payload);
+ }
+
+ const response = await fetch(this.url(url), args);
+
+ if (this.logger) {
+ this.logger(response);
+ }
+
+ const data: T = await (async () => {
+ try {
+ return await response.json();
+ } catch (e) {
+ return {} as T;
+ }
+ })();
+
+ return {
+ status: response.status,
+ error: !response.ok,
+ data,
+ response,
+ };
+ }
}
diff --git a/frontend/src/pages/home.vue b/frontend/src/pages/home.vue
index f159a2c7..5109a922 100644
--- a/frontend/src/pages/home.vue
+++ b/frontend/src/pages/home.vue
@@ -1,57 +1,73 @@
<script setup lang="ts">
- import { useUserApi } from '@/composables/use-api';
- useHead({
- title: 'Homebox | Home',
- });
-
- const links = [
- {
- name: 'Home',
- href: '/home',
- },
- {
- name: 'Logout',
- href: '/logout',
- last: true,
- },
- ];
- const api = useUserApi();
-
- const user = ref({});
-
- onMounted(async () => {
- const { data } = await api.self();
-
- if (data) {
- user.value = data.item;
- }
- });
+ import { useUserApi } from '@/composables/use-api';
+ import { useAuthStore } from '@/store/auth';
+ useHead({
+ title: 'Homebox | Home',
+ });
+
+ const api = useUserApi();
+
+ const user = ref({});
+
+ onMounted(async () => {
+ const { data } = await api.self();
+
+ 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">
diff --git a/frontend/src/store/auth.ts b/frontend/src/store/auth.ts
index 3e3e6b4f..092d1fb0 100644
--- a/frontend/src/store/auth.ts
+++ b/frontend/src/store/auth.ts
@@ -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;
+ },
+ },
});