Refactor deletePost() to use template request

This commit is contained in:
Angelo Stavrow 2021-05-11 16:49:30 -04:00
parent 013207a140
commit 0cdfbc4d33
No known key found for this signature in database
GPG Key ID: 1A49C7064E060EEE
1 changed files with 6 additions and 43 deletions

View File

@ -715,51 +715,14 @@ public class WFClient {
request.addValue(tokenToVerify, forHTTPHeaderField: "Authorization") request.addValue(tokenToVerify, forHTTPHeaderField: "Authorization")
request.addValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type") request.addValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
let dataTask = session.dataTask(with: request) { (data, response, error) in delete(with: request) { result in
// Something went wrong; return the error message. switch result {
if let error = error { case .success(_):
// HACK: There's something that URLSession doesn't like about 204 NO CONTENT response that the API completion(.success(true))
// server is returning. If we get back a "protocol error", the operation probably succeeded, case .failure(let error):
// but URLSession is being pedantic/cranky and throwing an NSPOSIXErrorDomain error code 100. completion(.failure(error))
// Here, we check for that error, make sure the token was invalidated, and only then fire the
// success case in the completion block.
let nsError = error as NSError
if nsError.code == 100 && nsError.domain == NSPOSIXErrorDomain {
// Confirm that the operation succeeded by testing for a 404 on the same token.
self.deletePost(postId: postId) { result in
do {
_ = try result.get()
completion(.failure(error))
} catch WFError.notFound {
completion(.success(true))
} catch WFError.unauthorized {
completion(.success(true))
} catch WFError.internalServerError {
// If you try to delete a non-existent post, the API returns a 500 Internal Server Error.
completion(.success(true))
} catch {
completion(.failure(error))
}
}
} else {
completion(.failure(error))
}
}
if let response = response as? HTTPURLResponse {
// We got a response. If it's a 204 NO CONTENT, return true as success;
// if not, return a WFError as failure.
if response.statusCode != 204 {
guard let data = data else { return }
guard let error = self.translateWFError(fromServerResponse: data) else { return }
completion(.failure(error))
} else {
completion(.success(true))
}
} }
} }
dataTask.resume()
} }
/* Placeholder method stub: API design for this feature is not yet finalized. /* Placeholder method stub: API design for this feature is not yet finalized.