Skip to content
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

Håkon Wullum #106

Open
wants to merge 2 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
16 changes: 16 additions & 0 deletions exercise.webapi/DTO/AuthorPayload.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
using exercise.webapi.Models;

namespace exercise.webapi.DTO
{
public class AuthorPayload
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }

public IEnumerable<TestBookPayload> Books { get; set; } //= new List<TestBookPayload>();


}
}
13 changes: 13 additions & 0 deletions exercise.webapi/DTO/BookPaylaod.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
namespace exercise.webapi.DTO
{
public class BookPaylaod<T> where T : class
{
public T Data { get; set; }

//public string FirstName { get; set; }
//public string LastName { get; set; }
//public string Email { get; set; }

public string Message { get; set; } = "Status";
}
}
11 changes: 11 additions & 0 deletions exercise.webapi/DTO/BookPost.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
using exercise.webapi.Models;

namespace exercise.webapi.DTO
{
public class BookPost
{
public string Title { get; set; }

public int AuthorId { get; set; }
}
}
15 changes: 15 additions & 0 deletions exercise.webapi/DTO/BookPut.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
using exercise.webapi.Models;

namespace exercise.webapi.DTO
{
public class BookPut
{
/*
public int? Id { get; set; }
public string? Title { get; set; }
public Author Author { get; set; }
*/

public required int AuthorId { get; set; }
}
}
14 changes: 14 additions & 0 deletions exercise.webapi/DTO/TestBookPayload.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
namespace exercise.webapi.DTO
{
public class TestBookPayload
{
public int Id { get; set; }
public string Title { get; set; }

public int? AuthorId { get; set; }

public string? FirstName { get; set; }
public string? LastName { get; set; }
public string? Email { get; set; }
}
}
64 changes: 64 additions & 0 deletions exercise.webapi/Endpoints/AuthorApi.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
using exercise.webapi.DTO;
using exercise.webapi.Models;
using exercise.webapi.Repository;

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

author.MapGet("/", GetAllAuthors);
author.MapGet("/{id}", GetAuthorById);
}

public static async Task<IResult> GetAllAuthors(IRepository<Author> authorRepository)
{

var payload = from a in authorRepository.GetAllEntities().Result
select new AuthorPayload()
{
Id = a.Id,
FirstName = a.FirstName,
LastName = a.LastName,
Email = a.Email,
Books = from b in a.Books
select new TestBookPayload()
{
Id = b.Id,
Title = b.Title,
AuthorId = a.Id,
FirstName = a.FirstName,
LastName = a.LastName,
Email = a.Email
}
};

return TypedResults.Ok(payload);
}

private static async Task<IResult> GetAuthorById(IRepository<Author> authorRepository, int id)
{

var author = await authorRepository.GetEntityById(id);

var payload = new AuthorPayload()
{
Id = author.Id,
FirstName = author.FirstName,
LastName = author.LastName,
Email = author.Email,
Books = from b in author.Books
select new TestBookPayload()
{
Id = b.Id,
Title = b.Title
}
};

return TypedResults.Ok(payload);
}
}
}
119 changes: 114 additions & 5 deletions exercise.webapi/Endpoints/BookApi.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using exercise.webapi.Models;
using exercise.webapi.DTO;
using exercise.webapi.Models;
using exercise.webapi.Repository;
using static System.Reflection.Metadata.BlobBuilder;

Expand All @@ -8,13 +9,121 @@ 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}", GetBookById);
books.MapPut("/{id}", UpdateBook);
books.MapDelete("/{id}", DeleteBook);
books.MapPost("/", CreateBook);
}

private static async Task<IResult> GetBooks(IRepository<Book> bookRepository)
{


var payload = from b in bookRepository.GetAllEntities().Result
select new TestBookPayload()
{
Id = b.Id,
Title = b.Title,
AuthorId = b.AuthorId,
FirstName = b.Author.FirstName,
LastName = b.Author.LastName,
Email = b.Author.Email
};

return TypedResults.Ok(payload);
}

private static async Task<IResult> GetBookById(IRepository<Book> bookRepository, int id)
{
var book = await bookRepository.GetEntityById(id);

var payload = new TestBookPayload()
{
Id = book.Id,
Title = book.Title,
AuthorId = book.AuthorId,
FirstName = book.Author.FirstName,
LastName = book.Author.LastName,
Email = book.Author.Email
};

return TypedResults.Ok(payload);
}

private static async Task<IResult> UpdateBook(IRepository<Book> bookRepository, IRepository<Author> authorRepository, int id, BookPut model)
{
var book = await bookRepository.GetEntityById(id);
if (book == null) return TypedResults.NotFound("No book matching provided ID");

try
{
book.Author = await authorRepository.GetEntityById(model.AuthorId);
book.AuthorId = model.AuthorId;

bookRepository.SaveRepository();
}
catch (Exception ex) { return TypedResults.BadRequest(ex); }

var payload = new TestBookPayload()
{
Id = book.Id,
Title = book.Title,
AuthorId = book.AuthorId,
FirstName = book.Author.FirstName,
LastName = book.Author.LastName,
Email = book.Author.Email
};

return TypedResults.Ok(payload);
}

private static async Task<IResult> GetBooks(IBookRepository bookRepository)
private static async Task<IResult> DeleteBook(IRepository<Book> bookRepository, int id)
{
var books = await bookRepository.GetAllBooks();
return TypedResults.Ok(books);
try
{
var book = await bookRepository.GetEntityById(id);
if (book == null) return TypedResults.NotFound("No book matching provided ID");

var status = await bookRepository.DeleteEntity(book);
bookRepository.SaveRepository();

return TypedResults.Ok(status);

} catch (Exception ex) { return TypedResults.BadRequest(ex); }
}


private static async Task<IResult> CreateBook(IRepository<Book> bookRepository, IRepository<Author> authorRepository, BookPost model)
{
try
{
var allBooks = await bookRepository.GetAllEntities();

Book book = new Book()
{
Id = allBooks.Max(b => b.Id) + 1,
Title = model.Title,
Author = await authorRepository.GetEntityById(model.AuthorId),
AuthorId = model.AuthorId
};

var payload = new TestBookPayload()
{
Id = book.Id,
Title = book.Title,
AuthorId = book.AuthorId,
FirstName = book.Author.FirstName,
LastName = book.Author.LastName,
Email = book.Author.Email
};

return TypedResults.Ok(payload);

}
catch (Exception ex) { return TypedResults.BadRequest(ex); }
}
}
}
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
//[JsonIgnore] // Todo: replace this with DTO approach
public ICollection<Book> Books { get; set; } = new List<Book>();
}
}
5 changes: 4 additions & 1 deletion exercise.webapi/Program.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using exercise.webapi.Data;
using exercise.webapi.Endpoints;
using exercise.webapi.Models;
using exercise.webapi.Repository;
using Microsoft.EntityFrameworkCore;

Expand All @@ -10,7 +11,8 @@
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddDbContext<DataContext>(opt => opt.UseInMemoryDatabase("Library"));
builder.Services.AddScoped<IBookRepository, BookRepository>();
builder.Services.AddScoped<IRepository<Book>, BookRepository>();
builder.Services.AddScoped<IRepository<Author>, AuthorRepository>();

var app = builder.Build();

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

app.UseHttpsRedirection();
app.ConfigureBooksApi();
app.ConfigureAuthorsApi();
app.Run();
36 changes: 36 additions & 0 deletions exercise.webapi/Repository/AuthorRepository.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
using exercise.webapi.Data;
using exercise.webapi.Models;
using Microsoft.EntityFrameworkCore;

namespace exercise.webapi.Repository
{
public class AuthorRepository : IRepository<Author>
{
DataContext _db;

public AuthorRepository(DataContext db)
{
_db = db;
}
public async void SaveRepository()
{
await _db.SaveChangesAsync();
}

public async Task<IEnumerable<Author>> GetAllEntities()
{
return await _db.Authors.Include(a => a.Books).ToListAsync();
}

public async Task<Author> GetEntityById(int id)
{
return await _db.Authors.Include(a => a.Books).FirstOrDefaultAsync(a => a.Id == id);
}

public Task<bool> DeleteEntity(Author author)
{
throw new NotImplementedException();
}

}
}
23 changes: 21 additions & 2 deletions exercise.webapi/Repository/BookRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

namespace exercise.webapi.Repository
{
public class BookRepository: IBookRepository
public class BookRepository: IRepository<Book>
{
DataContext _db;

Expand All @@ -13,10 +13,29 @@ public BookRepository(DataContext db)
_db = db;
}

public async Task<IEnumerable<Book>> GetAllBooks()
public async void SaveRepository()
{
await _db.SaveChangesAsync();
}

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

}

public async Task<Book> GetEntityById(int id)
{
return await _db.Books.Include(b => b.Author).FirstOrDefaultAsync(b => b.Id == id);
}

public async Task<bool> DeleteEntity(Book book)
{
try
{
_db.Books.Remove(book);
return true;
}catch (Exception ex) {return false;}
}
}
}
Loading