almost done need upload file for activity
continuous-integration/drone/push Build is passing Details

merging_EF-API
David D'ALMEIDA 1 year ago
parent cc834989d5
commit 3994b52ca9

@ -8,7 +8,7 @@ public static class ActivityMapper
{
private static GenericMapper<Activity, ActivityDto> _mapper = new GenericMapper<Activity, ActivityDto>();
public static ActivityDto? ToDto(this Activity activity)
public static ActivityDto ToDto(this Activity activity)
{
return activity.ToU(_mapper, activityDto => new ActivityDto
{
@ -29,7 +29,7 @@ public static class ActivityMapper
});
}
public static Activity? ToModel(this ActivityDto activityDto)
public static Activity ToModel(this ActivityDto activityDto)
{
return activityDto.ToT(_mapper, activity => new Activity
{

@ -8,7 +8,7 @@ public static class UserMappeur
{
private static GenericMapper<User, UserDto> _mapper = new GenericMapper<User, UserDto>();
public static UserDto? ToDto(this User user)
public static UserDto ToDto(this User user)
{
return user.ToU(_mapper, userDto => new UserDto
{
@ -32,7 +32,7 @@ public static class UserMappeur
// corégraphie => microservice TCP
public static User? ToModel(this UserDto userDto)
public static User ToModel(this UserDto userDto)
{
return userDto.ToT(_mapper, user => new User
{

@ -11,6 +11,7 @@ using Microsoft.Extensions.Options;
using Microsoft.OpenApi.Models;
using Model.Manager;
using Model2Entities;
using StubAPI;
namespace HeartTrackAPI;
@ -68,7 +69,8 @@ public class AppBootstrap(IConfiguration configuration)
}
private void AddModelService(IServiceCollection services)
{
services.AddSingleton<IDataManager>(provider => new DbDataManager(provider.GetService<HeartTrackContext>()));
//services.AddSingleton<IDataManager>(provider => new DbDataManager(provider.GetService<HeartTrackContext>()));
services.AddSingleton<IDataManager, StubData>();
//services.AddTransient<IActivityManager, ActivityManager>();
}

@ -3,8 +3,8 @@ using Dto;
using HeartTrackAPI.Request;
using HeartTrackAPI.Responce;
using Microsoft.AspNetCore.Mvc;
using Shared;
using Model;
using Shared;
using Model.Manager;
using Model.Repository;
@ -40,7 +40,7 @@ public class ActivityController : Controller
var activities = await _activityService.GetActivities(pageRequest.Index, pageRequest.Count, ActivityOrderCriteria.None, pageRequest.Descending ?? false);
if(activities == null)
{
return BadRequest("No activities found");
return NotFound("No activities found");
}
var pageResponse = new PageResponse<ActivityDto>(pageRequest.Index, pageRequest.Count, totalCount, activities.Select(a => a.ToDto()));
return Ok(pageResponse);
@ -52,22 +52,61 @@ public class ActivityController : Controller
}
}
/*
public async Task<IActionResult> PostFitFile([FromForm] IFormFile file)
{
[HttpPost]
[ProducesResponseType(StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status415UnsupportedMediaType)]
[MultipartFormData]
[DisableFormValueModelBinding]
public async Task<IActionResult> PostFitFile( Stream file, string contentType) // [FromForm]
{
if (!MultipartRequestHelper.IsMultipartContentType(Request.ContentType))
{
ModelState.AddModelError("File",
$"The request couldn't be processed (Error 1).");
// Log error
return BadRequest(ModelState);
}
if (file == null)
{
return BadRequest("No file was provided");
}
var activity = await _activityManager.AddActivityFromFitFile(file);
à l'intérieur du AddActivityFromFitFile ya un truc comme var result = await _activityRepo.AddActivity(activity);
//var fileUploadSummary = await _fileService.UploadFileAsync(HttpContext.Request.Body, Request.ContentType);
// var activity = await _activityManager.AddActivityFromFitFile(file);
var activity = new Activity
{
Id = 1,
Type = "Running",
Date = new DateTime(2021, 10, 10),
StartTime = new DateTime(2021, 10, 10, 10, 0, 0),
EndTime = new DateTime(2021, 10, 10, 11, 0, 0),
Effort = 3,
Variability = 0.5f,
Variance = 0.5f,
StandardDeviation = 0.5f,
Average = 5.0f,
Maximum = 10,
Minimum = 0,
AverageTemperature = 20.0f,
HasAutoPause = false,
Users =
{
new User
{
Id = 3, Username = "Athlete3",
ProfilePicture =
"https://plus.unsplash.com/premium_photo-1705091981693-6006f8a20479?q=80&w=1974&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D",
FirstName = "First3", LastName = "Last3",
Sexe = "M", Lenght = 190, Weight = 80, DateOfBirth = new DateTime(1994, 3, 3), Email = "ath@ex.fr",
Role = new Athlete()
}
}
};
if (activity == null)
{
return BadRequest("The file provided is not a valid fit file");
}
return CreatedAtAction(nameof(GetActivity), new { id = result.Id }, result.ToDto());
return CreatedAtAction(nameof(GetActivities), activity.ToDto());
return CreatedAtAction(nameof(GetActivity), new { id = activity.Id }, activity.ToDto());
}*/
[HttpGet("{id}")]
@ -107,4 +146,34 @@ public class ActivityController : Controller
}
return NoContent();
}
/*
public async Task<FileUploadSummary> UploadFileAsync(Stream fileStream, string contentType)
{
var fileCount = 0;
long totalSizeInBytes = 0;
var boundary = GetBoundary(MediaTypeHeaderValue.Parse(contentType));
var multipartReader = new MultipartReader(boundary, fileStream);
var section = await multipartReader.ReadNextSectionAsync();
var filePaths = new List<string>();
var notUploadedFiles = new List<string>();
while (section != null)
{
var fileSection = section.AsFileSection();
if (fileSection != null)
{
totalSizeInBytes += await SaveFileAsync(fileSection, filePaths, notUploadedFiles);
fileCount++;
}
section = await multipartReader.ReadNextSectionAsync();
}
return new FileUploadSummary
{
TotalFilesUploaded = fileCount,
TotalSizeUploaded = ConvertSizeToString(totalSizeInBytes),
FilePaths = filePaths,
NotUploadedFiles = notUploadedFiles
};
}*/
}

@ -1,11 +1,9 @@
using APIMappers;
using Dto;
using Entities;
using HeartTrackAPI.Request;
using HeartTrackAPI.Responce;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Model;
using Model.Manager;
using Model.Repository;
using Shared;
@ -18,11 +16,13 @@ namespace HeartTrackAPI.Controllers;
public class UsersController : Controller
{
private readonly ILogger<UsersController> _logger;
private readonly IActivityRepository _activityService;
private readonly IUserRepository _userService;
public UsersController(ILogger<UsersController> logger, IDataManager dataManager)
{
_logger = logger;
_userService = dataManager.UserRepo;
_activityService = dataManager.ActivityRepo;
}
[HttpGet]
@ -43,7 +43,7 @@ public class UsersController : Controller
_logger.LogInformation("Executing {Action} with parameters: {Parameters}", nameof(Get), null);
var athletes = await _userService.GetUsers(request.Index, request.Count, Enum.TryParse(request.OrderingPropertyName, out AthleteOrderCriteria result) ? result : AthleteOrderCriteria.None, request.Descending ?? false);
var pageResponse = new PageResponse<UserDto>(request.Index, request.Count, totalCount, athletes.Select(a => a.ToDto()));
var pageResponse = new PageResponse<UserDto>(request.Index, request.Count, totalCount, athletes!.Select(a => a.ToDto()));
return Ok(pageResponse);
}
catch (Exception e)
@ -118,7 +118,6 @@ public class UsersController : Controller
return StatusCode(500);
}
return Ok(updatedAthlete.ToDto());
return Ok();
}
catch (Exception e)
@ -160,6 +159,39 @@ public class UsersController : Controller
}
}
[HttpGet("{id}/friends")]
[ProducesResponseType(typeof(PageResponse<UserDto>), 200)]
[ProducesResponseType(404)]
[ProducesResponseType(500)]
public async Task<ActionResult<PageResponse<UserDto>>> GetFriends(int id, [FromQuery] PageRequest request)
{
try
{
_logger.LogInformation("Executing {Action} with parameters: {Parameters} for {Id}", nameof(GetFriends), null,id);
var athlete = await _userService.GetItemById(id);
if (athlete == null)
{
_logger.LogError("Athlete with id {id} not found", id);
return NotFound($"Athlete with id {id} not found");
}
var totalCount = await _userService.GetNbFriends(athlete);
if (request.Count * request.Index >= totalCount)
{
_logger.LogError("To many object is asked the max is {totalCount} but the request is superior of ", totalCount);
return BadRequest("To many object is asked the max is : " + totalCount);
}
var friends = await _userService.GetFriends(athlete, request.Index, request.Count, Enum.TryParse(request.OrderingPropertyName, out AthleteOrderCriteria result) ? result : AthleteOrderCriteria.None, request.Descending ?? false);
if (friends == null) return NotFound();
var pageResponse = new PageResponse<UserDto>(request.Index, request.Count, totalCount, friends.Select(a => a.ToDto()));
return Ok(pageResponse);
}
catch (Exception e)
{
_logger.LogError(e, "Error while getting the number of users");
return StatusCode(500);
}
}
[HttpPost("{id}/friend/{friendId}")]
[ProducesResponseType(200)]
@ -197,6 +229,115 @@ public class UsersController : Controller
}
}
[HttpDelete("{id}/friend/{friendId}")]
[ProducesResponseType(200)]
[ProducesResponseType(404)]
[ProducesResponseType(500)]
public async Task<IActionResult> RemoveFriend(int id, int friendId)
{
try
{
_logger.LogInformation("Executing {Action} with parameters: {Parameters} for {Id}", nameof(RemoveFriend), friendId,id);
var athlete = await _userService.GetItemById(id);
if (athlete == null)
{
_logger.LogError("Athlete with id {id} not found", id);
return NotFound($"Athlete with id {id} not found");
}
var friend = await _userService.GetItemById(friendId);
if (friend == null)
{
_logger.LogError("Athlete with id {id} not found", friendId);
return NotFound($"Athlete with id {friendId} not found");
}
var isRemoved = await _userService.RemoveFriend(athlete, friend);
if(!isRemoved)
{
_logger.LogError("Error while removing friend with id {friendId} to athlete with id {id}", friendId, id);
return StatusCode(500);
}
return Ok();
}
catch (Exception e)
{
_logger.LogError(e, "Error while getting the number of users");
return StatusCode(500);
}
}
// ou faire un get qui si le role est coach resend les athletes et si le role est athlete resend les coach
[HttpGet("{coachId}/athletes")]
[ProducesResponseType(typeof(PageResponse<UserDto>), 200)]
[ProducesResponseType(404)]
[ProducesResponseType(500)]
public async Task<ActionResult<PageResponse<UserDto>>> GetAthletes(int coachId, [FromQuery] PageRequest request)
{
try
{
_logger.LogInformation("Executing {Action} with parameters: {Parameters} for {Id}", nameof(GetAthletes), null,coachId);
var coach = await _userService.GetItemById(coachId);
if (coach == null)
{
_logger.LogError("Athlete with id {id} not found", coachId);
return NotFound($"Athlete with id {coachId} not found");
}
var totalCount = await _userService.GetNbFriends(coach);
if (request.Count * request.Index >= totalCount)
{
_logger.LogError("To many object is asked the max is {totalCount} but the request is superior of ", totalCount);
return BadRequest("To many object is asked the max is : " + totalCount);
}
var athletes = await _userService.GetFriends(coach, request.Index, request.Count, Enum.TryParse(request.OrderingPropertyName, out AthleteOrderCriteria result) ? result : AthleteOrderCriteria.None, request.Descending ?? false);
if (athletes == null) return NotFound();
var pageResponse = new PageResponse<UserDto>(request.Index, request.Count, totalCount, athletes.Select(a => a.ToDto()));
return Ok(pageResponse);
}
catch (Exception e)
{
_logger.LogError(e, "Error while getting the number of users");
return StatusCode(500);
}
}
[HttpGet("{userId}/activities")]
// should be tiny DTOActivity returned with only the necessary information (will be used in the list of activities of a user)
public async Task<ActionResult<PageResponse<ActivityDto>>> GetActivitiesByUser(int userId, [FromQuery] PageRequest pageRequest)
{
try
{
var totalCount = await _activityService.GetNbActivitiesByUser(userId);
if (pageRequest.Count * pageRequest.Index >= totalCount)
{
_logger.LogError("To many object is asked the max is {totalCount} but the request is superior of ", totalCount);
return BadRequest("To many object is asked the max is : " + totalCount);
}
_logger.LogInformation("Executing {Action} with parameters: {Parameters}", nameof(GetActivitiesByUser), pageRequest);
var activities = await _activityService.GetActivitiesByUser(userId, pageRequest.Index, pageRequest.Count, ActivityOrderCriteria.None, pageRequest.Descending ?? false);
if(activities == null)
{
return NotFound("No activities found");
}
var pageResponse = new PageResponse<ActivityDto>(pageRequest.Index, pageRequest.Count, totalCount, activities.Select(a => a.ToDto()));
return Ok(pageResponse);
}
catch (Exception e)
{
_logger.LogError(e, "Error while getting all activities");
return StatusCode(500);
}
}
/*
[HttpGet("{userId}/trainings")]
[ProducesResponseType(typeof(PageResponse<TrainingDto>), 200)]
[ProducesResponseType(404)]
[ProducesResponseType(500)]
public async Task<ActionResult<PageResponse<TrainingDto>> GetTrainings(int userId, [FromQuery] PageRequest request)
*/
[HttpPost("logout")]
[ProducesResponseType(200)]
[ProducesResponseType(401)]

@ -12,7 +12,8 @@ COPY ["StubbedContextLib/StubbedContextLib.csproj", "StubbedContextLib/"]
COPY ["Shared/Shared.csproj", "Shared/"]
COPY ["Entities/Entities.csproj", "Entities/"]
COPY ["Dto/Dto.csproj", "Dto/"]
COPY ["ApiMappeur/ApiMappeur.csproj", "ApiMappeur/"]
COPY ["APIMappers/APIMappers.csproj", "APIMappers/"]
COPY ["EFMappers/EFMappers.csproj", "EFMappers/"]
COPY ["DbContextLib/DbContextLib.csproj", "DbContextLib/"]
COPY ["Model/Model.csproj", "Model/"]
COPY ["Model2Entities/Model2Entities.csproj", "Model2Entities/"]

@ -0,0 +1,44 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.ModelBinding;
namespace HeartTrackAPI;
public class FileUploadSummary
{
public int TotalFilesUploaded { get; set; }
public string TotalSizeUploaded { get; set; }
public IList<string> FilePaths { get; set; } = new List<string>();
public IList<string> NotUploadedFiles { get; set; } = new List<string>();
}
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)]
public class MultipartFormDataAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext context)
{
var request = context.HttpContext.Request;
if (request.HasFormContentType
&& request.ContentType.StartsWith("multipart/form-data", StringComparison.OrdinalIgnoreCase))
{
return;
}
context.Result = new StatusCodeResult(StatusCodes.Status415UnsupportedMediaType);
}
}
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class DisableFormValueModelBindingAttribute : Attribute, IResourceFilter
{
public void OnResourceExecuting(ResourceExecutingContext context)
{
var factories = context.ValueProviderFactories;
factories.RemoveType<FormValueProviderFactory>();
factories.RemoveType<FormFileValueProviderFactory>();
factories.RemoveType<JQueryFormValueProviderFactory>();
}
public void OnResourceExecuted(ResourceExecutedContext context)
{
}
}

@ -4,6 +4,10 @@ using HeartTrackAPI;
var builder = WebApplication.CreateBuilder(args);
builder.Logging.AddConsole();
builder.WebHost.ConfigureKestrel(serverOptions =>
{
serverOptions.Limits.MaxRequestBodySize = long.MaxValue;
});
var init = new AppBootstrap(builder.Configuration);

@ -32,6 +32,7 @@ public class Activity
public float AverageTemperature { get; set; }
public bool HasAutoPause { get; set; }
public HashSet<User> Users { get; private set; } = new HashSet<User>();
public Activity(int idActivity ,string type, DateTime date, DateTime startTime, DateTime endTime,
int effort, float variability, float variance, float standardDeviation,
float average, int maximum, int minimum, float averageTemperature, bool hasAutoPause)

@ -4,10 +4,12 @@ namespace Model.Repository;
public interface IActivityRepository
{
public Task<IEnumerable<Activity>> GetActivities(int index, int count, ActivityOrderCriteria criteria, bool descending = false);
public Task<IEnumerable<Activity>?> GetActivities(int index, int count, ActivityOrderCriteria criteria, bool descending = false);
public Task<Activity?> GetActivityByIdAsync(int id);
public Task<Activity?> AddActivity(Activity activity);
public Task<Activity?> UpdateActivity(int id, Activity activity);
public Task<bool> DeleteActivity(int id);
public Task<int> GetNbItems();
public Task<IEnumerable<Activity>?> GetActivitiesByUser(int userId, int index, int count, ActivityOrderCriteria orderCriteria, bool descending= false);
public Task<int> GetNbActivitiesByUser(int userId);
}

@ -4,7 +4,14 @@ namespace Model.Repository;
public interface IUserRepository : IGenericRepository<User>
{
public Task<IEnumerable<User>> GetUsers(int index, int count, AthleteOrderCriteria? criteria , bool descending = false);
public Task<IEnumerable<User>?> GetUsers(int index, int count, AthleteOrderCriteria? criteria , bool descending = false);
public Task<bool> AddFriend(User user, User friend);
public Task<bool> RemoveFriend(User user, User friend);
// should be removed cause i just have to call the GetItem then get the friends
public Task<IEnumerable<User>?> GetFriends(User user, int index, int count, AthleteOrderCriteria? criteria, bool descending = false);
public Task<int> GetNbFriends(User user);
}

@ -121,5 +121,15 @@ public partial class DbDataManager : IDataManager
throw;
}
}
public Task<IEnumerable<Activity>> GetActivitiesByUser(int userId, int index, int count, ActivityOrderCriteria criteria, bool descending = false)
{
throw new NotImplementedException();
}
public Task<int> GetNbActivitiesByUser(int userId)
{
throw new NotImplementedException();
}
}
}

@ -54,5 +54,20 @@ public partial class DbDataManager
{
throw new NotImplementedException();
}
public async Task<bool> RemoveFriend(User user, User friend)
{
throw new NotImplementedException();
}
public Task<IEnumerable<User>?>? GetFriends(User user, int index, int count, AthleteOrderCriteria? criteria, bool descending = false)
{
throw new NotImplementedException();
}
public Task<int> GetNbFriends(User user)
{
throw new NotImplementedException();
}
}
}

@ -2,7 +2,7 @@ namespace Shared;
public static class Extensions
{
public static U? ToU<T, U>(this T t, GenericMapper<T, U> mapper, Func<T, U> func) where U :class where T :class
public static U ToU<T, U>(this T t, GenericMapper<T, U> mapper, Func<T, U> func) where U :class where T :class
{
var u = mapper.GetU(t);
if (u != null) {
@ -14,7 +14,7 @@ public static class Extensions
return u;
}
// , Action<T, U> action
public static T? ToT<T,U>(this U u, GenericMapper<T, U> mapper, Func<U, T> func) where U :class where T :class
public static T ToT<T,U>(this U u, GenericMapper<T, U> mapper, Func<U, T> func) where U :class where T :class
{
var t = mapper.GetT(u);
if (t != null) {

@ -6,33 +6,73 @@ namespace StubAPI;
public class ActivityService: IActivityRepository
{
public async Task<IEnumerable<Activity>> GetActivities(int index, int count, ActivityOrderCriteria criteria, bool descending = false)
private List<Activity> _activities = new List<Activity>(
new Activity[]
{
throw new NotImplementedException();
new Activity
{
Id = 1,
Type = "Running",
Date = new DateTime(2021, 10, 10),
StartTime = new DateTime(2021, 10, 10, 10, 0, 0),
EndTime = new DateTime(2021, 10, 10, 11, 0, 0),
Effort = 3,
Variability = 0.5f,
Variance = 0.5f,
StandardDeviation = 0.5f,
Average = 5.0f,
Maximum = 10,
Minimum = 0,
AverageTemperature = 20.0f,
HasAutoPause = false,
Users = {new User
{
Id = 3, Username = "Athlete3", ProfilePicture = "https://plus.unsplash.com/premium_photo-1705091981693-6006f8a20479?q=80&w=1974&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D", FirstName = "First3", LastName = "Last3",
Sexe = "M", Lenght = 190, Weight = 80, DateOfBirth = new DateTime(1994, 3, 3), Email = "ath@ex.fr",
Role = new Athlete()
}}
},
}
);
public async Task<Activity?> GetActivityByIdAsync(int id)
public async Task<IEnumerable<Activity>?> GetActivities(int index, int count, ActivityOrderCriteria criteria, bool descending = false)
=> await Task.FromResult(_activities.GetItemsWithFilterAndOrdering(c=>true,index, count,criteria != ActivityOrderCriteria.None ? criteria: null , descending));
public Task<Activity?> GetActivityByIdAsync(int id)
{
throw new NotImplementedException();
return Task.FromResult(_activities.FirstOrDefault(s => s.Id == id));
}
public async Task<Activity?> AddActivity(Activity activity)
public Task<Activity?> AddActivity(Activity activity)
=> _activities.AddItem(activity);
public async Task<Activity?> UpdateActivity(int id, Activity activity)
{
throw new NotImplementedException();
var oldActivity = _activities.FirstOrDefault(s => s.Id == id);
if (oldActivity == null) return null;
return await _activities.UpdateItem(oldActivity, activity);
}
public async Task<Activity?> UpdateActivity(int id, Activity activity)
public Task<bool> DeleteActivity(int id)
{
throw new NotImplementedException();
var activity = _activities.FirstOrDefault(s => s.Id == id);
if (activity == null) return Task.FromResult(false);
return _activities.DeleteItem(activity);
}
public async Task<bool> DeleteActivity(int id)
public Task<int> GetNbItems()
=> Task.FromResult(_activities.Count);
public async Task<IEnumerable<Activity>?> GetActivitiesByUser(int userId, int index, int count, ActivityOrderCriteria criteria, bool descending = false)
{
throw new NotImplementedException();
var activities = _activities.GetItemsWithFilterAndOrdering(c => c.Users.Any(u => u.Id == userId), index, count,
criteria != ActivityOrderCriteria.None ? criteria : null, descending);
return await Task.FromResult(activities);
}
public async Task<int> GetNbItems()
public Task<int> GetNbActivitiesByUser(int userId)
{
throw new NotImplementedException();
return Task.FromResult(_activities.Count(a => a.Users.Any(u => u.Id == userId)));
}
}

@ -51,14 +51,36 @@ public class UserService : IUserRepository
return true;
}
public async Task<IEnumerable<User>> GetItems(int index, int count, string? orderingProperty = null,
bool descending = false)
public async Task<bool> RemoveFriend(User user, User friend)
{
if (user == null || friend == null)
{
return false;
}
if (!user.Users.Contains(friend))
{
return false;
}
return await this.GetUsers(index, count, this.ToEnum(orderingProperty), descending);
user.Users.Remove(friend);
return true;
}
public async Task<IEnumerable<User>?>? GetFriends(User user, int index, int count, AthleteOrderCriteria? criteria, bool descending = false)
=>await Task.FromResult(athletes.FirstOrDefault(s => s.Id == user.Id)?.Users.GetItemsWithFilterAndOrdering(c=>true,index, count,criteria, descending));
public Task<int> GetNbFriends(User user)
{
return Task.FromResult(athletes.FirstOrDefault(s => s.Id == user.Id)?.Users.Count ?? 0);
}
public async Task<IEnumerable<User>> GetItems(int index, int count, string? orderingProperty = null,
bool descending = false)
=>await GetUsers(index, count, this.ToEnum(orderingProperty), descending);
public async Task<User?> GetItemById(int id)
=>await Task.FromResult(athletes.FirstOrDefault(s => s.Id == id));

@ -39,13 +39,15 @@ public static class Extensions
public static IEnumerable<T> GetItemsWithFilterAndOrdering<T>(this IEnumerable<T> list, Func<T, bool> filter, int index, int count, Enum? orderCriterium, bool descending = false ) where T : class
{
var filteredList = list.Where(filter);
IEnumerable<T> query = list;
query = query.Where(filter);
if(orderCriterium != null)
{
filteredList = filteredList.OrderByCriteria(orderCriterium, descending);
query = query.OrderByCriteria(orderCriterium, descending);
}
return filteredList
return query
.Skip(index * count)
.Take(count);
}

Loading…
Cancel
Save