using System.Text; using AutoMapper; using MediatR; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; using ExpenseTracker.Application.Common.Interfaces.Repositories; using ExpenseTracker.Application.Common.Interfaces.Services; using ExpenseTracker.Domain.Entities; using ExpenseTracker.Domain.Enums; namespace ExpenseTracker.Application.Accounts.Queries.Export.Json.Many; public class ExportJsonAccountsQueryHandler : IRequestHandler { private readonly IMapper _mapper; private readonly ISessionUserService _sessionUserService; private readonly IAccountRepository _accountRepository; private readonly ITransactionRepository _transactionRepository; public ExportJsonAccountsQueryHandler( IMapper mapper, ISessionUserService sessionUserService, IAccountRepository repository, ITransactionRepository transactionRepository) { _mapper = mapper; _sessionUserService = sessionUserService; _accountRepository = repository; _transactionRepository = transactionRepository; } public async Task Handle(ExportJsonAccountsQuery request, CancellationToken cancellationToken) { var entities = _accountRepository.Queryable .Where(e => e.UserId == _sessionUserService.Id) .GroupJoin( _transactionRepository.Queryable, b => b.Id, t => t.AccountId, (account, transactions) => new Account { Id = account.Id, Name = account.Name, Description = account.Description, Currency = account.Currency, UserId = account.UserId, Transactions = transactions } ) .ToArray(); var entityDtos = _mapper.ProjectTo(entities.AsQueryable()); var jsonSerializerSettings = new JsonSerializerSettings() { ContractResolver = new CamelCasePropertyNamesContractResolver() }; var json = JsonConvert.SerializeObject(entityDtos, jsonSerializerSettings); using (var memoryStream = new MemoryStream()) { using (var streamWriter = new StreamWriter(memoryStream, Encoding.UTF8)) { await streamWriter.WriteAsync(json); await streamWriter.FlushAsync(); } return memoryStream.ToArray(); } } }