Skip to content

Commit

Permalink
Handle one entry feeds
Browse files Browse the repository at this point in the history
  • Loading branch information
wacumov committed Aug 30, 2023
1 parent 568bd9a commit b0b7dc3
Showing 1 changed file with 27 additions and 4 deletions.
31 changes: 27 additions & 4 deletions Sources/AppStoreScraper/Scraper.swift
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ public struct Scraper {
}()
let url = "\(baseURL)/rss/\(feedTitle)/\(genre)limit=\(limit)/json?cc=\(country.rawValue.lowercased())"
let feed: Feed = try await get(url)
return .init(applications: feed.content.entry ?? [])
return .init(applications: feed.content.entry?.toArray ?? [])
}

public func searchApplications(
Expand Down Expand Up @@ -100,15 +100,15 @@ public struct Scraper {
return "&lang=\(code)"
}

private struct Feed: Codable {
private struct Feed: Decodable {
let content: Entries

enum CodingKeys: String, CodingKey {
case content = "feed"
}

struct Entries: Codable {
let entry: [Ranking.Application]?
struct Entries: Decodable {
let entry: OneOrMany<Ranking.Application>?
}
}

Expand All @@ -121,6 +121,29 @@ public struct Scraper {
}
}

private enum OneOrMany<T: Decodable>: Decodable {
case one(T)
case many([T])

var toArray: [T] {
switch self {
case let .one(item): return [item]
case let .many(items): return items
}
}

init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
if let many = try? container.decode([T].self) {
self = .many(many)
} else if let one = try? container.decode(T.self) {
self = .one(one)
} else {
throw DecodingError.dataCorruptedError(in: container, debugDescription: "Cannot decode \(OneOrMany.self)")
}
}
}

private extension URLSession {
func data(for request: URLRequest) async throws -> Data {
var dataTask: URLSessionDataTask?
Expand Down

0 comments on commit b0b7dc3

Please sign in to comment.