survey-webapp/SurveyBackend/SurveyBackend.Services/Services/SurveyService.cs
shept 658e25dd57 Fix deletion methods to directly use ID in services
Updated QuestionService and SurveyService to pass the ID directly to the repository's DeleteAsync method. This improves clarity and ensures consistency in how deletions are handled across both services.

Updated SurveyLib
2025-05-20 16:09:27 +05:00

69 lines
No EOL
1.9 KiB
C#

using SurveyBackend.Core.Contexts;
using SurveyBackend.Core.Repositories;
using SurveyBackend.Services.Exceptions;
using SurveyLib.Core.Models;
using SurveyLib.Core.Repositories;
using SurveyLib.Core.Services;
namespace SurveyBackend.Services.Services;
public class SurveyService : ISurveyService
{
private readonly ISurveyRepository _surveyRepository;
private readonly IUserContext _userContext;
public SurveyService(ISurveyRepository surveyRepository, IUserContext userContext)
{
_surveyRepository = surveyRepository;
_userContext = userContext;
}
public async Task AddSurveyAsync(Survey survey)
{
await _surveyRepository.AddAsync(survey);
}
public async Task UpdateSurveyAsync(Survey survey)
{
if (survey.CreatedBy != _userContext.UserId)
throw new UnauthorizedException("You are not authorized to update this survey.");
await _surveyRepository.UpdateAsync(survey);
}
public async Task DeleteSurveyAsync(int id)
{
var survey = await _surveyRepository.GetByIdAsync(id);
if (survey is null)
{
throw new NotFoundException("Survey not found");
}
if (survey.CreatedBy != _userContext.UserId)
{
throw new UnauthorizedException("You are not authorized to delete this survey.");
}
await _surveyRepository.DeleteAsync(id);
}
public async Task<IEnumerable<Survey>> GetSurveysAsync()
{
return await _surveyRepository.GetAllAsync();
}
public async Task<Survey> GetSurveyAsync(int id)
{
var survey = await _surveyRepository.GetByIdAsync(id);
if (survey is null)
{
throw new NotFoundException("Survey not found");
}
return survey;
}
public async Task<IEnumerable<Survey>> GetSurveysByUserIdAsync(int userId)
{
return await _surveyRepository.GetSurveysByUserIdAsync(userId);
}
}