twigs-ios/Twigs/Category/CategoryRepository.swift

75 lines
2.7 KiB
Swift
Raw Normal View History

//
// CategoryRepository.swift
// Budget
//
// Created by Billy Brawner on 10/1/19.
// Copyright © 2019 William Brawner. All rights reserved.
//
import Foundation
import Combine
protocol CategoryRepository {
2021-09-19 20:24:27 +00:00
func getCategories(budgetId: String?, expense: Bool?, archived: Bool?, count: Int?, page: Int?) -> AnyPublisher<[Category], NetworkError>
2021-09-10 04:47:57 +00:00
func getCategory(_ categoryId: String) -> AnyPublisher<Category, NetworkError>
}
class NetworkCategoryRepository: CategoryRepository {
let apiService: BudgetAppApiService
let cacheService: BudgetAppInMemoryCacheService?
init(_ apiService: BudgetAppApiService, cacheService: BudgetAppInMemoryCacheService? = nil) {
self.apiService = apiService
self.cacheService = cacheService
}
2021-09-19 20:24:27 +00:00
func getCategories(budgetId: String?, expense: Bool?, archived: Bool?, count: Int?, page: Int?) -> AnyPublisher<[Category], NetworkError> {
if let categories = cacheService?.getCategories(budgetId: budgetId, expense: expense, archived: archived, count: count, page: page) {
print("Returning categories from cache")
return categories
}
print("No cached categories, fetching from network")
2021-09-19 20:24:27 +00:00
return apiService.getCategories(budgetId: budgetId, expense: expense, archived: archived, count: count, page: page).map { (categories: [Category]) in
self.cacheService?.addCategories(categories)
return categories
}.eraseToAnyPublisher()
}
2021-09-10 04:47:57 +00:00
func getCategory(_ categoryId: String) -> AnyPublisher<Category, NetworkError> {
if let category = cacheService?.getCategory(categoryId) {
print("Returning category from cache")
return category
}
print("Category with ID \(categoryId) not cached, returning from network")
return apiService.getCategory(categoryId).map { category in
self.cacheService?.addCategory(category)
return category
}.eraseToAnyPublisher()
}
}
#if DEBUG
class MockCategoryRepository: CategoryRepository {
static let category = Category(
2021-09-10 04:47:57 +00:00
budgetId: MockBudgetRepository.budget.id,
id: "3",
title: "Test Category",
description: "This is a test category to help with testing",
2021-09-10 04:47:57 +00:00
amount: 10000,
expense: true,
archived: false
)
2021-09-19 20:24:27 +00:00
func getCategories(budgetId: String?, expense: Bool?, archived: Bool?, count: Int?, page: Int?) -> AnyPublisher<[Category], NetworkError> {
return Result.Publisher([MockCategoryRepository.category]).eraseToAnyPublisher()
}
2021-09-10 04:47:57 +00:00
func getCategory(_ categoryId: String) -> AnyPublisher<Category, NetworkError> {
return Result.Publisher(MockCategoryRepository.category).eraseToAnyPublisher()
}
}
#endif