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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -396,3 +396,4 @@ FodyWeavers.xsd

# JetBrains Rider
*.sln.iml
/Backend/backend.wwwapi/appsettings.json
22 changes: 22 additions & 0 deletions Backend/backend.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}") = "backend.wwwapi", "backend.wwwapi\backend.wwwapi.csproj", "{64E077E3-919C-4422-BAD5-CFE4433F1600}"
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
{64E077E3-919C-4422-BAD5-CFE4433F1600}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{64E077E3-919C-4422-BAD5-CFE4433F1600}.Debug|Any CPU.Build.0 = Debug|Any CPU
{64E077E3-919C-4422-BAD5-CFE4433F1600}.Release|Any CPU.ActiveCfg = Release|Any CPU
{64E077E3-919C-4422-BAD5-CFE4433F1600}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
EndGlobal
35 changes: 35 additions & 0 deletions Backend/backend.wwwapi/DataContext/DogContext.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
using backend.wwwapi.Models;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using System.Reflection.Emit;

namespace backend.wwwapi.DataContext
{
public class DogContext : 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<Dog>().HasData(
new Dog { Id = 1, Name = "First task", Completed = true },
new Dog { Id = 2, Name = "Second task", Completed = false },
new Dog { Id = 3, Name = "Third task", Completed = true }
);
}

public DbSet<Dog> Dogs { get; set; }
}
}
109 changes: 109 additions & 0 deletions Backend/backend.wwwapi/Endpoints/DogAPI.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
using backend.wwwapi.Repository;
using backend.wwwapi.Models;

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

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

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

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

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

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

// Update the fields
if (updatedTodo.Name != null)
existingTodo.Name = updatedTodo.Name;
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<Dog> 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);
}
}
}
}
69 changes: 69 additions & 0 deletions Backend/backend.wwwapi/Migrations/20241017135105_first.Designer.cs

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

48 changes: 48 additions & 0 deletions Backend/backend.wwwapi/Migrations/20241017135105_first.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
using Microsoft.EntityFrameworkCore.Migrations;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;

#nullable disable

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

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

migrationBuilder.InsertData(
table: "Dogs",
columns: new[] { "Id", "Completed", "Name" },
values: new object[,]
{
{ 1, true, "First task" },
{ 2, false, "Second task" },
{ 3, true, "Third task" }
});
}

/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Dogs");
}
}
}
66 changes: 66 additions & 0 deletions Backend/backend.wwwapi/Migrations/DogContextModelSnapshot.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
// <auto-generated />
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
using backend.wwwapi.DataContext;

#nullable disable

namespace backend.wwwapi.Migrations
{
[DbContext(typeof(DogContext))]
partial class DogContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "8.0.10")
.HasAnnotation("Relational:MaxIdentifierLength", 63);

NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);

modelBuilder.Entity("backend.wwwapi.Models.Dog", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");

NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));

b.Property<bool>("Completed")
.HasColumnType("boolean");

b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");

b.HasKey("Id");

b.ToTable("Dogs");

b.HasData(
new
{
Id = 1,
Completed = true,
Name = "First task"
},
new
{
Id = 2,
Completed = false,
Name = "Second task"
},
new
{
Id = 3,
Completed = true,
Name = "Third task"
});
});
#pragma warning restore 612, 618
}
}
}
10 changes: 10 additions & 0 deletions Backend/backend.wwwapi/Models/Dog.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
namespace backend.wwwapi.Models
{
public class Dog
{
public int Id { get; set; }
public string Name { get; set; }

public bool Completed { get; set; }
}
}
Loading