Skip to content

Magnus Nymo #90

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 10 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
11 changes: 6 additions & 5 deletions exercise.webapi/Data/DataContext.cs
Original file line number Diff line number Diff line change
@@ -1,21 +1,22 @@
using exercise.webapi.Models;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Reflection.Emit;
using Microsoft.EntityFrameworkCore.Diagnostics;

namespace exercise.webapi.Data
{
public class DataContext : DbContext
{
private readonly IConfiguration _configuration;

public DataContext(DbContextOptions<DataContext> options) : base(options)
public DataContext(DbContextOptions<DataContext> options, IConfiguration configuration) : base(options)
{

_configuration = configuration;
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
base.OnConfiguring(optionsBuilder);
optionsBuilder.UseInMemoryDatabase("Library");
optionsBuilder.UseNpgsql(_configuration.GetConnectionString("DefaultConnection"));
optionsBuilder.ConfigureWarnings(w => w.Ignore(RelationalEventId.PendingModelChangesWarning));
}

protected override void OnModelCreating(ModelBuilder modelBuilder)
Expand Down
29 changes: 29 additions & 0 deletions exercise.webapi/Dto/AuthorResponse.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
using System.Text.Json.Serialization;

namespace exercise.webapi.Dto;

public class AuthorResponse
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
public BookResponse[]? Books { get; set; }

public AuthorResponse(Models.Author author)
{
Id = author.Id;
FirstName = author.FirstName;
LastName = author.LastName;
Email = author.Email;
if (author.Books.Count > 0)
{
Books = author.Books.Select((b) =>
{
b.Author = null;
return new BookResponse(b);
}).ToArray();
}
}
}
13 changes: 13 additions & 0 deletions exercise.webapi/Dto/BookPost.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
using System.ComponentModel.DataAnnotations;

namespace exercise.webapi.Dto;

public class BookPost
{
[Required]
[MinLength(1)]
[MaxLength(100)]
public string Title { get; set; }
[Required]
public int AuthorId { get; set; }
}
11 changes: 11 additions & 0 deletions exercise.webapi/Dto/BookPut.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
using System.ComponentModel.DataAnnotations;

namespace exercise.webapi.Dto;

public class BookPut
{
[MinLength(1)]
[MaxLength(100)]
public string Title { get; set; }
public int AuthorId { get; set; }
}
23 changes: 23 additions & 0 deletions exercise.webapi/Dto/BookResponse.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
using System.Text.Json.Serialization;
using exercise.webapi.Models;

namespace exercise.webapi.Dto;

public class BookResponse
{
public int Id { get; set; }
public string Title { get; set; }
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
public AuthorResponse? Author { get; set; }

public BookResponse(Book book)
{
Id = book.Id;
Title = book.Title;
// TODO: Throws NullReferenceException when not in the if statement. FIX!
if (book.Author is not null)
{
Author = new AuthorResponse(book.Author);
}
}
}
36 changes: 36 additions & 0 deletions exercise.webapi/Endpoints/AuthorApi.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
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)
{
app.MapGet("/authors", GetAuthors);
app.MapGet("/authors/{id}", GetAuthor);
}

[ProducesResponseType(typeof(IEnumerable<AuthorResponse>), StatusCodes.Status200OK)]
private static async Task<IResult> GetAuthors(IAuthorRepository authorRepository)
{
var authors = await authorRepository.GetAllAuthors();
var response = authors.Select(a => new AuthorResponse(a));

return TypedResults.Ok(response);
}

[ProducesResponseType(typeof(AuthorResponse), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
private static async Task<IResult> GetAuthor(IAuthorRepository authorRepository, int id)
{
var author = await authorRepository.GetAuthorById(id);
if (author == null)
{
return TypedResults.NotFound();
}

return TypedResults.Ok(new AuthorResponse(author));
}
}
95 changes: 92 additions & 3 deletions exercise.webapi/Endpoints/BookApi.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
using exercise.webapi.Models;
using System.ComponentModel.DataAnnotations;
using exercise.webapi.Dto;
using exercise.webapi.Models;
using exercise.webapi.Repository;
using static System.Reflection.Metadata.BlobBuilder;
using Microsoft.AspNetCore.Mvc;

namespace exercise.webapi.Endpoints
{
Expand All @@ -9,12 +11,99 @@ public static class BookApi
public static void ConfigureBooksApi(this WebApplication app)
{
app.MapGet("/books", GetBooks);
app.MapGet("/books/{id}", GetBook);
app.MapPost("/books", CreateBook);
app.MapDelete("/books/{id}", DeleteBook);
app.MapPut("/books/{id}", UpdateBook);
}

[ProducesResponseType(typeof(IEnumerable<BookResponse>), StatusCodes.Status200OK)]
private static async Task<IResult> GetBooks(IBookRepository bookRepository)
{
var books = await bookRepository.GetAllBooks();
return TypedResults.Ok(books);
var response = books.Select(b => new BookResponse(b));

foreach (var book in books)
{
book.Author.Books = new List<Book>();
}
return TypedResults.Ok(response);
}

[ProducesResponseType(typeof(BookResponse), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
private static async Task<IResult> GetBook(IBookRepository bookRepository, int id)
{
var book = await bookRepository.GetBookById(id);
if (book == null)
{
return TypedResults.NotFound();
}
book.Author.Books = new List<Book>();
return TypedResults.Ok(new BookResponse(book));
}

[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
private static async Task<IResult> DeleteBook(IBookRepository bookRepository, int id)
{
var book = await bookRepository.GetBookById(id);
if (book == null)
{
return TypedResults.NotFound();
}
bookRepository.DeleteBook(book);
return TypedResults.NoContent();
}

[ProducesResponseType(typeof(BookResponse), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
private static async Task<IResult> UpdateBook(IBookRepository bookRepository, IAuthorRepository authorRepository, int id, [FromBody] BookPut book)
{
var existingBook = await bookRepository.GetBookById(id);
if (existingBook == null)
{
return TypedResults.NotFound();
}

existingBook.Title = book.Title;
Console.WriteLine(book.AuthorId);
existingBook.AuthorId = book.AuthorId;
var newBook = await bookRepository.UpdateBook(existingBook);

newBook.Author.Books = new List<Book>();
return TypedResults.Ok(new BookResponse(newBook));
}

[ProducesResponseType(StatusCodes.Status201Created)]
[ProducesResponseType(typeof(string), StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
private static async Task<IResult> CreateBook(IBookRepository bookRepository,
IAuthorRepository authorRepository, [FromBody] BookPost book)
{
try
{
Validator.ValidateObject(book, new ValidationContext(book), true);
}
catch (ValidationException e)
{
return TypedResults.BadRequest(e.Message);
}

var author = await authorRepository.GetAuthorById(book.AuthorId);
if (author == null)
{
return TypedResults.NotFound();
}

var newBook = new Book
{
Title = book.Title,
AuthorId = book.AuthorId
};
var createdBook = await bookRepository.AddBook(newBook);
createdBook.Author.Books = new List<Book>();
return TypedResults.Created("/books/" + createdBook.Id);
}
}
}
9 changes: 7 additions & 2 deletions exercise.webapi/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,17 @@
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddDbContext<DataContext>(opt => opt.UseInMemoryDatabase("Library"));
builder.Services.AddDbContext<DataContext>(options =>
options.UseNpgsql(builder.Configuration.GetConnectionString("DefaultConnection")));
builder.Services.AddScoped<IBookRepository, BookRepository>();
builder.Services.AddScoped<IAuthorRepository, AuthorRepository>();


var app = builder.Build();

using (var dbContext = new DataContext(new DbContextOptions<DataContext>()))
using (var scope = app.Services.CreateScope())
{
var dbContext = scope.ServiceProvider.GetRequiredService<DataContext>();
dbContext.Database.EnsureCreated();
}

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

app.UseHttpsRedirection();
app.ConfigureBooksApi();
app.ConfigureAuthorsApi();
app.Run();
31 changes: 31 additions & 0 deletions exercise.webapi/Repository/AuthorRepository.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
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?> GetAuthorById(int id)
{
var author = await _db.Authors
.Include(a => a.Books)
.FirstOrDefaultAsync(a => a.Id == id);

return author;
}
}
41 changes: 40 additions & 1 deletion exercise.webapi/Repository/BookRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,50 @@ public BookRepository(DataContext db)
{
_db = db;
}

public async Task<Book> AddBook(Book book)
{
await _db.Books.AddAsync(book);
await _db.SaveChangesAsync();
return book;
}

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

}

public async Task<Book?> GetBookById(int id)
{
return await _db.Books.Select(b => new Book
{
Id = b.Id,
Title = b.Title,
Author = new Author
{
Id = b.Author.Id,
FirstName = b.Author.FirstName,
LastName = b.Author.LastName,
Email = b.Author.Email
}
}).FirstOrDefaultAsync(b => b.Id == id);
}

public void DeleteBook(Book book)
{
_db.Books.Remove(book);
_db.SaveChanges();
}

public async Task<Book> UpdateBook(Book book)
{
//_db.Books.Update(book);
_db.Attach(book).State = EntityState.Modified;
await _db.SaveChangesAsync();
return book;
}
}
}
9 changes: 9 additions & 0 deletions exercise.webapi/Repository/IAuthorRepository.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
using exercise.webapi.Models;

namespace exercise.webapi.Repository;

public interface IAuthorRepository
{
public Task<IEnumerable<Author>> GetAllAuthors();
Task<Author?> GetAuthorById(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 @@ -4,6 +4,10 @@ namespace exercise.webapi.Repository
{
public interface IBookRepository
{
Task<Book> AddBook(Book book);
public Task<IEnumerable<Book>> GetAllBooks();
Task<Book?> GetBookById(int id);
void DeleteBook(Book book);
Task<Book> UpdateBook(Book book);
}
}
Loading