73 lines
2.4 KiB
C#
73 lines
2.4 KiB
C#
using IO.Swagger.Models.db;
|
|
using IO.Swagger.Models.RequestDto;
|
|
using IO.Swagger.Services;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace IO.Swagger.Repositories
|
|
{
|
|
/// <summary>
|
|
/// The EF implementation of this interface
|
|
/// </summary>
|
|
/// <seealso cref="ICurrencyRepository" />
|
|
public class CurrencyRepository : ICurrencyRepository
|
|
{
|
|
private readonly BankDbContext context;
|
|
|
|
/// <summary>
|
|
/// Initializes a new instance of the <see cref="CurrencyRepository"/> class.
|
|
/// </summary>
|
|
/// <param name="context">The db context.</param>
|
|
/// <exception cref="ArgumentNullException">context</exception>
|
|
public CurrencyRepository(BankDbContext context)
|
|
{
|
|
this.context = context ?? throw new ArgumentNullException(nameof(context));
|
|
}
|
|
|
|
/// <inheritdoc/>
|
|
public async Task<List<Currency>> GetAllCurrencies()
|
|
{
|
|
return await context.Currencies.Include(c => c.User).Include(c => c.Transactions).ToListAsync();
|
|
}
|
|
|
|
/// <inheritdoc/>
|
|
public async Task<bool> CreateCurrency(CurrencyCreateBody request, int userId)
|
|
{
|
|
request.Symbol = request.Symbol.Trim();
|
|
request.Name = request.Name.Trim();
|
|
if (await context.Currencies.AnyAsync(c => c.Symbol == request.Symbol || c.Name.ToLower() == request.Name.ToLower()))
|
|
return false;
|
|
|
|
await context.Currencies.AddAsync(new Currency
|
|
{
|
|
Name = request.Name,
|
|
Symbol = request.Symbol,
|
|
UserId = userId
|
|
});
|
|
|
|
return await context.SaveChangesAsync() > 0;
|
|
}
|
|
|
|
/// <inheritdoc/>
|
|
public async Task<bool> MintCurrency(CurrencyMintBody request, int userId)
|
|
{
|
|
var existsAndIsOwner = await context.Currencies.AnyAsync(c => c.CurrencyId == request.CurrencyId && c.UserId == userId);
|
|
if (!existsAndIsOwner)
|
|
return false;
|
|
|
|
await context.Transactions.AddAsync(new Transaction
|
|
{
|
|
Amount = request.Amount,
|
|
CurrencyId = request.CurrencyId,
|
|
ToUserId = userId,
|
|
FromUserId = userId,
|
|
Memo = "Minting"
|
|
});
|
|
|
|
return await context.SaveChangesAsync() > 0;
|
|
}
|
|
}
|
|
}
|