Skip to content

Noah Ekse #99

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 1 commit 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
9 changes: 9 additions & 0 deletions exercise.webapi/DTO/AddBookDto.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
namespace exercise.webapi.DTO
{
public class AddBookDto
{
public string Title { get; set; }

public int AuthorId { get; set; }
}
}
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 string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }

public ICollection<Book> Books { get; set; } = new List<Book>();
}
}
11 changes: 11 additions & 0 deletions exercise.webapi/DTO/AuthorResponseDto.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
namespace exercise.webapi.DTO
{
public class AuthorResponseDto
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public List<BookWithoutAuthorDto> Books { get; set; } = new List<BookWithoutAuthorDto>();
}
}
13 changes: 13 additions & 0 deletions exercise.webapi/DTO/BookDto.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 BookDto
{
public int Id { get; set; }
public string Title { get; set; }

public int AuthorId { get; set; }
public AuthorDto Author { get; set; }
}
}
8 changes: 8 additions & 0 deletions exercise.webapi/DTO/BookWithoutAuthorDto.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
namespace exercise.webapi.DTO
{
public class BookWithoutAuthorDto
{
public int Id { get; set; }
public string Title { get; set; }
}
}
9 changes: 5 additions & 4 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 Microsoft.Extensions.Configuration;
using System.Collections.Generic;
using System.Reflection.Emit;

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

public DataContext(DbContextOptions<DataContext> options) : base(options)
private readonly IConfiguration _configuration;
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("DefaultConnectionString"));
}

protected override void OnModelCreating(ModelBuilder modelBuilder)
Expand Down
71 changes: 71 additions & 0 deletions exercise.webapi/Endpoints/AuthorApi.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
using AutoMapper;
using exercise.webapi.DTO;
using exercise.webapi.Models;
using exercise.webapi.Repository;
using static System.Reflection.Metadata.BlobBuilder;

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

}

private static async Task<IResult> GetAuthors(IRepository<Author> repository, IRepository<Book> bookRepository, IMapper mapper)
{
try
{
var authors = await repository.GetAll();
List<AuthorResponseDto> response = new List<AuthorResponseDto>();

foreach (var author in authors)
{
var books = bookRepository.FindAll(b => b.AuthorId.Equals(author.Id));

AuthorResponseDto authorDto = new AuthorResponseDto();
authorDto.Id = author.Id;
authorDto.FirstName = author.FirstName;
authorDto.LastName = author.LastName;
authorDto.Email = author.Email;
authorDto.Books = (List<BookWithoutAuthorDto>)mapper.Map<IEnumerable<BookWithoutAuthorDto>>(books.Result);
response.Add(authorDto);
}

return TypedResults.Ok(response);
}
catch (Exception ex)
{
return TypedResults.NotFound(ex);
}
}

private static async Task<IResult> GetAuthor(IRepository<Author> repository, IRepository<Book> bookRepository, IMapper mapper, int id)
{
try
{
var author = await repository.Get(a => a.Id.Equals(id), a => a.Books);
var books = bookRepository.FindAll(b => b.AuthorId.Equals(author.Id));
if (author == null) return TypedResults.NotFound($"Author with {id} was not found");

AuthorResponseDto authorDto = new AuthorResponseDto();
authorDto.FirstName = author.FirstName;
authorDto.LastName = author.LastName;
authorDto.Email = author.Email;
authorDto.Books = (List<BookWithoutAuthorDto>)mapper.Map<IEnumerable<BookWithoutAuthorDto>>(books.Result);


return TypedResults.Ok(mapper.Map<AuthorResponseDto>(authorDto));
}
catch (Exception ex)
{
return TypedResults.BadRequest(ex);
}
}


}
}
91 changes: 87 additions & 4 deletions exercise.webapi/Endpoints/BookApi.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
using exercise.webapi.Models;
using AutoMapper;
using exercise.webapi.DTO;
using exercise.webapi.Models;
using exercise.webapi.Repository;
using static System.Reflection.Metadata.BlobBuilder;

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

private static async Task<IResult> GetBooks(IBookRepository bookRepository)
private static async Task<IResult> GetBooks(IRepository<Book> repository, IMapper mapper)
{
var books = await bookRepository.GetAllBooks();
return TypedResults.Ok(books);
try
{
var books = await repository.GetAll(b => b.Author);
var response = mapper.Map<IEnumerable<BookDto>>(books);
return TypedResults.Ok(response);
}
catch (Exception ex)
{
return TypedResults.NotFound(ex);
}
}

private static async Task<IResult> GetBook(IRepository<Book> repository, IMapper mapper, int id)
{
try
{
var book = await repository.Get(b => b.Id.Equals(id), b => b.Author);
if (book == null) return TypedResults.NotFound($"Book with {id} was not found");
return TypedResults.Ok(mapper.Map<BookDto>(book));
}
catch (Exception ex)
{
return TypedResults.BadRequest(ex);
}
}

private static async Task<IResult> AddBook(IRepository<Book> repository, IRepository<Author> authorRepository, IMapper mapper, AddBookDto model)
{
try
{
var author = await authorRepository.Get(a => a.Id.Equals(model.AuthorId));
if (author == null) return TypedResults.NotFound($"Author with {model.AuthorId} was not found");

Book newBook = new Book
{
Title = model.Title,
AuthorId = model.AuthorId,
Author = author,
};
var book = await repository.Add(newBook);
return TypedResults.Created($"https://localhost:7054/books/", mapper.Map<BookDto>(book));
}
catch (Exception ex)
{
return TypedResults.NotFound(ex);
}
}

private static async Task<IResult> UpdateBook(IRepository<Book> repository, IMapper mapper, int bookId, int authorId)
{
try
{
var book = await repository.Get(b => b.Id.Equals(bookId));
if (book == null) return TypedResults.NotFound($"Book with {bookId} was not found");
book.AuthorId = authorId;
await repository.Update(book);
var updatedBookWithInclude = await repository.Get(b => b.Id.Equals(bookId), b => b.Author);
return TypedResults.Ok(mapper.Map<BookDto>(updatedBookWithInclude));
}
catch (Exception ex)
{
return TypedResults.NotFound(ex);
}
}

private static async Task<IResult> DeleteBook(IRepository<Book> repository, IMapper mapper, int bookId)
{
try
{
var book = await repository.Get(b => b.Id.Equals(bookId), b => b.Author);
if (book == null) return TypedResults.NotFound($"Book with {bookId} was not found");
await repository.Delete(book);

return TypedResults.Ok(mapper.Map<BookDto>(book));
}
catch (Exception ex)
{
return TypedResults.NotFound(ex);
}
}
}
}
17 changes: 17 additions & 0 deletions exercise.webapi/Mapper/AutoMapperProfile.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
using AutoMapper;
using exercise.webapi.DTO;
using exercise.webapi.Models;

namespace exercise.webapi.Mapper
{
public class AutoMapperProfile : Profile
{
public AutoMapperProfile()
{
CreateMap<Author, AuthorDto>();
CreateMap<Author, AuthorResponseDto>();
CreateMap<Book, BookDto>();
CreateMap<Book, BookWithoutAuthorDto>();
}
}
}
20 changes: 16 additions & 4 deletions exercise.webapi/Program.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
using System.Diagnostics;
using exercise.webapi.Data;
using exercise.webapi.Endpoints;
using exercise.webapi.Mapper;
using exercise.webapi.Models;
using exercise.webapi.Repository;
using Microsoft.EntityFrameworkCore;

Expand All @@ -9,24 +12,33 @@
// 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.AddScoped<IBookRepository, BookRepository>();
builder.Services.AddAutoMapper(typeof(AutoMapperProfile));
builder.Services.AddScoped<IRepository<Book>, Repository<Book>>();
builder.Services.AddScoped<IRepository<Author>, Repository<Author>>();
builder.Services.AddDbContext<DataContext>(options =>
{
options.UseNpgsql(builder.Configuration.GetConnectionString("DefaultConnectionString"));
options.LogTo(message => Debug.WriteLine(message));
});


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


// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}


app.UseHttpsRedirection();
app.ConfigureBooksApi();
app.ConfigureAuthorApi();
app.Run();
22 changes: 0 additions & 22 deletions exercise.webapi/Repository/BookRepository.cs

This file was deleted.

9 changes: 0 additions & 9 deletions exercise.webapi/Repository/IBookRepository.cs

This file was deleted.

15 changes: 15 additions & 0 deletions exercise.webapi/Repository/IRepository.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
using System.Linq.Expressions;
using exercise.webapi.Models;

namespace exercise.webapi.Repository
{
public interface IRepository<TEntity> where TEntity : class
{
Task<IEnumerable<TEntity>> GetAll(params Expression<Func<TEntity, object>>[] includeProperties);
Task<IEnumerable<TEntity>> FindAll(Expression<Func<TEntity, bool>> predicate, params Expression<Func<TEntity, object>>[] includeProperties);
Task<TEntity> Get(Expression<Func<TEntity, bool>> predicate, params Expression<Func<TEntity, object>>[] includeProperties);
Task<TEntity> Add(TEntity entity);
Task<TEntity> Update(TEntity entity);
Task<TEntity> Delete(TEntity entity);
}
}
Loading