DamageAssessment_Backend/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Providers/AnswerServiceProvider.cs
2023-08-15 23:52:30 -04:00

88 lines
3.6 KiB
C#

using DamageAssesment.Api.SurveyResponses.Bases;
using DamageAssesment.Api.SurveyResponses.Db;
using DamageAssesment.Api.SurveyResponses.Interfaces;
using DamageAssesment.Api.SurveyResponses.Models;
using Newtonsoft.Json;
using System.Data.Common;
using System.Security.Cryptography;
using System.Text.Json.Nodes;
using System.Text;
namespace DamageAssesment.Api.SurveyResponses.Providers
{
public class AnswerServiceProvider : ServiceProviderBase, IAnswerServiceProvider
{
public AnswerServiceProvider(IConfiguration configuration, HttpClient httpClient, ILogger<AnswerServiceProvider> logger, IRegionServiceProvider regionServiceProvider, ILocationServiceProvider locationServiceProvider) : base(configuration, httpClient, logger, "/api/Answers", configuration.GetValue<string>("EndPointSettings:AnswerUrlBase"))
{
}
public async Task<List<Answer>> getAnswersAsync()
{
try
{
httpClient.BaseAddress = new Uri(urlBase);
var response = await httpClient.GetAsync(ressource);
response.EnsureSuccessStatusCode();
var responseString = await response.Content.ReadAsStringAsync();
var answers = JsonConvert.DeserializeObject<List<Answer>>(responseString);
if (answers == null || !answers.Any())
return null;
else return answers;
}
catch (Exception ex)
{
logger?.LogError($"Exception Found : {ex.Message} - Ref: AnswerServiceProvider.getAnswersAsync()");
return null;
}
}
public async Task<List<Answer>> GetAnswersByResponseIdAsync(int responseId)
{
try
{
httpClient.BaseAddress = new Uri(urlBase);
var response = await httpClient.GetAsync("/api/AnswersByResponse/"+ responseId);
response.EnsureSuccessStatusCode();
var responseString = await response.Content.ReadAsStringAsync();
var answers = JsonConvert.DeserializeObject<List<Answer>>(responseString);
if (answers == null || !answers.Any())
return null;
else return answers;
}
catch (Exception ex)
{
logger?.LogError($"Exception Found : {ex.Message} - Ref: AnswerServiceProvider.GetAnswersByResponseId()");
return null;
}
}
public async Task<Answer> PostAnswersAsync(Answer answer)
{
try
{
httpClient.BaseAddress = new Uri(urlBase);
var jsonObject = JsonConvert.SerializeObject(answer);
var content = new StringContent(jsonObject.ToString(), Encoding.UTF8, "application/json");
var response = await httpClient.PostAsync(ressource,content);
response.EnsureSuccessStatusCode();
var responseString = await response.Content.ReadAsStringAsync();
var answers = JsonConvert.DeserializeObject<Answer>(responseString);
if (answers == null) {
logger?.LogError($"Answer cannot be added - Ref: AnswerServiceProvider.PostAnswersAsync()");
return null;
}
else return answers;
}
catch (Exception ex)
{
logger?.LogError($"Exception Found : {ex.Message} - Ref: AnswerServiceProvider.PostAnswersAsync()");
return null;
}
}
}
}