Skip to content

Martin Vu #94

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 5 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
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -368,4 +368,4 @@ FodyWeavers.xsd
*/**/obj/Release
*/Migrations
/exercise.wwwapi/appsettings.json
/exercise.wwwapi/appsettings.Development.json
/exercise.wwwapi/appsettings.Development.json
13 changes: 13 additions & 0 deletions exercise.webapi/DTO/AuthorDTO.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
using exercise.webapi.Models;

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<BookPublisherDTO> Books { get; set; }
}
}
26 changes: 26 additions & 0 deletions exercise.webapi/DTO/BookDTO.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
using exercise.webapi.Models;

namespace exercise.webapi.DTO
{
public class BookDTO
{
public int Id { get; set; }
public string Title { get; set; }
public string AuthorName { get; set; } = string.Empty;
public string PublisherName { get; set; } = string.Empty;
}

public class BookAuthorDTO
{
public int Id { get; set; }
public string Title { get; set; }
public string AuthorName { get; set; } = string.Empty;
}

public class BookPublisherDTO
{
public int Id { get; set; }
public string Title { get; set; }
public string PublisherName { get; set; } = string.Empty;
}
}
9 changes: 9 additions & 0 deletions exercise.webapi/DTO/PublisherDTO.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
namespace exercise.webapi.DTO
{
public class PublisherDTO
{
public int Id { get; set; }
public string Name { get; set; }
public List<BookAuthorDTO> Books { get; set; }
}
}
2 changes: 2 additions & 0 deletions exercise.webapi/Data/DataContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,11 @@ 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; }
}
}
23 changes: 21 additions & 2 deletions exercise.webapi/Data/Seeder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -76,17 +76,35 @@ public class Seeder
"Flowers",
"Leopards"
};
private List<string> _publishernames = new List<string>()
{
"Penguin Random House",
"Hacette Livre",
"Harper Collins",
"Simon and Schuster",
"Macmillan Publishers",
"Chronicle Books",
"Persea Books"
};

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();


for (int y = 1; y < _publishernames.Count; y++)
{
Publisher publisher = new Publisher();
publisher.Id = y;
publisher.Name = _publishernames[y];
_publishers.Add(publisher);
}

for (int x = 1; x < 250; x++)
{
Expand All @@ -106,12 +124,13 @@ public Seeder()
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 = _publishers[publisherRandom.Next(_publishers.Count)].Id;
_books.Add(book);
}


}
public List<Author> Authors { get { return _authors; } }
public List<Book> Books { get { return _books; } }
public List<Publisher> Publishers { get { return _publishers; } }
}
}
78 changes: 78 additions & 0 deletions exercise.webapi/Endpoints/AuthorApi.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
using exercise.webapi.DTO;
using exercise.webapi.Models;
using exercise.webapi.Repository;
using Microsoft.AspNetCore.Mvc;

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

[ProducesResponseType(StatusCodes.Status200OK)]
private static async Task<IResult> GetAuthor(IAuthorRepository authorRepository, int id)
{
var author = await authorRepository.GetAuthor(id);
var result = new AuthorDTO()
{
Id = author.Id,
FirstName = author.FirstName,
LastName = author.LastName,
Email = author.Email,
Books = []
};

foreach (var b in author.Books)
{
BookPublisherDTO bookDTO = new BookPublisherDTO()
{
Id = b.Id,
Title = b.Title,
PublisherName = b.Publisher.Name
};
result.Books.Add(bookDTO);
}

return TypedResults.Ok(result);
}

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

foreach (var a in authors)
{
var authorDTO = new AuthorDTO()
{
Id = a.Id,
FirstName = a.FirstName,
LastName = a.LastName,
Email = a.Email,
Books = []
};

foreach(var b in a.Books)
{
BookPublisherDTO bookDTO = new BookPublisherDTO()
{
Id = b.Id,
Title = b.Title,
PublisherName = b.Publisher.Name
};
authorDTO.Books.Add(bookDTO);
}
result.Add(authorDTO);
}

return TypedResults.Ok(result);
}

}
}
134 changes: 131 additions & 3 deletions exercise.webapi/Endpoints/BookApi.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
using exercise.webapi.Models;
using System.Collections.Immutable;
using exercise.webapi.DTO;
using exercise.webapi.Models;
using exercise.webapi.Repository;
using exercise.webapi.ViewModel;
using Microsoft.AspNetCore.Mvc;
using static System.Reflection.Metadata.BlobBuilder;

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

[ProducesResponseType(StatusCodes.Status200OK)]
private static async Task<IResult> GetBook(IBookRepository bookRepository, int id)
{
var book = await bookRepository.GetBook(id);
var result = new BookDTO()
{
Id = book.Id,
Title = book.Title,
AuthorName = $"{book.Author.FirstName} {book.Author.LastName}",
PublisherName = book.Publisher.Name
};

return TypedResults.Ok(result);
}

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

foreach (var b in books)
{
var book = new BookDTO()
{
Id = b.Id,
Title = b.Title,
AuthorName = $"{b.Author.FirstName} {b.Author.LastName}",
PublisherName = b.Publisher.Name
};
result.Add(book);

}

return TypedResults.Ok(result);
}

[ProducesResponseType(StatusCodes.Status200OK)]
private static async Task<IResult> UpdateBook(IBookRepository bookRepository, int id, BookPut model)
{
try
{
var target = await bookRepository.GetBook(id);
if (model.AuthorId != null) target.AuthorId = (int)model.AuthorId;
if (model.PublisherId != null) target.PublisherId = (int)model.PublisherId;

await bookRepository.UpdateBook(target);
var update = await bookRepository.GetBook(id);
var result = new BookDTO()
{
Id = update.Id,
Title = update.Title,
AuthorName = $"{update.Author.FirstName} {update.Author.LastName}",
PublisherName = update.Publisher.Name
};

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

[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
private static async Task<IResult> DeleteBook(IBookRepository bookRepository, int id)
{
try
{
var target = await bookRepository.GetBook(id);
if (target == null) return TypedResults.NotFound("Book not found.");
if (bookRepository.DeleteBook(id) != null)
{
var result = new BookDTO()
{
Id = target.Id,
Title = target.Title,
AuthorName = $"{target.Author.FirstName} {target.Author.LastName}",
PublisherName = target.Publisher.Name
};
return TypedResults.Ok(result);
}
return TypedResults.NotFound("Book not found.");
}
catch (Exception ex)
{
return TypedResults.Problem(ex.Message);
}
}

[ProducesResponseType(StatusCodes.Status200OK)]
private static async Task<IResult> CreateBook(IBookRepository bookRepository, IAuthorRepository authorRepository, IPublisherRepository publisherRepository, BookPost model)
{
try
{
if (string.IsNullOrEmpty(model.Title)) return TypedResults.BadRequest("Title is required.");
if (model.AuthorId <= 0) return TypedResults.BadRequest("Valid AuthorId is required.");
if (model.PublisherId <= 0) return TypedResults.BadRequest("Valid PublisherId is required.");

var author = await authorRepository.GetAuthor(model.AuthorId);
if (author == null) return TypedResults.NotFound("Author does not exist in database");
var publisher = await publisherRepository.GetPublisher(model.PublisherId);
if (publisher == null) return TypedResults.NotFound("Publiser does not exist in database");

var newBook = await bookRepository.CreateBook(new Book(){ Title = model.Title, AuthorId = model.AuthorId, PublisherId = model.PublisherId});

var createdBook = await bookRepository.GetBook(newBook.Id);

BookDTO result = new BookDTO()
{
Id = createdBook.Id,
Title = createdBook.Title,
AuthorName = $"{createdBook.Author.FirstName} {createdBook.Author.LastName}",
PublisherName = createdBook.Publisher.Name
};
return TypedResults.Created($"/{createdBook.Id}", result);
}
catch (Exception ex)
{
return TypedResults.Problem(ex.Message);
}
}

}
}
Loading