From 096c190946c23feaa5fec4e008b46fdddc9107d2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tim=20Gr=C3=B6ger?= Date: Tue, 15 Oct 2024 07:29:24 +0200 Subject: [PATCH] [feat][apikey] add apikey store and logic --- api/src/stores/apiKeys.ts | 61 +++++++++++++++++++++++++++++++++++++++ api/src/stores/index.ts | 1 + 2 files changed, 62 insertions(+) create mode 100644 api/src/stores/apiKeys.ts diff --git a/api/src/stores/apiKeys.ts b/api/src/stores/apiKeys.ts new file mode 100644 index 0000000..086678e --- /dev/null +++ b/api/src/stores/apiKeys.ts @@ -0,0 +1,61 @@ +import { defineStore } from 'pinia'; +import { api } from '../internal'; +import { isAxiosError, useMainStore } from '.'; + +export const useApiKeyStore = defineStore({ + id: 'apiKeys', + + state: () => ({ + apiKeys: [] as FG.ApiKey[], + }), + + getters: {}, + + actions: { + async getApiKeys(): Promise { + try { + const mainStore = useMainStore(); + const { data } = await api.get( + `/users/${mainStore.currentUser.userid}/api_keys` + ); + + this.apiKeys = data; + + return data; + } catch (error) { + return [] as FG.ApiKey[]; + } + }, + + async deleteApiKey(id: number): Promise { + const mainStore = useMainStore(); + + try { + await api.delete(`/users/${mainStore.currentUser.userid}/api_keys/${id}`); + this.apiKeys = this.apiKeys.filter((apiKey: FG.ApiKey) => apiKey.id !== id); + return true; + } catch (error) { + // Ignore 401, as this means we are already logged out, throw all other + if (!isAxiosError(error, 401)) throw error; + } + return false; + }, + + async createApiKey(apiKey: FG.ApiKey): Promise { + const mainStore = useMainStore(); + + try { + const { data } = await api.post( + `/users/${mainStore.currentUser.userid}/api_keys`, + apiKey + ); + + this.apiKeys.push(data); + + return data; + } catch (error) { + throw error; + } + }, + }, +}); diff --git a/api/src/stores/index.ts b/api/src/stores/index.ts index aa47ccb..7c4842e 100644 --- a/api/src/stores/index.ts +++ b/api/src/stores/index.ts @@ -21,3 +21,4 @@ export function isAxiosError(error: unknown, status?: number) { export * from './main'; export * from './session'; export * from './user'; +export * from './apiKeys';