Skip to content

Kristoffer Blücher #112

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 3 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
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
10 changes: 10 additions & 0 deletions exercise.webapi/DTO/AuthorDTO.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
namespace exercise.webapi.DTO
{
public class AuthorDTO
{
public string Name { get; set; }
public string Email { get; set; }
public List<AuthorWithBooks> Books { get; set; }

}
}
10 changes: 10 additions & 0 deletions exercise.webapi/DTO/AuthorWithBooks.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
namespace exercise.webapi.DTO
{
public class AuthorWithBooks
{
public string Title { get; set; }
public string PublisherName { get; set; }


}
}
10 changes: 10 additions & 0 deletions exercise.webapi/DTO/BookDTO.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
namespace exercise.webapi.DTO
{
public class BookDTO
{
public string Title { get; set; }
public string AuthorName { get; set; }
public string AuthorEmail { get; set; }
public string PublisherName { get; set; }
}
}
12 changes: 12 additions & 0 deletions exercise.webapi/DTO/BookResponse.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
namespace exercise.webapi.DTO
{
public class BookResponse
{
public string Title { get; set; }
public string AuthorName { get; set; }
public string PublisherName { get; set; }



}
}
8 changes: 8 additions & 0 deletions exercise.webapi/DTO/PublisherDTO.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
namespace exercise.webapi.DTO
{
public class PublisherDTO
{
public string Name { get; set; }
public List<BookDTO> Books { get; set; }
}
}
12 changes: 11 additions & 1 deletion exercise.webapi/Data/DataContext.cs
Original file line number Diff line number Diff line change
@@ -1,16 +1,20 @@
using exercise.webapi.Models;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection.Emit;

namespace exercise.webapi.Data
{
public class DataContext : DbContext
{

private readonly string _connectionString;
public DataContext(DbContextOptions<DataContext> options) : base(options)
{

var configuration = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
_connectionString = configuration.GetValue<string>("ConnectionStrings:DefaultConnectionString")!;

}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
Expand All @@ -24,9 +28,15 @@ protected override void OnModelCreating(ModelBuilder modelBuilder)

modelBuilder.Entity<Author>().HasData(seeder.Authors);
modelBuilder.Entity<Book>().HasData(seeder.Books);
modelBuilder.Entity<Publisher>().HasData(seeder.Publishers);



}


public DbSet<Author> Authors { get; set; }
public DbSet<Book> Books { get; set; }
public DbSet<Publisher> Publishers { get; set; }
}
}
14 changes: 13 additions & 1 deletion exercise.webapi/Data/Seeder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -79,12 +79,14 @@ public class Seeder

private List<Author> _authors = new List<Author>();
private List<Book> _books = new List<Book>();
private List<Publisher> _publishers = new List<Publisher>();

public Seeder()
{

Random authorRandom = new Random();
Random bookRandom = new Random();
Random publisherRandom = new Random();



Expand All @@ -105,13 +107,23 @@ public Seeder()
book.Id = y;
book.Title = $"{_firstword[bookRandom.Next(_firstword.Count)]} {_secondword[bookRandom.Next(_secondword.Count)]} {_thirdword[bookRandom.Next(_thirdword.Count)]}";
book.AuthorId = _authors[authorRandom.Next(_authors.Count)].Id;
//book.Author = authors[book.AuthorId-1];
book.PublisherId = publisherRandom.Next(250);
// book.Author = _authors[book.AuthorId-1];
_books.Add(book);
}

for (int p = 1; p < 250; p++)
{
Publisher publisher = new Publisher();
publisher.Id = p;
publisher.Name = $"{_firstword[publisherRandom.Next(_firstword.Count)]} {_secondword[publisherRandom.Next(_secondword.Count)]} {_thirdword[publisherRandom.Next(_thirdword.Count)]}";
_publishers.Add(publisher);

}

}
public List<Author> Authors { get { return _authors; } }
public List<Book> Books { get { return _books; } }
public List <Publisher> Publishers { get { return _publishers; } }
}
}
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.Models;
using exercise.webapi.Repository;
using Microsoft.AspNetCore.Mvc;
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("/authors", GetAuthorById);
authors.MapGet("/", GetAllAuthors);
}


[ProducesResponseType(StatusCodes.Status200OK)]
private static async Task<IResult> GetAllAuthors(IAuthorRepository authorRepository)
{

try
{
var authors = await authorRepository.GetAllAuthors();

var bookDtos = authors.Select(x => new AuthorDTO
{
Name = $"{x.FirstName} {x.LastName}",
Email = x.Email,
Books = x.Books.Select(b => new AuthorWithBooks
{
Title = b.Title,
PublisherName = b.Publisher.Name,
}).ToList()

}).ToList();


return TypedResults.Ok(bookDtos);
}

catch (Exception ex)
{

return TypedResults.BadRequest(ex.Message);

}
}


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

if (author == null)
return TypedResults.NotFound($"Author with id {id} does not exist");


var authorDto = new AuthorDTO
{
Name = $"{author.FirstName} {author.LastName}",
Email = author.Email,
Books = author.Books.Select(b => new AuthorWithBooks
{
Title = b.Title,
PublisherName = b.Publisher.Name
}).ToList()
};
return TypedResults.Ok(authorDto);
}

}
}
163 changes: 157 additions & 6 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.Reflection;
using exercise.webapi.DTO;
using exercise.webapi.Models;
using exercise.webapi.Repository;
using exercise.webapi.ViewModels;
using Mapster;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.AspNetCore.Mvc;
using static System.Reflection.Metadata.BlobBuilder;

namespace exercise.webapi.Endpoints
Expand All @@ -8,13 +14,158 @@ public static class BookApi
{
public static void ConfigureBooksApi(this WebApplication app)
{
app.MapGet("/books", GetBooks);
var books = app.MapGroup("books");
books.MapGet("/books", GetAllBooks);
books.MapGet("/books{id}", GetBookById);
books.MapPost("/books/{id}", CreateBook);
books.MapDelete("/books{id}", DeleteBook);
books.MapPut("/books{id}", UpdateBookAuthor);
}

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

try
{
var books = await repository.GetAllBooks();
var bookDto = books.Select(b => new BookResponse
{
Title = b.Title,
AuthorName = $"{b.Author.FirstName} {b.Author.LastName}",
PublisherName = b.Publisher.Name}).ToList();


return TypedResults.Ok(bookDto);
}

catch (Exception ex)
{

return TypedResults.BadRequest(ex.Message);

}
}


[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
private static async Task<IResult> GetBookById(IBookRepository repository, int id)
{
var book = await repository.GetBookById(id);
if (book == null)
{
return TypedResults.NotFound("Book not found");

}
var response = book.Adapt<BookResponse>();

return TypedResults.Ok(response);

}



[ProducesResponseType(StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[ProducesResponseType (StatusCodes.Status400BadRequest)]
private static async Task<IResult> CreateBook(IBookRepository bookRepository, IAuthorRepository authorRepository, IPublisherRepository publisherRepository, BookPost model)
{
var author = await authorRepository.GetAuthorById(model.AuthorId);
var publisher = await publisherRepository.GetPublisherById(model.PublisherId);
if (author == null || publisher == null)
{
return TypedResults.NotFound("Author or Publisher not found");
}

if (model.Title == null)
{
return TypedResults.BadRequest("Book object not valid");

}

Console.WriteLine("Debug:" + author);

Book book = new Book()
{
Title = model.Title,
AuthorId = author.Id,
PublisherId = publisher.Id,
Author = author,
Publisher = publisher,


};

// Save the book to the repository
await bookRepository.CreateBook(book);

var response = new BookResponse
{
Title = book.Title,
AuthorName = $"{book.Author.FirstName} {book.Author.LastName}",
PublisherName = book.Publisher.Name
};

return TypedResults.Created($"/neondb/books/{book.Id}", response);
}


[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public static async Task<IResult> DeleteBook(IBookRepository repository, int id)
{
var book = await repository.GetBookById(id);

if (book == null)
{
return TypedResults.NotFound("Book not found");
}

await repository.DeleteBook(book.Id);

return TypedResults.Ok(book);


}


[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
private static async Task<IResult> UpdateBookAuthor(IBookRepository bookRepository, IAuthorRepository authorRepository, IPublisherRepository publisherRepository, int id, BookPost model)
{
var book = await bookRepository.GetBookById(id);
var author = await authorRepository.GetAuthorById(model.AuthorId);
var publisher = await publisherRepository.GetPublisherById(model.PublisherId);


if (book == null)
return TypedResults.NotFound($"Book with the id: {id} does not exist");

if (author == null)
return TypedResults.NotFound($"Author with the id: {model.AuthorId} not found");

if (publisher == null)
return TypedResults.NotFound($"Publisher with id {model.PublisherId} not found");

book.Title = model.Title;
book.AuthorId = model.AuthorId;
book.Author = author;
book.PublisherId = model.PublisherId;
book.Publisher = publisher;

var response = await bookRepository.UpdateBookAuthor(book.Id, book.AuthorId);
var bookDTO = new BookDTO
{
Title = response.Title,
AuthorName = response.Author.FirstName + " " + response.Author.LastName,
AuthorEmail = response.Author.Email,
PublisherName = response.Publisher.Name
};
return TypedResults.Ok(bookDTO);
}

}
}

}
Loading