Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Erik Bergvall #107

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -367,5 +367,5 @@ FodyWeavers.xsd
*/**/obj/Debug
*/**/obj/Release
*/Migrations
/workshop.wwwapi/appsettings.json
/workshop.wwwapi/appsettings.Development.json
/exercise.wwwapi/appsettings.json
/exercise.wwwapi/appsettings.Development.json
13 changes: 13 additions & 0 deletions exercise.webapi/DTO/AuthorDTO.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
using exercise.webapi.Models;

namespace exercise.webapi.DTO
{
public class AuthorDTO
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public IEnumerable<string> Books { get; set; } = new List<string>();
}
}
12 changes: 12 additions & 0 deletions exercise.webapi/DTO/BookDTO.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
using exercise.webapi.Models;

namespace exercise.webapi.DTO
{
public class BookDTO
{
public int Id { get; set; }
public string Title { get; set; }
public int AuthorId { get; set; }
public string AuthorName { get; set; }
}
}
8 changes: 8 additions & 0 deletions exercise.webapi/DTO/BookPost.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
namespace exercise.webapi.DTO
{
public class BookPost
{
public string Title { get; set; }
public int AuthorId { get; set; }
}
}
7 changes: 7 additions & 0 deletions exercise.webapi/DTO/BookPut.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
namespace exercise.webapi.DTO
{
public class BookPut
{
public int? AuthorId { get; set; }
}
}
48 changes: 48 additions & 0 deletions exercise.webapi/Endpoints/AuthorAPI.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
using exercise.webapi.DTO;
using exercise.webapi.Models;
using exercise.webapi.Repository;
using static System.Reflection.Metadata.BlobBuilder;

namespace exercise.webapi.Endpoints
{
public static class AuthorAPI
{
public static void ConfigureAuthorApi(this WebApplication app)
{
var authors = app.MapGroup("authors");

authors.MapGet("/", GetAuthors);
authors.MapGet("/{id}", GetAuthor);
}

private static async Task<IResult> GetAuthors(IAuthorRepository authorRepository)
{
List<AuthorDTO> authorsDTO = new List<AuthorDTO>();
var authors = await authorRepository.GetAllAuthors();
foreach (var author in authors)
{
authorsDTO.Add(new AuthorDTO
{
Id = author.Id,
FirstName = author.FirstName,
LastName = author.LastName,
Email = author.Email,
Books = author.Books.Select(b => b.Title),
});
}
return TypedResults.Ok(authorsDTO);
}

private static async Task<IResult> GetAuthor(IAuthorRepository authorRepository, int id)
{
AuthorDTO authorDTO = new AuthorDTO();
var author = authorRepository.GetAuthor(id);
authorDTO.Id = author.Result.Id;
authorDTO.FirstName = author.Result.FirstName;
authorDTO.LastName = author.Result.LastName;
authorDTO.Email = author.Result.Email;
authorDTO.Books = author.Result.Books.Select(b => b.Title);
return TypedResults.Ok(authorDTO);
}
}
}
141 changes: 138 additions & 3 deletions exercise.webapi/Endpoints/BookApi.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
using exercise.webapi.Models;
using System.Reflection;
using exercise.webapi.Data;
using exercise.webapi.DTO;
using exercise.webapi.Models;
using exercise.webapi.Repository;
using Microsoft.AspNetCore.Mvc;
using static System.Reflection.Metadata.BlobBuilder;

namespace exercise.webapi.Endpoints
Expand All @@ -8,13 +12,144 @@ public static class BookApi
{
public static void ConfigureBooksApi(this WebApplication app)
{
app.MapGet("/books", GetBooks);
var books = app.MapGroup("books");

books.MapGet("/", GetBooks);
books.MapGet("/{id}", GetBook);
books.MapPut("/{id}", UpdateBook);
books.MapDelete("/{id}", DeleteBook);
books.MapPost("/", AddBook);
books.MapPut("/removeAuthor/{id}", RemoveAuthor);
books.MapPut("/addAuthor/{id}", AddAuthor);
}
private static async Task<IResult> AddAuthor(IBookRepository bookRepository, IAuthorRepository authorRepository, int id, int authId)
{
BookDTO bookDTO = new BookDTO();
Book target = await bookRepository.GetBook(id);


var result = await bookRepository.AssignAuthor(id, authId);

Author author = await authorRepository.GetAuthor(target.AuthorId);
author.Books.Add(target);

bookDTO.Id = result.Id;
bookDTO.Title = result.Title;
bookDTO.AuthorId = result.AuthorId;
bookDTO.AuthorName = result.Author.FirstName + " " + result.Author.LastName;


return TypedResults.Ok(bookDTO);
}
private static async Task<IResult> RemoveAuthor(IBookRepository bookRepository, IAuthorRepository authorRepository, int id)
{
BookDTO bookDTO = new BookDTO();
Book target = await bookRepository.GetBook(id);
Author author = await authorRepository.GetAuthor(target.AuthorId);
author.Books.Remove(target);

var result = await bookRepository.RemoveAuthor(id);
bookDTO.Id = result.Id;
bookDTO.Title = result.Title;
bookDTO.AuthorId = result.AuthorId;
bookDTO.AuthorName = "";


return TypedResults.Ok(bookDTO);
}
private static async Task<IResult> AddBook(IBookRepository bookRepository, BookPost model)
{
BookDTO bookDTO = new BookDTO();

Book book = new Book()
{
Title = model.Title,
AuthorId = model.AuthorId
};

if( await bookRepository.AddBook(book) == null)
{
return TypedResults.NotFound("Author not found");
}

bookDTO.Id = book.Id;
bookDTO.Title = book.Title;
bookDTO.AuthorId = book.AuthorId;
bookDTO.AuthorName = book.Author.FirstName + " " + book.Author.LastName;


return TypedResults.Created($"https://localhost:7188/products/{bookDTO.Id}", bookDTO);
}

private static async Task<IResult> GetBooks(IBookRepository bookRepository)
{
List<BookDTO> booksDTO = new List<BookDTO>();
var books = await bookRepository.GetAllBooks();
return TypedResults.Ok(books);
foreach (var book in books)
{
booksDTO.Add(new BookDTO
{
Id = book.Id,
Title = book.Title,
AuthorId = book.AuthorId,
AuthorName = book.Author.FirstName + " " + book.Author.LastName,
});
}
return TypedResults.Ok(booksDTO);
}

private static async Task<IResult> GetBook(IBookRepository bookRepository, int id)
{
BookDTO bookDTO = new BookDTO();
var book = bookRepository.GetBook(id);
bookDTO.Id = book.Result.Id;
bookDTO.Title = book.Result.Title;
bookDTO.AuthorId = book.Result.AuthorId;
if(bookDTO.AuthorId != 0)
bookDTO.AuthorName = book.Result.Author.FirstName + " " + book.Result.Author.LastName;
return TypedResults.Ok(bookDTO);
}
private static async Task<IResult> UpdateBook(IBookRepository bookRepository, int id, BookPut model)
{

try
{
BookDTO bookDTO = new BookDTO();
var target = await bookRepository.GetBook(id);
if (target == null) return TypedResults.NotFound("Product was not found");

if (model.AuthorId != null) target.AuthorId = model.AuthorId.Value;

var result = await bookRepository.UpdateBook(target);
bookDTO.Id = result.Id;
bookDTO.Title = result.Title;
bookDTO.AuthorId = result.AuthorId;
bookDTO.AuthorName = result.Author.FirstName + " " + result.Author.LastName;
return Results.Created($"https://localhost:7188/books/{id}", bookDTO);
}
catch (Exception ex)
{
return TypedResults.Problem(ex.Message);
}
}

[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public static async Task<IResult> DeleteBook(IBookRepository repository, int id)
{
try
{
var model = await repository.GetBook(id);
if (model == null)
return TypedResults.NotFound("Book was not found");
if (await repository.DeleteBook(id)) return Results.Ok(new { When = DateTime.Now, Status = "Deleted", Name = model.Title, AuthorId = model.AuthorId, Author = model.Author.FirstName + " " + model.Author.LastName });
return TypedResults.NotFound();
}
catch (Exception ex)
{
return TypedResults.Problem(ex.Message);
}
}
}
}
2 changes: 2 additions & 0 deletions exercise.webapi/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
builder.Services.AddSwaggerGen();
builder.Services.AddDbContext<DataContext>(opt => opt.UseInMemoryDatabase("Library"));
builder.Services.AddScoped<IBookRepository, BookRepository>();
builder.Services.AddScoped<IAuthorRepository, AuthorRepository>();

var app = builder.Build();

Expand All @@ -29,4 +30,5 @@

app.UseHttpsRedirection();
app.ConfigureBooksApi();
app.ConfigureAuthorApi();
app.Run();
27 changes: 27 additions & 0 deletions exercise.webapi/Repository/AuthorRepository.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
using exercise.webapi.Data;
using exercise.webapi.Models;
using Microsoft.EntityFrameworkCore;

namespace exercise.webapi.Repository
{
public class AuthorRepository : IAuthorRepository
{
DataContext _db;

public AuthorRepository(DataContext db)
{
_db = db;
}
public async Task<IEnumerable<Author>> GetAllAuthors()
{
return await _db.Authors.Include(a => a.Books).ToListAsync();
}

public async Task<Author> GetAuthor(int id)
{
var target = await _db.Authors.FindAsync(id);
_db.Entry(target).Collection(x => x.Books).Load();
return target;
}
}
}
57 changes: 57 additions & 0 deletions exercise.webapi/Repository/BookRepository.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using exercise.webapi.Data;
using exercise.webapi.DTO;
using exercise.webapi.Models;
using Microsoft.EntityFrameworkCore;

Expand All @@ -13,10 +14,66 @@ public BookRepository(DataContext db)
_db = db;
}

public async Task<Book> AddBook(Book Book)
{
if (_db.Authors.Find(Book.Author) == null)
{
return Book = null;
}
await _db.Books.AddAsync(Book);
_db.Entry(Book).Reference(x => x.Author).Load();
await _db.SaveChangesAsync();
return Book;
}

public async Task<Book> AssignAuthor(int id, int authId)
{
var target = await _db.Books.FindAsync(id);
target.AuthorId = authId;
await _db.SaveChangesAsync();
return target;
}

public async Task<bool> DeleteBook(int id)
{
var target = await _db.Books.FindAsync(id);
_db.Books.Remove(target);
await _db.SaveChangesAsync();
return true;
}

public async Task<IEnumerable<Book>> GetAllBooks()
{
return await _db.Books.Include(b => b.Author).ToListAsync();
}

public async Task<Book> GetBook(int id)
{
var target = await _db.Books.FindAsync(id);
_db.Entry(target).Reference(x => x.Author).Load();
return target;
}

public async Task<Book> RemoveAuthor(int id)
{
var target = await _db.Books.FindAsync(id);
target.Author = null;
target.AuthorId = 0;
await _db.SaveChangesAsync();

return target;
}

public async Task<Book> UpdateBook(Book Book)
{
var target = await _db.Books.FindAsync(Book.Id);
_db.Books.Remove(target);
await _db.SaveChangesAsync();

await _db.Books.AddAsync(Book);
await _db.SaveChangesAsync();
_db.Entry(Book).Reference(x => x.Author).Load();
return Book;
}
}
}
11 changes: 11 additions & 0 deletions exercise.webapi/Repository/IAuthorRepository.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
using exercise.webapi.Models;

namespace exercise.webapi.Repository
{
public interface IAuthorRepository
{
public Task<IEnumerable<Author>> GetAllAuthors();

Task<Author> GetAuthor(int id);
}
}
Loading