From 72bf02b0a652bf4419a235aefa640f2c4451806f Mon Sep 17 00:00:00 2001 From: morganlloyd11 Date: Tue, 1 Jul 2025 21:10:30 -0600 Subject: [PATCH 1/2] updated password in connection string to connect to db --- MyFirstBlog/appsettings.Development.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MyFirstBlog/appsettings.Development.json b/MyFirstBlog/appsettings.Development.json index 68bd7dc3..91574de9 100644 --- a/MyFirstBlog/appsettings.Development.json +++ b/MyFirstBlog/appsettings.Development.json @@ -1,6 +1,6 @@ { "ConnectionStrings": { - "DefaultConnection": "Host=localhost; Database=bvc-blog; Username=postgres; Password=postgres" + "DefaultConnection": "Host=localhost; Database=bvc-blog; Username=postgres; Password=1111" }, "Logging": { "LogLevel": { From c0641588fed8e373b9bb81620c1893e30010e829 Mon Sep 17 00:00:00 2001 From: morganlloyd11 Date: Tue, 1 Jul 2025 21:16:08 -0600 Subject: [PATCH 2/2] added post endmoint with validation and 201/400 responses --- MyFirstBlog/Controllers/PostsController.cs | 17 +++++++++++++++++ MyFirstBlog/Services/PostService.cs | 21 +++++++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/MyFirstBlog/Controllers/PostsController.cs b/MyFirstBlog/Controllers/PostsController.cs index 8fa6bf2c..fa6255cc 100644 --- a/MyFirstBlog/Controllers/PostsController.cs +++ b/MyFirstBlog/Controllers/PostsController.cs @@ -31,4 +31,21 @@ public ActionResult GetPost(string slug) { return post; } + + // POST /posts + [HttpPost] + public IActionResult CreatePost([FromBody] PostDto postDto) + { + // simple validation + if (string.IsNullOrWhiteSpace(postDto.Title)) + { + return BadRequest(new { errors = new[] { "Title cannot be blank" } }); + } + + // use the service to create post + var createdPost = _postService.CreatePost(postDto); + + // return 201 Created with the new post + return Created("", new { post = new { createdPost.Title, createdPost.Body } }); + } } diff --git a/MyFirstBlog/Services/PostService.cs b/MyFirstBlog/Services/PostService.cs index 6bac099f..d1eef6ae 100644 --- a/MyFirstBlog/Services/PostService.cs +++ b/MyFirstBlog/Services/PostService.cs @@ -9,6 +9,8 @@ public interface IPostService { IEnumerable GetPosts(); PostDto GetPost(String slug); + + PostDto CreatePost(PostDto postDto); } public class PostService : IPostService @@ -34,4 +36,23 @@ private Post getPost(string slug) { return _context.Posts.Where(a=>a.Slug==slug.ToString()).SingleOrDefault(); } + + public PostDto CreatePost(PostDto postDto) + { + // create a simple slug from the title + var slug = Regex.Replace(postDto.Title.ToLower(), @"\s+", "-"); + + var newPost = new Post + { + Title = postDto.Title, + Body = postDto.Body, + Slug = slug, + CreatedDate = DateTime.UtcNow + }; + + _context.Posts.Add(newPost); + _context.SaveChanges(); + + return newPost.AsDto(); + } }