Skip to content
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
22 changes: 22 additions & 0 deletions exercise.sln
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.0.31903.59
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "exercise.wwwapi", "exercise.wwwapi\exercise.wwwapi.csproj", "{179BF0E1-48F6-433A-88CB-0B42A9CB3F7E}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{179BF0E1-48F6-433A-88CB-0B42A9CB3F7E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{179BF0E1-48F6-433A-88CB-0B42A9CB3F7E}.Debug|Any CPU.Build.0 = Debug|Any CPU
{179BF0E1-48F6-433A-88CB-0B42A9CB3F7E}.Release|Any CPU.ActiveCfg = Release|Any CPU
{179BF0E1-48F6-433A-88CB-0B42A9CB3F7E}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
EndGlobal
1 change: 1 addition & 0 deletions exercise.wwwapi/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
appsettings.json
33 changes: 33 additions & 0 deletions exercise.wwwapi/DataContext/TodoContext.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
using exercise.wwwapi.Models;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json.Linq;

namespace exercise.wwwapi.DataContext
{
public class TodoContext : DbContext
{
private static string GetConnectionString()
{
string jsonSettings = File.ReadAllText("appsettings.json");
JObject configuration = JObject.Parse(jsonSettings);
return configuration["ConnectionStrings"]["DefaultConnection"].ToString();
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseNpgsql(GetConnectionString());
}

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);

modelBuilder.Entity<Todo>().HasData(
new Todo { Id = 1, Title = "First task", Completed = true },
new Todo { Id = 2, Title = "Second task", Completed = false },
new Todo { Id = 3, Title = "Third task", Completed = true }
);
}

public DbSet<Todo> Todos { get; set; }
}
}
109 changes: 109 additions & 0 deletions exercise.wwwapi/Endpoints/TodoAPI.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
using exercise.wwwapi.Models;
using exercise.wwwapi.Repository;

namespace exercise.wwwapi.EndPoints
{
public static class TodoAPI
{
public static void ConfigureTodoAPI(this WebApplication app)
{
app.MapGet("/", GetIndex);
app.MapGet("/todos", GetTodos);
app.MapPost("/todos", CreateTodo);
app.MapPut("/todos/{id:int}", UpdateTodo);
app.MapDelete("/todos/{id:int}", DeleteTodo);
}

private static async Task<IResult> GetIndex(IDatabaseRepository<Todo> repository)
{
try
{
return Results.Ok("Working");
}
catch (Exception ex)
{
return Results.Problem(ex.Message);
}
}

private static async Task<IResult> GetTodos(IDatabaseRepository<Todo> repository)
{
try
{
return Results.Ok(repository.GetAll());
}
catch (Exception ex)
{
return Results.Problem(ex.Message);
}
}

private static async Task<IResult> CreateTodo(Todo todo, IDatabaseRepository<Todo> repository)
{
try
{
if (todo == null || string.IsNullOrWhiteSpace(todo.Title))
{
return Results.BadRequest("Invalid Todo item.");
}

repository.Insert(todo); // Assuming repository has an AddAsync method
return Results.Created($"/todos/{todo.Id}", todo); // Return the created todo with its location
}
catch (Exception ex)
{
return Results.Problem(ex.Message);
}
}

private static async Task<IResult> UpdateTodo(int id, Todo updatedTodo, IDatabaseRepository<Todo> repository)
{
try
{
// Find the existing Todo
var existingTodo = repository.GetById(id);
if (existingTodo == null)
{
return Results.NotFound($"Todo with Id {id} not found.");
}

// Update the fields
if (updatedTodo.Title != null)
existingTodo.Title = updatedTodo.Title;
if (updatedTodo.Completed != null)
existingTodo.Completed = updatedTodo.Completed;

// Save changes
repository.Update(existingTodo);

return Results.Ok(existingTodo);
}
catch (Exception ex)
{
return Results.Problem(ex.Message);
}
}

private static async Task<IResult> DeleteTodo(int id, IDatabaseRepository<Todo> repository)
{
try
{
// Find the Todo by Id
var existingTodo = repository.GetById(id);
if (existingTodo == null)
{
return Results.NotFound($"Todo with Id {id} not found.");
}

// Delete the Todo
repository.Delete(id);

return Results.Ok(existingTodo);
}
catch (Exception ex)
{
return Results.Problem(ex.Message);
}
}
}
}
2 changes: 2 additions & 0 deletions exercise.wwwapi/GUIDE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# Created a RDS database (PostgreSQL) for the application, and making sure the connection was successful. Adding the connection to my application, and then migrating to make sure the database is populated correctly.
# Created and configured a Elastic Beanstalk environment to deploy the backend API.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

36 changes: 36 additions & 0 deletions exercise.wwwapi/Migrations/20241008184527_InitialCreate.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
using Microsoft.EntityFrameworkCore.Migrations;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;

#nullable disable

namespace exercise.wwwapi.Migrations
{
/// <inheritdoc />
public partial class InitialCreate : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Todos",
columns: table => new
{
Id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
Title = table.Column<string>(type: "text", nullable: false),
Completed = table.Column<bool>(type: "boolean", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Todos", x => x.Id);
});
}

/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Todos");
}
}
}

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

45 changes: 45 additions & 0 deletions exercise.wwwapi/Migrations/20241008185152_SeedInitialData.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
using Microsoft.EntityFrameworkCore.Migrations;

#nullable disable

#pragma warning disable CA1814 // Prefer jagged arrays over multidimensional

namespace exercise.wwwapi.Migrations
{
/// <inheritdoc />
public partial class SeedInitialData : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.InsertData(
table: "Todos",
columns: new[] { "Id", "Completed", "Title" },
values: new object[,]
{
{ 1, true, "First task" },
{ 2, false, "Second task" },
{ 3, true, "Third task" }
});
}

/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DeleteData(
table: "Todos",
keyColumn: "Id",
keyValue: 1);

migrationBuilder.DeleteData(
table: "Todos",
keyColumn: "Id",
keyValue: 2);

migrationBuilder.DeleteData(
table: "Todos",
keyColumn: "Id",
keyValue: 3);
}
}
}
Loading