DamageAssessment_Backend/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Providers/AnswerServiceProvider.cs

82 lines
3.1 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;
using System.Net.Http.Headers;
using System;
namespace DamageAssesment.Api.SurveyResponses.Providers
{
public class AnswerServiceProvider : ServiceProviderBase, IAnswerServiceProvider
{
public AnswerServiceProvider(IConfiguration configuration, IHttpUtil httpUtil, ILogger<AnswerServiceProvider> logger) : base(configuration, httpUtil, logger, "/api/Answers", configuration.GetValue<string>("EndPointSettings:AnswerUrlBase"))
{
}
public async Task<List<Answer>> getAnswersAsync()
{
try
{
var url = urlBase + ressource;
var responseJsonString = await httpUtil.SendAsync(HttpMethod.Get, url, null);
var answers = JsonConvert.DeserializeObject<List<Answer>>(responseJsonString);
if (answers == null || !answers.Any())
return new List<Answer>();
else return answers;
}
catch (Exception ex)
{
logger?.LogError($"Exception Found : {ex.Message} - Ref: AnswerServiceProvider.getAnswersAsync()");
return new List<Answer>();
}
}
public async Task<List<Answer>> GetAnswersByResponseIdAsync(int responseId)
{
try
{
var url = urlBase + "/api/AnswersByResponse/" + responseId;
var responseJsonString = await httpUtil.SendAsync(HttpMethod.Get, url, null);
var answers = JsonConvert.DeserializeObject<List<Answer>>(responseJsonString);
if (answers == null || !answers.Any())
return new List<Answer>();
else return answers;
}
catch (Exception ex)
{
logger?.LogError($"Exception Found : {ex.Message} - Ref: AnswerServiceProvider.GetAnswersByResponseId()");
return new List<Answer>();
}
}
public async Task<Answer> PostAnswersAsync(Answer answer)
{
try
{
var url = urlBase + ressource;
var requestJsonString = JsonConvert.SerializeObject(answer);
var responseJsonString = await httpUtil.SendAsync(HttpMethod.Post, url, requestJsonString);
var answers = JsonConvert.DeserializeObject<Answer>(responseJsonString);
if (answers == null)
{
logger?.LogError($"Answers 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;
}
}
}
}