Skip to content

Commit 786ebab

Browse files
Refactor controller to consume new book service
1 parent cd90475 commit 786ebab

File tree

1 file changed

+31
-109
lines changed

1 file changed

+31
-109
lines changed
Lines changed: 31 additions & 109 deletions
Original file line numberDiff line numberDiff line change
@@ -1,163 +1,85 @@
11
using AzureRedisCacheApi.Entities;
2-
using AzureRedisCacheApi.Services.Repositories;
2+
using AzureRedisCacheApi.Services;
33
using Microsoft.AspNetCore.Mvc;
4-
using Microsoft.Extensions.Caching.Distributed;
5-
using System.Text;
6-
using System.Text.Json;
74

85
namespace AzureRedisCacheApi.Controllers
96
{
107
[Route("api/[controller]")]
118
[ApiController]
129
public class BookController : ControllerBase
1310
{
14-
private readonly IBookRepository _bookRepo;
15-
private readonly IDistributedCache _redis;
11+
private readonly IBookService _book;
1612

17-
public BookController(
18-
IBookRepository bookRepo,
19-
IDistributedCache redis)
13+
public BookController(IBookService book)
2014
{
21-
_bookRepo = bookRepo;
22-
_redis = redis;
15+
_book = book;
2316
}
2417

2518
[HttpGet("get")]
2619
public async Task<IActionResult> GetAllAsync()
2720
{
28-
// Retrieve any books stored in the Redis cache
29-
byte[] booksInRedis = await _redis.GetAsync("books");
21+
// Get the books from either the cache or database
22+
var (books, fromCache) = await _book.GetBooksAsync();
3023

31-
// Check that we actually got some books in return from the Redis cache
32-
if ((booksInRedis?.Count() ?? 0) > 0) // Amount of books is larger than 0?
24+
// Check if we got any books from the service
25+
if (books == null)
3326
{
34-
// Get the books in redis as a string
35-
string bookString = Encoding.UTF8.GetString(booksInRedis);
36-
37-
// Deserialize the string into a list of books
38-
List<Book> booksFromRedis = JsonSerializer.Deserialize<List<Book>>(bookString);
39-
40-
// Return the books
41-
return Ok(new
42-
{
43-
DataFromRedis = true,
44-
Data = booksFromRedis
45-
});
27+
// We did not get any books
28+
return NotFound("No books has been added to the service.");
4629
}
4730

48-
// We did not have any books in our Redis Cache. Let's add some books
49-
50-
// First we will get all of our books
51-
IReadOnlyList<Book> booksFromDb = await _bookRepo.GetBooksAsync();
52-
53-
// Then serialize the books into a string
54-
string serializedBooks = JsonSerializer.Serialize(booksFromDb);
55-
56-
// Convert the serialized books into a byte array
57-
byte[] booksToCache = Encoding.UTF8.GetBytes(serializedBooks);
58-
59-
// Configure Expiration for Caching
60-
DistributedCacheEntryOptions expiration = new DistributedCacheEntryOptions
61-
{
62-
AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(8),
63-
SlidingExpiration = TimeSpan.FromMinutes(5),
64-
};
65-
66-
// Store the books into the Redis Cache
67-
await _redis.SetAsync("books", booksToCache, expiration);
68-
69-
// Return the books
31+
// We got some books, let's return them
7032
return Ok(new
7133
{
72-
DataFromRedis = false,
73-
Data = booksFromDb
34+
DataFromCache = fromCache,
35+
Data = books
7436
});
7537
}
7638

7739
[HttpGet("get/{id}")]
7840
public async Task<IActionResult> GetSingleAsync(int id)
7941
{
80-
// Retrieve any books stored in the Redis cache
81-
byte[] booksInRedis = await _redis.GetAsync("books");
42+
// Get the books from either the cache or database
43+
var (book, fromCache) = await _book.GetBookAsync(id);
8244

83-
// Check that we actually got some books in return from the Redis cache
84-
if ((booksInRedis?.Count() ?? 0) > 0)
45+
// Check if we got any books from the service
46+
if (book == null)
8547
{
86-
// Decode and serialize into list of books
87-
string bookString = Encoding.UTF8.GetString(booksInRedis);
88-
List<Book> booksFromRedis = JsonSerializer.Deserialize<List<Book>>(bookString);
89-
90-
// Use LINQ to get the book we are looking for
91-
Book bookFromRedis = booksFromRedis.Where(x => x.Id == id).FirstOrDefault();
92-
93-
if (bookFromRedis == null)
94-
{
95-
return NotFound();
96-
}
97-
98-
// Return the book
99-
return Ok(new
100-
{
101-
DataFromRedis = true,
102-
Data = bookFromRedis
103-
});
48+
// We did no get a book matching the id specified
49+
return NotFound($"No book was found with the id: {id}.");
10450
}
10551

106-
// We did not get a book from the Redis Cache, let's retrieve it from our database
107-
Book book = await _bookRepo.GetBookAsync(id);
108-
if (book != null)
52+
// We got a book matching the id, let's return it
53+
return Ok(new
10954
{
110-
// Return the book we got from our database
111-
return Ok(new
112-
{
113-
DataFromRedis = false,
114-
Data = book
115-
});
116-
}
117-
118-
// No book with the given ID was able to be looked up
119-
return NotFound();
55+
DataFromCache = fromCache,
56+
Data = book
57+
});
12058

12159
}
12260

12361
[HttpPost("add")]
12462
public async Task<IActionResult> AddBookAsync(Book book)
12563
{
126-
// Add the new book to our database
127-
await _bookRepo.AddBookAsync(book);
128-
129-
// Clear the cache
130-
await _redis.RemoveAsync("books");
131-
132-
// Return the created book
133-
return Ok(new
134-
{
135-
DataFromRedis = false,
136-
Data = book
137-
});
64+
// Add the new book
65+
await _book.AddBookAsync(book);
66+
return Ok(book);
13867
}
13968

14069
[HttpPut("update")]
14170
public async Task<IActionResult> UpdateBookAsync(Book book)
14271
{
14372
// Update the book in our database
144-
await _bookRepo.UpdateBookAsync(book);
73+
await _book.UpdateBookAsync(book);
74+
return Ok(book);
14575

146-
// Clear the cache
147-
await _redis.RemoveAsync("books");
148-
149-
// Return the updated book
150-
return Ok(new
151-
{
152-
DataFromRedis = false,
153-
Data = book
154-
});
15576
}
15677

15778
[HttpDelete("delete/{id}")]
15879
public async Task<bool> DeleteBookAsync(int id)
15980
{
160-
return await _bookRepo.DeleteBookAsync(id);
81+
// Delete the book
82+
return await _book.DeleteBookAsync(id);
16183
}
16284
}
16385
}

0 commit comments

Comments
 (0)