Skip to content

Commit

Permalink
Allow to set language of search results
Browse files Browse the repository at this point in the history
  • Loading branch information
wacumov committed Aug 5, 2022
1 parent 3ee17a9 commit 8199a66
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 4 deletions.
30 changes: 27 additions & 3 deletions Sources/AppStoreScraper/Scraper.swift
Original file line number Diff line number Diff line change
Expand Up @@ -29,19 +29,23 @@ public struct Scraper {
public func searchApplications(
_ term: String,
country: Country = .US,
language: Language? = nil,
limit: Int = 10
) async throws -> [Application] {
let encodedTerm = term.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? term
let url = "\(baseURL)/search?term=\(encodedTerm)&country=\(country.rawValue.lowercased())&limit=\(limit)&entity=software"
let language = makeLanguage(language, country: country)
let url = "\(baseURL)/search?term=\(encodedTerm)&country=\(country.rawValue.lowercased())&limit=\(limit)&entity=software\(language)"
let result: SearchResult = try await get(url)
return result.applications
}

public func getApplication(
_ id: Int,
country: Country = .US
country: Country = .US,
language: Language? = nil
) async throws -> Application? {
let url = "\(baseURL)/\(country.rawValue.lowercased())/lookup?id=\(id)"
let language = makeLanguage(language, country: country)
let url = "\(baseURL)/\(country.rawValue.lowercased())/lookup?id=\(id)\(language)"
let result: SearchResult = try await get(url)
return result.applications.first
}
Expand Down Expand Up @@ -74,6 +78,26 @@ public struct Scraper {
return [rankingType.rawValue.lowercased(), suffix].joined()
}

private func makeLanguage(_ language: Language?, country: Country) -> String {
guard let language = language else {
return ""
}
let supported = country.languages
guard
language != supported.main,
supported.additional.contains(language)
else {
return ""
}
let code: String = {
switch language {
case .zh_Hans: return "zh_CN"
default: return String(language.rawValue.prefix(2))
}
}()
return "&lang=\(code)"
}

private struct Feed: Codable {
let content: Entries

Expand Down
2 changes: 1 addition & 1 deletion Tests/AppStoreScraperTests/ScraperTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ final class ScraperTests: XCTestCase {

func testSearchApplications() async throws {
let scraper = Scraper()
let applications = try await scraper.searchApplications("pros and cons")
let applications = try await scraper.searchApplications("pros and cons", language: .zh_Hans)
XCTAssertFalse(applications.isEmpty)
}

Expand Down

0 comments on commit 8199a66

Please sign in to comment.