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

MLIBZ-2581: replacing all fatalErrors() calls to throw Errors instead #305

Merged
merged 2 commits into from
Jul 11, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
44 changes: 28 additions & 16 deletions Kinvey/Kinvey/AggregateOperation.swift
Original file line number Diff line number Diff line change
Expand Up @@ -49,11 +49,23 @@ class AggregateOperation<T: Persistable>: ReadOperation<T, [JsonDictionary], Swi
}

func executeNetwork(_ completionHandler: CompletionHandler? = nil) -> AnyRequest<ResultType> {
let initialObject: JsonDictionary
let reduceJSFunction: String
do {
initialObject = try aggregation.initialObject()
reduceJSFunction = try aggregation.reduceJSFunction()
} catch {
let result: ResultType = .failure(error)
let request = LocalRequest<ResultType>()
request.result = result
completionHandler?(result)
return AnyRequest(request)
}
let request = client.networkRequestFactory.buildAppDataGroup(
collectionName: T.collectionName(),
collectionName: try! T.collectionName(),
keys: aggregation.keys,
initialObject: aggregation.initialObject,
reduceJSFunction: aggregation.reduceJSFunction,
initialObject: initialObject,
reduceJSFunction: reduceJSFunction,
condition: predicate,
options: options,
resultType: ResultType.self
Expand Down Expand Up @@ -98,7 +110,7 @@ enum Aggregation {
}
}

var resultKey: String {
func resultKey() throws -> String {
switch self {
case .count:
return "count"
Expand All @@ -111,41 +123,41 @@ enum Aggregation {
case .max:
return "max"
case .custom(_, _, _):
fatalError("Custom does not have a resultKey")
throw Error.invalidOperation(description: "Custom does not have a resultKey")
}
}

var initialObject: JsonDictionary {
func initialObject() throws -> JsonDictionary {
switch self {
case .custom(_, let initialObject, _):
return initialObject
case .count:
return [resultKey : 0]
return [try resultKey() : 0]
case .sum:
return [resultKey : 0.0]
return [try resultKey() : 0.0]
case .avg:
return ["sum" : 0.0, "count" : 0]
case .min:
return [resultKey : "Infinity"]
return [try resultKey() : "Infinity"]
case .max:
return [resultKey : "-Infinity"]
return [try resultKey() : "-Infinity"]
}
}

var reduceJSFunction: String {
func reduceJSFunction() throws -> String {
switch self {
case .custom(_, _, let reduceJSFunction):
return reduceJSFunction
case .count(_):
return "function(doc, out) { out.\(resultKey)++; }"
return "function(doc, out) { out.\(try resultKey())++; }"
case .sum(_, let sum):
return "function(doc, out) { out.\(resultKey) += doc.\(sum); }"
return "function(doc, out) { out.\(try resultKey()) += doc.\(sum); }"
case .avg(_, let avg):
return "function(doc, out) { out.count++; out.sum += doc.\(avg); out.\(resultKey) = out.sum / out.count; }"
return "function(doc, out) { out.count++; out.sum += doc.\(avg); out.\(try resultKey()) = out.sum / out.count; }"
case .min(_, let min):
return "function(doc, out) { out.\(resultKey) = Math.min(out.\(resultKey), doc.\(min)); }"
return "function(doc, out) { out.\(try resultKey()) = Math.min(out.\(try resultKey()), doc.\(min)); }"
case .max(_, let max):
return "function(doc, out) { out.\(resultKey) = Math.max(out.\(resultKey), doc.\(max)); }"
return "function(doc, out) { out.\(try resultKey()) = Math.max(out.\(try resultKey()), doc.\(max)); }"
}
}

Expand Down
2 changes: 1 addition & 1 deletion Kinvey/Kinvey/Cache.swift
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ internal class Cache<T: Persistable> where T: NSObject {

init(persistenceId: String, ttl: TimeInterval? = nil) {
self.persistenceId = persistenceId
self.collectionName = T.collectionName()
self.collectionName = try! T.collectionName()
self.ttl = ttl
}

Expand Down
4 changes: 2 additions & 2 deletions Kinvey/Kinvey/CacheManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ internal class CacheManager: NSObject {
self.schemaVersion = schemaVersion
}

func cache<T: Persistable>(fileURL: URL? = nil, type: T.Type) -> AnyCache<T>? where T: NSObject {
func cache<T: Persistable>(fileURL: URL? = nil, type: T.Type) throws -> AnyCache<T>? where T: NSObject {
let fileManager = FileManager.default
if let fileURL = fileURL {
do {
Expand All @@ -33,7 +33,7 @@ internal class CacheManager: NSObject {
}
}

return AnyCache(RealmCache<T>(persistenceId: persistenceId, fileURL: fileURL, encryptionKey: encryptionKey, schemaVersion: schemaVersion))
return AnyCache(try RealmCache<T>(persistenceId: persistenceId, fileURL: fileURL, encryptionKey: encryptionKey, schemaVersion: schemaVersion))
}

func fileCache<FileType: File>(fileURL: URL? = nil) -> AnyFileCache<FileType>? {
Expand Down
41 changes: 27 additions & 14 deletions Kinvey/Kinvey/Client.swift
Original file line number Diff line number Diff line change
Expand Up @@ -182,9 +182,9 @@ open class Client: Credential {
}
}

private func validateInitialize(appKey: String, appSecret: String) {
private func validateInitialize(appKey: String, appSecret: String) throws {
if appKey.isEmpty || appSecret.isEmpty {
fatalError("Please provide a valid appKey and appSecret. Your app's key and secret can be found on the Kinvey management console.")
throw Error.invalidOperation(description: "Please provide a valid appKey and appSecret. Your app's key and secret can be found on the Kinvey management console.")
}
}

Expand Down Expand Up @@ -219,9 +219,14 @@ open class Client: Credential {
encrypted: Bool,
schema: Schema? = nil,
options: Options? = nil,
completionHandler: @escaping (Result<U?, Swift.Error>) -> Void)
{
validateInitialize(appKey: appKey, appSecret: appSecret)
completionHandler: @escaping (Result<U?, Swift.Error>) -> Void
) {
do {
try validateInitialize(appKey: appKey, appSecret: appSecret)
} catch {
completionHandler(.failure(error))
return
}

var encryptionKey: Data? = nil
if encrypted {
Expand Down Expand Up @@ -302,12 +307,14 @@ open class Client: Credential {
) {
let apiHostNameString = "https://\(instanceId)-baas.kinvey.com"
guard let apiHostName = URL(string: apiHostNameString) else {
fatalError("Invalid InstanceID: \(instanceId). \(apiHostNameString) is not a valid URL.")
completionHandler(.failure(Error.invalidOperation(description: "Invalid InstanceID: \(instanceId). \(apiHostNameString) is not a valid URL.")))
return
}

let authHostNameString = "https://\(instanceId)-auth.kinvey.com"
guard let authHostName = URL(string: authHostNameString) else {
fatalError("Invalid InstanceID: \(instanceId). \(authHostNameString) is not a valid URL.")
completionHandler(.failure(Error.invalidOperation(description: "Invalid InstanceID: \(instanceId). \(authHostNameString) is not a valid URL.")))
return
}

return initialize(
Expand Down Expand Up @@ -335,7 +342,13 @@ open class Client: Credential {
options: Options? = nil,
completionHandler: @escaping (Result<U?, Swift.Error>) -> Void
) {
validateInitialize(appKey: appKey, appSecret: appSecret)
do {
try validateInitialize(appKey: appKey, appSecret: appSecret)
} catch {
completionHandler(.failure(error))
return
}

self.encryptionKey = encryptionKey
self.schemaVersion = schema?.version ?? 0
self.options = options
Expand Down Expand Up @@ -373,7 +386,7 @@ open class Client: Credential {
let customUser = user as! U
completionHandler(.success(customUser))
} else if let kinveyAuth = sharedKeychain?.kinveyAuth {
User.login(authSource: .kinvey, kinveyAuth, options: Options(client: self)) { (result: Result<U, Swift.Error>) in
User.login(authSource: .kinvey, kinveyAuth, options: try! Options(client: self)) { (result: Result<U, Swift.Error>) in
switch result {
case .success(let user):
completionHandler(.success(user))
Expand Down Expand Up @@ -404,11 +417,10 @@ open class Client: Credential {
return self.appKey != nil && self.appSecret != nil
}

internal func validate() -> Swift.Error? {
internal func validate() throws {
guard isInitialized() else {
return Error.clientNotInitialized
throw Error.clientNotInitialized
}
return nil
}

internal class func fileURL(appKey: String, tag: String = defaultTag) -> URL {
Expand Down Expand Up @@ -447,10 +459,11 @@ open class Client: Credential {
@discardableResult
public func ping(completionHandler: @escaping (Result<EnvironmentInfo, Swift.Error>) -> Void) -> AnyRequest<Result<EnvironmentInfo, Swift.Error>> {
guard let _ = appKey, let _ = appSecret else {
let result: Result<EnvironmentInfo, Swift.Error> = .failure(Error.invalidOperation(description: "Please initialize your client calling the initialize() method before call ping()"))
DispatchQueue.main.async {
completionHandler(.failure(Error.invalidOperation(description: "Please initialize your client calling the initialize() method before call ping()")))
completionHandler(result)
}
return AnyRequest(LocalRequest<Result<EnvironmentInfo, Swift.Error>>())
return AnyRequest(result)
}
let request = networkRequestFactory.buildAppDataPing(
options: options,
Expand Down
2 changes: 1 addition & 1 deletion Kinvey/Kinvey/CountOperation.swift
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ class CountOperation<T: Persistable>: ReadOperation<T, Int, Swift.Error>, ReadOp

func executeNetwork(_ completionHandler: CompletionHandler? = nil) -> AnyRequest<ResultType> {
let request = client.networkRequestFactory.buildAppDataCountByQuery(
collectionName: T.collectionName(),
collectionName: try! T.collectionName(),
query: query,
options: options,
resultType: ResultType.self
Expand Down
16 changes: 4 additions & 12 deletions Kinvey/Kinvey/CustomEndpoint.swift
Original file line number Diff line number Diff line change
Expand Up @@ -124,9 +124,7 @@ open class CustomEndpoint {
return execute(
name,
params: params,
options: Options(
client: client
),
options: try! Options(client: client),
completionHandler: completionHandler
)
}
Expand Down Expand Up @@ -201,9 +199,7 @@ open class CustomEndpoint {
return execute(
name,
params: params,
options: Options(
client: client
),
options: try! Options(client: client),
completionHandler: completionHandler
)
}
Expand Down Expand Up @@ -280,9 +276,7 @@ open class CustomEndpoint {
return execute(
name,
params: params,
options: Options(
client: client
),
options: try! Options(client: client),
completionHandler: completionHandler
)
}
Expand Down Expand Up @@ -357,9 +351,7 @@ open class CustomEndpoint {
return execute(
name,
params: params,
options: Options(
client: client
),
options: try! Options(client: client),
completionHandler: completionHandler
)
}
Expand Down
Loading