Skip to content

Instantly share code, notes, and snippets.

@diefferson
Last active October 21, 2020 13:22
Show Gist options
  • Save diefferson/0ab283bbfdc00961ffb571dacfb68fdd to your computer and use it in GitHub Desktop.
Save diefferson/0ab283bbfdc00961ffb571dacfb68fdd to your computer and use it in GitHub Desktop.
Swift Base Use Case
typealias UseCaseRun<Parameters, ResultType> = (_ parameters: Parameters, _ completion: @escaping (_ result: Result<ResultType, Error>) -> Void ) throws -> Void
public class AppResult<ResultType, Parameters> {
private var onSuccess: (ResultType) -> Void = {_ in }
private var onFailure: (Error) -> Void = {_ in }
init(
parameters: Parameters,
_ useCaseRun: UseCaseRun<Parameters, ResultType>
) {
self.runCatching( parameters: parameters, useCaseRun: useCaseRun)
}
private func runCatching(parameters: Parameters, useCaseRun: UseCaseRun<Parameters, ResultType>) {
do {
try useCaseRun(parameters) { result in
switch result {
case .success(let value):
self.onSuccess(value)
case .failure(let error):
self.onFailure(error)
}
}
} catch let error {
onFailure(error)
}
}
func onFailure(_ onFailure: @escaping (Error) -> Void) -> AppResult<ResultType, Parameters> {
self.onFailure = onFailure
return self
}
func onSuccess(_ onSuccess: @escaping (ResultType) -> Void) -> AppResult<ResultType, Parameters> {
self.onSuccess = onSuccess
return self
}
}
protocol BaseUseCase {
associatedtype ResultType
associatedtype Parameters
func run(
parameters: Parameters,
completion: @escaping (_ result: Result<ResultType, Error>) -> Void
) throws -> Void
}
extension BaseUseCase {
func execute(parameters: Parameters) -> AppResult<ResultType, Parameters> {
return AppResult(parameters: parameters, self.run)
}
}
class SignInCase : BaseUseCase {
typealias ResultType = Session
typealias Parameters = LoginRequest
let authGateway: AuthGateway
init( authGateway: AuthGateway) {
self.authGateway = authGateway
}
func run(parameters: LoginRequest, completion: @escaping (_ result: Result<Session, Error>) -> Void ) throws -> Void {
authGateway.login(parameters: parameters, completion: completion)
}
}
class AuthViewModel {
let signInCase: SignInCase
init(signInCase: SignInCase) {
self.signInCase = signInCase
}
func login (email: String, passWord: String) {
self.signInCase.execute(
parameters: LoginRequest(username: email, password: passWord)
).onSuccess { data in
//do success
}.onFailure { error in
// do error
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment