Skip to content

Sander Rasmussen #109

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

Open
wants to merge 2 commits 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
26 changes: 26 additions & 0 deletions exercise.webapi/DTO/AuthorDto.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
using exercise.webapi.Models;
using System.Text.Json.Serialization;

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 ICollection<string> Books { get; set; } = new List<string>();

public AuthorDto(Author author, List<string> books)
{
Id = author.Id;
FirstName = author.FirstName;
LastName = author.LastName;
Email = author.Email;
Books = books;

}

}
}
20 changes: 20 additions & 0 deletions exercise.webapi/DTO/BookDto.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
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; }

public BookDto(Book book)
{
Id = book.Id;
Title = book.Title;
AuthorId = book.AuthorId;
AuthorName = $"{book.Author.FirstName} {book.Author.LastName}";
}
}
}
23 changes: 23 additions & 0 deletions exercise.webapi/Endpoints/AuthorApi.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
using exercise.webapi.Repository;

namespace exercise.webapi.Endpoints
{
public static class AuthorApi
{
public static void ConfigureAuthorApi(this WebApplication app)
{
app.MapGet("/authors", GetAll);
app.MapGet("/author", Get);
}
public static async Task<IResult> GetAll(IBookRepository repo)
{
var authors = repo.GetAllAuthors();
return TypedResults.Ok(authors);
}
public static async Task<IResult> Get(IBookRepository repo, int id)
{
var author = repo.GetAuthor(id);
return TypedResults.Ok(author);
}
}
}
54 changes: 53 additions & 1 deletion exercise.webapi/Endpoints/BookApi.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
using exercise.webapi.Models;
using exercise.webapi.DTO;
using exercise.webapi.Models;
using exercise.webapi.Repository;
using exercise.webapi.ViewModel;
using Microsoft.EntityFrameworkCore.Update.Internal;
using static System.Reflection.Metadata.BlobBuilder;

namespace exercise.webapi.Endpoints
Expand All @@ -9,12 +12,61 @@ public static class BookApi
public static void ConfigureBooksApi(this WebApplication app)
{
app.MapGet("/books", GetBooks);
app.MapGet("/book", Get);
app.MapGet("/update", UpdateAuthor);
app.MapGet("/delete", DeleteBook);
app.MapGet("/create", CreateBook);
}

private static async Task<IResult> GetBooks(IBookRepository bookRepository)
{
var books = await bookRepository.GetAllBooks();
return TypedResults.Ok(books);
}
public static async Task<IResult> Get(IBookRepository repo, int id)
{
var book = await repo.GetBook(id);
return TypedResults.Ok(book);
}

public static async Task<IResult> UpdateAuthor(IBookRepository repository, int bookid, int authorid)
{
try
{
await repository.Update(bookid, authorid);
var book = repository.GetBook(bookid);

return TypedResults.Ok(book);
}
catch (Exception ex)
{
return TypedResults.NotFound(ex);
}

}
public static async Task<IResult> DeleteBook(IBookRepository repo, int bookid)
{
try
{
repo.Delete(bookid);
return TypedResults.Ok();
}
catch (Exception ex)
{
return TypedResults.NotFound(ex);
}

}
public static async Task<IResult> CreateBook(IBookRepository repo, string title, int authorid)
{
try
{
return TypedResults.Ok(await repo.CreateBook(title, authorid));
}
catch (Exception ex)
{
return TypedResults.NotFound(ex);
}
}
}
}
2 changes: 2 additions & 0 deletions exercise.webapi/Models/Author.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Text.Json.Serialization;
using exercise.webapi.DTO;

namespace exercise.webapi.Models
{
Expand All @@ -11,5 +12,6 @@ public class Author

[JsonIgnore] // Todo: replace this with DTO approach
public ICollection<Book> Books { get; set; } = new List<Book>();

}
}
2 changes: 2 additions & 0 deletions exercise.webapi/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
builder.Services.AddDbContext<DataContext>(opt => opt.UseInMemoryDatabase("Library"));
builder.Services.AddScoped<IBookRepository, BookRepository>();


var app = builder.Build();

using (var dbContext = new DataContext(new DbContextOptions<DataContext>()))
Expand All @@ -29,4 +30,5 @@

app.UseHttpsRedirection();
app.ConfigureBooksApi();
app.ConfigureAuthorApi();
app.Run();
115 changes: 112 additions & 3 deletions exercise.webapi/Repository/BookRepository.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,15 @@
using exercise.webapi.Data;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using exercise.webapi.Data;
using exercise.webapi.DTO;
using exercise.webapi.Models;
using exercise.webapi.ViewModel;
using Microsoft.AspNetCore.Server.Kestrel.Core;
using Microsoft.AspNetCore.SignalR;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using static System.Reflection.Metadata.BlobBuilder;

namespace exercise.webapi.Repository
{
Expand All @@ -13,10 +22,110 @@ public BookRepository(DataContext db)
_db = db;
}

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

var books = await _db.Books.Include(b => b.Author).ToListAsync();
List<BookDto> booksDto = new List<BookDto>();
books.ForEach(book => booksDto.Add(new BookDto(book)));
return booksDto;
}
public async Task<BookDto> GetBook(int id)
{
try
{
return new BookDto(await _db.Books.Include(b => b.Author).FirstOrDefaultAsync(book => book.Id == id));
}
catch (Exception ex)
{
Results.BadRequest(ex);
}
return null;

}
public async Task<BookDto> Update(int bookid, int authorId )
{
var book = await _db.Books.FirstOrDefaultAsync(book => book.Id == bookid);
try
{
book.Author = await _db.Authors.FirstOrDefaultAsync(author => author.Id == authorId);
if(book.Author != null)
{
await _db.SaveChangesAsync();
return await GetBook(bookid);
}
}
catch (Exception ex) { Results.BadRequest( ex); }
return null;
}
public async Task<bool> Delete(int bookid)
{
try
{
var book = _db.Books.FirstOrDefault(book => book.Id == bookid);
_db.Books.Remove(book);
await _db.SaveChangesAsync();
return true;
}
catch (Exception ex)
{
Results.BadRequest(ex.Message);
}
return false;
}
//implement the CREATE book - it should return NotFound when author id is not valid and BadRequest when book object not valid
public async Task<BookDto> CreateBook(string title, int authorid)
{
try
{
var book = new Book();
book.Title = title;
book.AuthorId = authorid;
book.Author = _db.Authors.FirstOrDefault(author => author.Id == authorid);

_db.Books.Add(book);
await _db.SaveChangesAsync();
return new BookDto(book);
}
catch(Exception e)
{
Results.BadRequest(e.Message);
}
return null;
}
public async Task<List<AuthorDto>> GetAllAuthors()
{


var authors = await _db.Authors.Include(b => b.Books).ToListAsync();
var authorDtos = new List<AuthorDto>();
foreach (var author in authors)
{
List<string> books = await findBooksByAuthor(author.Id);
authorDtos.Add(new AuthorDto(author, books));
}
return authorDtos;
}
public async Task<BookDto> GetAuthor(int id)
{
try
{
return new BookDto(await _db.Books.Include(b => b.Author).FirstOrDefaultAsync(book => book.Id == id));
}
catch (Exception ex)
{
Results.BadRequest(ex);
}
return null;

}
public async Task<List<string>> findBooksByAuthor(int authorid)
{
var books = await _db.Books.Where( b => b.AuthorId == authorid).ToListAsync();
List<string> bookTitles = new List<string>();
books.ForEach(b => bookTitles.Add(b.Title));
return bookTitles;
}

}
}
12 changes: 10 additions & 2 deletions exercise.webapi/Repository/IBookRepository.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,17 @@
using exercise.webapi.Models;
using exercise.webapi.DTO;
using exercise.webapi.Models;

namespace exercise.webapi.Repository
{
public interface IBookRepository
{
public Task<IEnumerable<Book>> GetAllBooks();
public Task<bool> Delete(int bookid);
public Task<IEnumerable<BookDto>> GetAllBooks();
Task<BookDto> GetBook(int id);
public Task<BookDto> Update(int bookid, int authorId);
public Task<BookDto> CreateBook(string title, int authorid);
public Task<List<string>> findBooksByAuthor(int authorid);
public Task<BookDto> GetAuthor(int id);
public Task<List<AuthorDto>> GetAllAuthors();
}
}
11 changes: 11 additions & 0 deletions exercise.webapi/ViewModel/AuthorUpdate.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
namespace exercise.webapi.ViewModel
{
public class AuthorUpdate
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }

}
}