diff --git a/APIGateway/APIGateway.csproj b/APIGateway/APIGateway.csproj index f277149..141574e 100644 --- a/APIGateway/APIGateway.csproj +++ b/APIGateway/APIGateway.csproj @@ -9,6 +9,7 @@ + diff --git a/APIGateway/Controllers/GatewayController.cs b/APIGateway/Controllers/GatewayController.cs index 0a13ef3..2fea38f 100644 --- a/APIGateway/Controllers/GatewayController.cs +++ b/APIGateway/Controllers/GatewayController.cs @@ -1,70 +1,121 @@ using System; using System.Collections.Generic; -using System.Linq; +using System.Net.Http; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; - -using Microsoft.Extensions.Caching.Distributed; -using System.Text.Json; +using System.Net.Http.Json; +using System.Text; namespace Gateway { + /// + /// Controller responsible for handling requests and responses at the gateway. + /// [ApiController] [Route("[controller]")] public class GatewayController : ControllerBase { - private static readonly List TheInfo = new List + private readonly HttpClient _httpClient; // Making readonly ensures thread safety + private readonly ILogger _logger; // Making readonly ensures thread safety + private readonly List TheInfo; + + public GatewayController(HttpClient httpClient, ILogger logger) { - new GameInfo { - //Id = 1, - Title = "Snake", - //Content = "~/js/snake.js", - Author = "Fall 2023 Semester", - DateAdded = "", - Description = "Snake is a classic arcade game that challenges the player to control a snake-like creature that grows longer as it eats apples. The player must avoid hitting the walls or the snake's own body, which can end the game.\r\n", - HowTo = "Control with arrow keys.", - //Thumbnail = "/images/snake.jpg" //640x360 resolution - LeaderBoardStack = new Stack>(), + _httpClient = httpClient; + _logger = logger; + TheInfo = new List(); + } - }, - new GameInfo { - //Id = 2, - Title = "Tetris", - //Content = "~/js/tetris.js", - Author = "Fall 2023 Semester", - DateAdded = "", - Description = "Tetris is a classic arcade puzzle game where the player has to arrange falling blocks, also known as Tetronimos, of different shapes and colors to form complete rows on the bottom of the screen. The game gets faster and harder as the player progresses, and ends when the Tetronimos reach the top of the screen.", - HowTo = "Control with arrow keys: Up arrow to spin, down to speed up fall, space to insta-drop.", - //Thumbnail = "/images/tetris.jpg" - LeaderBoardStack = new Stack>(), - - }, - new GameInfo { - //Id = 3, - Title = "Pong", - //Content = "~/js/pong.js", - Author = "Fall 2023 Semester", - DateAdded = "", - Description = "Pong is a classic arcade game where the player uses a paddle to hit a ball against a computer's paddle. Either party scores when the ball makes it past the opponent's paddle.", - HowTo = "Control with arrow keys.", - //Thumbnail = "/images/pong.jpg" - LeaderBoardStack = new Stack>(), - }, + /// + /// Handles GET requests to retrieve game information from microservices. + /// + /// A collection of GameInfo objects. + [HttpGet] + public async Task> Get() + { + try + { + var SnakeTask = AddGameInfo("https://localhost:1948", "/Snake" ); //Snake + var Tetristask = AddGameInfo("https://localhost:2626", "/Tetris"); //Tetris + var PongTask = AddGameInfo("https://localhost:1941", "Pong"); //Pong + await Task.WhenAll(SnakeTask, Tetristask, PongTask); + return TheInfo; + } + catch (Exception ex) + { + _logger.LogError($"An error occurred while fetching data from microservice: {ex.Message}"); + // Return a placeholder list of GameInfo objects indicating failure + return GenerateFailureResponse(); + } + } - }; + /// + /// Attempts to retrieve gameinfo object from a microservice that holds a game info object (snake, tetris, pong) + /// and adds the game info into a list of game info objects + /// + /// + /// + /// + /// + [ApiExplorerSettings(IgnoreApi = true)] + public async Task AddGameInfo(string baseUrl, string endpoint) + { + try + { + using var client = new HttpClient(); + //Set the base address of the microservice + client.BaseAddress = new Uri(baseUrl); - private readonly ILogger _logger; + //Read the data from the endpoint + HttpResponseMessage response = await client.GetAsync(endpoint); - public GatewayController(ILogger logger) - { - _logger = logger; + // Check if the request was successful + if (response.IsSuccessStatusCode) + { + // Deserialize the response content to a GameInfo object + var gameinfo = await response.Content.ReadAsAsync>(); + //Add object to list + lock (TheInfo) + { + TheInfo.AddRange(gameinfo); + } + } + else + { + _logger.LogError($"Failed to retrieve data from microservice at endpoint {endpoint}. Status code: {response.StatusCode}"); + } + + } + catch (Exception ex) //Log error and return false if any exception occurs + { + _logger.LogError(ex.Message); + } } - [HttpGet] - public IEnumerable Get() + /// + /// Generates a placeholder list of GameInfo objects indicating failure to retrieve data. + /// Written with ChatGPT + /// + /// A collection of GameInfo objects indicating failure. + private IEnumerable GenerateFailureResponse() { - return TheInfo; + // Using IEnumerable allows flexibility in returning a placeholder response. + // It allows the method to return different types of collections (e.g., List, Array) if needed in the future. + // In this case, IEnumerable provides a simple way to return a list of failed responses. + + // Generate a placeholder list of GameInfo objects indicating failure to retrieve data + return new List + { + new GameInfo + { + Title = "Failed to retrieve from Microservice", + Author = "Failed to retrieve from Microservice", + Description = "Failed to retrieve from Microservice", + HowTo = "Failed to retrieve from Microservice", + LeaderBoardStack = new Stack>() // Initializing an empty stack + } + }; } } -} \ No newline at end of file +} diff --git a/APIGateway/Dockerfile b/APIGateway/Dockerfile index d139dde..e045293 100644 --- a/APIGateway/Dockerfile +++ b/APIGateway/Dockerfile @@ -7,16 +7,16 @@ EXPOSE 443 FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build WORKDIR /src -COPY ["GameMicroServer/GameMicroServer.csproj", "GameMicroServer/"] -RUN dotnet restore "GameMicroServer/GameMicroServer.csproj" +COPY ["APIGateway/APIGateway.csproj", "APIGateway/"] +RUN dotnet restore "APIGateway/APIGateway.csproj" COPY . . -WORKDIR "/src/GameMicroServer" -RUN dotnet build "GameMicroServer.csproj" -c Release -o /app/build +WORKDIR "/src/APIGateway" +RUN dotnet build "APIGateway.csproj" -c Release -o /app/build FROM build AS publish -RUN dotnet publish "GameMicroServer.csproj" -c Release -o /app/publish /p:UseAppHost=false +RUN dotnet publish "APIGateway.csproj" -c Release -o /app/publish /p:UseAppHost=false FROM base AS final WORKDIR /app COPY --from=publish /app/publish . -ENTRYPOINT ["dotnet", "GameMicroServer.dll"] \ No newline at end of file +ENTRYPOINT ["dotnet", "APIGateway.dll"] \ No newline at end of file diff --git a/APIGateway/GameInfo.cs b/APIGateway/GameInfo.cs index c3110d3..028ccda 100644 --- a/APIGateway/GameInfo.cs +++ b/APIGateway/GameInfo.cs @@ -2,11 +2,14 @@ { public class GameInfo { + public int Id { get; set; } public string Title { get; set; } public string Author { get; set; } + public string Content { get; set; } public string Description { get; set; } public string DateAdded { get; set; } public string HowTo { get; set; } + public string Thumbnail { get; set; } public Stack> LeaderBoardStack { get; set; } } } \ No newline at end of file diff --git a/APIGateway/Program.cs b/APIGateway/Program.cs index 378a9f7..217f16e 100644 --- a/APIGateway/Program.cs +++ b/APIGateway/Program.cs @@ -11,6 +11,16 @@ builder.Services.AddSwaggerGen(); builder.Services.AddOcelot(builder.Configuration); +// Register HttpClient +builder.Services.AddHttpClient(); + +// This creates the timestamp for the logger. +builder.Logging.AddSimpleConsole(options => +{ + options.IncludeScopes = true; + options.TimestampFormat = "yyyy-MM-dd HH:mm:ss "; +}); + var app = builder.Build(); // Configure the HTTP request pipeline.