Skip to content

Petter Karstensen #93

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
20 changes: 20 additions & 0 deletions exercise.webapi/DTO/AuthorDTO.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
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 List<MinimalBookDTO> Books { get; set; }
}
public class MinimalBookDTO
{
public int Id { get; set; }
public string Title { get; set; }
}
}
21 changes: 21 additions & 0 deletions exercise.webapi/DTO/BookDTO.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
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 MinimalAuthorDTO Author { get; set; }
}
public class MinimalAuthorDTO
{
public int Id { get; set; }
public string FirsName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }

}
}
8 changes: 8 additions & 0 deletions exercise.webapi/DTO/PostBook.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
namespace exercise.webapi.DTO
{
public class PostBook
{
public string Title { get; set; }
public int AuthorId { get; set; }
}
}
8 changes: 8 additions & 0 deletions exercise.webapi/DTO/PutBook.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
namespace exercise.webapi.DTO
{
public class PutBook
{
public string? Title { get; set; }
public int? AuthorId { get; set; }
}
}
56 changes: 56 additions & 0 deletions exercise.webapi/Endpoints/AuthorApi.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
using exercise.webapi.DTO;
using exercise.webapi.Models;
using exercise.webapi.Repository;

namespace exercise.webapi.Endpoints
{
public static class AuthorApi
{
public static void ConfigureAuthorsApi(this WebApplication app)
{
app.MapGet("/authors", GetAuthors);
app.MapGet("/authors{id}", GetAuthor);
}

private static async Task<IResult> GetAuthors(IAuthorRepository authorRepository)
{
var authors = await authorRepository.GetAllAuthors();

var authorDTOs = authors.Select(author => new AuthorDTO
{
Id = author.Id,
FirstName = author.FirstName,
LastName = author.LastName,
Email = author.Email,
Books = author.Books.Select(book => new MinimalBookDTO
{
Id = book.Id,
Title = book.Title
}).ToList()
}).ToList();

return TypedResults.Ok(authorDTOs);
}
private static async Task<IResult> GetAuthor(IAuthorRepository authorRepository, int id)
{
var author = await authorRepository.GetAuthor(id);
if (author == null)
{
return TypedResults.NotFound();
}
var authorDTOs = new AuthorDTO
{
Id = author.Id,
FirstName = author.FirstName,
LastName = author.LastName,
Email = author.Email,
Books = author.Books.Select(book => new MinimalBookDTO
{
Id = book.Id,
Title = book.Title
}).ToList()
};
return TypedResults.Ok(authorDTOs);
}
}
}
148 changes: 145 additions & 3 deletions exercise.webapi/Endpoints/BookApi.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
using exercise.webapi.Models;
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 +10,153 @@ 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.MapPost("/", AddBook);
books.MapPut("/{id}", UpdateBook);
books.MapDelete("/{id}", DeleteBook);
}

private static async Task<IResult> GetBooks(IBookRepository bookRepository)
{
var books = await bookRepository.GetAllBooks();
return TypedResults.Ok(books);
var bookDTO = books.Select(book => new BookDTO
{
Id = book.Id,
Title = book.Title,
AuthorId = book.AuthorId,
Author = new MinimalAuthorDTO
{
Id = book.Author.Id,
FirsName = book.Author.FirstName,
LastName = book.Author.LastName,
Email = book.Author.Email,
}
}).ToList();

return TypedResults.Ok(bookDTO);
}
private static async Task<IResult> GetBook(IBookRepository bookRepository, int id)
{
var book = await bookRepository.GetBook(id);
if (book == null)
{
return TypedResults.NotFound();
}
var bookDTOs = new BookDTO
{
Id = book.Id,
Title = book.Title,
Author = new MinimalAuthorDTO
{
Id = book.Author.Id,
FirsName= book.Author.FirstName,
LastName = book.Author.LastName,
Email = book.Author.Email,
}
};
return TypedResults.Ok(bookDTOs);
}
[ProducesResponseType(StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public static async Task<IResult> AddBook(IBookRepository bookRepository, IAuthorRepository authorRepository, PostBook model)
{
try
{

var author = await authorRepository.GetAuthor(model.AuthorId);
if (author == null)
{
return TypedResults.NotFound("Author not found");
}
if (string.IsNullOrEmpty(model.Title))
{
return TypedResults.BadRequest("Title is empty");
}
Book book = new Book()
{
Title = model.Title,
AuthorId = model.AuthorId
};
await bookRepository.AddBook(book);

var bookDTOs = new BookDTO
{
Id = book.Id,
Title = book.Title,
AuthorId = book.AuthorId,
Author = new MinimalAuthorDTO
{
Id = book.Author.Id,
FirsName = book.Author.FirstName,
LastName = book.Author.LastName,
Email = book.Author.Email,
}
};

return TypedResults.Created($"https://localhost:7010/products/{book.Id}", bookDTOs);
}
catch (Exception ex)
{
return TypedResults.Problem(ex.Message);
}
}
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public static async Task<IResult> UpdateBook(IBookRepository bookRepository, IAuthorRepository authorRepository, int id, PutBook model)
{
try
{
var target = await bookRepository.GetBook(id);
if (target == null) return Results.NotFound("Book not found");

Author authorTarget = null;

if (model.AuthorId != null)
{
authorTarget = await authorRepository.GetAuthor((int)model.AuthorId);
target.AuthorId = (int)model.AuthorId;
target.Author = authorTarget;
}

if (!string.IsNullOrEmpty(model.Title)) target.Title = model.Title;

await bookRepository.UpdateBook(target);

var bookDTOs = new BookDTO
{
Id = target.Id,
Title = target.Title,
AuthorId = target.AuthorId,
Author = new MinimalAuthorDTO
{
Id = target.Author.Id,
FirsName = target.Author.FirstName,
LastName = target.Author.LastName,
Email = target.Author.Email,
}
};
return TypedResults.Ok(bookDTOs);
}
catch (Exception ex)
{
return TypedResults.Problem(ex.Message);
}
}
public static async Task<IResult> DeleteBook(IBookRepository bookRepository, int id)
{
try
{
var target = await bookRepository.GetBook(id);
if (await bookRepository.DeleteBook(id)) return Results.Ok($"Book: {target.Title} Deleted");
return TypedResults.NotFound("Book not found");
}
catch (Exception ex)
{
return TypedResults.Problem(ex.Message);
}
}
}
}
2 changes: 1 addition & 1 deletion exercise.webapi/Models/Author.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ public class Author
public string LastName { get; set; }
public string Email { get; set; }

[JsonIgnore] // Todo: replace this with DTO approach
//[JsonIgnore] // Todo: replace this with DTO approach
public ICollection<Book> Books { get; set; } = new List<Book>();
}
}
3 changes: 2 additions & 1 deletion exercise.webapi/Models/Book.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.ComponentModel.DataAnnotations.Schema;
using exercise.webapi.DTO;
using System.ComponentModel.DataAnnotations.Schema;

namespace exercise.webapi.Models
{
Expand Down
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.ConfigureAuthorsApi();
app.Run();
26 changes: 26 additions & 0 deletions exercise.webapi/Repository/AuthorRepository.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
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)
{
return await _db.Authors.Include(a => a.Books).FirstOrDefaultAsync(a => a.Id == id);
}
}
}
25 changes: 24 additions & 1 deletion exercise.webapi/Repository/BookRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,30 @@ public BookRepository(DataContext db)
public async Task<IEnumerable<Book>> GetAllBooks()
{
return await _db.Books.Include(b => b.Author).ToListAsync();

}
public async Task<Book> GetBook(int id)
{
return await _db.Books.Include(b => b.Author).FirstOrDefaultAsync(b => b.Id == id);
}
public async Task<Book> AddBook(Book book)
{
await _db.Books.AddAsync(book);
await _db.SaveChangesAsync();
return book;
}
public async Task<Book> UpdateBook(Book book)
{
var target = await _db.Books.FindAsync(book.Id);
_db.Entry(target).CurrentValues.SetValues(book);
await _db.SaveChangesAsync();
return book;
}
public async Task<bool> DeleteBook(int id)
{
var target = await _db.Books.FindAsync(id);
_db.Books.Remove(target);
await _db.SaveChangesAsync();
return true;
}
}
}
10 changes: 10 additions & 0 deletions exercise.webapi/Repository/IAuthorRepository.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
using exercise.webapi.Models;

namespace exercise.webapi.Repository
{
public interface IAuthorRepository
{
public Task<IEnumerable<Author>> GetAllAuthors();
public Task<Author> GetAuthor(int id);
}
}
4 changes: 4 additions & 0 deletions exercise.webapi/Repository/IBookRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,9 @@ namespace exercise.webapi.Repository
public interface IBookRepository
{
public Task<IEnumerable<Book>> GetAllBooks();
public Task<Book> GetBook(int id);
public Task<Book> AddBook(Book book);
public Task<Book> UpdateBook(Book book);
public Task<bool> DeleteBook(int id);
}
}