41 lines
1.4 KiB
C#
41 lines
1.4 KiB
C#
![]() |
using System.Data;
|
|||
|
using Dapper;
|
|||
|
using Microsoft.Extensions.Configuration;
|
|||
|
using Npgsql;
|
|||
|
|
|||
|
namespace UserOfTheDayBot.Data;
|
|||
|
|
|||
|
public interface IUserRepository
|
|||
|
{
|
|||
|
Task<int> RegisterUserAsync(long chatId, long userId, string userName);
|
|||
|
Task<IEnumerable<(long userId, string userName)>> GetUsersWithNamesAsync(long chatId);
|
|||
|
}
|
|||
|
|
|||
|
public class UserRepository : IUserRepository
|
|||
|
{
|
|||
|
private readonly string _connectionString;
|
|||
|
|
|||
|
public UserRepository(IConfiguration configuration)
|
|||
|
{
|
|||
|
_connectionString = configuration["DatabaseSettings:ConnectionString"];
|
|||
|
}
|
|||
|
|
|||
|
|
|||
|
public async Task<int> RegisterUserAsync(long chatId, long userId, string userName)
|
|||
|
{
|
|||
|
using (IDbConnection db = new NpgsqlConnection(_connectionString))
|
|||
|
{
|
|||
|
string query = "INSERT INTO users (chat_id, user_id, user_name) VALUES (@ChatId, @UserId, @UserName) ON CONFLICT (chat_id, user_id) DO NOTHING";
|
|||
|
return await db.ExecuteAsync(query, new { ChatId = chatId, UserId = userId, UserName = userName });
|
|||
|
}
|
|||
|
}
|
|||
|
|
|||
|
public async Task<IEnumerable<(long userId, string userName)>> GetUsersWithNamesAsync(long chatId)
|
|||
|
{
|
|||
|
using (IDbConnection db = new NpgsqlConnection(_connectionString))
|
|||
|
{
|
|||
|
string query = "SELECT user_id, user_name FROM users WHERE chat_id = @ChatId";
|
|||
|
return await db.QueryAsync<(long, string)>(query, new { ChatId = chatId });
|
|||
|
}
|
|||
|
}
|
|||
|
}
|