Skip to content

Hans Jakob Håland #121

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 11 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
/exercise.wwwapi/appsettings.json
/exercise.wwwapi/appsettings.Development.json
/exercise.webapi/appsettings.json
/exercise.webapi/appsettings.Development.json
7 changes: 7 additions & 0 deletions exercise.webapi/DTOs/AuthorBookGet.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
namespace exercise.webapi.DTOs
{
public class AuthorBookGet
{
public string Title { get; set; }
}
}
11 changes: 11 additions & 0 deletions exercise.webapi/DTOs/AuthorGet.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
using exercise.webapi.Models;

namespace exercise.webapi.DTOs
{
public class AuthorGet
{
public string FirstName { get; set; }
public string LastName { get; set; }
public ICollection<AuthorBookGet> Books { get; set; } = new List<AuthorBookGet>();
}
}
9 changes: 9 additions & 0 deletions exercise.webapi/DTOs/BookAuthorGet.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
namespace exercise.webapi.DTOs
{
public class BookAuthorGet
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
}
}
10 changes: 10 additions & 0 deletions exercise.webapi/DTOs/BookGet.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
using exercise.webapi.Models;

namespace exercise.webapi.DTOs
{
public class BookGet
{
public string Title { get; set; }
public BookAuthorGet Author { get; set; }
}
}
8 changes: 8 additions & 0 deletions exercise.webapi/DTOs/BookPost.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
namespace exercise.webapi.DTOs
{
public class BookPost
{
public string Title { get; set; }
public int AuthorId { get; set; }
}
}
10 changes: 5 additions & 5 deletions exercise.webapi/Data/DataContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,11 @@ public DataContext(DbContextOptions<DataContext> options) : base(options)
{

}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
base.OnConfiguring(optionsBuilder);
optionsBuilder.UseInMemoryDatabase("Library");
}
//protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
//{
// //base.OnConfiguring(optionsBuilder);
// //optionsBuilder.UseInMemoryDatabase("Library");
//}

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
Expand Down
6 changes: 4 additions & 2 deletions exercise.webapi/Data/Seeder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -82,9 +82,10 @@ public class Seeder

public Seeder()
{
int seed = 42;

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



Expand All @@ -107,6 +108,7 @@ public Seeder()
book.AuthorId = _authors[authorRandom.Next(_authors.Count)].Id;
//book.Author = authors[book.AuthorId-1];
_books.Add(book);

}


Expand Down
54 changes: 54 additions & 0 deletions exercise.webapi/Endpoints/AuthorApi.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
using exercise.webapi.DTOs;
using exercise.webapi.Repository;
using System.Runtime.CompilerServices;

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

private static async Task<IResult> GetAuthorsById(IAuthorRepository repository, int id)
{
var entity = await repository.GetAuthorById(id);
if (entity == null) return TypedResults.NotFound();

var author = new AuthorGet();
author.FirstName = entity.FirstName;
author.LastName = entity.LastName;

foreach (var book in entity.Books)
{
author.Books.Add(new AuthorBookGet() { Title = book.Title } );
}
return TypedResults.Ok(author);
}

private static async Task<IResult> GetAuthors(IAuthorRepository repository)
{
List<Object> response = new List<Object>();
var results = await repository.GetAllAuthors();
foreach (var result in results)
{
List<AuthorBookGet> books = new List<AuthorBookGet>();
foreach (var authorBook in result.Books)
{
var book = new AuthorBookGet();
book.Title = authorBook.Title;
books.Add(book);
}
var author = new AuthorGet();
author.FirstName = result.FirstName;
author.LastName = result.LastName;
author.Books = books;

response.Add(author);
}
return TypedResults.Ok(response);
}
}
}
90 changes: 86 additions & 4 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.DTOs;
using exercise.webapi.Models;
using exercise.webapi.Repository;
using static System.Reflection.Metadata.BlobBuilder;

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

private static async Task<IResult> GetBooks(IBookRepository bookRepository)
private static async Task<IResult> CreateBook(IBookRepository repository, BookPost book)
{
var books = await bookRepository.GetAllBooks();
return TypedResults.Ok(books);
var entity = await repository.CreateBook(book);
if (book.Title == "" || book.AuthorId == null) return TypedResults.BadRequest();
if (entity == null)
{
return TypedResults.NotFound();
}
return TypedResults.Created();
}

public static async Task<IResult> DeleteBook(IBookRepository repository, int id)
{
var entity = await repository.DeleteBook(id);
if (entity == null)
{
return TypedResults.NotFound();
}
return TypedResults.Ok(entity);
}

public static async Task<IResult> UpdateBook(IBookRepository repository, int id, int authorId)
{
var entity = await repository.UpdateBook(id, authorId);
if (entity == null)
{
return TypedResults.NotFound();
}
var authorGet = new BookAuthorGet();
authorGet.FirstName = entity.Author.FirstName;
authorGet.LastName = entity.Author.LastName;
authorGet.Email = entity.Author.Email;

var bookGet = new BookGet();
bookGet.Title = entity.Title;
bookGet.Author = authorGet;

return TypedResults.Ok(bookGet);
}

public static async Task<IResult> GetBookById(IBookRepository repository, int id)
{
var entity = await repository.GetBookById(id);

if (entity == null)
{
return TypedResults.NotFound();
}

var authorGet = new BookAuthorGet();
authorGet.FirstName = entity.Author.FirstName;
authorGet.LastName = entity.Author.LastName;
authorGet.Email = entity.Author.Email;

var bookGet = new BookGet();
bookGet.Title = entity.Title;
bookGet.Author = authorGet;

return TypedResults.Ok(bookGet);
}

public static async Task<IResult> GetBooks(IBookRepository bookRepository)
{
List<Object> response = new List<Object>();
var results = await bookRepository.GetAllBooks();
foreach (Book book in results)
{
var authorGet = new BookAuthorGet();
authorGet.FirstName = book.Author.FirstName;
authorGet.LastName= book.Author.LastName;
authorGet.Email = book.Author.Email;

var bookGet = new BookGet();
bookGet.Title = book.Title;
bookGet.Author = authorGet;

response.Add(bookGet);
}

return TypedResults.Ok(response);
}
}
}

18 changes: 13 additions & 5 deletions exercise.webapi/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,29 @@
using exercise.webapi.Endpoints;
using exercise.webapi.Repository;
using Microsoft.EntityFrameworkCore;
using System.Diagnostics;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
// 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>(opt => opt.UseInMemoryDatabase("Library"));
builder.Services.AddDbContext<DataContext>(options =>
{
options.UseNpgsql(builder.Configuration.GetConnectionString("DefaultConnectionString"));
options.LogTo(message => Debug.WriteLine(message));
});
builder.Services.AddScoped<IBookRepository, BookRepository>();
builder.Services.AddScoped<IAuthorRepository, AuthorRepository>();

var app = builder.Build();

using (var dbContext = new DataContext(new DbContextOptions<DataContext>()))
{
dbContext.Database.EnsureCreated();
}
//using (var dbContext = new DataContext(new DbContextOptions<DataContext>()))
//{
// dbContext.Database.EnsureCreated();
//}


// Configure the HTTP request pipeline.
Expand All @@ -29,4 +36,5 @@

app.UseHttpsRedirection();
app.ConfigureBooksApi();
app.ConfigureAuthorsApi();
app.Run();
26 changes: 26 additions & 0 deletions exercise.webapi/Repository/AuthorRepository.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
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)
{
return await _db.Authors.Where(a => a.Id == id).Include(a => a.Books).FirstOrDefaultAsync();
}
}
}
54 changes: 54 additions & 0 deletions exercise.webapi/Repository/BookRepository.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using exercise.webapi.Data;
using exercise.webapi.DTOs;
using exercise.webapi.Models;
using Microsoft.EntityFrameworkCore;

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

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

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

}

public async Task<Book> UpdateBook(int id, int authorId)
{
Book book = await _db.Books.Where(b => b.Id == id).Include(book => book.Author).FirstOrDefaultAsync();
Author? author = _db.Authors.FirstOrDefault(author => author.Id == authorId);
if (author == null)
{
return null;
}

book.AuthorId = authorId;
book.Author = author;

await _db.SaveChangesAsync();

return book;

}

public async Task<Book> DeleteBook(int id)
{
var entity = await _db.Books.FindAsync(id);
if (entity == null)
{
return null;
}
_db.Books.Remove(entity);
await _db.SaveChangesAsync();
return entity;
}

public async Task<Book> CreateBook(BookPost book)
{
var author = _db.Authors.FirstOrDefault(a => a.Id == book.AuthorId);
if (author == null)
{
return null;
}
var newBook = new Book();
newBook.Title = book.Title;
newBook.AuthorId = book.AuthorId;
newBook.Author = author;

_db.Books.Add(newBook);
await _db.SaveChangesAsync();

return newBook;
}
}
}
Loading