- Alamofire 라우터 공부하고 작성해봤다. 다른 코드들 좀 더 참고해서 가다듬어야겠다.
enum APIRouter: URLRequestConvertible {
// auth
case emailSignIn(email: String, username: String, password: String)
case emailLogin(email: String, password: String)
// timer
case postTime(second: Int)
var baseURL: URL {
return URL(string: "localhost:8080/api/")!
}
var endPoint: String {
guard let user = UserDefaultService.shared.getUser()?.userInfo else { return ""}
switch self {
case .emailSignIn:
return "members"
case .emailLogin:
return "login"
case .postTime:
return "timer/\(user.id)"
}
}
var method: HTTPMethod {
switch self {
case .emailSignIn:
return .post
case .emailLogin:
return .post
case .postTime:
return .post
}
}
var parameters: Parameters {
var params = Parameters()
switch self {
case let .emailSignIn(email, username, password):
params["email"] = email
params["username"] = username
params["password"] = password
case let .emailLogin(email, password):
params["email"] = email
params["password"] = password
case let .postTime(second):
params["second"] = second
}
return params
}
var headers: HTTPHeaders {
switch self {
case .emailSignIn, .emailLogin:
return [
"Accept": "application/json"
]
default:
return [
"Accept": "application/json",
"X-AUTH": "토큰" // TODO: 토큰 값 넣어주기!!!!!!!
]
}
}
func asURLRequest() throws -> URLRequest {
let url = baseURL.appendingPathComponent(endPoint)
var request = URLRequest(url: url)
request.headers = self.headers
request.method = self.method
switch self.method {
case .get:
return request
case .post:
request.httpBody = try JSONEncoding.default.encode(request, with: parameters).httpBody
return request
default:
return request
}
}
}
참고
참고
참고
참고