Skip to content

Instantly share code, notes, and snippets.

@davbeck
Created May 11, 2022 17:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davbeck/fcbdd03a1de59ef302739a9148d308b8 to your computer and use it in GitHub Desktop.
Save davbeck/fcbdd03a1de59ef302739a9148d308b8 to your computer and use it in GitHub Desktop.
func fetch<Result: Codable>(_ endpoint: Endpoint<Result>, cacheBehavior: CacheBehavior = .cacheElseNetwork) async throws -> Result {
switch cacheBehavior {
case .cacheElseNetwork:
if let cached = self.cache[endpoint.cacheKey] {
return cached.payload
} else {
return try await self.networkFetch(endpoint)
}
case .networkOnly:
return try await self.networkFetch(endpoint)
case .cacheOnly:
if let cached = self.cache[endpoint.cacheKey] {
return cached.payload
} else {
throw Error.cacheMiss
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment