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/README.md b/README.md index 93b8f8a..c25c8ff 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 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/.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..c5c0c45 --- /dev/null +++ b/cohort-backend.wwwapi/.gitignore @@ -0,0 +1,401 @@ +## 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 + +appsettings.json +appsettings.Development.json + +# 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/DTO/CommentDTO.cs b/cohort-backend.wwwapi/DTO/CommentDTO.cs new file mode 100644 index 0000000..4bf62ee --- /dev/null +++ b/cohort-backend.wwwapi/DTO/CommentDTO.cs @@ -0,0 +1,9 @@ +namespace cohort_backend.wwwapi.DTO +{ + 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/PostDTO.cs b/cohort-backend.wwwapi/DTO/PostDTO.cs new file mode 100644 index 0000000..08066e5 --- /dev/null +++ b/cohort-backend.wwwapi/DTO/PostDTO.cs @@ -0,0 +1,10 @@ +namespace cohort_backend.wwwapi.DTO +{ + 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/DTO/PostModels/CommentPostModel.cs b/cohort-backend.wwwapi/DTO/PostModels/CommentPostModel.cs new file mode 100644 index 0000000..496f78f --- /dev/null +++ b/cohort-backend.wwwapi/DTO/PostModels/CommentPostModel.cs @@ -0,0 +1,9 @@ +namespace cohort_backend.wwwapi.DTO.PostModels +{ + public class CommentPostModel + { + public int PostId { 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/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..3a30933 --- /dev/null +++ b/cohort-backend.wwwapi/Data/DatabaseContext.cs @@ -0,0 +1,51 @@ +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 Users { get; set; } + public DbSet Posts { get; set; } + public DbSet Comments { get; set; } + } +} diff --git a/cohort-backend.wwwapi/Endpoints/PostEndpoint.cs b/cohort-backend.wwwapi/Endpoints/PostEndpoint.cs new file mode 100644 index 0000000..3ce847d --- /dev/null +++ b/cohort-backend.wwwapi/Endpoints/PostEndpoint.cs @@ -0,0 +1,158 @@ +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 +{ + public static class PostEndpoint + { + public static void ConfigurePostEndpoint(this WebApplication app) + { + var postGroup = app.MapGroup("/posts"); + + postGroup.MapPost("/", CreateAPost); + postGroup.MapGet("/", GetAllPosts); + postGroup.MapGet("/{postId}", GetAPost); + + postGroup.MapPost("/{postId}/comments", CreateAComment); + postGroup.MapGet("/{postId}/comments", GetAllComments); + } + + + [ProducesResponseType(StatusCodes.Status201Created)] + [ProducesResponseType(StatusCodes.Status400BadRequest)] + [ProducesResponseType(StatusCodes.Status401Unauthorized)] + public static async Task CreateAPost(IPostRepository repository, PostModel model) + { + + 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); + + } + + + [ProducesResponseType(StatusCodes.Status200OK)] + [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() + { + Id = post.Id, + Title = post.Title, + Content = post.Content, + ContactId = post.UserId + }; + + response.ResponseData.Add(postDTO); + } + + + + return TypedResults.Ok(response.ResponseData); + } + + [ProducesResponseType(StatusCodes.Status201Created)] + [ProducesResponseType(StatusCodes.Status400BadRequest)] + [ProducesResponseType(StatusCodes.Status401Unauthorized)] + [ProducesResponseType(StatusCodes.Status404NotFound)] + public static async Task GetAPost(IPostRepository repository, int postId) + { + var post = await repository.GetPostById(postId); + + PostDTO postDTO = new PostDTO() + { + Id = post.Id, + Title = post.Title, + Content = post.Content, + ContactId = post.UserId + }; + + 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.PostId, + 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); + } + + + } +} diff --git a/cohort-backend.wwwapi/Endpoints/UserEndpoint.cs b/cohort-backend.wwwapi/Endpoints/UserEndpoint.cs new file mode 100644 index 0000000..c88b734 --- /dev/null +++ b/cohort-backend.wwwapi/Endpoints/UserEndpoint.cs @@ -0,0 +1,36 @@ +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); + userGroup.MapGet("/{id}", GetUserById); + } + + [ProducesResponseType(StatusCodes.Status200OK)] + 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 user = await repository.GetUserById(id); + + if (user == null) + { + return TypedResults.NotFound(); + } + + return TypedResults.Ok(user); + } + } +} 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/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/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; } + } +} diff --git a/cohort-backend.wwwapi/Program.cs b/cohort-backend.wwwapi/Program.cs new file mode 100644 index 0000000..0f02c1e --- /dev/null +++ b/cohort-backend.wwwapi/Program.cs @@ -0,0 +1,44 @@ +using cohort_backend.wwwapi.Data; +using cohort_backend.wwwapi.Endpoints; +using cohort_backend.wwwapi.Repository; + +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(); +builder.Services.AddScoped(); +builder.Services.AddScoped(); + +// Add CORS configuration +builder.Services.AddCors(options => +{ + options.AddPolicy("AllowSpecificOrigin", + policy => + { + policy.WithOrigins("http://georgebucketboolean.s3-website.eu-north-1.amazonaws.com") // Allow your frontend's URL + .AllowAnyHeader() + .AllowAnyMethod(); + }); +}); + +var app = builder.Build(); + +app.UseCors("AllowSpecificOrigin"); + + +// Configure the HTTP request pipeline. +if (app.Environment.IsDevelopment()) +{ + app.UseSwagger(); + app.UseSwaggerUI(); +} + +app.UseHttpsRedirection(); + +app.ConfigurePostEndpoint(); +app.ConfigureUserEndpoint(); + +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/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 diff --git a/cohort-backend.wwwapi/Repository/IPostRepository.cs b/cohort-backend.wwwapi/Repository/IPostRepository.cs new file mode 100644 index 0000000..2ee5d1d --- /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 CreateComment(Comment entity); + Task> GetAllCommentsInPost(int postId); + Task UpdateComment(Comment entity, int commentId); + Task DeleteComment(int commentId); + } +} diff --git a/cohort-backend.wwwapi/Repository/IUserRepository.cs b/cohort-backend.wwwapi/Repository/IUserRepository.cs new file mode 100644 index 0000000..6736c5d --- /dev/null +++ b/cohort-backend.wwwapi/Repository/IUserRepository.cs @@ -0,0 +1,10 @@ +using cohort_backend.wwwapi.Models; + +namespace cohort_backend.wwwapi.Repository +{ + public interface IUserRepository + { + Task> GetUsers(); + Task GetUserById(int id); + } +} diff --git a/cohort-backend.wwwapi/Repository/PostRepository.cs b/cohort-backend.wwwapi/Repository/PostRepository.cs new file mode 100644 index 0000000..21d1a89 --- /dev/null +++ b/cohort-backend.wwwapi/Repository/PostRepository.cs @@ -0,0 +1,94 @@ +using cohort_backend.wwwapi.Data; +using cohort_backend.wwwapi.Models; +using Microsoft.EntityFrameworkCore; + +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) + { + _db.Posts.Add(entity); + await _db.SaveChangesAsync(); + + return entity; + } + + public async Task> GetAllPosts() + { + return await _db.Posts.ToListAsync(); + } + + public async Task UpdatePostById(Post entity, int postId) + { + 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) + { + 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) + { + 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 CreateComment(Comment entity) + { + _db.Comments.Add(entity); + await _db.SaveChangesAsync(); + + return entity; + } + + public async Task> GetAllCommentsInPost(int postId) + { + return await _db.Comments.Where(p => p.PostId == postId).ToListAsync(); + } + + public async Task UpdateComment(Comment entity, int commentId) + { + throw new NotImplementedException(); + } + + public async Task DeleteComment(int commentId) + { + throw new NotImplementedException(); + } + } +} diff --git a/cohort-backend.wwwapi/Repository/UserRepository.cs b/cohort-backend.wwwapi/Repository/UserRepository.cs new file mode 100644 index 0000000..0a06564 --- /dev/null +++ b/cohort-backend.wwwapi/Repository/UserRepository.cs @@ -0,0 +1,26 @@ +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 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/appsettings.Development.json b/cohort-backend.wwwapi/appsettings.Development.json new file mode 100644 index 0000000..0c208ae --- /dev/null +++ b/cohort-backend.wwwapi/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} 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 + +###