Api.swift 1.87 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
//
//  Api.swift
//  Pods
//
//  Created by Mauro Bender on 13/8/16.
//
//

import Alamofire

public typealias ApiMethod = Alamofire.Method

public class Api {
	let baseURL: NSURL
	let apiPath: String
	
	var apiURL: NSURL { return baseURL.URLByAppendingPathComponent( apiPath ) }
	
	public init( baseURL: NSURL, apiPath: String ) {
		self.baseURL = baseURL
		self.apiPath = apiPath
	}
	
	// RESOURCE
25
	public func resource( path: String ) -> Resource {
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
		return Resource( api: self, path: path )
	}
	
	// REQUESTS
	public func request( method: ApiMethod, path: String,
		parameters: [String: AnyObject]? = nil, encoding: ParameterEncoding = .URL,
		headers: [String: String]? = nil, completion: Response<AnyObject, NSError> -> Void )
	{
		Alamofire.request( method, urlForPath( path ).absoluteString, parameters: parameters,
		                   encoding: encoding, headers: headers ).responseJSON( completionHandler: completion )
	}
	
	public func get( path: String, parameters: [String: AnyObject]? = nil, encoding: ParameterEncoding = .URL,
	                 headers: [String: String]? = nil, completion: Response<AnyObject, NSError> -> Void )
	{
		return request( .GET, path: path, parameters: parameters, encoding: encoding,
		                headers: headers, completion: completion)
	}
	
	public func post( path: String, parameters: [String: AnyObject]? = nil, encoding: ParameterEncoding = .URL,
	                 headers: [String: String]? = nil, completion: Response<AnyObject, NSError> -> Void )
	{
		return request( .POST, path: path, parameters: parameters, encoding: encoding,
		                headers: headers, completion: completion)
	}
	
	func urlForPath( path: String ) -> NSURL {
		return apiURL.URLByAppendingPathComponent( path )
	}
}

// MARK: Equatable
extension Api: Equatable {}

public func ==(lhs: Api, rhs: Api) -> Bool {
	return lhs.baseURL == rhs.baseURL && lhs.apiPath == rhs.apiPath
}