Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adopt .apollo.method() namespacing for extensions #1256

Merged
merged 17 commits into from
Jun 12, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 49 additions & 16 deletions Apollo.xcodeproj/project.pbxproj

Large diffs are not rendered by default.

10 changes: 5 additions & 5 deletions Sources/Apollo/ApolloStore.swift
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ public final class ApolloStore {
self.cacheLock.withWriteLock {
self.cache.clearPromise()
}.andThen {
DispatchQueue.apollo_returnResultAsyncIfNeeded(on: callbackQueue,
DispatchQueue.apollo.returnResultAsyncIfNeeded(on: callbackQueue,
action: completion,
result: .success(()))
}
Expand Down Expand Up @@ -115,12 +115,12 @@ public final class ApolloStore {
Promise(fulfilled: try body($0))
}
.andThen { object in
DispatchQueue.apollo_returnResultAsyncIfNeeded(on: callbackQueue,
DispatchQueue.apollo.returnResultAsyncIfNeeded(on: callbackQueue,
action: completion,
result: .success(object))
}
.catch { error in
DispatchQueue.apollo_returnResultAsyncIfNeeded(on: callbackQueue,
DispatchQueue.apollo.returnResultAsyncIfNeeded(on: callbackQueue,
action: completion,
result: .failure(error))
}
Expand Down Expand Up @@ -153,12 +153,12 @@ public final class ApolloStore {
Promise(fulfilled: try body($0))
}
.andThen { object in
DispatchQueue.apollo_returnResultAsyncIfNeeded(on: callbackQueue,
DispatchQueue.apollo.returnResultAsyncIfNeeded(on: callbackQueue,
action: completion,
result: .success(object))
}
.catch { error in
DispatchQueue.apollo_returnResultAsyncIfNeeded(on: callbackQueue,
DispatchQueue.apollo.returnResultAsyncIfNeeded(on: callbackQueue,
action: completion,
result: .failure(error))
}
Expand Down
7 changes: 5 additions & 2 deletions Sources/Apollo/Bundle+Helpers.swift
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
import Foundation
import ApolloCore

extension Bundle {
extension Bundle: ApolloCompatible {}

extension ApolloExtension where Base == Bundle {

/// Type-safe getter for info dictionary key objects
///
/// - Parameter key: The key to try to grab an object for
/// - Returns: The object of the desired type, or nil if it is not present or of the incorrect type.
func bundleValue<T>(forKey key: String) -> T? {
return object(forInfoDictionaryKey: key) as? T
return base.object(forInfoDictionaryKey: key) as? T
}

/// The bundle identifier of this bundle, or nil if not present.
Expand Down
35 changes: 0 additions & 35 deletions Sources/Apollo/Collection+Helpers.swift
Original file line number Diff line number Diff line change
@@ -1,40 +1,5 @@
import Foundation

// MARK: - Emptiness + Optionality

extension Collection {

/// Convenience helper to make `guard` statements more readable
///
/// - returns: `true` if the collection has contents.
var isNotEmpty: Bool {
return !self.isEmpty
}
}

extension Optional where Wrapped: Collection {

/// - returns: `true` if the collection is empty or nil
var isEmptyOrNil: Bool {
switch self {
case .none:
return true
case .some(let collection):
return collection.isEmpty
}
}

/// - returns: `true` if the collection is non-nil AND has contents.
var isNotEmpty: Bool {
switch self {
case .none:
return false
case .some(let collection):
return collection.isNotEmpty
}
}
}

// MARK: - Unzipping
// MARK: Arrays of tuples to tuples of arrays

Expand Down
15 changes: 9 additions & 6 deletions Sources/Apollo/DispatchQueue+Optional.swift
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
import Foundation
import ApolloCore

public extension DispatchQueue {
extension DispatchQueue: ApolloCompatible {}

static func apollo_performAsyncIfNeeded(on callbackQueue: DispatchQueue?, action: @escaping () -> Void) {
public extension ApolloExtension where Base == DispatchQueue {

static func performAsyncIfNeeded(on callbackQueue: DispatchQueue?, action: @escaping () -> Void) {
if let callbackQueue = callbackQueue {
// A callback queue was provided, perform the action on that queue
callbackQueue.async {
Expand All @@ -14,14 +17,14 @@ public extension DispatchQueue {
}
}

static func apollo_returnResultAsyncIfNeeded<T>(on callbackQueue: DispatchQueue?,
action: ((Result<T, Error>) -> Void)?,
result: Result<T, Error>) {
static func returnResultAsyncIfNeeded<T>(on callbackQueue: DispatchQueue?,
action: ((Result<T, Error>) -> Void)?,
result: Result<T, Error>) {
guard let action = action else {
return
}

self.apollo_performAsyncIfNeeded(on: callbackQueue) {
self.performAsyncIfNeeded(on: callbackQueue) {
action(result)
}
}
Expand Down
4 changes: 2 additions & 2 deletions Sources/Apollo/GraphQLHTTPResponseError.swift
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ public struct GraphQLHTTPResponseError: Error, LocalizedError {
return "[Empty response body]"
}

guard let description = String(data: body, encoding: response.textEncoding ?? .utf8) else {
guard let description = String(data: body, encoding: response.apollo.textEncoding ?? .utf8) else {
return "[Unreadable response body]"
}

Expand All @@ -69,7 +69,7 @@ public struct GraphQLHTTPResponseError: Error, LocalizedError {

return "\(kind.description): \(description)"
} else {
return "\(kind.description) (\(response.statusCode) \(response.statusCodeDescription)): \(bodyDescription)"
return "\(kind.description) (\(response.statusCode) \(response.apollo.statusCodeDescription)): \(bodyDescription)"
}
}
}
4 changes: 3 additions & 1 deletion Sources/Apollo/GraphQLSelectionSet.swift
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import ApolloCore

public typealias ResultMap = [String: Any?]

public protocol GraphQLSelectionSet {
Expand Down Expand Up @@ -56,7 +58,7 @@ public struct GraphQLField: GraphQLSelection {
func cacheKey(with variables: [String: JSONEncodable]?) throws -> String {
if
let argumentValues = try arguments?.evaluate(with: variables),
argumentValues.isNotEmpty {
argumentValues.apollo.isNotEmpty {
let argumentsKey = orderIndependentKey(for: argumentValues)
return "\(name)(\(argumentsKey))"
} else {
Expand Down
6 changes: 3 additions & 3 deletions Sources/Apollo/HTTPNetworkTransport.swift
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,7 @@ public class HTTPNetworkTransport {
response: nil,
completionHandler: completionHandler)
case .success(let (data, httpResponse)):
guard httpResponse.isSuccessful == true else {
guard httpResponse.apollo.isSuccessful == true else {
let unsuccessfulError = GraphQLHTTPResponseError(body: data,
response: httpResponse,
kind: .errorResponse)
Expand Down Expand Up @@ -226,7 +226,7 @@ public class HTTPNetworkTransport {
guard
let delegate = self.delegate as? HTTPNetworkTransportGraphQLErrorDelegate,
let graphQLErrors = response.parseErrorsOnlyFast(),
graphQLErrors.isNotEmpty else {
graphQLErrors.apollo.isNotEmpty else {
completionHandler(.success(response))
return
}
Expand Down Expand Up @@ -391,7 +391,7 @@ public class HTTPNetworkTransport {
do {
if
let files = files,
files.isNotEmpty {
files.apollo.isNotEmpty {
let formData = try requestCreator.requestMultipartFormData(
for: operation,
files: files,
Expand Down
11 changes: 7 additions & 4 deletions Sources/Apollo/HTTPURLResponse+Helpers.swift
Original file line number Diff line number Diff line change
@@ -1,16 +1,19 @@
import Foundation
import ApolloCore

extension HTTPURLResponse {
extension HTTPURLResponse: ApolloCompatible {}

extension ApolloExtension where Base == HTTPURLResponse {
var isSuccessful: Bool {
return (200..<300).contains(statusCode)
return (200..<300).contains(base.statusCode)
}

var statusCodeDescription: String {
return HTTPURLResponse.localizedString(forStatusCode: statusCode)
return HTTPURLResponse.localizedString(forStatusCode: base.statusCode)
}

var textEncoding: String.Encoding? {
guard let encodingName = textEncodingName else { return nil }
guard let encodingName = base.textEncodingName else { return nil }

return String.Encoding(rawValue: CFStringConvertEncodingToNSStringEncoding(CFStringConvertIANACharSetNameToEncoding(encodingName as CFString)))
}
Expand Down
6 changes: 3 additions & 3 deletions Sources/Apollo/InMemoryNormalizedCache.swift
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ public final class InMemoryNormalizedCache: NormalizedCache {
self.recordsLock.lock()
let records = keys.map { self.records[$0] }
self.recordsLock.unlock()
DispatchQueue.apollo_returnResultAsyncIfNeeded(on: callbackQueue,
DispatchQueue.apollo.returnResultAsyncIfNeeded(on: callbackQueue,
action: completion,
result: .success(records))
}
Expand All @@ -25,7 +25,7 @@ public final class InMemoryNormalizedCache: NormalizedCache {
self.recordsLock.lock()
let cacheKeys = self.records.merge(records: records)
self.recordsLock.unlock()
DispatchQueue.apollo_returnResultAsyncIfNeeded(on: callbackQueue,
DispatchQueue.apollo.returnResultAsyncIfNeeded(on: callbackQueue,
action: completion,
result: .success(cacheKeys))
}
Expand All @@ -38,7 +38,7 @@ public final class InMemoryNormalizedCache: NormalizedCache {
return
}

DispatchQueue.apollo_returnResultAsyncIfNeeded(on: callbackQueue,
DispatchQueue.apollo.returnResultAsyncIfNeeded(on: callbackQueue,
action: completion,
result: .success(()))
}
Expand Down
4 changes: 2 additions & 2 deletions Sources/Apollo/NetworkTransport.swift
Original file line number Diff line number Diff line change
Expand Up @@ -48,11 +48,11 @@ public extension NetworkTransport {
/// The default client version to use when setting up the `clientVersion` property.
static var defaultClientVersion: String {
var version = String()
if let shortVersion = Bundle.main.shortVersion {
if let shortVersion = Bundle.main.apollo.shortVersion {
version.append(shortVersion)
}

if let buildNumber = Bundle.main.buildNumber {
if let buildNumber = Bundle.main.apollo.buildNumber {
if version.isEmpty {
version.append(buildNumber)
} else {
Expand Down
2 changes: 1 addition & 1 deletion Sources/Apollo/Promise.swift
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ func whenAll<Value>(_ promises: [Promise<Value>], notifyOn queue: DispatchQueue

group.notify(queue: queue) {
if !rejected {
fulfill(promises.map { $0.result!.value! })
fulfill(promises.map { $0.result!.apollo.value! })
}
}
}
Expand Down
3 changes: 2 additions & 1 deletion Sources/Apollo/RequestCreator.swift
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import Foundation
import ApolloCore

public protocol RequestCreator {
/// Creates a `GraphQLMap` out of the passed-in operation
Expand Down Expand Up @@ -70,7 +71,7 @@ extension RequestCreator {
hash = operationIdentifier
} else {
// The codegen needed more info for the correct hash - regenerate it.
hash = operation.queryDocument.sha256Hash
hash = operation.queryDocument.apollo.sha256Hash
}

body["extensions"] = [
Expand Down
13 changes: 8 additions & 5 deletions Sources/Apollo/Result+Helpers.swift
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
import Foundation
import ApolloCore

extension Result {
extension Result: ApolloCompatible {}

extension ApolloExtension where Base: ResultType, Base.SuccessType: Any {

/// Converts the result into an optional value. Returns the value for a `success` case and nil for a `failure` case.
var value: Success? {
switch self {
var value: Base.SuccessType? {
switch base.underlying {
case .success(let value):
return value
case .failure:
Expand All @@ -14,8 +17,8 @@ extension Result {

/// Converts the result into an optional error. Returns the error for a `failure` case and nil for a `success` case.
/// Mostly useful for testing to make sure appropriate errors are received.
var error: Failure? {
switch self {
var error: Base.FailureType? {
switch base.underlying {
case .success:
return nil
case .failure(let error):
Expand Down
2 changes: 1 addition & 1 deletion Sources/Apollo/ResultOrPromise.swift
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ func whenAll<Value>(_ resultsOrPromises: [ResultOrPromise<Value>], notifyOn queu

group.notify(queue: queue) {
if !rejected {
fulfill(resultsOrPromises.map { $0.result!.value! })
fulfill(resultsOrPromises.map { $0.result!.apollo.value! })
}
}
})
Expand Down
1 change: 1 addition & 0 deletions Sources/Apollo/URLSessionClient.swift
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import Foundation
import ApolloCore

/// A class to handle URL Session calls that will support background execution,
/// but still (mostly) use callbacks for its primary method of communication.
Expand Down
35 changes: 0 additions & 35 deletions Sources/ApolloCodegenLib/ApolloExtension.swift

This file was deleted.

9 changes: 5 additions & 4 deletions Sources/ApolloCodegenLib/Dictionary+Apollo.swift
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import Foundation
import ApolloCore

public extension ApolloExtension where Base: DictionaryType, Base.KeyType: RawRepresentable, Base.KeyType.RawValue == String, Base.ValueType: Any {

public extension Dictionary where Key: RawRepresentable, Key.RawValue == String, Value: Any {

/// Transforms a dictionary keyed by a String enum into a dictionary keyed by the
/// string values of that enum.
var apollo_toStringKeyedDict: [String: Any] {
var toStringKeyedDict: [String: Any] {
var updatedDict = [String: Any]()
for (_, (key, value)) in self.enumerated() {
for (_, (key, value)) in base.underlying.enumerated() {
updatedDict[key.rawValue] = value
}
return updatedDict
Expand Down
2 changes: 1 addition & 1 deletion Sources/ApolloCodegenLib/EnumGenerator.swift
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ public class EnumGenerator {
.cases: cases.map { SanitizedEnumValue(astEnumValue: $0) }
]

return try Environment().renderTemplate(string: self.enumTemplate, context: context.apollo_toStringKeyedDict)
return try Environment().renderTemplate(string: self.enumTemplate, context: context.apollo.toStringKeyedDict)
}

/// A stencil template to use to render enums.
Expand Down
1 change: 1 addition & 0 deletions Sources/ApolloCodegenLib/FileManager+Apollo.swift
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import Foundation
import CommonCrypto
import ApolloCore

extension FileManager: ApolloCompatible {}

Expand Down
Loading