bruno
bruno

Reputation: 2169

Build endpoints using struct

I'm building a struct with constants to form URL endpoints.

struct Constants {
    struct Api {
        static let BaseUrl = "http://srv.com/ws_rest/"
        static let LoginPassword1 = "credentials?member_account_pwd="
        static let LoginUsername2 = "&member_account_login="
        static let Login3 = "&channelId=4"
    }
}

The final result is:

let url = URL.baseUrlWith(string: Constants.Api.LoginPassword1 + "pass" + Constants.Api.LoginUsername2 + "user" + Constants.Api.Login3)

This is only for one endpoint. Does anyone knows of a better pratical aproach to this?

Upvotes: 0

Views: 405

Answers (1)

Giuseppe Lanza
Giuseppe Lanza

Reputation: 3699

it might be useful to have a function that helps you

    func urlString(with baseURL: String, and parameters: [String: String])->String {
        var mutableBaseURL = baseURL
        for (i, param) in parameters.enumerated() {
            var symbol = "&"
            if i == 0 { symbol = "?" }

            mutableBaseURL += "\(symbol)\(param.key)=\(param.value)"
        }
        return mutableBaseURL
    }

So your constants would become something like

struct Constants {
    struct Endpoints {
        static let login = "http://srv.com/ws_rest/credentials"
    }

    struct Parameters {
        static let username = "member_account_login"
        static let password = "member_account_pwd"
        static let channelId = "channelId"
    }
}

Somewhere in your code you will have

let url = urlString(with: Constants.Endpoints.login, and: [
                Constants.Parameters.username: username,
                Constants.Parameters.password: pass, 
                Constants.Parameters.channelId: "4"
            ])

Hope it helps.

Upvotes: 1

Related Questions