69 lines
No EOL
1.9 KiB
C#
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 UnauthorizedAccessException("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 UnauthorizedAccessException("You are not authorized to delete this survey.");
|
|
}
|
|
|
|
await _surveyRepository.DeleteAsync(survey);
|
|
}
|
|
|
|
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);
|
|
}
|
|
} |