/// <summary> /// Will request the data and invoke the callback with the result /// </summary> /// <param name="request">Request data for the request</param> /// <param name="callback">Callback to be invoked after the request</param> public static void Request(CurrencyRequestData request, System.Action <CurrencyRequestData> callback) { string countryRequest; if (request.CurrencyOneCode == "EUR" || string.IsNullOrEmpty(request.CurrencyTwoCode)) { countryRequest = request.CurrencyTwoCode; } else if (request.CurrencyTwoCode == "EUR" || string.IsNullOrEmpty(request.CurrencyOneCode)) { countryRequest = request.CurrencyOneCode; } else { countryRequest = string.Format("{0},{1}", request.CurrencyOneCode, request.CurrencyTwoCode); } string url; if (string.IsNullOrEmpty(request.Date)) { url = string.Format(_apiRouteLastest, countryRequest); } else { url = string.Format(_apiRoute, request.Date, request.Date, countryRequest); } Request(m_ApiClient, url, request, callback); }
/// <summary> /// Will parse the json response of API request and return a ResultData /// </summary> /// <param name="json">json response of API request</param> /// <param name="request">request used to perform the request</param> /// <returns>ResultData is returned containing the returned informations</returns> public static ResultData ParseFromJson(string json, CurrencyRequestData request) { ResultData result = null; try { var datas = SimpleJSON.JSON.Parse(json); if (datas == null) { Debug.LogWarning("Parse json data is null"); return(null); } var currencies = GetDesiredDateData(datas, request.Date); if (currencies == null) { Debug.LogWarning("Parse json currencies at the date specified is null"); return(null); } result = new ResultData() { CurrencyOne = currencies[request.CurrencyOneCode] ?? -1, CurrencyTwo = currencies[request.CurrencyTwoCode] ?? -1 }; if (request.CurrencyOneCode == "EUR") { result.CurrencyOne = 1; } else if (request.CurrencyTwoCode == "EUR") { result.CurrencyTwo = 1; } } catch (System.Exception e) { Debug.LogError("An exception occured " + e.Message); } return(result); }
private static async void Request(HttpClient client, string url, CurrencyRequestData request, System.Action <CurrencyRequestData> callback) { using (var response = await client.GetAsync(url)) { if (!response.IsSuccessStatusCode) { request.isError = true; request.errorMessage = string.Format("Error ({0})", response.StatusCode); } else { string json = await response.Content.ReadAsStringAsync(); JsonDataConverter.ResultData data = JsonDataConverter.ParseFromJson(json, request); if (data == null) { request.isError = true; request.errorMessage = "Failed to parse data from API"; } else { request.CurrencyOneResult = data.CurrencyOne; request.CurrencyTwoResult = data.CurrencyTwo; if (request.CurrencyOneResult <= 0 || request.CurrencyTwoResult <= 0) { request.isError = true; request.errorMessage = "Invalid value (<= 0)"; } } } callback?.Invoke(request); } }