Skip to content

Instantly share code, notes, and snippets.

@kphetrungnapha
Created January 10, 2019 09:15
Show Gist options
  • Select an option

  • Save kphetrungnapha/3d1dcfce605cbc8b7c28060fbee998bf to your computer and use it in GitHub Desktop.

Select an option

Save kphetrungnapha/3d1dcfce605cbc8b7c28060fbee998bf to your computer and use it in GitHub Desktop.

Revisions

  1. Kittisak Phetrungnapha created this gist Jan 10, 2019.
    71 changes: 71 additions & 0 deletions Router.swift
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,71 @@
    enum Router {
    case getContacts
    case getContact(id: Int)
    case createContact(body: [String: Any])
    case updateContact(id: Int, body: [String: Any])

    private static let baseURLString = "YOUR_BASE_URL_STRING"

    private enum HTTPMethod {
    case get
    case post
    case put
    case delete

    var value: String {
    switch self {
    case .get: return "GET"
    case .post: return "POST"
    case .put: return "PUT"
    case .delete: return "DELETE"
    }
    }
    }

    private var method: HTTPMethod {
    switch self {
    case .getContacts: return .get
    case .getContact: return .get
    case .createContact: return .post
    case .updateContact: return .put
    }
    }

    private var path: String {
    switch self {
    case .getContacts:
    return "/contacts.json"
    case .getContact(let id):
    return "/contacts/\(id).json"
    case .createContact:
    return "/contacts.json"
    case .updateContact(let id, _):
    return "/contacts/\(id).json"
    }
    }

    func request() throws -> URLRequest {
    let urlString = "\(Router.baseURLString)\(path)"

    guard let url = URL(string: urlString) else {
    throw ErrorType.parseUrlFail
    }

    var request = URLRequest(url: url, cachePolicy: .reloadIgnoringCacheData, timeoutInterval: 10)
    request.httpMethod = method.value
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")

    switch self {
    case .getContacts:
    return request
    case .getContact:
    return request
    case .createContact(let body):
    request.httpBody = try JSONSerialization.data(withJSONObject: body, options: .prettyPrinted)
    return request
    case .updateContact(_, let body):
    request.httpBody = try JSONSerialization.data(withJSONObject: body, options: .prettyPrinted)
    return request
    }
    }
    }