Skip to content

Commit f92b0c7

Browse files
committed
Change API's /random endpoint to accept string query param
1 parent 5838115 commit f92b0c7

File tree

2 files changed

+34
-2
lines changed

2 files changed

+34
-2
lines changed

QbQuestionsAPI.UnitTests/ControllerTests/QbQuestionsControllerTests.cs

+15
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,21 @@ public async Task GetRandomAsyncSuccessTest()
6666
result.Should().BeOfType<OkObjectResult>();
6767
}
6868

69+
[Fact]
70+
public async Task GetRandomAsyncBadRequestFailureTest()
71+
{
72+
// Arrange
73+
const string invalidLevel = "invalid";
74+
IQbQuestionService qbQuestionService = Substitute.For<IQbQuestionService>();
75+
QbQuestionsController controller = new QbQuestionsController(qbQuestionService, mapper);
76+
77+
// Act
78+
IActionResult result = await controller.GetRandomAsync(invalidLevel);
79+
80+
// Assert
81+
result.Should().BeOfType<BadRequestResult>();
82+
}
83+
6984
[Fact]
7085
public async Task GetRandomAsyncFailureTest()
7186
{

QbQuestionsAPI/Controllers/QbQuestionsController.cs

+19-2
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
using AutoMapper;
22
using Microsoft.AspNetCore.Authorization;
33
using Microsoft.AspNetCore.Mvc;
4+
using System;
45
using System.Collections.Generic;
56
using System.Threading.Tasks;
67

@@ -41,9 +42,25 @@ public async Task<IActionResult> GetAsync(int id)
4142
}
4243

4344
[HttpGet("random")]
44-
public async Task<IActionResult> GetRandomAsync(int? level = null)
45+
public async Task<IActionResult> GetRandomAsync(string level = null)
4546
{
46-
QbQuestion question = await _qbQuestionService.GetRandomAsync(level);
47+
int? levelInt = null;
48+
49+
if (!String.IsNullOrEmpty(level))
50+
{
51+
Enum.TryParse(level, true, out ETournamentLevel levelEnum);
52+
// 0 is default enum value, which is returned if TryParse fails
53+
if (levelEnum != 0)
54+
{
55+
levelInt = (int?)levelEnum;
56+
}
57+
else
58+
{
59+
return BadRequest();
60+
}
61+
}
62+
63+
QbQuestion question = await _qbQuestionService.GetRandomAsync(levelInt);
4764

4865
if (question == null)
4966
{

0 commit comments

Comments
 (0)