50 lines
1.7 KiB
C#
50 lines
1.7 KiB
C#
using Metrolog_API.Models;
|
|
using MongoDB.Driver;
|
|
|
|
namespace Metrolog_API.Services
|
|
{
|
|
public class UserService
|
|
{
|
|
private readonly IMongoCollection<UserModel> _users;
|
|
|
|
public UserService(IConfiguration config)
|
|
{
|
|
var client = new MongoClient(System.Environment.GetEnvironmentVariable("MONGODB_CONNECTION_STRING"));
|
|
var database = client.GetDatabase(System.Environment.GetEnvironmentVariable("MONGODB_DATABASE"));
|
|
_users = database.GetCollection<UserModel>("users");
|
|
}
|
|
|
|
/// <summary>
|
|
/// Read all items in collection ordered by "Surname" by page (100 items)
|
|
/// </summary>
|
|
/// <param name="page">Page number</param>
|
|
/// <returns>List of users on specified page</returns>
|
|
public async Task<List<UserModel>> GetPageAsync(int page = 1) =>
|
|
await _users.Find<UserModel>(user => true).SortByDescending(x => x.Surname).Skip((page - 1) * 100).Limit(100).ToListAsync();
|
|
|
|
/// <summary>
|
|
/// Get user by Email
|
|
/// </summary>
|
|
/// <param name="email">user Email</param>
|
|
/// <returns>User</returns>
|
|
public async Task<UserModel?> GetByEmailAsync(string email) =>
|
|
await _users.Find<UserModel>(user => user.Email == email).FirstOrDefaultAsync();
|
|
|
|
|
|
public async Task<UserModel?> GetByIdAsync(string id) =>
|
|
await _users.Find<UserModel>(user => user.Id == id).FirstOrDefaultAsync();
|
|
|
|
/// <summary>
|
|
/// Create user
|
|
/// </summary>
|
|
/// <param name="user">user</param>
|
|
public async Task CreateAsync(UserModel user) =>
|
|
await _users.InsertOneAsync(user);
|
|
|
|
public async Task UpdateAsync(string id, UserModel calibration) =>
|
|
await _users.ReplaceOneAsync(c => c.Id == id, calibration);
|
|
|
|
public async Task RemoveAsync(string id) =>
|
|
await _users.DeleteOneAsync(c => c.Id == id);
|
|
}
|
|
}
|