Created
May 19, 2017 13:03
-
-
Save Akhu/0449fa61fd3a3c97c81dd72a0bbbfccc to your computer and use it in GitHub Desktop.
Simple Router built with Alamofire based on their documentation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// Router.swift | |
// | |
// Created by Anthony on 28/04/2017. | |
// Copyright © 2017 Anthony Da Cruz. All rights reserved. | |
// | |
import Foundation | |
import Alamofire | |
internal enum Router: URLRequestConvertible { | |
static let baseURLString:String = "https://myApi.io" | |
internal static let authenticationRoutes = "/auth" | |
internal static let userRoutes = "/user" | |
internal static let logRoutes = "/log" | |
case connect | |
case log(parametersBag: Parameters) | |
var method: HTTPMethod { | |
switch self { | |
case .connect: | |
return .post | |
case .log: | |
return .post | |
} | |
} | |
var path: String { | |
switch self { | |
case .connect: | |
return Router.authenticationRoutes + "/connect" | |
case .log: | |
return Router.logRoutes + "/infos" | |
} | |
} | |
func asURLRequest() throws -> URLRequest { | |
let url = try Router.baseURLString.asURL() | |
var urlRequest = try URLRequest(url: url.appendingPathComponent(self.path, isDirectory: false), method: self.method) | |
switch self { | |
case .log(parametersBag: let parametersBag): | |
urlRequest = try JSONEncoding.default.encode(urlRequest, with: parametersBag) | |
break | |
case .connect: | |
do{ | |
let bodyParameters = try self.generateAuthenticationParameters() | |
urlRequest = try JSONEncoding.default.encode(urlRequest, with: bodyParameters) | |
} catch { | |
throw SomeException.authenticationException | |
} | |
break | |
default: | |
break | |
} | |
return urlRequest | |
} | |
private func generateAuthenticationParameters() -> HTTPHeaders { | |
return ["X-AUTH-TOKEN":"token"] | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment