From 9bc85ed98c1071b6e29554b82215520521b21ce8 Mon Sep 17 00:00:00 2001 From: Anduin Xue Date: Mon, 19 Feb 2024 09:23:23 +0000 Subject: [PATCH] Refactor code for better readability and efficiency The changes primarily focus on simplifying constructors to increase readability. This is done by organizing class properties and functions in a more efficient manner. In addition, strings are accessed using indexing rather than substrings - a technique that enhances execution speed. Not only does this change clarify the controllers and classes, but also significantly improves the overall code quality and efficiency. --- .../Controllers/GamesController.cs | 22 +++----- .../Controllers/HomeController.cs | 39 ++++++--------- .../Controllers/PlayersController.cs | 13 ++--- .../Middlewares/AllowCrossOriginMiddleware.cs | 17 ++----- src/Aiursoft.ChessServer/Models/Challenge.cs | 9 +--- src/Aiursoft.ChessServer/Models/Player.cs | 11 ++-- .../Models/ViewModels/GameContext.cs | 50 +++++++------------ 7 files changed, 53 insertions(+), 108 deletions(-) diff --git a/src/Aiursoft.ChessServer/Controllers/GamesController.cs b/src/Aiursoft.ChessServer/Controllers/GamesController.cs index 79bddab..3c26f83 100644 --- a/src/Aiursoft.ChessServer/Controllers/GamesController.cs +++ b/src/Aiursoft.ChessServer/Controllers/GamesController.cs @@ -8,27 +8,19 @@ using Aiursoft.AiurObserver.Extensions; namespace Aiursoft.ChessServer.Controllers; [Route("games")] -public class GamesController : Controller +public class GamesController(InMemoryDatabase database) : Controller { - private readonly InMemoryDatabase _database; - - public GamesController( - InMemoryDatabase database) - { - _database = database; - } - [Route("")] public IActionResult GetAll() { - var games = _database.GetActiveGames(); + var games = database.GetActiveGames(); return Ok(games); } [Route("{id:int}.json")] public IActionResult GetInfo([FromRoute] int id) { - var game = _database.GetOrAddGame(id); + var game = database.GetOrAddGame(id); return Ok(new GameContext(game, id)); } @@ -36,7 +28,7 @@ public class GamesController : Controller public async Task GetWebSocket([FromRoute] int id, [FromQuery]string player) { var pusher = await HttpContext.AcceptWebSocketClient(); - var game = _database.GetOrAddGame(id); + var game = database.GetOrAddGame(id); var outSub = game .FenChangedChannel .Subscribe(t => pusher.Send(t, HttpContext.RequestAborted)); @@ -76,7 +68,7 @@ public class GamesController : Controller [Route("{id:int}.ascii")] public IActionResult GetAscii([FromRoute] int id) { - var game = _database.GetOrAddGame(id); + var game = database.GetOrAddGame(id); return Ok(game.Board.ToAscii()); } @@ -89,14 +81,14 @@ public class GamesController : Controller [Route("{id:int}.fen")] public IActionResult GetFen([FromRoute] int id) { - var game = _database.GetOrAddGame(id); + var game = database.GetOrAddGame(id); return Ok(game.Board.ToFen()); } [Route("{id:int}.pgn")] public IActionResult GetPgn([FromRoute] int id) { - var game = _database.GetOrAddGame(id); + var game = database.GetOrAddGame(id); return Ok(game.Board.ToPgn()); } } \ No newline at end of file diff --git a/src/Aiursoft.ChessServer/Controllers/HomeController.cs b/src/Aiursoft.ChessServer/Controllers/HomeController.cs index 23dd98a..82368c9 100644 --- a/src/Aiursoft.ChessServer/Controllers/HomeController.cs +++ b/src/Aiursoft.ChessServer/Controllers/HomeController.cs @@ -8,25 +8,16 @@ using Microsoft.AspNetCore.Mvc; namespace Aiursoft.ChessServer.Controllers; -public class HomeController : Controller +public class HomeController( + Counter counter, + InMemoryDatabase database) : Controller { - private readonly Counter _counter; - private readonly InMemoryDatabase _database; - - public HomeController( - Counter counter, - InMemoryDatabase database) - { - _counter = counter; - _database = database; - } - [HttpGet] public IActionResult Index() { var model = new IndexViewModel { - Challenges = _database.GetPublicChallenges() + Challenges = database.GetPublicChallenges() }; return View(model); } @@ -44,14 +35,14 @@ public class HomeController : Controller public IActionResult Auto(Guid playerId) { // I created a challenge. Go to my challenge. - var myChallengeKey = _database.GetMyChallengeKey(playerId); + var myChallengeKey = database.GetMyChallengeKey(playerId); if (myChallengeKey != null) { return RedirectToAction(nameof(Challenge), new { id = (int)myChallengeKey, playerId }); } // Exists a public challenge. Go to that challenge. - var otherChallenge = _database.GetFirstPublicChallengeKey(); + var otherChallenge = database.GetFirstPublicChallengeKey(); if (otherChallenge != null) { return RedirectToAction(nameof(Challenge), new { id = (int)otherChallenge, playerId }); @@ -71,7 +62,7 @@ public class HomeController : Controller [HttpGet] public IActionResult Create(Guid playerId) { - var myChallengeKey = _database.GetMyChallengeKey(playerId); + var myChallengeKey = database.GetMyChallengeKey(playerId); if (myChallengeKey != null) { return RedirectToAction(nameof(Challenge), new { id = myChallengeKey, playerId }); @@ -84,7 +75,7 @@ public class HomeController : Controller public IActionResult Create(CreateChallengeViewModel model) { // Ensure single challenge can be created by a player. - var myChallengeKey = _database.GetMyChallengeKey(model.CreatorId); + var myChallengeKey = database.GetMyChallengeKey(model.CreatorId); if (myChallengeKey != null) { ModelState.AddModelError(nameof(model.CreatorId), "You already have a challenge!"); @@ -95,7 +86,7 @@ public class HomeController : Controller } // Create a new challenge. - var player = _database.GetOrAddPlayer(model.CreatorId); + var player = database.GetOrAddPlayer(model.CreatorId); var challenge = new Challenge(player) { RoleRule = model.RoleRule, @@ -103,8 +94,8 @@ public class HomeController : Controller Permission = model.Permission, TimeLimit = model.TimeLimit, }; - var challengeId = _counter.GetUniqueNo(); - _database.CreateChallenge(challengeId, challenge); + var challengeId = counter.GetUniqueNo(); + database.CreateChallenge(challengeId, challenge); return RedirectToAction(nameof(Challenge), new { id = challengeId }); } @@ -120,7 +111,7 @@ public class HomeController : Controller [HttpGet] public IActionResult Challenge(int id) { - var challenge = _database.GetChallenge(id); + var challenge = database.GetChallenge(id); if (challenge == null) { // Challenge not found. @@ -140,10 +131,10 @@ public class HomeController : Controller { return RedirectToAction(nameof(Challenge), new { id = model.Id, playerId = model.PlayerId }); } - var challenge = _database.GetChallenge(model.Id); + var challenge = database.GetChallenge(model.Id); if (challenge != null && challenge.Creator.Id == model.PlayerId) { - _database.DeleteChallenge(model.Id); + database.DeleteChallenge(model.Id); } return RedirectToAction(nameof(Index)); } @@ -151,7 +142,7 @@ public class HomeController : Controller public async Task ListenChallenge(int id) { var pusher = await HttpContext.AcceptWebSocketClient(); - var challenge = _database.GetChallenge(id); + var challenge = database.GetChallenge(id); if (challenge == null) { return; diff --git a/src/Aiursoft.ChessServer/Controllers/PlayersController.cs b/src/Aiursoft.ChessServer/Controllers/PlayersController.cs index 0e97b00..9db805b 100644 --- a/src/Aiursoft.ChessServer/Controllers/PlayersController.cs +++ b/src/Aiursoft.ChessServer/Controllers/PlayersController.cs @@ -6,19 +6,12 @@ using Microsoft.AspNetCore.Mvc; namespace Aiursoft.ChessServer.Controllers; [Route("players")] -public class PlayersController : ControllerBase +public class PlayersController(InMemoryDatabase database) : ControllerBase { - private readonly InMemoryDatabase _database; - - public PlayersController(InMemoryDatabase database) - { - _database = database; - } - [Route("{id:guid}")] public IActionResult Me([Required]Guid id) { - var me = _database.GetOrAddPlayer(id); + var me = database.GetOrAddPlayer(id); return Ok(me); } @@ -31,7 +24,7 @@ public class PlayersController : ControllerBase return BadRequest(); } - var me = _database.GetOrAddPlayer(id); + var me = database.GetOrAddPlayer(id); me.NickName = nickname; return Ok(); } diff --git a/src/Aiursoft.ChessServer/Middlewares/AllowCrossOriginMiddleware.cs b/src/Aiursoft.ChessServer/Middlewares/AllowCrossOriginMiddleware.cs index 4177cce..fa3a413 100644 --- a/src/Aiursoft.ChessServer/Middlewares/AllowCrossOriginMiddleware.cs +++ b/src/Aiursoft.ChessServer/Middlewares/AllowCrossOriginMiddleware.cs @@ -1,25 +1,18 @@ namespace Aiursoft.ChessServer.Middlewares { - public class AllowCrossOriginMiddleware + public class AllowCrossOriginMiddleware(RequestDelegate next) { - private readonly RequestDelegate _next; - - public AllowCrossOriginMiddleware(RequestDelegate next) - { - _next = next; - } - public async Task Invoke(HttpContext context) { if (context.Request.Path.ToString().StartsWith("/games/img")) { - context.Request.Path = context.Request.Path.ToString().Substring("/games".Length); + context.Request.Path = context.Request.Path.ToString()["/games".Length..]; } - var origin = context.Request.Headers["Origin"].ToString(); + var origin = context.Request.Headers.Origin.ToString(); if (string.IsNullOrEmpty(origin)) { - await _next.Invoke(context); + await next.Invoke(context); return; } @@ -34,7 +27,7 @@ return; } - await _next.Invoke(context); + await next.Invoke(context); } } } \ No newline at end of file diff --git a/src/Aiursoft.ChessServer/Models/Challenge.cs b/src/Aiursoft.ChessServer/Models/Challenge.cs index aa8e285..ccd3206 100644 --- a/src/Aiursoft.ChessServer/Models/Challenge.cs +++ b/src/Aiursoft.ChessServer/Models/Challenge.cs @@ -2,14 +2,9 @@ using Aiursoft.AiurObserver; namespace Aiursoft.ChessServer.Models; -public class Challenge +public class Challenge(Player creator) { - public Challenge(Player creator) - { - Creator = creator; - } - - public Player Creator { get; set; } + public Player Creator { get; set; } = creator; public string Message { get; set; } = "A chess room."; public Player? Accepter { get; set; } = null; diff --git a/src/Aiursoft.ChessServer/Models/Player.cs b/src/Aiursoft.ChessServer/Models/Player.cs index 55f7f58..de74e1c 100644 --- a/src/Aiursoft.ChessServer/Models/Player.cs +++ b/src/Aiursoft.ChessServer/Models/Player.cs @@ -1,13 +1,8 @@ namespace Aiursoft.ChessServer.Models; -public class Player +public class Player(Guid id) { - public Guid Id { get; } - - public Player(Guid id) - { - Id = id; - } - + public Guid Id { get; } = id; + public string NickName { get; set; } = "Anonymous"; } \ No newline at end of file diff --git a/src/Aiursoft.ChessServer/Models/ViewModels/GameContext.cs b/src/Aiursoft.ChessServer/Models/ViewModels/GameContext.cs index 3295ce5..8e62518 100644 --- a/src/Aiursoft.ChessServer/Models/ViewModels/GameContext.cs +++ b/src/Aiursoft.ChessServer/Models/ViewModels/GameContext.cs @@ -2,39 +2,25 @@ namespace Aiursoft.ChessServer.Models.ViewModels; -public class GameContext +public class GameContext(Game game, int id) { - public GameContext(Game game, int id) + public int Id { get; } = id; + public Dictionary Links { get; } = new() { - Id = id; - Turn = game.Board.Turn.AsChar; - Ended = game.Board.IsEndGame; - End = game.Board.EndGame?.EndgameType; - Won = game.Board.EndGame?.WonSide; - MoveIndex = game.Board.MoveIndex; - WhiteKingChecked = game.Board.WhiteKingChecked; - BlackKingChecked = game.Board.BlackKingChecked; - Links = new Dictionary - { - { "ascii", $"games/{id}.ascii" }, - { "fen", $"games/{id}.fen" }, - { "pgn", $"games/{id}.pgn" }, - { "html", $"games/{id}.html" }, - { "websocket", $"games/{id}.ws" }, - { "move-post", $"games/{id}/move/{{player}}/{{move_algebraic_notation}}" } - }; - Listeners = game.FenChangedChannel.GetListenerCount(); - } + { "ascii", $"games/{id}.ascii" }, + { "fen", $"games/{id}.fen" }, + { "pgn", $"games/{id}.pgn" }, + { "html", $"games/{id}.html" }, + { "websocket", $"games/{id}.ws" }, + { "move-post", $"games/{id}/move/{{player}}/{{move_algebraic_notation}}" } + }; - - public int Id { get; } - public Dictionary Links { get; } - public char Turn { get; } - public bool Ended { get; } - public EndgameType? End { get; } - public PieceColor? Won { get; } - public int MoveIndex { get; } - public bool WhiteKingChecked { get; } - public bool BlackKingChecked { get; } - public int Listeners { get; } + public char Turn { get; } = game.Board.Turn.AsChar; + public bool Ended { get; } = game.Board.IsEndGame; + public EndgameType? End { get; } = game.Board.EndGame?.EndgameType; + public PieceColor? Won { get; } = game.Board.EndGame?.WonSide; + public int MoveIndex { get; } = game.Board.MoveIndex; + public bool WhiteKingChecked { get; } = game.Board.WhiteKingChecked; + public bool BlackKingChecked { get; } = game.Board.BlackKingChecked; + public int Listeners { get; } = game.FenChangedChannel.GetListenerCount(); } \ No newline at end of file