implemented notification component and logic

This commit is contained in:
Sockenklaus
2021-10-21 01:24:46 +02:00
parent 5017be6d42
commit 7e5ab9b445
6 changed files with 129 additions and 26 deletions

View File

@@ -0,0 +1,20 @@
import { defineStore, acceptHMRUpdate } from 'pinia'
export const useNotifications = defineStore('notifications', {
state: () => {
return {
/**@type {{type: string, text: string}[]} */
notifications: new Array<{type: string, text: string}>()
}
},
actions: {
removeAlert(index : number) : void {
this.notifications.splice(index, 1)
}
}
})
if(import.meta.hot) {
import.meta.hot.accept(acceptHMRUpdate(useNotifications, import.meta.hot))
}

View File

@@ -1,5 +1,22 @@
import { defineStore } from 'pinia'
import { defineStore, storeToRefs } from 'pinia'
import axios, {AxiosResponse, AxiosError} from 'axios'
import { useNotifications } from './notifications'
type AuthSuccResult = {
notification: {
type: string,
text: string
}
user: string,
role: string
}
type AuthErrResult = {
notification: {
text: string,
type: string
}
}
export const useUser = defineStore('userStore', {
state: () => {
@@ -12,27 +29,37 @@ export const useUser = defineStore('userStore', {
actions: {
async login(username: string, password: string) : Promise<boolean> {
const { notifications } = storeToRefs(useNotifications())
try {
const response: AxiosResponse<{
user: string,
role: string,
Message: string
}> = await axios.post('http://localhost:3333/api/v1/login', {
const response = await axios.post<AuthSuccResult>('http://localhost:3333/api/v1/login', {
username: username,
password: password
})
console.log(response.data)
this.isLoggedIn = true
this.user = response.data.user
this.role = response.data.role
notifications.value.push({
type: response.data.notification.type,
text: response.data.notification.text,
})
return true
} catch(err) {
if (axios.isAxiosError(err)){
console.log(err.response)
} catch(err : unknown) {
if (axios.isAxiosError(err) && err.response && err.response.data){
const data = err.response.data as AuthErrResult
const note = {
type: data.notification.type,
text: data.notification.text
}
notifications.value.push(note)
}
return false
}