Files
purchases-ios/Sources/Networking/Operations/PostSubscriberAttributesOperation.swift
T
NachoSoto 23f63c5ef7 HTTPClient now handles response deserialization + Introduced NetworkError and BackendError (#1425)
Closes #695 and finishes [CF-195]. 
Depends on ~~#1431, #1432, #1433, #1437~~.

## Goals:

- [x] Handle all requests / response / deserialization errors in `HTTPClient`. Clients of `HTTPClient` will only have to handle the "happy" path: #1431
- [x] `HTTPClient` shouldn't return `Result.success` with failed responses, forcing clients to verify the response is actually a failure: https://github.com/RevenueCat/purchases-ios/pull/1431
- [x] Abstract error response deserialization / error creation: #1427
- [x] Abstract attribute error parsing: #1427 
- [x] Move response deserialization to `HTTPClient` based on a `ResponseType: Decodable` type, so the completion block will simply return a `Result<HTTPResponse<ResponseType>, Error>`
- [x] `ETagManager` should store response `Data` instead of a deserialized `[String: Any]`
- [x] Improved error types in `HTTPClient` to fix tests: #1437
- [x] Dealt with non-backwards compatible `ETagManager: #1438

## Changes:
- Replaced `HTTPResponse`'s body from `[String: Any]` to a generic `HTTPResponseBody`.
- Created `HTTPResponseBody` to abstract `Decodable` and provide some default implementations for types like `Data,` `[String: Any]` (for backwards compatibility to types that aren't `Decodable` yet), and `Decodable` itself.
- New `HTTPResponse.Result` typealias (`Result<HTTPResponse<HTTPResponseBody>, Error>`) used everywhere. This will allow replacing `Error` with a more specific `Error` so we can forward known typed errors, and make sure that we don't end up with the wrong error type, or with a very complex error hierarchy and the details buried in `underlyingError`.
- Each layer (only a few for now) has its own error type: `NetworkError`, `BackendError`, `OfferingsManager.Error`.
- `HTTPClient` for example has to produce `NetworkError`, operations produce `BackendError`
- The parent `BackendError` can have specific errors like `.missingAppUserID`, but also be simply a child error `case networkError(NetworkError)`
- All of these conform to a `ErrorCodeConvertible`, so there is a single point of code that converts from simple and readable errors (like `BackendError.emptySubscriberAttributes`, `.unexpectedBackendResponse(.loginResponseDecoding)`) into errors with all the context using `ErrorUtils`
- Converted `DNSError` into `NetworkError.dnsError`. Its functionality remains unchanged.
- Removed `Backend.RCSuccessfullySyncedKey` and `ErrorDetails.finishableKey` in favor of tested properties on `NetworkError`

### Leftovers

There's a few things I've decided to not finish for now:
- [ ] `CustomerInfo` still does't conform to `Decodable` (manual deserialization is still supported by the current system): #1496
- `SubscriberAttributeDict` could also be `Codable`
- [x] Replace `OfferingsFactory` with `Decodable`: #1435

[CF-195]: https://revenuecats.atlassian.net/browse/CF-195?atlOrigin=eyJpIjoiNWRkNTljNzYxNjVmNDY3MDlhMDU5Y2ZhYzA5YTRkZjUiLCJwIjoiZ2l0aHViLWNvbS1KU1cifQ
2022-04-12 15:11:22 -07:00

81 lines
2.4 KiB
Swift

//
// Copyright RevenueCat Inc. All Rights Reserved.
//
// Licensed under the MIT License (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://opensource.org/licenses/MIT
//
// PostSubscriberAttributesOperation.swift
//
// Created by Joshua Liebowitz on 11/18/21.
import Foundation
class PostSubscriberAttributesOperation: NetworkOperation {
private let configuration: UserSpecificConfiguration
private let subscriberAttributes: SubscriberAttributeDict
private let responseHandler: Backend.SimpleResponseHandler?
init(configuration: UserSpecificConfiguration,
subscriberAttributes: SubscriberAttributeDict,
completion: Backend.SimpleResponseHandler?) {
self.configuration = configuration
self.subscriberAttributes = subscriberAttributes
self.responseHandler = completion
super.init(configuration: configuration)
}
override func begin(completion: @escaping () -> Void) {
post(completion: completion)
}
private func post(completion: @escaping () -> Void) {
guard self.subscriberAttributes.count > 0 else {
Logger.warn(Strings.attribution.empty_subscriber_attributes)
self.responseHandler?(.emptySubscriberAttributes())
return
}
guard let appUserID = try? self.configuration.appUserID.escapedOrError() else {
self.responseHandler?(.missingAppUserID())
completion()
return
}
let request = HTTPRequest(method: .post(Body(self.subscriberAttributes)),
path: .postSubscriberAttributes(appUserID: appUserID))
httpClient.perform(request,
authHeaders: self.authHeaders) { (response: HTTPResponse<HTTPEmptyResponseBody>.Result) in
defer {
completion()
}
self.responseHandler?(response.error.map(BackendError.networkError))
}
}
}
extension PostSubscriberAttributesOperation {
private struct Body: Encodable {
let attributes: AnyEncodable
init(_ attributes: SubscriberAttributeDict) {
self.attributes = AnyEncodable(
SubscriberAttributesMarshaller.map(subscriberAttributes: attributes)
)
}
}
}