1.1. GameStore Dto
namespace GameStore.Api.Dtos;
// A DTO is a contract between the client and the server since it represents
// a shared agreement about how data will be transferred and used
public record GameDto
{
public int Id { get; init; }
public string Name { get; init; } = string.Empty;
public string Genre { get; init; } = string.Empty;
public decimal Price { get; init; }
public DateOnly ReleaseDate { get; init; }
}
namespace GameStore.Api.Dtos;
// A DTO is a contract between the client and the server since it represents
// a shared agreement about how data will be transferred and used
public record GameDto(
int Id,
string Name,
string Genre,
decimal Price,
DateOnly ReleaseDate
);
1.2. How to Write an Endpoint?
- First, write a DTO.
- Second, write the endpoint
namespace GameStore.Api.Dtos;
public record CreateGameDto(
string Name,
string Genre,
decimal Price,
DateOnly ReleaseDate
);
app.MapPost("/games", (CreateGameDto newGame) =>
{
GameDto game = new(
games.Count + 1,
newGame.Name,
newGame.Genre,
newGame.Price,
newGame.ReleaseDate
);
games.Add(game);
return Results.CreatedAtRoute("GetGame", new {id = game.Id}, game);
});
1.2.1. PUT
app.MapPut("/games/{id}", (int id, UpdateGameDto updatedGame) =>
{
var index = games.FindIndex(game => game.Id == id);
games[index] = new GameDto(
id,
updatedGame.Name,
updatedGame.Genre,
updatedGame.Price,
updatedGame.ReleaseDate
);
return Results.NoContent();
});