From 8013cc90e2a271bea5c41957f3e7aa337cc7f245 Mon Sep 17 00:00:00 2001 From: George Date: Fri, 18 Oct 2024 09:25:09 +0200 Subject: [PATCH 01/20] Rebase --- cohort-backend.sln | 22 ++ .../DTO/Response/GetAllResponse.cs | 7 + cohort-backend.wwwapi/Data/DatabaseContext.cs | 55 ++++ .../Endpoints/UserEndpoint.cs | 27 ++ .../20241017131641_First.Designer.cs | 253 ++++++++++++++++++ .../Migrations/20241017131641_First.cs | 143 ++++++++++ .../DatabaseContextModelSnapshot.cs | 250 +++++++++++++++++ cohort-backend.wwwapi/Models/Comment.cs | 24 ++ cohort-backend.wwwapi/Models/Post.cs | 23 ++ cohort-backend.wwwapi/Models/User.cs | 31 +++ cohort-backend.wwwapi/Program.cs | 22 ++ .../Properties/launchSettings.json | 41 +++ .../Repository/IUserRepository.cs | 11 + .../Repository/UserRepository.cs | 31 +++ .../cohort-backend.wwwapi.csproj | 25 ++ .../cohort-backend.wwwapi.http | 6 + 16 files changed, 971 insertions(+) create mode 100644 cohort-backend.sln create mode 100644 cohort-backend.wwwapi/DTO/Response/GetAllResponse.cs create mode 100644 cohort-backend.wwwapi/Data/DatabaseContext.cs create mode 100644 cohort-backend.wwwapi/Endpoints/UserEndpoint.cs create mode 100644 cohort-backend.wwwapi/Migrations/20241017131641_First.Designer.cs create mode 100644 cohort-backend.wwwapi/Migrations/20241017131641_First.cs create mode 100644 cohort-backend.wwwapi/Migrations/DatabaseContextModelSnapshot.cs create mode 100644 cohort-backend.wwwapi/Models/Comment.cs create mode 100644 cohort-backend.wwwapi/Models/Post.cs create mode 100644 cohort-backend.wwwapi/Models/User.cs create mode 100644 cohort-backend.wwwapi/Program.cs create mode 100644 cohort-backend.wwwapi/Properties/launchSettings.json create mode 100644 cohort-backend.wwwapi/Repository/IUserRepository.cs create mode 100644 cohort-backend.wwwapi/Repository/UserRepository.cs create mode 100644 cohort-backend.wwwapi/cohort-backend.wwwapi.csproj create mode 100644 cohort-backend.wwwapi/cohort-backend.wwwapi.http diff --git a/cohort-backend.sln b/cohort-backend.sln new file mode 100644 index 0000000..05c08ea --- /dev/null +++ b/cohort-backend.sln @@ -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}") = "cohort-backend.wwwapi", "cohort-backend.wwwapi\cohort-backend.wwwapi.csproj", "{0B2A287D-7823-49DA-A949-8180094623D8}" +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 + {0B2A287D-7823-49DA-A949-8180094623D8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {0B2A287D-7823-49DA-A949-8180094623D8}.Debug|Any CPU.Build.0 = Debug|Any CPU + {0B2A287D-7823-49DA-A949-8180094623D8}.Release|Any CPU.ActiveCfg = Release|Any CPU + {0B2A287D-7823-49DA-A949-8180094623D8}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection +EndGlobal diff --git a/cohort-backend.wwwapi/DTO/Response/GetAllResponse.cs b/cohort-backend.wwwapi/DTO/Response/GetAllResponse.cs new file mode 100644 index 0000000..d13e03e --- /dev/null +++ b/cohort-backend.wwwapi/DTO/Response/GetAllResponse.cs @@ -0,0 +1,7 @@ +namespace cohort_backend.wwwapi.DTO.Response +{ + public class GetAllResponse where T : class + { + public List ResponseData { get; set; } = new List(); + } +} diff --git a/cohort-backend.wwwapi/Data/DatabaseContext.cs b/cohort-backend.wwwapi/Data/DatabaseContext.cs new file mode 100644 index 0000000..9942315 --- /dev/null +++ b/cohort-backend.wwwapi/Data/DatabaseContext.cs @@ -0,0 +1,55 @@ +using System.Collections.Generic; +using System.Reflection.Emit; +using cohort_backend.wwwapi.Models; +using cohort_backend.wwwapi.Models; +using Microsoft.EntityFrameworkCore; + +namespace cohort_backend.wwwapi.Data +{ + public class DatabaseContext : DbContext + { + private string _connectionString; + + public DatabaseContext(DbContextOptions options) : base(options) + { + var configuration = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build(); + _connectionString = configuration.GetValue("ConnectionStrings:DefaultConnectionString")!; + } + + protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) + { + optionsBuilder.UseNpgsql(_connectionString); + } + + protected override void OnModelCreating(ModelBuilder modelBuilder) + { + //TODO: Seed data + modelBuilder.Entity().HasData( + new User { Id = 1, FirstName = "Julia", LastName = "Doe", Street = "Lakkegata", City = "Oslo", Email = "julia@gmail.com", FavoriteColor = "#FFC0CB" }, + new User { Id = 2, FirstName = "John", LastName = "Doe", Street = "Nannestad", City = "Gardermoen", Email = "john@gmail.com", FavoriteColor = "#0000FF" }, + new User { Id = 3, FirstName = "George", LastName = "Doe", Street = "Georgia", City = "Mega-City One", Email = "george@gmail.com", FavoriteColor = "#301934" } + ); + + modelBuilder.Entity().HasData( + new Post { Id = 1, Title = "Julia's post", Content = "Hi :3", UserId = 1 }, + new Post { Id = 2, Title = "John's post", Content = "uwu", UserId = 2 }, + new Post { Id = 3, Title = "George's post", Content = "I love Judge Dredd", UserId = 3 } + ); + + modelBuilder.Entity().HasData( + new Comment { Id = 1, Content = "Goodbye", PostId = 1, UserId = 2 }, + new Comment { Id = 2, Content = "Kawaii", PostId = 2, UserId = 1 }, + new Comment { Id = 3, Content = "Nani", PostId = 2, UserId = 3 }, + new Comment { Id = 4, Content = "Me too!", PostId = 3, UserId = 2 }, + new Comment { Id = 5, Content = "What is that?", PostId = 3, UserId = 1 } + ); + + base.OnModelCreating(modelBuilder); + } + + //public DbSet Post { get; set; } + public DbSet Users { get; set; } + public DbSet Post { get; set; } + public DbSet Comments { get; set; } + } +} diff --git a/cohort-backend.wwwapi/Endpoints/UserEndpoint.cs b/cohort-backend.wwwapi/Endpoints/UserEndpoint.cs new file mode 100644 index 0000000..450b0a7 --- /dev/null +++ b/cohort-backend.wwwapi/Endpoints/UserEndpoint.cs @@ -0,0 +1,27 @@ +using cohort_backend.wwwapi.Repository; +using Microsoft.AspNetCore.Mvc; + +namespace cohort_backend.wwwapi.Endpoints +{ + public static class UserEndpoint + { + public static void ConfigureUserEndpoint(this WebApplication app) + { + var userGroup = app.MapGroup("/users"); + + userGroup.MapGet("/", GetUsers); + } + + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status404NotFound)] + public static async Task GetUsers(IUserRepository repository) + { + var users = await repository.GetUsers(); + if (users != null) + { + + } + return TypedResults.Ok(); + } + } +} diff --git a/cohort-backend.wwwapi/Migrations/20241017131641_First.Designer.cs b/cohort-backend.wwwapi/Migrations/20241017131641_First.Designer.cs new file mode 100644 index 0000000..559df31 --- /dev/null +++ b/cohort-backend.wwwapi/Migrations/20241017131641_First.Designer.cs @@ -0,0 +1,253 @@ +// +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; +using cohort_backend.wwwapi.Data; + +#nullable disable + +namespace cohort_backend.wwwapi.Migrations +{ + [DbContext(typeof(DatabaseContext))] + [Migration("20241017131641_First")] + partial class First + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "8.0.10") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("cohort_backend.wwwapi.Models.Comment", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasColumnName("id"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Content") + .IsRequired() + .HasColumnType("text") + .HasColumnName("content"); + + b.Property("PostId") + .HasColumnType("integer"); + + b.Property("UserId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("PostId"); + + b.HasIndex("UserId"); + + b.ToTable("comments"); + + b.HasData( + new + { + Id = 1, + Content = "Goodbye", + PostId = 1, + UserId = 2 + }, + new + { + Id = 2, + Content = "Kawaii", + PostId = 2, + UserId = 1 + }, + new + { + Id = 3, + Content = "Nani", + PostId = 2, + UserId = 3 + }, + new + { + Id = 4, + Content = "Me too!", + PostId = 3, + UserId = 2 + }, + new + { + Id = 5, + Content = "What is that?", + PostId = 3, + UserId = 1 + }); + }); + + modelBuilder.Entity("cohort_backend.wwwapi.Models.Post", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasColumnName("id"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Content") + .IsRequired() + .HasColumnType("text") + .HasColumnName("content"); + + b.Property("Title") + .IsRequired() + .HasColumnType("text") + .HasColumnName("title"); + + b.Property("UserId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("posts"); + + b.HasData( + new + { + Id = 1, + Content = "Hi :3", + Title = "Julia's post", + UserId = 1 + }, + new + { + Id = 2, + Content = "uwu", + Title = "John's post", + UserId = 2 + }, + new + { + Id = 3, + Content = "I love Judge Dredd", + Title = "George's post", + UserId = 3 + }); + }); + + modelBuilder.Entity("cohort_backend.wwwapi.Models.User", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasColumnName("id"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("City") + .IsRequired() + .HasColumnType("text") + .HasColumnName("city"); + + b.Property("Email") + .IsRequired() + .HasColumnType("text") + .HasColumnName("email"); + + b.Property("FavoriteColor") + .IsRequired() + .HasColumnType("text") + .HasColumnName("favoriteColor"); + + b.Property("FirstName") + .IsRequired() + .HasColumnType("text") + .HasColumnName("firstName"); + + b.Property("LastName") + .IsRequired() + .HasColumnType("text") + .HasColumnName("lastName"); + + b.Property("Street") + .IsRequired() + .HasColumnType("text") + .HasColumnName("street"); + + b.HasKey("Id"); + + b.ToTable("users"); + + b.HasData( + new + { + Id = 1, + City = "Oslo", + Email = "julia@gmail.com", + FavoriteColor = "#FFC0CB", + FirstName = "Julia", + LastName = "Doe", + Street = "Lakkegata" + }, + new + { + Id = 2, + City = "Gardermoen", + Email = "john@gmail.com", + FavoriteColor = "#0000FF", + FirstName = "John", + LastName = "Doe", + Street = "Nannestad" + }, + new + { + Id = 3, + City = "Mega-City One", + Email = "george@gmail.com", + FavoriteColor = "#301934", + FirstName = "George", + LastName = "Doe", + Street = "Georgia" + }); + }); + + modelBuilder.Entity("cohort_backend.wwwapi.Models.Comment", b => + { + b.HasOne("cohort_backend.wwwapi.Models.Post", "Post") + .WithMany() + .HasForeignKey("PostId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("cohort_backend.wwwapi.Models.User", "User") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Post"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("cohort_backend.wwwapi.Models.Post", b => + { + b.HasOne("cohort_backend.wwwapi.Models.User", "User") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/cohort-backend.wwwapi/Migrations/20241017131641_First.cs b/cohort-backend.wwwapi/Migrations/20241017131641_First.cs new file mode 100644 index 0000000..432e27d --- /dev/null +++ b/cohort-backend.wwwapi/Migrations/20241017131641_First.cs @@ -0,0 +1,143 @@ +using Microsoft.EntityFrameworkCore.Migrations; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +#pragma warning disable CA1814 // Prefer jagged arrays over multidimensional + +namespace cohort_backend.wwwapi.Migrations +{ + /// + public partial class First : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "users", + columns: table => new + { + id = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + firstName = table.Column(type: "text", nullable: false), + lastName = table.Column(type: "text", nullable: false), + street = table.Column(type: "text", nullable: false), + city = table.Column(type: "text", nullable: false), + email = table.Column(type: "text", nullable: false), + favoriteColor = table.Column(type: "text", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_users", x => x.id); + }); + + migrationBuilder.CreateTable( + name: "posts", + columns: table => new + { + id = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + title = table.Column(type: "text", nullable: false), + content = table.Column(type: "text", nullable: false), + UserId = table.Column(type: "integer", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_posts", x => x.id); + table.ForeignKey( + name: "FK_posts_users_UserId", + column: x => x.UserId, + principalTable: "users", + principalColumn: "id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "comments", + columns: table => new + { + id = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + content = table.Column(type: "text", nullable: false), + PostId = table.Column(type: "integer", nullable: false), + UserId = table.Column(type: "integer", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_comments", x => x.id); + table.ForeignKey( + name: "FK_comments_posts_PostId", + column: x => x.PostId, + principalTable: "posts", + principalColumn: "id", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_comments_users_UserId", + column: x => x.UserId, + principalTable: "users", + principalColumn: "id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.InsertData( + table: "users", + columns: new[] { "id", "city", "email", "favoriteColor", "firstName", "lastName", "street" }, + values: new object[,] + { + { 1, "Oslo", "julia@gmail.com", "#FFC0CB", "Julia", "Doe", "Lakkegata" }, + { 2, "Gardermoen", "john@gmail.com", "#0000FF", "John", "Doe", "Nannestad" }, + { 3, "Mega-City One", "george@gmail.com", "#301934", "George", "Doe", "Georgia" } + }); + + migrationBuilder.InsertData( + table: "posts", + columns: new[] { "id", "content", "title", "UserId" }, + values: new object[,] + { + { 1, "Hi :3", "Julia's post", 1 }, + { 2, "uwu", "John's post", 2 }, + { 3, "I love Judge Dredd", "George's post", 3 } + }); + + migrationBuilder.InsertData( + table: "comments", + columns: new[] { "id", "content", "PostId", "UserId" }, + values: new object[,] + { + { 1, "Goodbye", 1, 2 }, + { 2, "Kawaii", 2, 1 }, + { 3, "Nani", 2, 3 }, + { 4, "Me too!", 3, 2 }, + { 5, "What is that?", 3, 1 } + }); + + migrationBuilder.CreateIndex( + name: "IX_comments_PostId", + table: "comments", + column: "PostId"); + + migrationBuilder.CreateIndex( + name: "IX_comments_UserId", + table: "comments", + column: "UserId"); + + migrationBuilder.CreateIndex( + name: "IX_posts_UserId", + table: "posts", + column: "UserId"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "comments"); + + migrationBuilder.DropTable( + name: "posts"); + + migrationBuilder.DropTable( + name: "users"); + } + } +} diff --git a/cohort-backend.wwwapi/Migrations/DatabaseContextModelSnapshot.cs b/cohort-backend.wwwapi/Migrations/DatabaseContextModelSnapshot.cs new file mode 100644 index 0000000..7f122e7 --- /dev/null +++ b/cohort-backend.wwwapi/Migrations/DatabaseContextModelSnapshot.cs @@ -0,0 +1,250 @@ +// +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; +using cohort_backend.wwwapi.Data; + +#nullable disable + +namespace cohort_backend.wwwapi.Migrations +{ + [DbContext(typeof(DatabaseContext))] + partial class DatabaseContextModelSnapshot : 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("cohort_backend.wwwapi.Models.Comment", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasColumnName("id"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Content") + .IsRequired() + .HasColumnType("text") + .HasColumnName("content"); + + b.Property("PostId") + .HasColumnType("integer"); + + b.Property("UserId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("PostId"); + + b.HasIndex("UserId"); + + b.ToTable("comments"); + + b.HasData( + new + { + Id = 1, + Content = "Goodbye", + PostId = 1, + UserId = 2 + }, + new + { + Id = 2, + Content = "Kawaii", + PostId = 2, + UserId = 1 + }, + new + { + Id = 3, + Content = "Nani", + PostId = 2, + UserId = 3 + }, + new + { + Id = 4, + Content = "Me too!", + PostId = 3, + UserId = 2 + }, + new + { + Id = 5, + Content = "What is that?", + PostId = 3, + UserId = 1 + }); + }); + + modelBuilder.Entity("cohort_backend.wwwapi.Models.Post", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasColumnName("id"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Content") + .IsRequired() + .HasColumnType("text") + .HasColumnName("content"); + + b.Property("Title") + .IsRequired() + .HasColumnType("text") + .HasColumnName("title"); + + b.Property("UserId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("posts"); + + b.HasData( + new + { + Id = 1, + Content = "Hi :3", + Title = "Julia's post", + UserId = 1 + }, + new + { + Id = 2, + Content = "uwu", + Title = "John's post", + UserId = 2 + }, + new + { + Id = 3, + Content = "I love Judge Dredd", + Title = "George's post", + UserId = 3 + }); + }); + + modelBuilder.Entity("cohort_backend.wwwapi.Models.User", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasColumnName("id"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("City") + .IsRequired() + .HasColumnType("text") + .HasColumnName("city"); + + b.Property("Email") + .IsRequired() + .HasColumnType("text") + .HasColumnName("email"); + + b.Property("FavoriteColor") + .IsRequired() + .HasColumnType("text") + .HasColumnName("favoriteColor"); + + b.Property("FirstName") + .IsRequired() + .HasColumnType("text") + .HasColumnName("firstName"); + + b.Property("LastName") + .IsRequired() + .HasColumnType("text") + .HasColumnName("lastName"); + + b.Property("Street") + .IsRequired() + .HasColumnType("text") + .HasColumnName("street"); + + b.HasKey("Id"); + + b.ToTable("users"); + + b.HasData( + new + { + Id = 1, + City = "Oslo", + Email = "julia@gmail.com", + FavoriteColor = "#FFC0CB", + FirstName = "Julia", + LastName = "Doe", + Street = "Lakkegata" + }, + new + { + Id = 2, + City = "Gardermoen", + Email = "john@gmail.com", + FavoriteColor = "#0000FF", + FirstName = "John", + LastName = "Doe", + Street = "Nannestad" + }, + new + { + Id = 3, + City = "Mega-City One", + Email = "george@gmail.com", + FavoriteColor = "#301934", + FirstName = "George", + LastName = "Doe", + Street = "Georgia" + }); + }); + + modelBuilder.Entity("cohort_backend.wwwapi.Models.Comment", b => + { + b.HasOne("cohort_backend.wwwapi.Models.Post", "Post") + .WithMany() + .HasForeignKey("PostId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("cohort_backend.wwwapi.Models.User", "User") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Post"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("cohort_backend.wwwapi.Models.Post", b => + { + b.HasOne("cohort_backend.wwwapi.Models.User", "User") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/cohort-backend.wwwapi/Models/Comment.cs b/cohort-backend.wwwapi/Models/Comment.cs new file mode 100644 index 0000000..728b62a --- /dev/null +++ b/cohort-backend.wwwapi/Models/Comment.cs @@ -0,0 +1,24 @@ +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; + +namespace cohort_backend.wwwapi.Models +{ + [Table("comments")] + public class Comment + { + [Key] + [Column("id")] + public int Id { get; set; } + + [Column("content")] + public string Content { get; set; } + + [ForeignKey("posts")] + public int PostId { get; set; } + public Post Post { get; set; } + + [ForeignKey("users")] + public int UserId { get; set; } + public User User { get; set; } + } +} diff --git a/cohort-backend.wwwapi/Models/Post.cs b/cohort-backend.wwwapi/Models/Post.cs new file mode 100644 index 0000000..1dad003 --- /dev/null +++ b/cohort-backend.wwwapi/Models/Post.cs @@ -0,0 +1,23 @@ +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; + +namespace cohort_backend.wwwapi.Models +{ + [Table("posts")] + public class Post + { + [Key] + [Column("id")] + public int Id { get; set; } + + [Column("title")] + public string Title { get; set; } + + [Column("content")] + public string Content { get; set; } + + [ForeignKey("users")] + public int UserId { get; set; } + public User User { get; set; } + } +} diff --git a/cohort-backend.wwwapi/Models/User.cs b/cohort-backend.wwwapi/Models/User.cs new file mode 100644 index 0000000..719ded0 --- /dev/null +++ b/cohort-backend.wwwapi/Models/User.cs @@ -0,0 +1,31 @@ +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; + +namespace cohort_backend.wwwapi.Models +{ + [Table("users")] + public class User + { + [Key] + [Column("id")] + public int Id { get; set; } + + [Column("firstName")] + public string FirstName { get; set; } + + [Column("lastName")] + public string LastName { get; set; } + + [Column("street")] + public string Street { get; set; } + + [Column("city")] + public string City { get; set; } + + [Column("email")] + public string Email { get; set; } + + [Column("favoriteColor")] + public string FavoriteColor { get; set; } + } +} \ No newline at end of file diff --git a/cohort-backend.wwwapi/Program.cs b/cohort-backend.wwwapi/Program.cs new file mode 100644 index 0000000..4b830de --- /dev/null +++ b/cohort-backend.wwwapi/Program.cs @@ -0,0 +1,22 @@ +using cohort_backend.wwwapi.Data; + +var builder = WebApplication.CreateBuilder(args); + +// Add services to the container. +// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle +builder.Services.AddEndpointsApiExplorer(); +builder.Services.AddSwaggerGen(); +builder.Services.AddDbContext(); + +var app = builder.Build(); + +// Configure the HTTP request pipeline. +if (app.Environment.IsDevelopment()) +{ + app.UseSwagger(); + app.UseSwaggerUI(); +} + +app.UseHttpsRedirection(); + +app.Run(); diff --git a/cohort-backend.wwwapi/Properties/launchSettings.json b/cohort-backend.wwwapi/Properties/launchSettings.json new file mode 100644 index 0000000..f28d17e --- /dev/null +++ b/cohort-backend.wwwapi/Properties/launchSettings.json @@ -0,0 +1,41 @@ +{ + "$schema": "http://json.schemastore.org/launchsettings.json", + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:56793", + "sslPort": 44322 + } + }, + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "launchUrl": "swagger", + "applicationUrl": "http://localhost:5202", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "launchUrl": "swagger", + "applicationUrl": "https://localhost:7066;http://localhost:5202", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "launchUrl": "swagger", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/cohort-backend.wwwapi/Repository/IUserRepository.cs b/cohort-backend.wwwapi/Repository/IUserRepository.cs new file mode 100644 index 0000000..c31d270 --- /dev/null +++ b/cohort-backend.wwwapi/Repository/IUserRepository.cs @@ -0,0 +1,11 @@ +using cohort_backend.wwwapi.Models; + +namespace cohort_backend.wwwapi.Repository +{ + public interface IUserRepository + { + Task> GetUsers(); + Task GetPrimeUser(int id); + Task GetUserById(int id); + } +} diff --git a/cohort-backend.wwwapi/Repository/UserRepository.cs b/cohort-backend.wwwapi/Repository/UserRepository.cs new file mode 100644 index 0000000..1615460 --- /dev/null +++ b/cohort-backend.wwwapi/Repository/UserRepository.cs @@ -0,0 +1,31 @@ +using cohort_backend.wwwapi.Data; +using cohort_backend.wwwapi.Models; +using Microsoft.EntityFrameworkCore; + +namespace cohort_backend.wwwapi.Repository +{ + public class UserRepository : IUserRepository + { + private DatabaseContext _databaseContext; + + public UserRepository (DatabaseContext db) + { + _databaseContext = db; + } + + public async Task GetPrimeUser(int id) + { + return await _databaseContext.Users.FirstOrDefaultAsync(x => x.Id == id); + } + + public async Task GetUserById(int id) + { + return await _databaseContext.Users.FirstOrDefaultAsync(x => x.Id == id); + } + + public async Task> GetUsers() + { + return await _databaseContext.Users.ToListAsync(); + } + } +} diff --git a/cohort-backend.wwwapi/cohort-backend.wwwapi.csproj b/cohort-backend.wwwapi/cohort-backend.wwwapi.csproj new file mode 100644 index 0000000..329aabc --- /dev/null +++ b/cohort-backend.wwwapi/cohort-backend.wwwapi.csproj @@ -0,0 +1,25 @@ + + + + net8.0 + enable + enable + cohort_backend.wwwapi + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + diff --git a/cohort-backend.wwwapi/cohort-backend.wwwapi.http b/cohort-backend.wwwapi/cohort-backend.wwwapi.http new file mode 100644 index 0000000..2ffe7fb --- /dev/null +++ b/cohort-backend.wwwapi/cohort-backend.wwwapi.http @@ -0,0 +1,6 @@ +@cohort_backend.wwwapi_HostAddress = http://localhost:5202 + +GET {{cohort_backend.wwwapi_HostAddress}}/weatherforecast/ +Accept: application/json + +### From 601c4febaacfeba5b953205cc06d74e7b48f3290 Mon Sep 17 00:00:00 2001 From: George Date: Fri, 18 Oct 2024 09:27:16 +0200 Subject: [PATCH 02/20] File move --- cohort-backend.wwwapi/.gitattributes | 2 + cohort-backend.wwwapi/.gitignore | 398 +++++++++++++++++++++++++++ cohort-backend.wwwapi/GUIDE.md | 13 + cohort-backend.wwwapi/LICENSE | 21 ++ cohort-backend.wwwapi/README.md | 25 ++ 5 files changed, 459 insertions(+) create mode 100644 cohort-backend.wwwapi/.gitattributes create mode 100644 cohort-backend.wwwapi/.gitignore create mode 100644 cohort-backend.wwwapi/GUIDE.md create mode 100644 cohort-backend.wwwapi/LICENSE create mode 100644 cohort-backend.wwwapi/README.md diff --git a/cohort-backend.wwwapi/.gitattributes b/cohort-backend.wwwapi/.gitattributes new file mode 100644 index 0000000..dfe0770 --- /dev/null +++ b/cohort-backend.wwwapi/.gitattributes @@ -0,0 +1,2 @@ +# Auto detect text files and perform LF normalization +* text=auto diff --git a/cohort-backend.wwwapi/.gitignore b/cohort-backend.wwwapi/.gitignore new file mode 100644 index 0000000..8a30d25 --- /dev/null +++ b/cohort-backend.wwwapi/.gitignore @@ -0,0 +1,398 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.tlog +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio 6 auto-generated project file (contains which files were open etc.) +*.vbp + +# Visual Studio 6 workspace and project file (working project files containing files to include in project) +*.dsw +*.dsp + +# Visual Studio 6 technical files +*.ncb +*.aps + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# Visual Studio History (VSHistory) files +.vshistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd + +# VS Code files for those working on multiple tools +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +*.code-workspace + +# Local History for Visual Studio Code +.history/ + +# Windows Installer files from build outputs +*.cab +*.msi +*.msix +*.msm +*.msp + +# JetBrains Rider +*.sln.iml diff --git a/cohort-backend.wwwapi/GUIDE.md b/cohort-backend.wwwapi/GUIDE.md new file mode 100644 index 0000000..e44888e --- /dev/null +++ b/cohort-backend.wwwapi/GUIDE.md @@ -0,0 +1,13 @@ +**Note: Change any headings in this document** + +# Project Guide + +## Setup + +## Introduction + +## Technical Designs + +## Technical Descriptions + +## References diff --git a/cohort-backend.wwwapi/LICENSE b/cohort-backend.wwwapi/LICENSE new file mode 100644 index 0000000..b011ea1 --- /dev/null +++ b/cohort-backend.wwwapi/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 AJ + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/cohort-backend.wwwapi/README.md b/cohort-backend.wwwapi/README.md new file mode 100644 index 0000000..93b8f8a --- /dev/null +++ b/cohort-backend.wwwapi/README.md @@ -0,0 +1,25 @@ +# C# Cloud AWS - Day Five + +## Learning Objectives + +- Use a combination of any AWS technologies covered to create a full stack application. E.g. + - Elastic Beanstalk + - S3 Bucket + - SQS / SNS + - EC2 + - Terraform + - Lamda + - RDS + - VPC + +## Instructions + +1. Fork this repository. +2. Clone your fork to your machine. + +# Core & Extension Activity + +- Your project should consist of at least a backend contained in this repository +- Include a [GUIDE](GUIDE.md) to document & describe your project +- If you want to include a front end then using a technology of your choice, link to the repository in the [GUIDE](GUIDE.md) +- Share resources amongst projects like a `dotnet new classlib --name exercise.models` library From bff96db8c941633c5eaae5613aecc4112f7a3c5b Mon Sep 17 00:00:00 2001 From: George Date: Fri, 18 Oct 2024 09:35:15 +0200 Subject: [PATCH 03/20] Changes --- cohort-backend.wwwapi/.gitignore | 2 ++ cohort-backend.wwwapi/appsettings.json | 7 +++++++ 2 files changed, 9 insertions(+) create mode 100644 cohort-backend.wwwapi/appsettings.json diff --git a/cohort-backend.wwwapi/.gitignore b/cohort-backend.wwwapi/.gitignore index 8a30d25..7cd82e2 100644 --- a/cohort-backend.wwwapi/.gitignore +++ b/cohort-backend.wwwapi/.gitignore @@ -3,6 +3,8 @@ ## ## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore +appsettings.json + # User-specific files *.rsuser *.suo diff --git a/cohort-backend.wwwapi/appsettings.json b/cohort-backend.wwwapi/appsettings.json new file mode 100644 index 0000000..8c4d28e --- /dev/null +++ b/cohort-backend.wwwapi/appsettings.json @@ -0,0 +1,7 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information" + } + } +} \ No newline at end of file From 739f664d9f9c9fd0f74d08d76a58dc637bb99e9e Mon Sep 17 00:00:00 2001 From: George Date: Fri, 18 Oct 2024 09:38:38 +0200 Subject: [PATCH 04/20] changes --- .gitignore | 1 + cohort-backend.wwwapi/appsettings.json | 7 ------- 2 files changed, 1 insertion(+), 7 deletions(-) delete mode 100644 cohort-backend.wwwapi/appsettings.json diff --git a/.gitignore b/.gitignore index 8a30d25..47e1028 100644 --- a/.gitignore +++ b/.gitignore @@ -396,3 +396,4 @@ FodyWeavers.xsd # JetBrains Rider *.sln.iml +/cohort-backend.wwwapi/appsettings.json diff --git a/cohort-backend.wwwapi/appsettings.json b/cohort-backend.wwwapi/appsettings.json deleted file mode 100644 index 8c4d28e..0000000 --- a/cohort-backend.wwwapi/appsettings.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "Logging": { - "LogLevel": { - "Default": "Information" - } - } -} \ No newline at end of file From c8543678e19598b5948d0036e3f6d30272ae716b Mon Sep 17 00:00:00 2001 From: John Ferdie Abueg Date: Fri, 18 Oct 2024 10:02:05 +0200 Subject: [PATCH 05/20] skeleton post repo --- .../Repository/IPostRepository.cs | 20 ++++++ .../Repository/PostRepository.cs | 62 +++++++++++++++++++ 2 files changed, 82 insertions(+) create mode 100644 cohort-backend.wwwapi/Repository/IPostRepository.cs create mode 100644 cohort-backend.wwwapi/Repository/PostRepository.cs diff --git a/cohort-backend.wwwapi/Repository/IPostRepository.cs b/cohort-backend.wwwapi/Repository/IPostRepository.cs new file mode 100644 index 0000000..9e07c37 --- /dev/null +++ b/cohort-backend.wwwapi/Repository/IPostRepository.cs @@ -0,0 +1,20 @@ +using cohort_backend.wwwapi.Models; + +namespace cohort_backend.wwwapi.Repository +{ + public interface IPostRepository + { + // POSTS + Task CreatePost(Post entity); + Task> GetAllPosts(); + Task UpdatePostById(Post entity, int postId); + Task DeletePostById(int postId); + Task GetPostById(int postId); + + // COMMENTS + Task CreateCommentInPost(Comment entity, int postId); + Task> GetAllCommentsInPost(int postId); + Task UpdateCommentInPost(Comment entity, int postId); + Task DeleteCommentInPost(int commentId, int postId); + } +} diff --git a/cohort-backend.wwwapi/Repository/PostRepository.cs b/cohort-backend.wwwapi/Repository/PostRepository.cs new file mode 100644 index 0000000..0868786 --- /dev/null +++ b/cohort-backend.wwwapi/Repository/PostRepository.cs @@ -0,0 +1,62 @@ +using cohort_backend.wwwapi.Data; +using cohort_backend.wwwapi.Models; + +namespace cohort_backend.wwwapi.Repository +{ + public class PostRepository : IPostRepository + { + private DatabaseContext _db; + + public PostRepository(DatabaseContext db) + { + _db = db; + } + + // POSTS + public async Task CreatePost(Post entity) + { + throw new NotImplementedException(); + } + + public async Task> GetAllPosts() + { + throw new NotImplementedException(); + } + + public async Task UpdatePostById(Post entity, int postId) + { + throw new NotImplementedException(); + } + + public async Task DeletePostById(int postId) + { + throw new NotImplementedException(); + } + + public async Task GetPostById(int postId) + { + throw new NotImplementedException(); + } + + // COMMENTS + public async Task CreateCommentInPost(Comment entity, int postId) + { + throw new NotImplementedException(); + } + + public async Task> GetAllCommentsInPost(int postId) + { + throw new NotImplementedException(); + } + + public async Task UpdateCommentInPost(Comment entity, int postId) + { + throw new NotImplementedException(); + } + + public async Task DeleteCommentInPost(int commentId, int postId) + { + throw new NotImplementedException(); + } + } +} From 38dbc1fb5664a6ccd181992421782f9ad896e4bd Mon Sep 17 00:00:00 2001 From: George Date: Fri, 18 Oct 2024 10:03:11 +0200 Subject: [PATCH 06/20] generic payload --- cohort-backend.wwwapi/Payload/Payload.cs | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 cohort-backend.wwwapi/Payload/Payload.cs diff --git a/cohort-backend.wwwapi/Payload/Payload.cs b/cohort-backend.wwwapi/Payload/Payload.cs new file mode 100644 index 0000000..e66f0ea --- /dev/null +++ b/cohort-backend.wwwapi/Payload/Payload.cs @@ -0,0 +1,8 @@ +namespace cohort_backend.wwwapi.Payload +{ + public class Payload where T : class + { + public string status { get; set; } + public T data { get; set; } + } +} From 264fa6d8a7aafa7cde49cb8460bf5eafc5721027 Mon Sep 17 00:00:00 2001 From: Kaja Thoresen Plaszko Date: Fri, 18 Oct 2024 10:07:37 +0200 Subject: [PATCH 07/20] commentendpoint --- .../Endpoints/PostEndpoint.cs | 74 +++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 cohort-backend.wwwapi/Endpoints/PostEndpoint.cs diff --git a/cohort-backend.wwwapi/Endpoints/PostEndpoint.cs b/cohort-backend.wwwapi/Endpoints/PostEndpoint.cs new file mode 100644 index 0000000..ae7ca64 --- /dev/null +++ b/cohort-backend.wwwapi/Endpoints/PostEndpoint.cs @@ -0,0 +1,74 @@ +using cohort_backend.wwwapi.Repository; +using Microsoft.AspNetCore.Mvc; + +namespace cohort_backend.wwwapi.Endpoints +{ + public static class PostEndpoint + { + public static void ConfigurePostEndpoint(this WebApplication app) + { + var postGroup = app.MapGroup("/post"); + + app.MapPost("/", CreateAPost); + app.MapGet("/", GetAllPosts); + app.MapGet("/{id}", GetAPost); + app.MapPut("/{id}", UpdateAPost); + app.MapDelete("/{id}", DeleteAPost); + + + } + + + [ProducesResponseType(StatusCodes.Status201Created)] + [ProducesResponseType(StatusCodes.Status400BadRequest)] + [ProducesResponseType(StatusCodes.Status401Unauthorized)] + public static async Task CreateAPost(IPostRepository repository) + { + return TypedResults.Ok(); + + } + + + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status401Unauthorized)] + public static async Task GetAllPosts(IPostRepository repository) + { + + return TypedResults.Ok(); + } + + [ProducesResponseType(StatusCodes.Status201Created)] + [ProducesResponseType(StatusCodes.Status400BadRequest)] + [ProducesResponseType(StatusCodes.Status401Unauthorized)] + [ProducesResponseType(StatusCodes.Status404NotFound)] + public static async Task GetAPost(IPostRepository repository, int id) + { + + return TypedResults.Ok(); + } + + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status400BadRequest)] + [ProducesResponseType(StatusCodes.Status401Unauthorized)] + [ProducesResponseType(StatusCodes.Status404NotFound)] + public static async Task UpdateAPost(IPostRepository repository, int id) + { + + return TypedResults.Ok(); + } + + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status400BadRequest)] + [ProducesResponseType(StatusCodes.Status401Unauthorized)] + [ProducesResponseType(StatusCodes.Status404NotFound)] + public static async Task DeleteAPost(IPostRepository repository, int id) + { + + return TypedResults.Ok(); + } + + + + + } +} From df26e93375fa5c4327f35845702cedb6d6808f51 Mon Sep 17 00:00:00 2001 From: bjorgastrid Date: Fri, 18 Oct 2024 10:41:03 +0200 Subject: [PATCH 08/20] enpoint set up --- .../Endpoints/UserEndpoint.cs | 19 ++++++++++++++----- cohort-backend.wwwapi/Program.cs | 5 +++++ .../Repository/IUserRepository.cs | 1 - .../Repository/UserRepository.cs | 9 ++------- .../appsettings.Development.json | 9 +++++++++ 5 files changed, 30 insertions(+), 13 deletions(-) create mode 100644 cohort-backend.wwwapi/appsettings.Development.json diff --git a/cohort-backend.wwwapi/Endpoints/UserEndpoint.cs b/cohort-backend.wwwapi/Endpoints/UserEndpoint.cs index 450b0a7..c88b734 100644 --- a/cohort-backend.wwwapi/Endpoints/UserEndpoint.cs +++ b/cohort-backend.wwwapi/Endpoints/UserEndpoint.cs @@ -10,18 +10,27 @@ public static void ConfigureUserEndpoint(this WebApplication app) var userGroup = app.MapGroup("/users"); userGroup.MapGet("/", GetUsers); + userGroup.MapGet("/{id}", GetUserById); } [ProducesResponseType(StatusCodes.Status200OK)] - [ProducesResponseType(StatusCodes.Status404NotFound)] public static async Task GetUsers(IUserRepository repository) + { + return TypedResults.Ok(await repository.GetUsers()); + } + + [Route("/{id}")] + [ProducesResponseType(StatusCodes.Status200OK)] + public static async Task GetUserById(IUserRepository repository, int id) { - var users = await repository.GetUsers(); - if (users != null) - { + var user = await repository.GetUserById(id); + if (user == null) + { + return TypedResults.NotFound(); } - return TypedResults.Ok(); + + return TypedResults.Ok(user); } } } diff --git a/cohort-backend.wwwapi/Program.cs b/cohort-backend.wwwapi/Program.cs index 4b830de..d9b2e16 100644 --- a/cohort-backend.wwwapi/Program.cs +++ b/cohort-backend.wwwapi/Program.cs @@ -1,4 +1,6 @@ using cohort_backend.wwwapi.Data; +using cohort_backend.wwwapi.Endpoints; +using cohort_backend.wwwapi.Repository; var builder = WebApplication.CreateBuilder(args); @@ -7,6 +9,7 @@ builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); builder.Services.AddDbContext(); +builder.Services.AddScoped(); var app = builder.Build(); @@ -19,4 +22,6 @@ app.UseHttpsRedirection(); +app.ConfigureUserEndpoint(); + app.Run(); diff --git a/cohort-backend.wwwapi/Repository/IUserRepository.cs b/cohort-backend.wwwapi/Repository/IUserRepository.cs index c31d270..6736c5d 100644 --- a/cohort-backend.wwwapi/Repository/IUserRepository.cs +++ b/cohort-backend.wwwapi/Repository/IUserRepository.cs @@ -5,7 +5,6 @@ namespace cohort_backend.wwwapi.Repository public interface IUserRepository { Task> GetUsers(); - Task GetPrimeUser(int id); Task GetUserById(int id); } } diff --git a/cohort-backend.wwwapi/Repository/UserRepository.cs b/cohort-backend.wwwapi/Repository/UserRepository.cs index 1615460..0a06564 100644 --- a/cohort-backend.wwwapi/Repository/UserRepository.cs +++ b/cohort-backend.wwwapi/Repository/UserRepository.cs @@ -7,15 +7,10 @@ namespace cohort_backend.wwwapi.Repository public class UserRepository : IUserRepository { private DatabaseContext _databaseContext; - - public UserRepository (DatabaseContext db) - { - _databaseContext = db; - } - public async Task GetPrimeUser(int id) + public UserRepository(DatabaseContext db) { - return await _databaseContext.Users.FirstOrDefaultAsync(x => x.Id == id); + _databaseContext = db; } public async Task GetUserById(int id) diff --git a/cohort-backend.wwwapi/appsettings.Development.json b/cohort-backend.wwwapi/appsettings.Development.json new file mode 100644 index 0000000..6f73a17 --- /dev/null +++ b/cohort-backend.wwwapi/appsettings.Development.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} + From 3139f61350970b1aab11279239989e66a2eba4ed Mon Sep 17 00:00:00 2001 From: John Ferdie Abueg Date: Fri, 18 Oct 2024 10:47:03 +0200 Subject: [PATCH 09/20] postrepo --- cohort-backend.wwwapi/Data/DatabaseContext.cs | 6 +-- cohort-backend.wwwapi/Program.cs | 2 + .../Repository/IPostRepository.cs | 6 +-- .../Repository/PostRepository.cs | 52 +++++++++++++++---- 4 files changed, 48 insertions(+), 18 deletions(-) diff --git a/cohort-backend.wwwapi/Data/DatabaseContext.cs b/cohort-backend.wwwapi/Data/DatabaseContext.cs index 9942315..3a30933 100644 --- a/cohort-backend.wwwapi/Data/DatabaseContext.cs +++ b/cohort-backend.wwwapi/Data/DatabaseContext.cs @@ -1,6 +1,3 @@ -using System.Collections.Generic; -using System.Reflection.Emit; -using cohort_backend.wwwapi.Models; using cohort_backend.wwwapi.Models; using Microsoft.EntityFrameworkCore; @@ -47,9 +44,8 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) base.OnModelCreating(modelBuilder); } - //public DbSet Post { get; set; } public DbSet Users { get; set; } - public DbSet Post { get; set; } + public DbSet Posts { get; set; } public DbSet Comments { get; set; } } } diff --git a/cohort-backend.wwwapi/Program.cs b/cohort-backend.wwwapi/Program.cs index 4b830de..18d7d9d 100644 --- a/cohort-backend.wwwapi/Program.cs +++ b/cohort-backend.wwwapi/Program.cs @@ -1,4 +1,5 @@ using cohort_backend.wwwapi.Data; +using cohort_backend.wwwapi.Repository; var builder = WebApplication.CreateBuilder(args); @@ -7,6 +8,7 @@ builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); builder.Services.AddDbContext(); +builder.Services.AddScoped(); var app = builder.Build(); diff --git a/cohort-backend.wwwapi/Repository/IPostRepository.cs b/cohort-backend.wwwapi/Repository/IPostRepository.cs index 9e07c37..2ee5d1d 100644 --- a/cohort-backend.wwwapi/Repository/IPostRepository.cs +++ b/cohort-backend.wwwapi/Repository/IPostRepository.cs @@ -12,9 +12,9 @@ public interface IPostRepository Task GetPostById(int postId); // COMMENTS - Task CreateCommentInPost(Comment entity, int postId); + Task CreateComment(Comment entity); Task> GetAllCommentsInPost(int postId); - Task UpdateCommentInPost(Comment entity, int postId); - Task DeleteCommentInPost(int commentId, int postId); + Task UpdateComment(Comment entity, int commentId); + Task DeleteComment(int commentId); } } diff --git a/cohort-backend.wwwapi/Repository/PostRepository.cs b/cohort-backend.wwwapi/Repository/PostRepository.cs index 0868786..3ad2dfa 100644 --- a/cohort-backend.wwwapi/Repository/PostRepository.cs +++ b/cohort-backend.wwwapi/Repository/PostRepository.cs @@ -1,5 +1,6 @@ using cohort_backend.wwwapi.Data; using cohort_backend.wwwapi.Models; +using Microsoft.EntityFrameworkCore; namespace cohort_backend.wwwapi.Repository { @@ -15,46 +16,77 @@ public PostRepository(DatabaseContext db) // POSTS public async Task CreatePost(Post entity) { - throw new NotImplementedException(); + _db.Posts.Add(entity); + await _db.SaveChangesAsync(); + + return entity; } public async Task> GetAllPosts() { - throw new NotImplementedException(); + return await _db.Posts.ToListAsync(); } public async Task UpdatePostById(Post entity, int postId) { - throw new NotImplementedException(); + var existingEntity = await _db.Posts.FirstOrDefaultAsync(p => p.Id == postId); + + if (entity == null) + { + throw new NotImplementedException($"Post with id {postId} does not exist."); + } + + _db.Posts.Update(entity); + await _db.SaveChangesAsync(); + + return entity; } public async Task DeletePostById(int postId) { - throw new NotImplementedException(); + var entity = await _db.Posts.FirstOrDefaultAsync(p => p.Id == postId); + + if (entity == null) { + throw new NotImplementedException($"Post with id {postId} does not exist."); + } + + _db.Posts.Remove(entity); + await _db.SaveChangesAsync(); + + return entity; } public async Task GetPostById(int postId) { - throw new NotImplementedException(); + var entity = await _db.Posts.FirstOrDefaultAsync(p => p.Id == postId); + + if (entity == null) { + throw new KeyNotFoundException($"Post with id {postId} does not exist."); + } + + return entity; } // COMMENTS - public async Task CreateCommentInPost(Comment entity, int postId) + public async Task CreateComment(Comment entity) { - throw new NotImplementedException(); + _db.Comments.Add(entity); + await _db.SaveChangesAsync(); + + return entity; } public async Task> GetAllCommentsInPost(int postId) { - throw new NotImplementedException(); + return await _db.Comments.ToListAsync(); } - public async Task UpdateCommentInPost(Comment entity, int postId) + public async Task UpdateComment(Comment entity, int commentId) { throw new NotImplementedException(); } - public async Task DeleteCommentInPost(int commentId, int postId) + public async Task DeleteComment(int commentId) { throw new NotImplementedException(); } From ab7b7cff5572e3261dbc1878c1b924afde39ac99 Mon Sep 17 00:00:00 2001 From: Kaja Thoresen Plaszko Date: Fri, 18 Oct 2024 11:00:50 +0200 Subject: [PATCH 10/20] post endpoints --- cohort-backend.wwwapi/DTO/PostDTO.cs | 9 ++ .../DTO/PostModels/PostModel.cs | 9 ++ .../Endpoints/PostEndpoint.cs | 85 +++++++++++++------ cohort-backend.wwwapi/Program.cs | 6 ++ .../Repository/PostRepository.cs | 4 +- .../appsettings.Development.json | 8 ++ 6 files changed, 92 insertions(+), 29 deletions(-) create mode 100644 cohort-backend.wwwapi/DTO/PostDTO.cs create mode 100644 cohort-backend.wwwapi/DTO/PostModels/PostModel.cs create mode 100644 cohort-backend.wwwapi/appsettings.Development.json diff --git a/cohort-backend.wwwapi/DTO/PostDTO.cs b/cohort-backend.wwwapi/DTO/PostDTO.cs new file mode 100644 index 0000000..a287aad --- /dev/null +++ b/cohort-backend.wwwapi/DTO/PostDTO.cs @@ -0,0 +1,9 @@ +namespace cohort_backend.wwwapi.DTO +{ + public class PostDTO + { + public string Title { get; set; } + public string Content { get; set; } + public int ContactId { get; set; } + } +} diff --git a/cohort-backend.wwwapi/DTO/PostModels/PostModel.cs b/cohort-backend.wwwapi/DTO/PostModels/PostModel.cs new file mode 100644 index 0000000..33c10d0 --- /dev/null +++ b/cohort-backend.wwwapi/DTO/PostModels/PostModel.cs @@ -0,0 +1,9 @@ +namespace cohort_backend.wwwapi.DTO.PostModels +{ + public class PostModel + { + public string Title { get; set; } + public string Content { get; set; } + public int ContactId { get; set; } + } +} diff --git a/cohort-backend.wwwapi/Endpoints/PostEndpoint.cs b/cohort-backend.wwwapi/Endpoints/PostEndpoint.cs index ae7ca64..62d6140 100644 --- a/cohort-backend.wwwapi/Endpoints/PostEndpoint.cs +++ b/cohort-backend.wwwapi/Endpoints/PostEndpoint.cs @@ -1,5 +1,12 @@ -using cohort_backend.wwwapi.Repository; +using cohort_backend.wwwapi.DTO; +using cohort_backend.wwwapi.DTO.PostModels; +using cohort_backend.wwwapi.DTO.Response; +using cohort_backend.wwwapi.Models; +using cohort_backend.wwwapi.Repository; using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Hosting; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata.Conventions; +using System.Reflection; namespace cohort_backend.wwwapi.Endpoints { @@ -12,8 +19,7 @@ public static void ConfigurePostEndpoint(this WebApplication app) app.MapPost("/", CreateAPost); app.MapGet("/", GetAllPosts); app.MapGet("/{id}", GetAPost); - app.MapPut("/{id}", UpdateAPost); - app.MapDelete("/{id}", DeleteAPost); + } @@ -22,9 +28,27 @@ public static void ConfigurePostEndpoint(this WebApplication app) [ProducesResponseType(StatusCodes.Status201Created)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status401Unauthorized)] - public static async Task CreateAPost(IPostRepository repository) + public static async Task CreateAPost(IPostRepository repository, PostModel model) { - return TypedResults.Ok(); + + Post post = await repository.CreatePost(new Post() + { + Title = model.Title, + Content = model.Content, + UserId = model.ContactId + }); + + + PostDTO postDTO = new PostDTO() + { + Title = post.Title, + Content = post.Content, + ContactId = post.UserId + + }; + + + return TypedResults.Ok(postDTO); } @@ -33,8 +57,24 @@ public static async Task CreateAPost(IPostRepository repository) [ProducesResponseType(StatusCodes.Status401Unauthorized)] public static async Task GetAllPosts(IPostRepository repository) { + GetAllResponse response = new GetAllResponse(); + var results = await repository.GetAllPosts(); + + foreach (var post in results) + { + PostDTO postDTO = new PostDTO() + { + Title = post.Title, + Content = post.Content, + ContactId = post.UserId + }; + + response.ResponseData.Add(postDTO); + } + + - return TypedResults.Ok(); + return TypedResults.Ok(response.ResponseData); } [ProducesResponseType(StatusCodes.Status201Created)] @@ -43,30 +83,19 @@ public static async Task GetAllPosts(IPostRepository repository) [ProducesResponseType(StatusCodes.Status404NotFound)] public static async Task GetAPost(IPostRepository repository, int id) { - - return TypedResults.Ok(); - } - - [ProducesResponseType(StatusCodes.Status200OK)] - [ProducesResponseType(StatusCodes.Status400BadRequest)] - [ProducesResponseType(StatusCodes.Status401Unauthorized)] - [ProducesResponseType(StatusCodes.Status404NotFound)] - public static async Task UpdateAPost(IPostRepository repository, int id) - { - - return TypedResults.Ok(); - } + var post = await repository.GetPostById(id); - [ProducesResponseType(StatusCodes.Status200OK)] - [ProducesResponseType(StatusCodes.Status400BadRequest)] - [ProducesResponseType(StatusCodes.Status401Unauthorized)] - [ProducesResponseType(StatusCodes.Status404NotFound)] - public static async Task DeleteAPost(IPostRepository repository, int id) - { - - return TypedResults.Ok(); - } + PostDTO postDTO = new PostDTO() + { + Title = post.Title, + Content = post.Content, + ContactId = post.UserId + }; + return TypedResults.Ok(postDTO); + } + + diff --git a/cohort-backend.wwwapi/Program.cs b/cohort-backend.wwwapi/Program.cs index 4b830de..baa64b9 100644 --- a/cohort-backend.wwwapi/Program.cs +++ b/cohort-backend.wwwapi/Program.cs @@ -1,4 +1,6 @@ using cohort_backend.wwwapi.Data; +using cohort_backend.wwwapi.Endpoints; +using cohort_backend.wwwapi.Repository; var builder = WebApplication.CreateBuilder(args); @@ -8,6 +10,8 @@ builder.Services.AddSwaggerGen(); builder.Services.AddDbContext(); +builder.Services.AddScoped(); + var app = builder.Build(); // Configure the HTTP request pipeline. @@ -19,4 +23,6 @@ app.UseHttpsRedirection(); +app.ConfigurePostEndpoint(); + app.Run(); diff --git a/cohort-backend.wwwapi/Repository/PostRepository.cs b/cohort-backend.wwwapi/Repository/PostRepository.cs index 0868786..137923e 100644 --- a/cohort-backend.wwwapi/Repository/PostRepository.cs +++ b/cohort-backend.wwwapi/Repository/PostRepository.cs @@ -1,5 +1,6 @@ using cohort_backend.wwwapi.Data; using cohort_backend.wwwapi.Models; +using Microsoft.EntityFrameworkCore; namespace cohort_backend.wwwapi.Repository { @@ -20,7 +21,8 @@ public async Task CreatePost(Post entity) public async Task> GetAllPosts() { - throw new NotImplementedException(); + return await _db.Post.ToListAsync(); + } public async Task UpdatePostById(Post entity, int postId) diff --git a/cohort-backend.wwwapi/appsettings.Development.json b/cohort-backend.wwwapi/appsettings.Development.json new file mode 100644 index 0000000..1b2d3ba --- /dev/null +++ b/cohort-backend.wwwapi/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} \ No newline at end of file From 4e036411f7a26121c6773f4962ea2bc0f69e1277 Mon Sep 17 00:00:00 2001 From: Kaja Thoresen Plaszko Date: Fri, 18 Oct 2024 11:41:52 +0200 Subject: [PATCH 11/20] comment endpoints --- cohort-backend.wwwapi/DTO/CommentDTO.cs | 6 ++ .../DTO/PostModels/CommentPostModel.cs | 6 ++ .../Endpoints/PostEndpoint.cs | 64 +++++++++++++++++-- 3 files changed, 72 insertions(+), 4 deletions(-) create mode 100644 cohort-backend.wwwapi/DTO/CommentDTO.cs create mode 100644 cohort-backend.wwwapi/DTO/PostModels/CommentPostModel.cs diff --git a/cohort-backend.wwwapi/DTO/CommentDTO.cs b/cohort-backend.wwwapi/DTO/CommentDTO.cs new file mode 100644 index 0000000..dd72b3e --- /dev/null +++ b/cohort-backend.wwwapi/DTO/CommentDTO.cs @@ -0,0 +1,6 @@ +namespace cohort_backend.wwwapi.DTO +{ + public class CommentDTO + { + } +} diff --git a/cohort-backend.wwwapi/DTO/PostModels/CommentPostModel.cs b/cohort-backend.wwwapi/DTO/PostModels/CommentPostModel.cs new file mode 100644 index 0000000..edfa47e --- /dev/null +++ b/cohort-backend.wwwapi/DTO/PostModels/CommentPostModel.cs @@ -0,0 +1,6 @@ +namespace cohort_backend.wwwapi.DTO.PostModels +{ + public class CommentPostModel + { + } +} diff --git a/cohort-backend.wwwapi/Endpoints/PostEndpoint.cs b/cohort-backend.wwwapi/Endpoints/PostEndpoint.cs index 62d6140..ad0ba60 100644 --- a/cohort-backend.wwwapi/Endpoints/PostEndpoint.cs +++ b/cohort-backend.wwwapi/Endpoints/PostEndpoint.cs @@ -18,7 +18,10 @@ public static void ConfigurePostEndpoint(this WebApplication app) app.MapPost("/", CreateAPost); app.MapGet("/", GetAllPosts); - app.MapGet("/{id}", GetAPost); + app.MapGet("/{id}", GetAPost); + + app.MapPost("/{id}/comment", CreateAComment); + app.MapGet("/{id}/comment", GetAllComments); @@ -93,11 +96,64 @@ public static async Task GetAPost(IPostRepository repository, int id) }; return TypedResults.Ok(postDTO); - } - - + } + + + + + + + + [ProducesResponseType(StatusCodes.Status201Created)] + [ProducesResponseType(StatusCodes.Status400BadRequest)] + [ProducesResponseType(StatusCodes.Status401Unauthorized)] + public static async Task CreateAComment(IPostRepository repository, CommentPostModel model) + { + + Comment comment = await repository.CreateComment(new Comment() + { + PostId= model.Id, + Content = model.Content, + UserId = model.ContactId + }); + + CommentDTO commentDTO = new CommentDTO() + { + PostId = comment.PostId, + Content = comment.Content, + ContactId= comment.UserId + }; + return TypedResults.Ok(commentDTO); + + } + + + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status401Unauthorized)] + public static async Task GetAllComments(IPostRepository repository, int postid) + { + GetAllResponse response = new GetAllResponse(); + var results = await repository.GetAllCommentsInPost(postid); + + foreach (var comment in results) + { + CommentDTO commentDTO = new CommentDTO() + { + PostId = comment.PostId, + Content = comment.Content, + ContactId = comment.UserId + }; + + response.ResponseData.Add(commentDTO); + } + + + + return TypedResults.Ok(response.ResponseData); + } + } } From e4eae26891fc1a596dcb1d1f24da7908d570e10d Mon Sep 17 00:00:00 2001 From: Kaja Thoresen Plaszko Date: Fri, 18 Oct 2024 11:58:45 +0200 Subject: [PATCH 12/20] small fix --- cohort-backend.wwwapi/.gitignore | 1 + cohort-backend.wwwapi/DTO/CommentDTO.cs | 3 +++ cohort-backend.wwwapi/DTO/PostModels/CommentPostModel.cs | 3 +++ 3 files changed, 7 insertions(+) diff --git a/cohort-backend.wwwapi/.gitignore b/cohort-backend.wwwapi/.gitignore index 7cd82e2..c5c0c45 100644 --- a/cohort-backend.wwwapi/.gitignore +++ b/cohort-backend.wwwapi/.gitignore @@ -4,6 +4,7 @@ ## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore appsettings.json +appsettings.Development.json # User-specific files *.rsuser diff --git a/cohort-backend.wwwapi/DTO/CommentDTO.cs b/cohort-backend.wwwapi/DTO/CommentDTO.cs index dd72b3e..4bf62ee 100644 --- a/cohort-backend.wwwapi/DTO/CommentDTO.cs +++ b/cohort-backend.wwwapi/DTO/CommentDTO.cs @@ -2,5 +2,8 @@ { public class CommentDTO { + public int PostId { get; set; } + public string Content { get; set; } + public int ContactId { get; set; } } } diff --git a/cohort-backend.wwwapi/DTO/PostModels/CommentPostModel.cs b/cohort-backend.wwwapi/DTO/PostModels/CommentPostModel.cs index edfa47e..7ad1de9 100644 --- a/cohort-backend.wwwapi/DTO/PostModels/CommentPostModel.cs +++ b/cohort-backend.wwwapi/DTO/PostModels/CommentPostModel.cs @@ -2,5 +2,8 @@ { public class CommentPostModel { + public int Id { get; set; } + public string Content { get; set; } + public int ContactId { get; set; } } } From aadf334027ff2f7a436587ef7fcb9647f8b02432 Mon Sep 17 00:00:00 2001 From: John Ferdie Abueg Date: Fri, 18 Oct 2024 13:06:37 +0200 Subject: [PATCH 13/20] patch --- cohort-backend.wwwapi/Endpoints/PostEndpoint.cs | 15 ++++++--------- cohort-backend.wwwapi/Program.cs | 3 --- .../Repository/PostRepository.cs | 2 +- 3 files changed, 7 insertions(+), 13 deletions(-) diff --git a/cohort-backend.wwwapi/Endpoints/PostEndpoint.cs b/cohort-backend.wwwapi/Endpoints/PostEndpoint.cs index ad0ba60..908a88b 100644 --- a/cohort-backend.wwwapi/Endpoints/PostEndpoint.cs +++ b/cohort-backend.wwwapi/Endpoints/PostEndpoint.cs @@ -14,17 +14,14 @@ public static class PostEndpoint { public static void ConfigurePostEndpoint(this WebApplication app) { - var postGroup = app.MapGroup("/post"); - - app.MapPost("/", CreateAPost); - app.MapGet("/", GetAllPosts); - app.MapGet("/{id}", GetAPost); - - app.MapPost("/{id}/comment", CreateAComment); - app.MapGet("/{id}/comment", GetAllComments); - + var postGroup = app.MapGroup("/posts"); + postGroup.MapPost("/", CreateAPost); + postGroup.MapGet("/", GetAllPosts); + postGroup.MapGet("/{id}", GetAPost); + postGroup.MapPost("/{id}/comments", CreateAComment); + postGroup.MapGet("/{id}/comments", GetAllComments); } diff --git a/cohort-backend.wwwapi/Program.cs b/cohort-backend.wwwapi/Program.cs index 91cfa49..083bbe6 100644 --- a/cohort-backend.wwwapi/Program.cs +++ b/cohort-backend.wwwapi/Program.cs @@ -12,8 +12,6 @@ builder.Services.AddScoped(); builder.Services.AddScoped(); -builder.Services.AddScoped(); - var app = builder.Build(); // Configure the HTTP request pipeline. @@ -28,5 +26,4 @@ app.ConfigurePostEndpoint(); app.ConfigureUserEndpoint(); - app.Run(); diff --git a/cohort-backend.wwwapi/Repository/PostRepository.cs b/cohort-backend.wwwapi/Repository/PostRepository.cs index 3ad2dfa..21d1a89 100644 --- a/cohort-backend.wwwapi/Repository/PostRepository.cs +++ b/cohort-backend.wwwapi/Repository/PostRepository.cs @@ -78,7 +78,7 @@ public async Task CreateComment(Comment entity) public async Task> GetAllCommentsInPost(int postId) { - return await _db.Comments.ToListAsync(); + return await _db.Comments.Where(p => p.PostId == postId).ToListAsync(); } public async Task UpdateComment(Comment entity, int commentId) From a1fada5740a4b146692d6786bcbbc4d6f45365b1 Mon Sep 17 00:00:00 2001 From: John Ferdie Abueg Date: Fri, 18 Oct 2024 13:43:13 +0200 Subject: [PATCH 14/20] added id to dto --- cohort-backend.wwwapi/DTO/PostDTO.cs | 1 + cohort-backend.wwwapi/Endpoints/PostEndpoint.cs | 2 ++ 2 files changed, 3 insertions(+) diff --git a/cohort-backend.wwwapi/DTO/PostDTO.cs b/cohort-backend.wwwapi/DTO/PostDTO.cs index a287aad..08066e5 100644 --- a/cohort-backend.wwwapi/DTO/PostDTO.cs +++ b/cohort-backend.wwwapi/DTO/PostDTO.cs @@ -2,6 +2,7 @@ { public class PostDTO { + public int Id { get; set; } public string Title { get; set; } public string Content { get; set; } public int ContactId { get; set; } diff --git a/cohort-backend.wwwapi/Endpoints/PostEndpoint.cs b/cohort-backend.wwwapi/Endpoints/PostEndpoint.cs index 908a88b..00041ae 100644 --- a/cohort-backend.wwwapi/Endpoints/PostEndpoint.cs +++ b/cohort-backend.wwwapi/Endpoints/PostEndpoint.cs @@ -64,6 +64,7 @@ public static async Task GetAllPosts(IPostRepository repository) { PostDTO postDTO = new PostDTO() { + Id = post.Id, Title = post.Title, Content = post.Content, ContactId = post.UserId @@ -87,6 +88,7 @@ public static async Task GetAPost(IPostRepository repository, int id) PostDTO postDTO = new PostDTO() { + Id = post.Id, Title = post.Title, Content = post.Content, ContactId = post.UserId From 2eedda00f87bbd5088d53bd442e8ad68f19ad6e3 Mon Sep 17 00:00:00 2001 From: George Date: Fri, 18 Oct 2024 13:44:12 +0200 Subject: [PATCH 15/20] enabled cors --- cohort-backend.wwwapi/Program.cs | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/cohort-backend.wwwapi/Program.cs b/cohort-backend.wwwapi/Program.cs index 083bbe6..8e39603 100644 --- a/cohort-backend.wwwapi/Program.cs +++ b/cohort-backend.wwwapi/Program.cs @@ -12,8 +12,23 @@ builder.Services.AddScoped(); builder.Services.AddScoped(); +// Add CORS configuration +builder.Services.AddCors(options => +{ + options.AddPolicy("AllowSpecificOrigin", + policy => + { + policy.WithOrigins("http://localhost:5173") // Allow your frontend's URL + .AllowAnyHeader() + .AllowAnyMethod(); + }); +}); + var app = builder.Build(); +app.UseCors("AllowSpecificOrigin"); + + // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { From 01d507ed86a16e8101a2e6da5751e080b6a56a6e Mon Sep 17 00:00:00 2001 From: John Ferdie Abueg Date: Fri, 18 Oct 2024 13:51:25 +0200 Subject: [PATCH 16/20] id --- cohort-backend.wwwapi/Endpoints/PostEndpoint.cs | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/cohort-backend.wwwapi/Endpoints/PostEndpoint.cs b/cohort-backend.wwwapi/Endpoints/PostEndpoint.cs index 00041ae..22cfb95 100644 --- a/cohort-backend.wwwapi/Endpoints/PostEndpoint.cs +++ b/cohort-backend.wwwapi/Endpoints/PostEndpoint.cs @@ -18,10 +18,10 @@ public static void ConfigurePostEndpoint(this WebApplication app) postGroup.MapPost("/", CreateAPost); postGroup.MapGet("/", GetAllPosts); - postGroup.MapGet("/{id}", GetAPost); + postGroup.MapGet("/{postId}", GetAPost); - postGroup.MapPost("/{id}/comments", CreateAComment); - postGroup.MapGet("/{id}/comments", GetAllComments); + postGroup.MapPost("/{postId}/comments", CreateAComment); + postGroup.MapGet("/{postId}/comments", GetAllComments); } @@ -82,9 +82,9 @@ public static async Task GetAllPosts(IPostRepository repository) [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status401Unauthorized)] [ProducesResponseType(StatusCodes.Status404NotFound)] - public static async Task GetAPost(IPostRepository repository, int id) + public static async Task GetAPost(IPostRepository repository, int postId) { - var post = await repository.GetPostById(id); + var post = await repository.GetPostById(postId); PostDTO postDTO = new PostDTO() { @@ -131,10 +131,10 @@ public static async Task CreateAComment(IPostRepository repository, Com [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status401Unauthorized)] - public static async Task GetAllComments(IPostRepository repository, int postid) + public static async Task GetAllComments(IPostRepository repository, int postId) { GetAllResponse response = new GetAllResponse(); - var results = await repository.GetAllCommentsInPost(postid); + var results = await repository.GetAllCommentsInPost(postId); foreach (var comment in results) { From 59e6049b46a6a9006cc38e953fcae8a3d518d7c7 Mon Sep 17 00:00:00 2001 From: John Ferdie Abueg Date: Fri, 18 Oct 2024 14:05:52 +0200 Subject: [PATCH 17/20] commentpostmodel --- cohort-backend.wwwapi/DTO/PostModels/CommentPostModel.cs | 2 +- cohort-backend.wwwapi/Endpoints/PostEndpoint.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/cohort-backend.wwwapi/DTO/PostModels/CommentPostModel.cs b/cohort-backend.wwwapi/DTO/PostModels/CommentPostModel.cs index 7ad1de9..496f78f 100644 --- a/cohort-backend.wwwapi/DTO/PostModels/CommentPostModel.cs +++ b/cohort-backend.wwwapi/DTO/PostModels/CommentPostModel.cs @@ -2,7 +2,7 @@ { public class CommentPostModel { - public int Id { get; set; } + public int PostId { get; set; } public string Content { get; set; } public int ContactId { get; set; } } diff --git a/cohort-backend.wwwapi/Endpoints/PostEndpoint.cs b/cohort-backend.wwwapi/Endpoints/PostEndpoint.cs index 22cfb95..3ce847d 100644 --- a/cohort-backend.wwwapi/Endpoints/PostEndpoint.cs +++ b/cohort-backend.wwwapi/Endpoints/PostEndpoint.cs @@ -111,7 +111,7 @@ public static async Task CreateAComment(IPostRepository repository, Com Comment comment = await repository.CreateComment(new Comment() { - PostId= model.Id, + PostId= model.PostId, Content = model.Content, UserId = model.ContactId }); From 1500082eaabd7f2e076220f2b3d1152cdbaab10d Mon Sep 17 00:00:00 2001 From: George Date: Fri, 18 Oct 2024 15:02:30 +0200 Subject: [PATCH 18/20] Done --- cohort-backend.wwwapi/Program.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cohort-backend.wwwapi/Program.cs b/cohort-backend.wwwapi/Program.cs index 8e39603..0f02c1e 100644 --- a/cohort-backend.wwwapi/Program.cs +++ b/cohort-backend.wwwapi/Program.cs @@ -18,7 +18,7 @@ options.AddPolicy("AllowSpecificOrigin", policy => { - policy.WithOrigins("http://localhost:5173") // Allow your frontend's URL + policy.WithOrigins("http://georgebucketboolean.s3-website.eu-north-1.amazonaws.com") // Allow your frontend's URL .AllowAnyHeader() .AllowAnyMethod(); }); From 817798bfede751a17b54a4de6ae3cb5e5ba4068b Mon Sep 17 00:00:00 2001 From: George-Alexander-S <88212297+George-Alexander-S@users.noreply.github.com> Date: Fri, 18 Oct 2024 15:03:59 +0200 Subject: [PATCH 19/20] Update README.md --- README.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/README.md b/README.md index 93b8f8a..4bc893e 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,8 @@ +## +Our solution is hosted on AWS with Elastic Beanstalk for the backend, a frontend in a S3 bucket, and a neon-db +The frontend is from this repo: +https://github.com/George-Alexander-S/react-cohort-dashboard-challenge + # C# Cloud AWS - Day Five ## Learning Objectives From beb609ca2c5782b58ee0cd99f387da51d8478b8f Mon Sep 17 00:00:00 2001 From: George-Alexander-S <88212297+George-Alexander-S@users.noreply.github.com> Date: Fri, 18 Oct 2024 15:04:09 +0200 Subject: [PATCH 20/20] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 4bc893e..c25c8ff 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -## +# Our solution is hosted on AWS with Elastic Beanstalk for the backend, a frontend in a S3 bucket, and a neon-db The frontend is from this repo: https://github.com/George-Alexander-S/react-cohort-dashboard-challenge