Fix db and fix endpoints

This commit is contained in:
2025-08-05 22:30:18 +07:00
parent 2dcbcc3ef2
commit 36529ae403
36 changed files with 5073 additions and 245 deletions

View File

@@ -41,12 +41,12 @@ public class PostgreSqlUserRepository : IUserRepository
try
{
await EnsureConnectionOpenAsync();
var userEntity = await _context.Users
.AsNoTracking()
.FirstOrDefaultAsync(u => u.AgentName == agentName)
.ConfigureAwait(false);
return PostgreSqlMappers.Map(userEntity);
}
catch (Exception)
@@ -62,12 +62,12 @@ public class PostgreSqlUserRepository : IUserRepository
try
{
await EnsureConnectionOpenAsync();
var userEntity = await _context.Users
.AsNoTracking()
.FirstOrDefaultAsync(u => u.Name == name)
.ConfigureAwait(false);
return PostgreSqlMappers.Map(userEntity);
}
catch (Exception)
@@ -78,25 +78,17 @@ public class PostgreSqlUserRepository : IUserRepository
}
}
public async Task InsertUserAsync(User user)
{
var userEntity = PostgreSqlMappers.Map(user);
_context.Users.Add(userEntity);
await _context.SaveChangesAsync().ConfigureAwait(false);
}
public async Task<IEnumerable<User>> GetAllUsersAsync()
{
try
{
await EnsureConnectionOpenAsync();
var userEntities = await _context.Users
.AsNoTracking()
.ToListAsync()
.ConfigureAwait(false);
return userEntities.Select(PostgreSqlMappers.Map);
}
catch (Exception)
@@ -107,31 +99,45 @@ public class PostgreSqlUserRepository : IUserRepository
}
}
public async Task UpdateUser(User user)
public async Task SaveOrUpdateUserAsync(User user)
{
try
{
var userEntity = await _context.Users
.AsTracking() // Explicitly enable tracking for update operations
var existingUser = await _context.Users
.AsTracking()
.FirstOrDefaultAsync(u => u.Name == user.Name)
.ConfigureAwait(false);
if (userEntity == null)
if (existingUser != null)
{
throw new InvalidOperationException($"User with name '{user.Name}' not found");
// Update existing user
existingUser.AgentName = user.AgentName;
existingUser.AvatarUrl = user.AvatarUrl;
existingUser.TelegramChannel = user.TelegramChannel;
_context.Users.Update(existingUser);
// Update the user object with the existing user's ID
user.Id = existingUser.Id;
}
else
{
// Insert new user
var userEntity = PostgreSqlMappers.Map(user);
_context.Users.Add(userEntity);
// Update the user object with the database-generated ID after save
await _context.SaveChangesAsync().ConfigureAwait(false);
user.Id = userEntity.Id;
return; // Exit early since we already saved
}
userEntity.AgentName = user.AgentName;
userEntity.AvatarUrl = user.AvatarUrl;
userEntity.TelegramChannel = user.TelegramChannel;
_context.Users.Update(userEntity);
await _context.SaveChangesAsync().ConfigureAwait(false);
}
catch (Exception e)
{
Console.WriteLine(e);
throw new Exception("Cannot update user");
throw new Exception("Cannot save or update user");
}
}
}
}