Files
survey-beta/survey-beta/Services/SurveyServices.cs
majed adel 3aabe1a367 PATCH
Refactored DTOs to use AutoMapper instead of manual mapping and made some additional improvements and fixes.
Added : GetAllSurveys&DeleteUser.
2025-02-07 06:40:57 -08:00

103 lines
3.0 KiB
C#

using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using survey_beta.DataBaseContext;
using survey_beta.DTOs.Create;
using survey_beta.DTOs.Update;
using survey_beta.DTOs.Response;
using survey_beta.Models;
using AutoMapper;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System;
using survey_beta.DTOs.Default;
public class SurveyService
{
private readonly AppDbContext _context;
private readonly IMapper _mapper;
private readonly ResponsesService _responsesService;
public SurveyService(AppDbContext context, IMapper mapper, ResponsesService responsesService)
{
_context = context;
_mapper = mapper;
_responsesService = responsesService;
}
public async Task<List<SurveyDto>> GetAllSurveysAsync(string id = null)
{
IQueryable<Survey> query = _context.Surveys.Include(s => s.Questions);
if (!string.IsNullOrEmpty(id))
{
query = query.Where(s => s.Id == id);
}
var surveys = await query.ToListAsync();
return _mapper.Map<List<SurveyDto>>(surveys);
}
public async Task<SurveyDto> GetSurveyByIdAsync(string id)
{
var survey = await _context.Surveys.AsNoTracking()
.Include(s => s.Questions)
.ThenInclude(q => q.Choices)
.FirstOrDefaultAsync(s => s.Id == id);
return survey == null ? null : _mapper.Map<SurveyDto>(survey);
}
public async Task<SurveyDto> CreateSurveyAsync(CreateSurveyDto request, string userId)
{
var survey = _mapper.Map<Survey>(request);
survey.Id = Guid.NewGuid().ToString();
survey.AuthorId = userId;
_context.Surveys.Add(survey);
await _context.SaveChangesAsync();
return _mapper.Map<SurveyDto>(survey);
}
public async Task<bool> UpdateSurveyAsync(UpdateSurveyDto request)
{
var survey = await _context.Surveys.FindAsync(request.Id);
if (survey == null) return false;
_mapper.Map(request, survey);
await _context.SaveChangesAsync();
return true;
}
public async Task<bool> PublishSurveyAsync(string id)
{
var survey = await _context.Surveys.FindAsync(id);
if (survey == null) return false;
survey.IsPublished = true;
await _context.SaveChangesAsync();
return true;
}
public async Task<bool> UnpublishSurveyAsync(string id)
{
var survey = await _context.Surveys.FindAsync(id);
if (survey == null) return false;
survey.IsPublished = false;
await _context.SaveChangesAsync();
return true;
}
public async Task<bool> DeleteSurveyAsync(string id)
{
var survey = await _context.Surveys.AsNoTracking()
.Include(s => s.Questions)
.ThenInclude(q => q.Choices)
.FirstOrDefaultAsync(s => s.Id == id);
if (survey == null) return false;
_context.Surveys.Remove(survey);
await _context.SaveChangesAsync();
return true;
}
}