Skip to content

Hans Eivind Skinstad #98

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 4 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
5 changes: 5 additions & 0 deletions exercise.webapi/DTO/AuthorDTO.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
namespace exercise.webapi.DTO
{
public record AuthorGet(int Id, string FirstName, string LastName, string Email, IEnumerable<BookInternal> Books);
public record AuthorInternal(int id, string FirstName, string LastName, string Email);
}
7 changes: 7 additions & 0 deletions exercise.webapi/DTO/BookDTO.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
namespace exercise.webapi.DTO
{
public record BookGet(int Id, string Title, AuthorInternal author);
public record BookPost(string Title, int AuthorId);
public record BookPut(int AuthorId);
public record BookInternal(int id, string Title);
}
75 changes: 75 additions & 0 deletions exercise.webapi/Endpoints/AuthorApi.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
using exercise.webapi.DTO;
using exercise.webapi.Repository;
using Microsoft.AspNetCore.Mvc;

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

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

[ProducesResponseType(StatusCodes.Status200OK)]
private static async Task<IResult> GetAuthors(IAuthorRepository authorRepository)
{
try
{
var authors = await authorRepository.GetAllAuthors();

var atrs = authors.Select(author =>
{
return new AuthorGet(
author.Id,
author.FirstName,
author.LastName,
author.Email,
author.Books.Select(b => new BookInternal(
b.Id,
b.Title
)
));
});

return TypedResults.Ok(atrs);
}
catch(Exception ex)
{
return TypedResults.Problem(ex.Message);
}
}

[ProducesResponseType(StatusCodes.Status200OK)]
private static async Task<IResult> GetAuthor(IAuthorRepository authorRepository, int id)
{
try
{
var author = await authorRepository.GetAuthor(id);

if (author == null)
return TypedResults.Problem(null);

AuthorGet atr = new AuthorGet(
author.Id,
author.FirstName,
author.LastName,
author.Email,
author.Books.Select(b => new BookInternal(
b.Id,
b.Title
))
);

return TypedResults.Ok(atr);
}
catch (Exception ex)
{
return TypedResults.Problem(ex.Message);
}
}
}
}
120 changes: 116 additions & 4 deletions exercise.webapi/Endpoints/BookApi.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
using exercise.webapi.Models;
using System;
using System.Security.Principal;
using exercise.webapi.DTO;
using exercise.webapi.Models;
using exercise.webapi.Repository;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.TagHelpers;
using static System.Reflection.Metadata.BlobBuilder;

namespace exercise.webapi.Endpoints
Expand All @@ -8,13 +14,119 @@ 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);
}

[ProducesResponseType(StatusCodes.Status200OK)]
private static async Task<IResult> GetBooks(IBookRepository bookRepository)
{
var books = await bookRepository.GetAllBooks();
return TypedResults.Ok(books);
try
{
var books = await bookRepository.GetAllBooks();

var bks = books.Select(book =>
{
return new BookGet(
book.Id,
book.Title,
new AuthorInternal(
book.Author.Id,
book.Author.FirstName,
book.Author.LastName,
book.Author.Email
)
);
});

return TypedResults.Ok(bks);
}
catch (Exception ex)
{
return TypedResults.Problem(ex.Message);
}
}

[ProducesResponseType(StatusCodes.Status200OK)]
private static async Task<IResult> GetBook(IBookRepository bookRepository, int id)
{
try
{
var book = await bookRepository.GetBook(id);

BookGet bk = new BookGet(
book.Id,
book.Title,
new AuthorInternal(
book.Author.Id,
book.Author.FirstName,
book.Author.LastName,
book.Author.Email
)
);

return TypedResults.Ok(bk);
}
catch (Exception ex)
{
return TypedResults.Problem(ex.Message);
}
}

[ProducesResponseType(StatusCodes.Status200OK)]
private static async Task<IResult> UpdateBook(IBookRepository bookRepository, int id, int newAuthorId)
{
try
{
return TypedResults.Ok(await bookRepository.UpdateBook(id, newAuthorId));
}
catch (Exception ex)
{
return TypedResults.Problem(ex.Message);
}
}

[ProducesResponseType(StatusCodes.Status200OK)]
private static async Task<IResult> DeleteBook(IBookRepository bookRepository, int id)
{
try
{
return TypedResults.Ok(await bookRepository.DeleteBook(id));
}
catch (Exception ex)
{
return TypedResults.Problem(ex.Message);
}
}

[ProducesResponseType(StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
private static async Task<IResult> AddBook(IBookRepository bookRepository, IAuthorRepository authorRepository, BookPost book)
{
try
{
if (await authorRepository.GetAuthor(book.AuthorId) == null)
return TypedResults.NotFound("Author not found.");

Book bk = new Book()
{
Title = book.Title,
AuthorId = book.AuthorId
};
await bookRepository.AddBook(bk);

return TypedResults.Created($"https://localhost:7054/books/{bk.Id}", bk);
}
catch (Exception ex)
{
return TypedResults.BadRequest(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

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 @@ -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();
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)
{
return await _db.Authors.Include(a => a.Books).FirstOrDefaultAsync(a => a.Id == id);
}
}
}
28 changes: 28 additions & 0 deletions exercise.webapi/Repository/BookRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,33 @@ 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> UpdateBook(int id, int newAuthorId)
{
var book = await _db.Books.FirstOrDefaultAsync(b => b.Id == id);
book.AuthorId = newAuthorId;
await _db.SaveChangesAsync();
return book;
}

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

public async Task<Book> AddBook(Book book)
{
await _db.Books.AddAsync(book);
await _db.SaveChangesAsync();
return book;
}
}
}
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> UpdateBook(int id, int newAuthorId);
public Task<bool> DeleteBook(int id);
public Task<Book> AddBook(Book book);
}
}
16 changes: 13 additions & 3 deletions exercise.webapi/exercise.webapi.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,20 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="8.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="8.0.1" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="9.0.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="9.0.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="9.0.1">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="9.0.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="9.0.1">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="9.0.3" />
<PackageReference Include="Scalar.AspNetCore" Version="2.0.4" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="7.2.0" />
</ItemGroup>

</Project>