-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.html
211 lines (187 loc) · 6.12 KB
/
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<title>Хранилище данных</title>
</head>
<style>
/* Сброс стилей браузера */
html,
body {
margin: 0;
padding: 0
}
/* Расположение двУх блоков рядом по горизонтали */
body,
.container {
height: 100%;
width: 100%;
display: flex;
justify-content: space-around;
align-items: center;
}
.for-read,
.for-write {
width: 40%;
}
.alert-message{
color:red;
align-items: center;
position: absolute;
top:30%;
left:5%;
padding-top: 5%;
}
.alert-hidden{
visibility: hidden;
}
</style>
<body>
<div class="container">
<form class="for-write" id="write-form">
<div>
<label for="text-input">Ввод</label>
<input id="text-input" type="text">
</div>
<div><label for="file-input">Выбор файла</label>
<input id="file-input" type="file">
<input type="submit">
</div>
<div id="save-result"></div>
</form>
<div class="for-read">
<h2>Просмотр по категориям</h2>
<ul id="categories">
</ul>
<h3>Сохраненный объект</h3>
<pre id="saved-object"></pre>
</div>
<div id="error" class="alert-message">
</div>
</div>
</body>
<script>
const API = "https://itis2021archserv.herokuapp.com/api"
/**
* Фабрика методов апишки
* @param method HTTP метод
* @param endpoint
*/
function makeApiFunction(method, endpoint) {
return async function (data = null) {
try {
const response = await fetch(`${API}/${endpoint}`, {
method: method,
body: data != null ? JSON.stringify(data) : undefined,
headers: {
"Content-Type": "application/json",
},
})
console.log(response);
if (response.ok)
return await response.json()
if(response.status == 500){
document.getElementById("error").innerText = "Невозможно получить данные, ошибка сервера";
document.getElementById("error").className='alert-message';
}
} catch (error) {
console.log(error.message);
}
}
}
const api = {
user_input: makeApiFunction("POST", "user_input/"),
sendFile: async function (file) {
const formData = new FormData()
formData.append("file", file)
const response = await fetch(`${API}/file/`, {
method: "POST",
body: formData,
})
if(response.ok){
return await response.json()
}
if(response.status == 400 ){
document.getElementById("error").innerText = "Запись такой категории уже существует";
document.getElementById("error").className='alert-message';
}
},
getCategories: makeApiFunction("GET", "category/"),
getData: function (id) {
const response = fetch(`${API}/data/${id}`, {
method: "GET",
})
if(response.status == 400 ){
document.getElementById("error").innerText = "Файл уже был получен";
document.getElementById("error").className='alert-message';
}
if(response.status == 500 ){
document.getElementById("error").innerText = "Невозможно получить файл, ошибка сервера";
document.getElementById("error").className='alert-message';
}
},
}
/**
* Отправляет строку данных на сервер, проверяя длину, и обновляет список категорий
*/
async function sendForm(event) {
// Знак браузеру, что не надо ничего делать, мы сами
event.preventDefault()
const inputElement = document.getElementById("text-input")
const input = inputElement.value
let saveResult
if (input.length === 0) {
const fileInputElement = document.getElementById("file-input")
if (fileInputElement.files.length === 0) return
saveResult = await api.sendFile(fileInputElement.files[0])
} else {
saveResult = await api.user_input({ data: input })
inputElement.value = ""
}
if (saveResult.category != null) showSaveResult(saveResult.category)
await updateCategories()
if (document.getElementById("error")){
document.getElementById("error").className='alert-hidden';
}
}
function showSaveResult(objectType) {
const saveResultElement = document.getElementById("save-result")
saveResultElement.innerText = `Объект сохранен под категорией ${objectType}`
setTimeout(function () {
saveResultElement.innerText = ""
}, 3500)
}
/**
* Запрашивает категории с сервера и рендерит их в список
*/
async function updateCategories() {
const categoriesElement = document.getElementById("categories")
const categories = await api.getCategories()
categoriesElement.innerHTML = ""
for (let category of categories) {
const newElement = document.createElement("li")
newElement.innerText = category.name
newElement.dataset.id = category.id
newElement.onclick = onCategoryClick
categoriesElement.appendChild(newElement)
}
if (document.getElementById("error")){
document.getElementById("error").className='alert-hidden';
}
}
/**
* Функция, вызывающаяся по клику на категорию
* Получает данные и отображает их в виде текста
*/
async function onCategoryClick(event) {
const categoryId = event.target.dataset.id
const response = await api.getData(categoryId)
const savedObject = await response.text()
document.getElementById("saved-object").innerText = savedObject
await updateCategories()
}
document.getElementById("write-form").onsubmit = sendForm
updateCategories()
setInterval(updateCategories, 5000)
</script>
</html>