Last active
October 2, 2017 15:20
-
-
Save NikitaKozlov/d3f66e524d4fb922db3d9747d644a4fc to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ItemRepository(val backendApi: BackendApi, val cache: ItemCache) { | |
fun getOrderedItemIds(pageNumber: Int) = backendApi.getItemIds(pageNumber) | |
fun getItemsByIds(itemIds: List<ItemId>): List<Item> { | |
val cachedItems = getCachedItems(itemIds) | |
val notCachedItemIds = getItemIdsNotRepresentedInCache(itemIds) | |
val newlyRequestedItems = requestItemsById(notCachedItemIds) | |
return merge(itemIds, cachedItems, newlyRequestedItems) | |
} | |
private fun getCachedItems(itemIds: List<ItemId>) = | |
itemIds.filter { cache.contains(it) } | |
.associate { Pair(it, cache.get(it)) } | |
private fun getItemIdsNotRepresentedInCache(itemIds: List<ItemId>) = | |
itemIds.filterNot { cache.contains(it) } | |
private fun requestItemsById(itemIds: List<ItemId>): Map<ItemId, Item> { | |
val response: Response<List<Item>> = backendApi.getItems(itemIds) | |
val items = response.body() | |
val responseValidUntil = getCachingTimestampFromHeaders(response.headers()) | |
putItemsInCache(items, responseValidUntil) | |
return items.associateBy { it.id } | |
} | |
private fun putItemsInCache(items: List<Item>, validUntil: Timestamp?) { | |
items.forEach { cache.put(it, validUntil) } | |
} | |
private fun merge(itemIds: List<ItemId>, cachedItems: Map<ItemId, Item>, | |
newlyRequestedItems: Map<ItemId, Item>): List<Item> { | |
return itemIds.map { it -> | |
if (cachedItems.containsKey(it)) { | |
cachedItems[it]!! | |
} else newlyRequestedItems[it]!! | |
} | |
} | |
private fun getCachingTimestampFromHeaders(headers: Headers): Timestamp? { | |
//Extraction of the timestamp is out of scope for this gist | |
return headers.getCachingTimestamp() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment