BCards/src/BCards.Web/Repositories/UserRepository.cs
2025-06-24 23:25:02 -03:00

57 lines
1.6 KiB
C#

using BCards.Web.Models;
using MongoDB.Driver;
namespace BCards.Web.Repositories;
public class UserRepository : IUserRepository
{
private readonly IMongoCollection<User> _users;
public UserRepository(IMongoDatabase database)
{
_users = database.GetCollection<User>("users");
// Create indexes
var indexKeys = Builders<User>.IndexKeys.Ascending(x => x.Email);
var indexOptions = new CreateIndexOptions { Unique = true };
_users.Indexes.CreateOneAsync(new CreateIndexModel<User>(indexKeys, indexOptions));
}
public async Task<User?> GetByIdAsync(string id)
{
return await _users.Find(x => x.Id == id && x.IsActive).FirstOrDefaultAsync();
}
public async Task<User?> GetByEmailAsync(string email)
{
return await _users.Find(x => x.Email == email && x.IsActive).FirstOrDefaultAsync();
}
public async Task<User> CreateAsync(User user)
{
user.CreatedAt = DateTime.UtcNow;
user.UpdatedAt = DateTime.UtcNow;
await _users.InsertOneAsync(user);
return user;
}
public async Task<User> UpdateAsync(User user)
{
user.UpdatedAt = DateTime.UtcNow;
await _users.ReplaceOneAsync(x => x.Id == user.Id, user);
return user;
}
public async Task DeleteAsync(string id)
{
await _users.UpdateOneAsync(
x => x.Id == id,
Builders<User>.Update.Set(x => x.IsActive, false).Set(x => x.UpdatedAt, DateTime.UtcNow)
);
}
public async Task<bool> ExistsAsync(string email)
{
return await _users.Find(x => x.Email == email && x.IsActive).AnyAsync();
}
}