add get team method

This commit is contained in:
Владимир Фёдоров 2026-03-22 00:52:12 +07:00
parent ccad38799f
commit 614ec9e059
5 changed files with 115 additions and 92 deletions

View File

@ -1,12 +1,13 @@
<script setup lang="ts"> <script setup lang="ts">
import { ref, nextTick, watch, onMounted } from 'vue'; import { ref, nextTick, watch, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router'; import { useRoute, useRouter } from 'vue-router';
import { encodeUTF8ToBase64, getApiUrl } from './utils';
import VueQrcode from '@chenfengyuan/vue-qrcode'; import VueQrcode from '@chenfengyuan/vue-qrcode';
import BeltBlock from './BeltBlock.vue'; import BeltBlock from './BeltBlock.vue';
import MetalPlate from './MetalPlate.vue'; import MetalPlate from './MetalPlate.vue';
import GameHeader from './GameHeader.vue'; import GameHeader from './GameHeader.vue';
import type { Action, Door, Team } from './models'; import type { Action, Door, Team } from './models';
import { apiGetTeam, encodeUTF8ToBase64, getApiUrl } from './client';
import { UnauthorizedError } from './UnauthorizedError';
const router = useRouter(); const router = useRouter();
const route = useRoute(); const route = useRoute();
@ -39,28 +40,22 @@ const qrOptions = ref<QROptions>({
} }
}); });
function getTeam() { async function getTeam() {
fetch( let data: Team
getApiUrl("/team"), try {
{ data = await apiGetTeam(login.value, password.value)
method: "GET", } catch (error: unknown) {
headers: { if (error instanceof UnauthorizedError) {
"X-Id": encodeUTF8ToBase64(login.value), // Действия при 401:
"X-Password": password.value // Сделать редирект на страницу логина
},
}
)
.then(response => {
if (response.status == 401) {
router.push('/login'); router.push('/login');
} else {
console.error('Неизвестная ошибка:', error);
}
return return
} }
const res = response.json()
return res
})
.then(data => {
const oldActions = team.value.actions
const oldActions = team.value.actions
team.value = data team.value = data
const newActions = team.value?.actions const newActions = team.value?.actions
newActions.forEach(item => { newActions.forEach(item => {
@ -76,10 +71,6 @@ function getTeam() {
const element = team.value.actions[i]; const element = team.value.actions[i];
team.value.actions[i].buttons = element.doors.filter((door: Door) => { return door.show }) team.value.actions[i].buttons = element.doors.filter((door: Door) => { return door.show })
} }
})
.catch(error => {
console.error('Ошибка:', error)
});
} }
function addAction() { function addAction() {

View File

@ -1,56 +1,50 @@
<script setup lang="ts"> <script setup lang="ts">
import { onMounted, ref } from 'vue'; import { onMounted, ref } from 'vue';
import { useRouter } from 'vue-router'; import { useRouter } from 'vue-router';
import { encodeUTF8ToBase64, getApiUrl } from './utils'; import { apiGetTeam } from './client';
import { UnauthorizedError } from './UnauthorizedError';
const router = useRouter(); const router = useRouter();
const login = ref("") const login = ref("")
const password = ref("") const password = ref("")
const buttonText = ref("Вход") const buttonText = ref("Вход")
const errorMsg = ref("") const errorMsg = ref("")
function onClickLogin() { async function onClickLogin() {
const oldText = buttonText.value const oldText = buttonText.value
buttonText.value = "Загрузка..." buttonText.value = "Загрузка..."
errorMsg.value = "" errorMsg.value = ""
fetch(
getApiUrl("/team"), try {
{ await apiGetTeam(login.value, password.value)
method: "GET", } catch (error: unknown) {
headers: { if (error instanceof UnauthorizedError) {
"X-Id": encodeUTF8ToBase64(login.value), // Действия при 401:
"X-Password": password.value // Вывести ошибку
},
}
)
.then(response => {
if (response.status == 200) {
sessionStorage.setItem("teamId", login.value)
sessionStorage.setItem("password", password.value)
router.push('/');
return
}
if (response.status == 401) {
if (login.value == "" && password.value == "") { if (login.value == "" && password.value == "") {
return return
} }
errorMsg.value = "Не верны название команды или пароль" errorMsg.value = "Не верны название команды или пароль"
return } else {
}
errorMsg.value = "ХЗ что это " + response
})
.catch(() => {
errorMsg.value = "Сервер не доступен" errorMsg.value = "Сервер не доступен"
})
.finally(() => {buttonText.value = oldText});
} }
onMounted(() => { return
} finally {
buttonText.value = oldText
}
sessionStorage.setItem("teamId", login.value)
sessionStorage.setItem("password", password.value)
router.push('/');
}
onMounted(() => {
login.value = sessionStorage.getItem("teamId") || "" login.value = sessionStorage.getItem("teamId") || ""
password.value = sessionStorage.getItem("password") || "" password.value = sessionStorage.getItem("password") || ""
onClickLogin() onClickLogin()
}) })
</script> </script>
<template> <template>

View File

@ -0,0 +1,9 @@
export class UnauthorizedError extends Error {
constructor(message: string = 'Пользователь не авторизован (401)') {
super(message)
this.name = 'UnauthorizedError'
// Восстанавливаем цепочку прототипов (нужно для корректной работы instanceof в TS)
Object.setPrototypeOf(this, UnauthorizedError.prototype)
}
}

37
src/components/client.ts Normal file
View File

@ -0,0 +1,37 @@
import type { Team } from './models'
import { UnauthorizedError } from './UnauthorizedError'
export const apiGetTeam = async (login: string, password: string): Promise<Team> => {
try {
const response = await fetch(getApiUrl('/team'), {
method: 'GET',
headers: {
'X-Id': encodeUTF8ToBase64(login),
'X-Password': password,
},
})
if (response.status === 401) {
throw new UnauthorizedError('Ошибка авторизации')
}
if (!response.ok) {
throw new Error(`http error status: ${response.status}`)
}
return await response.json()
} catch (error) {
console.error('[apiGetTeam] error:', error)
throw error
}
}
export function getApiUrl(path: string) {
const url = 'http://' + window.location.host.split(':')[0] + ':8090' + path
return url
}
export function encodeUTF8ToBase64(s: string) {
return btoa(
encodeURIComponent(s).replace(/%([0-9A-F]{2})/g, (_, p1) =>
String.fromCharCode(parseInt(p1, 16)),
),
)
}

View File

@ -1,8 +0,0 @@
export function getApiUrl(path: string) {
const url = "http://" + window.location.host.split(":")[0] + ":8090" + path
return url
}
export function encodeUTF8ToBase64(s: string) {
return btoa(encodeURIComponent(s).replace(/%([0-9A-F]{2})/g, (_, p1) => String.fromCharCode(parseInt(p1, 16))))
}