update web requset data

This commit is contained in:
2023-07-03 19:36:02 +05:00
parent a7fc084abf
commit b6785dd862
8 changed files with 396 additions and 130 deletions
+45 -33
View File
@@ -14,14 +14,31 @@ public class Authorization : MonoBehaviour
[SerializeField] private TMP_InputField _codeInputField;
[SerializeField] private Button _codeAcceptButton;
[SerializeField] private TMP_Text _errorText;
[SerializeField] private UIInputField _inputField;
private void Start()
{
var clientData = _clientDataService.data;
if(clientData != null)
if(_clientDataService.data != null)
{
Debug.LogWarning($"данные клианта загружены: город - {clientData.city}, найдено тэгов - {clientData.games.Count}");
Debug.LogWarning($"данные клианта {_clientDataService.data.id} загружены: город - {(Cities)_clientDataService.data.city}, найдено тэгов - {_clientDataService.data.games.Count}");
UniTask.Void(async ()=>
{
Response<int> result = new Response<int>();
int counter = 0;
while(result.responseData == 0)
{
Debug.LogWarning($"ещё не все метки найдены ({counter})");
result = await _networkService.GetAsync<int>("game/find", $"id={_clientDataService.data.id}", $"game={counter}");
Debug.LogWarning(result.responseCode + "/" + result.responseData);
counter++;
await UniTask.Delay(500);
}
Debug.LogWarning($"поздравляем! Ваше место в общем зачете - {result.responseData}");
});
return;
}
@@ -46,42 +63,37 @@ public class Authorization : MonoBehaviour
private async UniTask SendCode(string inputFieldText)
{
CityUniqueCode cityUniqueCode = null;
_networkService.OnGetResponse += CheckResponseAdmin;
cityUniqueCode = await _networkService.GetAsync<CityUniqueCode>($"auth/admin/{inputFieldText}");
var resultAdmin = await _networkService.GetAsync<CityUniqueCode>($"auth/admin/{inputFieldText}");
cityUniqueCode = resultAdmin.responseData;
async void CheckResponseAdmin(int responseCode)
if(resultAdmin.responseCode == 0)
{
_networkService.OnGetResponse -= CheckResponseAdmin;
var message = "Нет соединения с сервером";
Debug.LogError(message);
_inputField.ShowErrorAsync(message).Forget();
}
else if (resultAdmin.responseCode == 404)
{
Debug.LogWarning("такого админа нет в базе. ищем город...");
if(responseCode == 0) Debug.LogError("Нет соединения с сервером");
else if (responseCode == 404)
var result = await _networkService.GetAsync<Client>($"auth/{inputFieldText}");
Debug.Log(_clientDataService.citiesTranslation[result.responseData.city]);
if(result.responseCode == 404)
{
Client client = new Client();
Debug.LogWarning("такого админа нет в базе. ищем город...");
_networkService.OnGetResponse += CheckResponse;
client = await _networkService.GetAsync<Client>($"auth/{inputFieldText}");
void CheckResponse(int responseCode)
{
_networkService.OnGetResponse -= CheckResponse;
if(responseCode == 404)
{
Debug.LogError("такого кода нет в базе");
}
else if(responseCode == 0) Debug.LogError("Нет соединения с сервером");
else if( responseCode == 200)
{
_clientDataService.data = client;
Debug.Log(client.city.ToString());
}
}
Debug.LogError(result.responseText);
_inputField.ShowErrorAsync(result.responseText).Forget();
}
else if(responseCode == 200)
else if(result.responseCode == 0) Debug.LogError("Нет соединения с сервером");
else if(result.responseCode == 200)
{
Debug.Log(cityUniqueCode.city);
_clientDataService.data = result.responseData;
Debug.Log(result.responseData.city.ToString());
}
}
else if(resultAdmin.responseCode == 200)
{
Debug.Log(cityUniqueCode.city);
}
}
}
+1 -1
View File
@@ -64,7 +64,7 @@ namespace YandexQuest.Models
{
public string id { get; set; }
public Cities city { get; set; }
public List<Games> games { get; set; }
public List<Games> games { get; set; } = new List<Games>();
public DateTime? gameFinishedDate { get; set; }
public bool isAdmin { get; set; }
}
@@ -6,6 +6,36 @@ using Newtonsoft.Json;
public class ClientDataService
{
public readonly Dictionary<Cities, string> citiesTranslation = new Dictionary<Cities, string>()
{
{ Cities.MoscowRedRose, "Москва, Красная Роза" },
{ Cities.MoscowCity, "Москва, Москва-Сити" },
{ Cities.MoscowSkolkovo, "Москва, Сколково" },
{ Cities.SaintPetersburg, "Санкт-Петербург" },
{ Cities.Yekaterinburg, "Екатеринбург" },
{ Cities.Novosibirsk, "Новосибирск" },
{ Cities.Kazan, "Казань" },
{ Cities.Innopolis, "Иннополис" },
{ Cities.RostovOnDon, "Ростов-На-Дону" },
{ Cities.NizhnyNovgorod, "Нижний Новгород" },
{ Cities.Simferopol, "Симферополь" },
{ Cities.Vladivostok, "Владивосток" },
{ Cities.Krasnodar, "Краснодар" },
{ Cities.Samara, "Самара" },
{ Cities.Chelyabinsk, "Челябинск" },
{ Cities.Perm, "Пермь" },
{ Cities.Tula, "Тула" },
{ Cities.Sochi, "Сочи" },
{ Cities.Ufa, "Уфа" },
{ Cities.Krasnoyarsk, "Красноярск" },
{ Cities.Tumen, "Тюмень" },
{ Cities.Voronezh, "Воронеж" },
{ Cities.Minsk, "Минск" },
{ Cities.Serbia, "Сербия" }
};
public Client data
{
get
+58 -36
View File
@@ -7,18 +7,25 @@ using UnityEngine.Networking;
using System.Collections.Generic;
using Cysharp.Threading.Tasks;
public struct Response<T>
{
public long responseCode { get; set; }
public string responseText { get; set; }
public T responseData { get; set; }
}
public class NetworkService
{
public event Action<int> OnGetResponse;
#if !UNITY_EDITOR
private string _apiUrl = "https://yandexquest.graff.tech/";
#else
private string _apiUrl = "http://localhost:5000/";
#endif
public async UniTask<TValue> GetAsync<TValue>(string requestString)
public async UniTask<Response<TValue>> GetAsync<TValue>(string requestString)
{
Response<TValue> responseStruct = new Response<TValue>();
using var getRequest = UnityWebRequest.Get(_apiUrl + requestString);
getRequest.SetRequestHeader("Content-type", "application/json");
UnityWebRequest operation = new UnityWebRequest();
@@ -29,27 +36,33 @@ public class NetworkService
}
catch { }
OnGetResponse?.Invoke((int)getRequest.responseCode);
responseStruct.responseCode = getRequest.responseCode;
if(getRequest.responseCode != 200)
{
return default;
responseStruct.responseText = getRequest.downloadHandler.text;
return responseStruct;
}
try
{
TValue result = JsonConvert.DeserializeObject<TValue>(operation.downloadHandler.text);
return result;
responseStruct.responseData = result;
return responseStruct;
}
catch(Exception ex)
{
Debug.LogError(ex.Message);
OnGetResponse?.Invoke(-1);
return default;
responseStruct.responseCode = -1;
responseStruct.responseText = ex.Message;
return responseStruct;
}
}
public async UniTask<TValue> GetAsync<TValue>(string requestString, params string[] query)
public async UniTask<Response<TValue>> GetAsync<TValue>(string requestString, params string[] query)
{
Response<TValue> responseStruct = new Response<TValue>();
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.Append(requestString);
stringBuilder.Append("?");
@@ -72,27 +85,31 @@ public class NetworkService
}
catch { }
OnGetResponse?.Invoke((int)getRequest.responseCode);
responseStruct.responseCode = getRequest.responseCode;
if(getRequest.responseCode != 200)
{
return default;
responseStruct.responseText = getRequest.downloadHandler.text;
return responseStruct;
}
try
{
TValue result = JsonConvert.DeserializeObject<TValue>(operation.downloadHandler.text);
return result;
responseStruct.responseData = result;
return responseStruct;
}
catch(Exception ex)
{
Debug.LogError(ex.Message);
OnGetResponse?.Invoke(-1);
return default;
responseStruct.responseCode = -1;
responseStruct.responseText = ex.Message;
return responseStruct;
}
}
public async UniTask<TValue> GetAsync<TValue>(string requestString, Dictionary<string, string> headers = null, params string[] query)
public async UniTask<Response<TValue>> GetAsync<TValue>(string requestString, Dictionary<string, string> headers = null, params string[] query)
{
Response<TValue> responseStruct = new Response<TValue>();
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.Append(requestString);
stringBuilder.Append("?");
@@ -115,31 +132,34 @@ public class NetworkService
try
{
operation = await getRequest.SendWebRequest();
OnGetResponse?.Invoke((int)operation.responseCode);
}
catch { }
OnGetResponse?.Invoke((int)getRequest.responseCode);
responseStruct.responseCode = getRequest.responseCode;
if(getRequest.responseCode != 200)
{
return default;
responseStruct.responseText = getRequest.downloadHandler.text;
return responseStruct;
}
try
{
TValue result = JsonConvert.DeserializeObject<TValue>(operation.downloadHandler.text);
return result;
responseStruct.responseData = result;
return responseStruct;
}
catch(Exception ex)
{
Debug.LogError(ex.Message);
OnGetResponse?.Invoke(-1);
responseStruct.responseCode = -1;
responseStruct.responseText = ex.Message;
return default;
}
}
public async UniTask PostAsync<TValue> (string requestString, TValue data, Dictionary<string, string> headers = null)
{
{
string sendingData = JsonConvert.SerializeObject(data);
using var postRequest = UnityWebRequest.Post(_apiUrl + requestString, sendingData);
byte[] dataBytes = new UTF8Encoding().GetBytes(sendingData);
@@ -160,12 +180,12 @@ public class NetworkService
operation = await postRequest.SendWebRequest();
}
catch { }
OnGetResponse?.Invoke((int)postRequest.responseCode);
}
public async UniTask<TResponseValue> PostAsync<TSendingValue, TResponseValue> (string requestString, TSendingValue data)
public async UniTask<Response<TResponseValue>> PostAsync<TSendingValue, TResponseValue> (string requestString, TSendingValue data)
{
Response<TResponseValue> responseStruct = new Response<TResponseValue>();
string sendingData = JsonConvert.SerializeObject(data);
using var postRequest = UnityWebRequest.Post(_apiUrl + requestString, sendingData);
byte[] dataBytes = new UTF8Encoding().GetBytes(sendingData);
@@ -181,22 +201,26 @@ public class NetworkService
}
catch { }
OnGetResponse?.Invoke((int)postRequest.responseCode);
if(postRequest.responseCode == 0)
responseStruct.responseCode = postRequest.responseCode;
if(postRequest.responseCode != 200)
{
return default;
responseStruct.responseText = postRequest.downloadHandler.text;
return responseStruct;
}
try
{
return JsonConvert.DeserializeObject<TResponseValue>(operation.downloadHandler.text);
TResponseValue result = JsonConvert.DeserializeObject<TResponseValue>(operation.downloadHandler.text);
responseStruct.responseData = result;
return responseStruct;
}
catch(Exception ex)
{
Debug.LogError(ex.Message);
OnGetResponse?.Invoke(-1);
responseStruct.responseCode = -1;
responseStruct.responseText = ex.Message;
return default;
return responseStruct;
}
}
@@ -217,7 +241,5 @@ public class NetworkService
operation = await putRequest.SendWebRequest();
}
catch { }
OnGetResponse?.Invoke((int)putRequest.responseCode);
}
}
+35
View File
@@ -0,0 +1,35 @@
using System.Collections;
using System.Collections.Generic;
using TMPro;
using DG.Tweening;
using UnityEngine;
using UnityEngine.UI;
using Cysharp.Threading.Tasks;
public class UIInputField : MonoBehaviour
{
[SerializeField] private Image _outline;
[SerializeField] private TMP_Text _text;
private TMP_InputField _inputField;
private void Start()
{
_inputField = GetComponent<TMP_InputField>();
}
public async UniTaskVoid ShowErrorAsync(string text)
{
Color startColor = _outline.color;
Color textColor = _text.color;
textColor.a = 1;
_text.text = text;
_text.DOFade(1, .25f);
await UniTask.Delay(2000);
_outline.DOColor(startColor, .25f);
_text.DOFade(0, .25f);
}
}
+11
View File
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 71868102bdcab694bad257204a24561e
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant: