Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NikitaKozlov/d3f66e524d4fb922db3d9747d644a4fc to your computer and use it in GitHub Desktop.
Save NikitaKozlov/d3f66e524d4fb922db3d9747d644a4fc to your computer and use it in GitHub Desktop.
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