survey-webapp/SurveyBackend/SurveyBackend.Services/Services/SurveyService.cs
2025-05-31 01:34:42 +05:00

69 lines
No EOL
2 KiB
C#

using SurveyBackend.Core.Contexts;
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)
{
// TODO: проверить существование юзера
return await _surveyRepository.GetSurveysByUserIdAsync(userId);
}
}