Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

List Leaderboards Endpoint #249

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions LeaderboardBackend.Test/Leaderboards.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
using LeaderboardBackend.Test.TestApi.Extensions;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.AspNetCore.TestHost;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using NodaTime;
using NodaTime.Testing;
Expand Down Expand Up @@ -339,6 +340,40 @@ public async Task DeletedBoardsDontConsumeSlugs()
created!.CreatedAt.Should().Be(_clock.GetCurrentInstant());
}

[Test]
public async Task GetLeaderboards()
{
ApplicationContext context = _factory.Services.CreateScope().ServiceProvider.GetRequiredService<ApplicationContext>();
await context.Leaderboards.ExecuteDeleteAsync();

Leaderboard[] boards = [
new()
{
Name = "The Legend of Zelda",
Slug = "legend-of-zelda",
Info = "The original for the NES"
},
new()
{
Name = "Zelda II: The Adventure of Link",
Slug = "adventure-of-link",
Info = "The daring sequel"
},
new()
{
Name = "Link: The Faces of Evil",
Slug = "link-faces-of-evil",
Info = "Nobody should play this one.",
DeletedAt = _clock.GetCurrentInstant()
}
];

context.Leaderboards.AddRange(boards);
await context.SaveChangesAsync();
LeaderboardViewModel[] returned = await _apiClient.Get<LeaderboardViewModel[]>("/api/leaderboards", new());
returned.Should().BeEquivalentTo(boards.Take(2));
}

private static string ListToQueryString<T>(IEnumerable<T> list, string key)
{
IEnumerable<string> queryList = list.Select(l => $"{key}={l}");
Expand Down
9 changes: 5 additions & 4 deletions LeaderboardBackend/Controllers/LeaderboardsController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -50,11 +50,12 @@ public async Task<ActionResult<LeaderboardViewModel>> GetLeaderboardBySlug([From
[HttpGet("api/leaderboards")]
[SwaggerOperation("Gets leaderboards by their IDs.", OperationId = "getLeaderboards")]
[SwaggerResponse(200)]
public async Task<ActionResult<List<LeaderboardViewModel>>> GetLeaderboards(
[FromQuery] long[] ids
)
public async Task<ActionResult<List<LeaderboardViewModel>>> GetLeaderboards([FromQuery] long[] ids)
{
List<Leaderboard> result = await leaderboardService.GetLeaderboards(ids);
List<Leaderboard> result = Request.Query.ContainsKey("ids") ?
await leaderboardService.GetLeaderboardsById(ids) :
await leaderboardService.ListLeaderboards();

return Ok(result.Select(LeaderboardViewModel.MapFrom));
}

Expand Down
10 changes: 7 additions & 3 deletions LeaderboardBackend/Models/ViewModels/LeaderboardViewModel.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
using System.Text.Json.Serialization;
using LeaderboardBackend.Models.Entities;
using NodaTime;

namespace LeaderboardBackend.Models.ViewModels;

#nullable disable warnings

/// <summary>
/// Represents a collection of `Leaderboard` entities.
/// </summary>
Expand Down Expand Up @@ -51,11 +54,12 @@ public record LeaderboardViewModel
/// <summary>
/// A collection of `Category` entities for the `Leaderboard`.
/// </summary>
public required IList<CategoryViewModel> Categories { get; init; }
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

With this change though; we'll have to ensure we do the same thing for any future endpoint with possibly-null relations, for consistency. Imo it's fine to default to an empty array, anyway

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All this does is not serialize it when there are no cats to be returned.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ergo the field itself won't appear in the return object, right?

Copy link
Contributor

@Eein Eein Oct 2, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That could be a problem if frontend is expecting it.

I'd ask the frontend people what they would expect here.
Anecdotally the frontend teams I generally work with would expect an empty array. It just helps avoid safe access checks cluttering up the code, and having to write a new type for leaderboards with and without the field. nvm, theres optionals

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The frontend code that actually deals with the models is autogenerated so it'll mark the field as potentially absent. If they try to access it without doing a null check, it'll produce a warning.

public IList<CategoryViewModel> Categories { get; init; }

public static LeaderboardViewModel MapFrom(Leaderboard leaderboard)
{
IList<CategoryViewModel>? categories = leaderboard.Categories
IList<CategoryViewModel> categories = leaderboard.Categories
?.Select(CategoryViewModel.MapFrom)
.ToList();
return new LeaderboardViewModel
Expand All @@ -67,7 +71,7 @@ public static LeaderboardViewModel MapFrom(Leaderboard leaderboard)
CreatedAt = leaderboard.CreatedAt,
UpdatedAt = leaderboard.UpdatedAt,
DeletedAt = leaderboard.DeletedAt,
Categories = categories ?? Array.Empty<CategoryViewModel>(),
Categories = categories,
};
}
}
3 changes: 2 additions & 1 deletion LeaderboardBackend/Services/ILeaderboardService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@ public interface ILeaderboardService
{
Task<Leaderboard?> GetLeaderboard(long id);
Task<Leaderboard?> GetLeaderboardBySlug(string slug);
Task<List<Leaderboard>> GetLeaderboards(long[]? ids = null);
Task<List<Leaderboard>> ListLeaderboards();
Task<List<Leaderboard>> GetLeaderboardsById(long[] ids);
Task<CreateLeaderboardResult> CreateLeaderboard(CreateLeaderboardRequest request);
}

Expand Down
23 changes: 9 additions & 14 deletions LeaderboardBackend/Services/Impl/LeaderboardService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,20 +15,15 @@ public class LeaderboardService(ApplicationContext applicationContext) : ILeader
await applicationContext.Leaderboards
.FirstOrDefaultAsync(b => b.Slug == slug && b.DeletedAt == null);

// FIXME: Paginate this
public async Task<List<Leaderboard>> GetLeaderboards(long[]? ids = null)
{
if (ids is null)
{
return await applicationContext.Leaderboards.ToListAsync();
}
else
{
return await applicationContext.Leaderboards
.Where(leaderboard => ids.Contains(leaderboard.Id))
.ToListAsync();
}
}
// FIXME: Paginate these
public async Task<List<Leaderboard>> ListLeaderboards() =>
await applicationContext.Leaderboards
.Where(lb => lb.DeletedAt == null).ToListAsync();

public async Task<List<Leaderboard>> GetLeaderboardsById(long[] ids) =>
await applicationContext.Leaderboards
.Where(leaderboard => ids.Contains(leaderboard.Id))
.ToListAsync();

public async Task<CreateLeaderboardResult> CreateLeaderboard(CreateLeaderboardRequest request)
{
Expand Down
1 change: 0 additions & 1 deletion LeaderboardBackend/openapi.json
Original file line number Diff line number Diff line change
Expand Up @@ -1106,7 +1106,6 @@
},
"LeaderboardViewModel": {
"required": [
"categories",
"createdAt",
"deletedAt",
"id",
Expand Down