Skip to content

Commit

Permalink
Merge pull request #277 from NickAtGit/FixDeepLQueryItems
Browse files Browse the repository at this point in the history
Fix DeepL query items
  • Loading branch information
Jeehut authored Apr 20, 2023
2 parents da21794 + 4acb357 commit 89fbbf0
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 7 deletions.
25 changes: 18 additions & 7 deletions Sources/BartyCrouchTranslator/DeeplApi/DeepLApi.swift
Original file line number Diff line number Diff line change
Expand Up @@ -57,13 +57,24 @@ extension DeepLApi: Endpoint {
var method: HttpMethod {
switch self {
case .translate(let texts, let sourceLanguage, let targetLanguage, let authKey):
let textEntries = texts.map { "text=\($0.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!)" }
.joined(separator: "&")
let authKeyEntry = "auth_key=\(authKey)"
let sourceLanguageEntry = "source_lang=\(sourceLanguage.deepLParameterValue)"
let targetLanguageEntry = "target_lang=\(targetLanguage.deepLParameterValue)"
let bodyString = [authKeyEntry, sourceLanguageEntry, targetLanguageEntry, textEntries].joined(separator: "&")
return .post(body: bodyString.data(using: .utf8)!)

let authKeyItem = URLQueryItem(name: "auth_key", value: authKey)
let textItems = texts.map { URLQueryItem(name: "text", value: $0) }
let targetLangItem = URLQueryItem(name: "target_lang", value: targetLanguage.deepLParameterValue)
let sourceLangItem = URLQueryItem(name: "source_lang", value: sourceLanguage.deepLParameterValue)

var components = URLComponents()
components.queryItems = ([authKeyItem, targetLangItem, sourceLangItem] + textItems).compactMap { $0 }

guard var queryItemsString = components.string else {
fatalError("Invalid arguments.")
}
// queryItemsString starts with a ? but post API expects the query string without leading ?
if queryItemsString.hasPrefix("?") {
queryItemsString.removeFirst()
}

return .post(body: queryItemsString.data(using: .utf8)!)
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ class DeepLTranslatorApiTests: XCTestCase {
switch apiProvider.performRequestAndWait(on: endpoint, decodeBodyTo: DeepLTranslateResponse.self) {
case let .success(translateResponses):
XCTAssertEqual(translateResponses.translations[0].text, "Wie alt sind Sie?")
XCTAssertEqual(translateResponses.translations[1].text, "Liebe")

case let .failure(failure):
XCTFail(failure.localizedDescription)
Expand Down

0 comments on commit 89fbbf0

Please sign in to comment.