This repository was archived by the owner on Jun 7, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 430
Expand file tree
/
Copy pathAPIRequest.swift
More file actions
78 lines (59 loc) · 1.96 KB
/
APIRequest.swift
File metadata and controls
78 lines (59 loc) · 1.96 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
//
// APIRequest.swift
// Rocket.Chat
//
// Created by Matheus Cardoso on 9/18/17.
// Copyright © 2017 Rocket.Chat. All rights reserved.
//
import Foundation
protocol APIRequest {
associatedtype APIResourceType: APIResource
var requiredVersion: Version { get }
var path: String { get }
var method: HTTPMethod { get }
var contentType: String { get }
var query: String? { get }
func body() -> Data?
func request(for api: API, options: APIRequestOptionSet) -> URLRequest?
}
extension APIRequest {
var requiredVersion: Version {
return .zero
}
var method: HTTPMethod {
return .get
}
var contentType: String {
return "application/json"
}
var query: String? {
return nil
}
func body() -> Data? {
return nil
}
func request(for api: API, options: APIRequestOptionSet = []) -> URLRequest? {
var components = URLComponents(url: api.host, resolvingAgainstBaseURL: false)
components?.path += path
components?.query = query
options.compactMap { $0.query }.forEach { optionQuery in
components?.query = "\(query ?? "")&\(optionQuery)"
}
guard let url = components?.url else {
return nil
}
var request = URLRequest(url: url)
request.httpMethod = method.rawValue
request.httpBody = body()
request.addValue(contentType, forHTTPHeaderField: "Content-Type")
request.addValue(API.userAgent, forHTTPHeaderField: "User-Agent")
func addValueIfSome(_ value: String?, forHTTPHeaderField field: String) {
guard let value = value else { return }
request.addValue(value, forHTTPHeaderField: field)
}
addValueIfSome(api.authToken, forHTTPHeaderField: "X-Auth-Token")
addValueIfSome(api.userId, forHTTPHeaderField: "X-User-Id")
addValueIfSome(api.language, forHTTPHeaderField: "Accept-Language")
return request
}
}