Skip to content

Commit

Permalink
Caching the suggestions from endpoint after the removal
Browse files Browse the repository at this point in the history
  • Loading branch information
tomasstrba committed Oct 25, 2024
1 parent 35cb637 commit 3d68df1
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 2 deletions.
17 changes: 16 additions & 1 deletion DuckDuckGo/Suggestions/Model/SuggestionContainer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,9 @@ final class SuggestionContainer {
private let startupPreferences: StartupPreferences
private let loading: SuggestionLoading

// Used for presenting the same suggestions after the removal of the local suggestion
private var suggestionDataCache: Data?

private var latestQuery: Query?

fileprivate let suggestionsURLSession = URLSession(configuration: .ephemeral)
Expand All @@ -55,8 +58,14 @@ final class SuggestionContainer {
bookmarkManager: LocalBookmarkManager.shared)
}

func getSuggestions(for query: String) {
func getSuggestions(for query: String, useCachedData: Bool = false) {
latestQuery = query

// Don't use cache by default
if !useCachedData {
suggestionDataCache = nil
}

loading.getSuggestions(query: query, usingDataSource: self) { [weak self] result, error in
dispatchPrecondition(condition: .onQueue(.main))

Expand Down Expand Up @@ -122,11 +131,17 @@ extension SuggestionContainer: SuggestionLoadingDataSource {
suggestionDataFromUrl url: URL,
withParameters parameters: [String: String],
completion: @escaping (Data?, Error?) -> Void) {
if let suggestionDataCache = suggestionDataCache {
completion(suggestionDataCache, nil)
return
}

let url = url.appendingParameters(parameters)
var request = URLRequest.defaultRequest(with: url)
request.timeoutInterval = 1

suggestionsURLSession.dataTask(with: request) { (data, _, error) in
self.suggestionDataCache = data
completion(data, error)
}.resume()
}
Expand Down
2 changes: 1 addition & 1 deletion DuckDuckGo/Suggestions/View/SuggestionViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -238,7 +238,7 @@ final class SuggestionViewController: NSViewController {

if let userStringValue = suggestionContainerViewModel.userStringValue {
suggestionContainerViewModel.isTopSuggestionSelectionExpected = false
self.suggestionContainerViewModel.suggestionContainer.getSuggestions(for: userStringValue)
self.suggestionContainerViewModel.suggestionContainer.getSuggestions(for: userStringValue, useCachedData: true)
} else {
self.suggestionContainerViewModel.removeSuggestionFromResult(suggestion: suggestion)
}
Expand Down

0 comments on commit 3d68df1

Please sign in to comment.