LabWork06, уююююю :)))

Но если для души делать, то для доп. метода допилить запросы и убрать при заходе от клиента кнопки со страниц
This commit is contained in:
Programmist73 2023-05-16 13:57:35 +04:00
parent 74625c1a88
commit fef50dbb5c
11 changed files with 231 additions and 146 deletions

View File

@ -4,6 +4,9 @@ import '../styles/App.css';
import LevelList from './items/Level/LevelList';
import './AddLevel.css';
const hostURL = "http://localhost:8080";
const host = hostURL + "/api/1.0/level";
//компонент для просмотра, создания и удаления уровней
const AddLevel = () => {
const [levelItems, setLevelItems] = useState([]);
@ -13,35 +16,50 @@ const AddLevel = () => {
//загрузка всех имеющихся уровней при старте
useEffect(() => {
console.log('Обращение к БД');
axios.get('http://localhost:8080/level/')
.then((responce) => {
console.log(responce.data);
setLevelItems(responce.data)
})
getLevels();
}, [])
const getTokenForHeader = function () {
return "Bearer " + localStorage.getItem("token");
}
//загрузка всех имеющихся уровней при старте
const getLevels = async function () {
const requestParams = {
method: "GET",
headers: {
"Authorization": getTokenForHeader(),
}
};
const requestUrl = host + `/getLevels`;
const response = await fetch(requestUrl, requestParams);
const data = await response.json();
console.log(data);
setLevelItems(data);
}
//обновить список уровней
function CheckArray(){
console.log('Обращение к БД');
axios.get('http://localhost:8080/level/')
.then((responce) => {
console.log(responce.data);
setLevelItems(responce.data)
})
getLevels();
}
//добавление нового уровня
function addNewLevel(){
const addNewLevel = async function (){
if(level.level === ''){
return;
}
else {
axios.post('http://localhost:8080/level/?Level=' + parseInt(level.level, 10))
.then((response) => {
CheckArray();
setLevel({level: ''});
});
const requestParams = {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": getTokenForHeader(),
}
};
const requestUrl = host + `/?Level=${level.level}`;
const response = await fetch(requestUrl, requestParams);
getLevels();
setLevel({level: ''});
}
}

View File

@ -4,6 +4,9 @@ import '../styles/App.css';
import TankList from './items/Tank/TankList';
import './AddTank.css';
const hostURL = "http://localhost:8080";
const host = hostURL + "/api/1.0/";
const AddTank = () => {
const [tankItems, setTankItems] = useState([]);
@ -23,34 +26,66 @@ const AddTank = () => {
const [fileByte, setFileByte] = useState(null);
const inputRef = useRef();
//загрузка всех имеющихся танков, а также уровней и наций при старте
const getTokenForHeader = function () {
return "Bearer " + localStorage.getItem("token");
}
//загрузка всеГо необходимого при старте
useEffect(() => {
console.log('Обращение к БД');
axios.get('http://localhost:8080/tank/')
.then((responce) => {
console.log(responce.data);
setTankItems(responce.data)
});
axios.get('http://localhost:8080/level/')
.then((responce) => {
console.log(responce.data);
setLevelItems(responce.data)
});
axios.get('http://localhost:8080/nation/')
.then((responce) => {
console.log(responce.data);
setNationItems(responce.data)
});
getTanks();
getLevels();
getNations();
}, [])
//загрузка всех имеющихся танков, а также уровней и наций при старте
const getTanks = async function () {
const requestParams = {
method: "GET",
headers: {
"Authorization": getTokenForHeader(),
}
};
const requestUrl = host + `tank/`;
const response = await fetch(requestUrl, requestParams);
const data = await response.json();
console.log(data);
setTankItems(data);
}
const getNations = async function () {
const requestParams = {
method: "GET",
headers: {
"Authorization": getTokenForHeader(),
}
};
const requestUrl = host + `nation/getNations`;
const response = await fetch(requestUrl, requestParams);
const data = await response.json();
console.log(data);
setNationItems(data);
}
//загрузка всех имеющихся уровней при старте
const getLevels = async function () {
const requestParams = {
method: "GET",
headers: {
"Authorization": getTokenForHeader(),
}
};
const requestUrl = host + `level/getLevels`;
const response = await fetch(requestUrl, requestParams);
const data = await response.json();
console.log(data);
setLevelItems(data);
}
//обновить список танков
function CheckArray(){
console.log('Обращение к БД');
axios.get('http://localhost:8080/tank/')
.then((responce) => {
console.log(responce.data);
setTankItems(responce.data)
})
getTanks();
getLevels();
getNations();
}
//добавление нового танка
@ -59,37 +94,19 @@ const AddTank = () => {
console.log(tankCost);
console.log(chooiceNation);
console.log(chooiceLevel);
//console.log(imageURL);
//const header = new Headers({ "Access-Control-Allow-Origin": "*" });
axios.post("http://localhost:8080/tank/?firstName=" + tankName.tankName +
"&id=" + chooiceNation.id + "&nationId=" + chooiceNation + "&levelId=" + chooiceLevel +
"&cost=" + tankCost.tankCost)
.then((response) => {
console.log("Успешное добавление");
console.log(response.data);
CheckArray();
setTankCost({tankCost: ''});
setTankName({tankName: ''});
});
//}*/
}
//хранит картинку для танка
const [imageURL, setImageURL] = useState();
const fileReader = new FileReader();
fileReader.onloadend = () => {
const tempval = fileReader.result
setImageURL(tempval);
};
function handleOnChange(event) {
event.preventDefault();
const file = event.target.files[0];
fileReader.readAsDataURL(file);
const requestParams = {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": getTokenForHeader(),
}
};
const requestUrl = host + `tank/create/?firstName=${tankName.tankName}&nationId=${chooiceNation}&levelId=${chooiceLevel}&cost=${tankCost.tankCost}`;
const response = await fetch(requestUrl, requestParams);
CheckArray();
setTankCost({tankCost: ''});
setTankName({tankName: ''});
}
const getChoiceNation = (newId) => {
@ -100,20 +117,6 @@ const AddTank = () => {
setChooiceLevel(levelItems[newId - 1].id);
}
//для добавления картинок
/*<p style={{fontWeight: "900", marginTop: "10px"}}>
Выберите изображение:
<input className="add-tank-input" id="formFileSm" type="file"
accept="image/jpeg, image/png, image/jpg"
value=''
style={{marginTop: "10px"}}
//onChange={e => setTank({tankImage: e.target.value})}
//onChange={() => setTank({tankImage: inputRef.current.files[0]})}
onChange={handleOnChange}
//ref={inputRef}
/>
</p>*/
//добавили условную отрисовку
return(
<div>

View File

@ -19,12 +19,12 @@ const ModalClient = ({data, visible, setVisible}) => {
const [tankItems, setTankItems] = useState([]);
useEffect(() => {
console.log('Обращение к БД');
/*console.log('Обращение к БД');
axios.get('http://localhost:8080/tank/')
.then((responce) => {
console.log(responce.data);
setTankItems(responce.data)
});
});*/
}, [])
//для контроля видимости модалки
@ -37,12 +37,12 @@ const ModalClient = ({data, visible, setVisible}) => {
//добавление нового уровня
function updateLevel(){
axios.put('http://localhost:8080/client/' + data.id + '?login='
/*axios.put('http://localhost:8080/client/' + data.id + '?login='
+ clientNickName + '&email=' + clientEmail + '&password=' + clientPassword + + '&balance=' + clientBalance + '&tankId=' + clientTank)
.then((response) => {
console.log("Обновление клиента с id " + data.id)
});
setVisible(false);
setVisible(false);*/
}
const getChoiceNation = (newId) => {

View File

@ -3,6 +3,9 @@ import axios from 'axios';
import './LevelItem.css';
import ModalLevel from './ModalLevel';
const hostURL = "http://localhost:8080";
const host = hostURL + "/api/1.0/level";
//отвечает за отдельно взятый уровень (вывод карточки с ним)
const LevelItem = (data) => {
@ -11,11 +14,20 @@ const LevelItem = (data) => {
//состояние для контроля вызова модального окна
const[modal, setModal] = useState(false);
function deleteLevel(){
axios.delete('http://localhost:8080/level/' + data.levelItem.id)
.then((response) => {
console.log("Удаление уровня с id " + data.levelItem.id)
});
const getTokenForHeader = function () {
return "Bearer " + localStorage.getItem("token");
}
const deleteLevel = async function (id) {
const requestParams = {
method: "DELETE",
headers: {
"Content-Type": "application/json",
"Authorization": getTokenForHeader(),
}
};
const requestUrl = host + `/${id}`;
await fetch(requestUrl, requestParams);
}
return (
@ -29,7 +41,7 @@ const LevelItem = (data) => {
Редактировать
</button>
<button className="level-button" type="button"
onClick={deleteLevel}
onClick={event => deleteLevel(data.levelItem.id)}
>
Удалить
</button>

View File

@ -3,6 +3,9 @@ import axios from 'axios';
import cl from './ModalLevel.module.css';
import '../../AddLevel.css';
const hostURL = "http://localhost:8080";
const host = hostURL + "/api/1.0/level";
const ModalLevel = ({data, visible, setVisible}) => {
//для обновления уровня
@ -16,13 +19,23 @@ const ModalLevel = ({data, visible, setVisible}) => {
rootClasses.push(cl.active);
}
const getTokenForHeader = function () {
return "Bearer " + localStorage.getItem("token");
}
//добавление нового уровня
function updateLevel(){
setLevel()
axios.put('http://localhost:8080/level/' + data.id + '?Level=' + level)
.then((response) => {
console.log("Обновление уровня с id " + data.id)
});
const updateLevel = async function () {
const requestParams = {
method: "PUT",
headers: {
"Content-Type": "application/json",
"Authorization": getTokenForHeader(),
}
};
console.log(level);
const requestUrl = host + `/${data.id}?Level=${level}`;
const response = await fetch(requestUrl, requestParams);
console.log("Обновление успешно!")
setVisible(false);
}
@ -37,7 +50,7 @@ const ModalLevel = ({data, visible, setVisible}) => {
<button
className={cl.modalButton}
type="button"
onClick={updateLevel}
onClick={event => updateLevel()}
>
Сохранить
</button>

View File

@ -24,17 +24,7 @@ const ModalNation = ({data, visible, setVisible}) => {
return "Bearer " + localStorage.getItem("token");
}
//добавление новой нации
/*function updateLevel(){
setNation()
axios.put('http://localhost:8080/nation/' + data.id + '?nation=' + nation + '&tankId=' + nullId)
.then((response) => {
console.log("Обновление нации с id " + data.id)
});
setVisible(false);
}*/
const updateLevel = async function () {
const updateNation = async function () {
const requestParams = {
method: "PUT",
headers: {
@ -45,6 +35,7 @@ const ModalNation = ({data, visible, setVisible}) => {
const requestUrl = host + `/${data.id}?nation=${nation}&tankId=${nullId}`;
const response = await fetch(requestUrl, requestParams);
console.log("Обновление успешно!")
setVisible(false);
}
return (
@ -58,7 +49,7 @@ const ModalNation = ({data, visible, setVisible}) => {
<button
className={cl.modalButton}
type="button"
onClick={event => updateLevel()}
onClick={event => updateNation()}
>
Сохранить
</button>

View File

@ -13,7 +13,7 @@ const ModalTankNation = ({data, visible, setVisible}) => {
//загрузка всех имеющихся танков, а также уровней и наций при старте
useEffect(() => {
console.log("Загрузка МОДАЛКИ №1")
console.log("Загрузка МОДАЛКИ")
console.log(nation);
}, [])

View File

@ -3,6 +3,9 @@ import axios from 'axios';
import cl from './ModalTank.module.css';
import '../../AddTank.css';
const hostURL = "http://localhost:8080";
const host = hostURL + "/api/1.0/";
const ModalTank = ({data, visible, setVisible}) => {
//для обновления танка
const [tankName, setTankName] = useState(data.name);
@ -17,20 +20,6 @@ const ModalTank = ({data, visible, setVisible}) => {
const [levelItems, setLevelItems] = useState([]);
//загрузка всех имеющихся танков, а также уровней и наций при старте
useEffect(() => {
axios.get('http://localhost:8080/level/')
.then((responce) => {
console.log(responce.data);
setLevelItems(responce.data)
});
axios.get('http://localhost:8080/nation/')
.then((responce) => {
console.log(responce.data);
setNationItems(responce.data)
});
}, [])
//для контроля видимости модалки
const rootClasses = [cl.myModal];
@ -39,14 +28,58 @@ const ModalTank = ({data, visible, setVisible}) => {
rootClasses.push(cl.active);
}
//добавление нового танка
function updateLevel(){
setTankName()
axios.put('http://localhost:8080/tank/' + data.id + '?firstName=' + tankName + '&nationId='
+ chooiceNation + '&levelId=' + chooiceLevel + '&cost=' + tankCost)
.then((response) => {
console.log("Обновление танка с id " + data.id)
});
//загрузка всего необходимого при старте
useEffect(() => {
getLevels();
getNations();
}, [])
const getTokenForHeader = function () {
return "Bearer " + localStorage.getItem("token");
}
const getNations = async function () {
const requestParams = {
method: "GET",
headers: {
"Authorization": getTokenForHeader(),
}
};
const requestUrl = host + `nation/getNations`;
const response = await fetch(requestUrl, requestParams);
const data = await response.json();
console.log(data);
setNationItems(data);
}
//загрузка всех имеющихся уровней при старте
const getLevels = async function () {
const requestParams = {
method: "GET",
headers: {
"Authorization": getTokenForHeader(),
}
};
const requestUrl = host + `level/getLevels`;
const response = await fetch(requestUrl, requestParams);
const data = await response.json();
console.log(data);
setLevelItems(data);
}
const updateTank = async function () {
const requestParams = {
method: "PUT",
headers: {
"Content-Type": "application/json",
"Authorization": getTokenForHeader(),
}
};
console.log(data);
console.log(chooiceNation);
const requestUrl = host + `tank/${data.id}?firstName=${tankName}&nationId=${chooiceNation}&levelId=${chooiceLevel}&cost=${tankCost}`;
const response = await fetch(requestUrl, requestParams);
console.log("Обновление успешно!")
setVisible(false);
}
@ -113,7 +146,7 @@ const ModalTank = ({data, visible, setVisible}) => {
<button
className={cl.modalButton}
type="button"
onClick={updateLevel}
onClick={event => updateTank()}
>
Сохранить
</button>

View File

@ -3,6 +3,9 @@ import axios from 'axios';
import './TankItem.css';
import ModalTank from './ModalTank';
const hostURL = "http://localhost:8080";
const host = hostURL + "/api/1.0/tank";
const TankItem = (data) => {
const [tank, setTank] = useState(null);
@ -10,11 +13,20 @@ const TankItem = (data) => {
//состояние для контроля вызова модального окна
const[modal, setModal] = useState(false);
function deleteTank(){
axios.delete('http://localhost:8080/tank/' + data.tankItem.id)
.then((response) => {
console.log("Удаление танка с id " + data.tankItem.id)
});
const getTokenForHeader = function () {
return "Bearer " + localStorage.getItem("token");
}
const deleteTank = async function (id) {
const requestParams = {
method: "DELETE",
headers: {
"Content-Type": "application/json",
"Authorization": getTokenForHeader(),
}
};
const requestUrl = host + `/${id}`;
await fetch(requestUrl, requestParams);
}
return (
@ -31,7 +43,7 @@ const TankItem = (data) => {
Редактировать
</button>
<button className="tank-button" type="button"
onClick={deleteTank}
onClick={event => deleteTank(data.tankItem.id)}
>
Удалить
</button>

View File

@ -1,9 +1,11 @@
package premium_store.controller.controller;
import org.springframework.security.access.annotation.Secured;
import org.springframework.web.bind.annotation.*;
import premium_store.configuration.OpenAPI30Configuration;
import premium_store.configuration.WebConfiguration;
import premium_store.controller.DTO.TankDTO;
import premium_store.model.UserRole;
import premium_store.service.NationService;
import premium_store.service.TankLevelService;
import premium_store.service.TankService;
@ -47,7 +49,8 @@ public class TankController {
.toList();
}
@PostMapping("/")
@PostMapping("/create")
@Secured({UserRole.AsString.ADMIN})
public TankDTO createTank(@RequestParam("firstName") String name,
@RequestParam("nationId") Long nationId,
@RequestParam("levelId") Long tankLevelId,

View File

@ -27,7 +27,7 @@ public class TankLevelController {
}
//с помощью Java Stream преобразуем набор пришедших данных в объекты StudentDto
@GetMapping("/")
@GetMapping("/getLevels")
public List<LevelDTO> getLevels() {
return tankLevelService.findAllLevels().stream()
.map(LevelDTO::new)