mercredi 22 mai 2019

Same protocol objects, but not the same functions

I'm trying to build an API pattern.

I have several different APIs that have the same functions for some, and some have additional functions that other APIs do not have and should not have access.

The problem with the protocol is that they all have access. How to limit access if the function is not override?

apiRequest:

class APIRequest {
    static func loginCli(completion: (UserClinic) -> ()) {

    }

    static func loginFami(completion: (User) -> ()) {

    }

    static func loginDavid(completion: (UserDavid) -> ()) {

    }
}

Protol and API:

protocol API {
    func login<T>(completion: (T) -> ())
    func saveClient()
}

extension API {
    func saveClient() {
        saveClient()
    }
}

class FirstAPI: API {
    func login<T>(completion: (T) -> ()) {
        APIRequest.loginFami { (user) in

        }
    }
}

class SecondAPI: API {
    func login<T>(completion: (T) -> ()) {
        APIRequest.loginCli { (user) in

        }
    }
}

class ThreeAPI: API {
    func login<T>(completion: (T) -> ()) {
        APIRequest.loginDavid { (user) in

        }
    }

    func saveClient() {
        // Save client
    }
}

View model:

class LoginViewModel {
    var apiClient: API

    init() {
        // Below its good
        apiClient = ThreeAPI()
        apiClient.saveClient()

        // Below its not good
        apiClient = FirstAPI()
        apiClient.saveClient() // I want this is not accessible

        // Below its good
        apiClient = SecondAPI()
        apiClient.saveClient() // I want this is not accessible
    }
}

In my case I need only the third API to have access to the function saveClient()

Aucun commentaire:

Enregistrer un commentaire