Skip to content
This repository was archived by the owner on Nov 24, 2020. It is now read-only.

Commit cf1f457

Browse files
committed
fix (namespacing)
Add the ApiInternal to the API.
1 parent dd3d11b commit cf1f457

File tree

1 file changed

+157
-158
lines changed

1 file changed

+157
-158
lines changed

src/target/swift_ios.cr

Lines changed: 157 additions & 158 deletions
Original file line numberDiff line numberDiff line change
@@ -80,204 +80,203 @@ END
8080
end
8181

8282
@io << <<-END
83-
}
8483
85-
class ApiInternal {
86-
var baseUrl = #{@ast.options.url.inspect}
84+
class ApiInternal {
85+
var baseUrl = #{@ast.options.url.inspect}
8786
88-
// MARK: ApiInternal Inner classes
89-
enum Result<T> {
90-
case success(T)
91-
case failure(Error)
92-
}
87+
// MARK: ApiInternal Inner classes
88+
enum Result<T> {
89+
case success(T)
90+
case failure(Error)
91+
}
9392
94-
class Error: Codable {
95-
var type: API.ErrorType
96-
var message: String
93+
class Error: Codable {
94+
var type: API.ErrorType
95+
var message: String
9796
98-
init(type: API.ErrorType, message: String) {
99-
self.type = type
100-
self.message = message
97+
init(type: API.ErrorType, message: String) {
98+
self.type = type
99+
self.message = message
100+
}
101101
}
102-
}
103102
104-
class HttpResponse<T: Codable>: Codable {
105-
var ok: Bool
106-
var deviceId: String
107-
var result: T?
108-
var error: Error?
109-
110-
required init(from decoder: Decoder) throws {
111-
let values = try decoder.container(keyedBy: CodingKeys.self)
112-
ok = try values.decode(Bool.self, forKey: .ok)
113-
deviceId = try values.decode(String.self, forKey: .deviceId)
114-
result = (try? values.decode(T.self, forKey: .result)) ?? (API.NoReply() as? T)
115-
error = try? values.decode(Error.self, forKey: .error)
103+
class HttpResponse<T: Codable>: Codable {
104+
var ok: Bool
105+
var deviceId: String?
106+
var result: T?
107+
var error: Error?
108+
109+
required init(from decoder: Decoder) throws {
110+
let values = try decoder.container(keyedBy: CodingKeys.self)
111+
ok = try values.decode(Bool.self, forKey: .ok)
112+
deviceId = try? values.decode(String.self, forKey: .deviceId)
113+
result = (try? values.decode(T.self, forKey: .result)) ?? (API.NoReply() as? T)
114+
error = try? values.decode(Error.self, forKey: .error)
115+
}
116116
}
117-
}
118-
119-
// MARK: ApiInternal Date Handler
120-
let dateAndTimeFormatter: DateFormatter = {
121-
let formatter = DateFormatter()
122-
formatter.calendar = Calendar(identifier: .gregorian)
123-
formatter.timeZone = TimeZone(abbreviation: "UTC")
124-
formatter.locale = Locale(identifier: "en_US_POSIX")
125-
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS"
126-
return formatter
127-
}()
128-
129-
let dateFormatter: DateFormatter = {
130-
let formatter = DateFormatter()
131-
formatter.calendar = Calendar(identifier: .gregorian)
132-
formatter.locale = Locale(identifier: "en_US_POSIX")
133-
formatter.dateFormat = "yyyy-MM-dd"
134-
return formatter
135-
}()
136117
137-
func decodeDate(str: String) -> Date? {
138-
return dateFormatter.date(from: str)
139-
}
140-
141-
func encodeDate(date: Date) -> String {
142-
return dateFormatter.string(from: date)
143-
}
144-
145-
func decodeDateTime(str: String) -> Date? {
146-
return dateAndTimeFormatter.date(from: str)
147-
}
118+
// MARK: ApiInternal Date Handler
119+
let dateAndTimeFormatter: DateFormatter = {
120+
let formatter = DateFormatter()
121+
formatter.calendar = Calendar(identifier: .gregorian)
122+
formatter.timeZone = TimeZone(abbreviation: "UTC")
123+
formatter.locale = Locale(identifier: "en_US_POSIX")
124+
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS"
125+
return formatter
126+
}()
127+
128+
let dateFormatter: DateFormatter = {
129+
let formatter = DateFormatter()
130+
formatter.calendar = Calendar(identifier: .gregorian)
131+
formatter.locale = Locale(identifier: "en_US_POSIX")
132+
formatter.dateFormat = "yyyy-MM-dd"
133+
return formatter
134+
}()
135+
136+
func decodeDate(str: String) -> Date? {
137+
return dateFormatter.date(from: str)
138+
}
148139
149-
func encodeDateTime(date: Date) -> String {
150-
return dateAndTimeFormatter.string(from: date)
151-
}
140+
func encodeDate(date: Date) -> String {
141+
return dateFormatter.string(from: date)
142+
}
152143
153-
// MARK: ApiInternal Device Handler
154-
func device() -> [String: Any] {
155-
var device = [String: Any]()
156-
device["platform"] = "ios"
157-
device["fingerprint"] = phoneFingerprint()
158-
device["platformVersion"] = "iOS " + UIDevice.current.systemVersion + " on " + UIDevice.current.model
159-
if let version = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String {
160-
device["version"] = version
161-
} else {
162-
device["version"] = "unknown"
144+
func decodeDateTime(str: String) -> Date? {
145+
return dateAndTimeFormatter.date(from: str)
163146
}
164147
165-
device["language"] = Locale.preferredLanguages[0]
166-
if let currentId = deviceId {
167-
device["id"] = currentId
148+
func encodeDateTime(date: Date) -> String {
149+
return dateAndTimeFormatter.string(from: date)
168150
}
169151
170-
return device
171-
}
152+
// MARK: ApiInternal Device Handler
153+
func device() -> [String: Any] {
154+
var device = [String: Any]()
155+
device["platform"] = "ios"
156+
device["fingerprint"] = phoneFingerprint()
157+
device["platformVersion"] = "iOS " + UIDevice.current.systemVersion + " on " + UIDevice.current.model
158+
if let version = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String {
159+
device["version"] = version
160+
} else {
161+
device["version"] = "unknown"
162+
}
172163
173-
func randomBytesHex(len: Int) -> String {
174-
var randomBytes = [UInt8](repeating: 0, count: len)
175-
let _ = SecRandomCopyBytes(kSecRandomDefault, len, &randomBytes)
176-
return randomBytes.map({String(format: "%02hhx", $0)}).joined(separator: "")
177-
}
164+
device["language"] = Locale.preferredLanguages[0]
165+
if let currentId = deviceId {
166+
device["id"] = currentId
167+
}
178168
179-
var deviceId: String? {
180-
return UserDefaults.standard.value(forKey: "device-id") as? String
181-
}
169+
return device
170+
}
182171
183-
func saveDeviceId(_ id: String) {
184-
UserDefaults.standard.setValue(id, forKey: "device-id")
185-
UserDefaults.standard.synchronize()
186-
}
172+
func randomBytesHex(len: Int) -> String {
173+
var randomBytes = [UInt8](repeating: 0, count: len)
174+
let _ = SecRandomCopyBytes(kSecRandomDefault, len, &randomBytes)
175+
return randomBytes.map({String(format: "%02hhx", $0)}).joined(separator: "")
176+
}
187177
188-
func phoneFingerprint() -> String {
189-
let keychain = KeychainSwift()
190-
guard let phoneFingerprint = keychain.get("phoneFingerprint") else {
191-
let newPhoneFingerprint = randomBytesHex(len: 32)
192-
keychain.set(newPhoneFingerprint, forKey: "phoneFingerprint", withAccess: .accessibleAlwaysThisDeviceOnly)
193-
return newPhoneFingerprint
178+
var deviceId: String? {
179+
return UserDefaults.standard.value(forKey: "device-id") as? String
194180
}
195181
196-
return phoneFingerprint
197-
}
182+
func saveDeviceId(_ id: String) {
183+
UserDefaults.standard.setValue(id, forKey: "device-id")
184+
UserDefaults.standard.synchronize()
185+
}
198186
199-
// MARK: ApiInternal request functions
200-
func globalCallback<T: Codable>(result: Result<T>, method: String, callback: ((Result<T>) -> Void)?) {
187+
func phoneFingerprint() -> String {
188+
let keychain = KeychainSwift()
189+
guard let phoneFingerprint = keychain.get("phoneFingerprint") else {
190+
let newPhoneFingerprint = randomBytesHex(len: 32)
191+
keychain.set(newPhoneFingerprint, forKey: "phoneFingerprint", withAccess: .accessibleAlwaysThisDeviceOnly)
192+
return newPhoneFingerprint
193+
}
201194
202-
//Convert result to result of type Any
203-
let anyResult: Result<Any?>
204-
switch result {
205-
case .success(let value):
206-
anyResult = Result.success(value as Any?)
207-
case .failure(let error):
208-
anyResult = Result.failure(error)
195+
return phoneFingerprint
209196
}
210197
211-
API.globalCallback(method, anyResult) { result in
212-
//Convert result to result of type T.
213-
let tResult: Result<T>
198+
// MARK: ApiInternal request functions
199+
func globalCallback<T: Codable>(result: Result<T>, method: String, callback: ((Result<T>) -> Void)?) {
200+
201+
//Convert result to result of type Any
202+
let anyResult: Result<Any?>
214203
switch result {
215204
case .success(let value):
216-
217-
if let tValue = value as? T {
218-
tResult = Result.success(tValue)
219-
} else {
220-
tResult = Result.failure(Error(type: API.ErrorType.Serialization,message: "Erro ao mapear os dados, tente novamente mais tarde"))
221-
}
222-
205+
anyResult = Result.success(value as Any?)
223206
case .failure(let error):
224-
tResult = Result.failure(error)
207+
anyResult = Result.failure(error)
225208
}
226209
227-
callback?(tResult)
228-
}
229-
}
210+
API.globalCallback(method, anyResult) { result in
211+
//Convert result to result of type T.
212+
let tResult: Result<T>
213+
switch result {
214+
case .success(let value):
230215
231-
@discardableResult
232-
func makeRequest<T: Codable>(_ name: String, _ args: [String: Any], callback: ((Result<T>) -> Void)?) -> DataRequest {
233-
let api = SessionManager.default
234-
235-
let body = [
236-
"id": randomBytesHex(len: 8),
237-
"device": device(),
238-
"name": name,
239-
"args": args,
240-
"staging": API.useStaging
241-
] as [String : Any]
242-
243-
let url = API.customUrl ?? "https://\\(baseUrl)\\(API.useStaging ? "-staging" : "")"
244-
return api.request(
245-
"\\(url)/\\(name)",
246-
method: .post,
247-
parameters: body,
248-
encoding: JSONEncoding.default
249-
).responseData { [weak self] response in
250-
guard let this = self else { return }
251-
252-
let responseResult: Result<T>
253-
switch response.result {
254-
case .success(let data):
255-
256-
do {
257-
let response = try API.decoder.decode(HttpResponse<T>.self, from: data)
258-
this.saveDeviceId(response.deviceId)
259-
if let result = response.result, response.ok {
260-
responseResult = Result.success(result)
261-
} else if let error = response.error {
262-
responseResult = Result.failure(error)
216+
if let tValue = value as? T {
217+
tResult = Result.success(tValue)
263218
} else {
264-
responseResult = Result.failure(Error(type: API.ErrorType.Serialization, message: "Algo de errado está acontecendo em nosso servidor, tente novamente mais tarde"))
219+
tResult = Result.failure(Error(type: API.ErrorType.Serialization,message: "Erro ao mapear os dados, tente novamente mais tarde"))
265220
}
266221
267-
} catch let error {
268-
if API.isEnabledAssertion { assert(false, "Erro ao serializar dados, error: \\(error)") }
269-
responseResult = Result.failure(Error(type: API.ErrorType.Serialization, message: "Erro ao carregar seus dados, tente novamente mais tarde"))
222+
case .failure(let error):
223+
tResult = Result.failure(error)
270224
}
271225
272-
case .failure:
273-
responseResult = Result.failure(Error(type: API.ErrorType.Connection, message: "Erro de Conexão, tente novamente mais tarde"))
226+
callback?(tResult)
274227
}
228+
}
229+
230+
@discardableResult
231+
func makeRequest<T: Codable>(_ name: String, _ args: [String: Any], callback: ((Result<T>) -> Void)?) -> DataRequest {
232+
let api = SessionManager.default
233+
234+
let body = [
235+
"id": randomBytesHex(len: 8),
236+
"device": device(),
237+
"name": name,
238+
"args": args,
239+
"staging": API.useStaging
240+
] as [String : Any]
241+
242+
let url = API.customUrl ?? "https://\\(baseUrl)\\(API.useStaging ? "-staging" : "")"
243+
return api.request(
244+
"\\(url)/\\(name)",
245+
method: .post,
246+
parameters: body,
247+
encoding: JSONEncoding.default
248+
).responseData { [weak self] response in
249+
guard let this = self else { return }
250+
251+
let responseResult: Result<T>
252+
switch response.result {
253+
case .success(let data):
254+
255+
do {
256+
let response = try API.decoder.decode(HttpResponse<T>.self, from: data)
257+
if let deviceId = response.deviceId { this.saveDeviceId(deviceId) }
258+
if let result = response.result, response.ok {
259+
responseResult = Result.success(result)
260+
} else if let error = response.error {
261+
responseResult = Result.failure(error)
262+
} else {
263+
responseResult = Result.failure(Error(type: API.ErrorType.Serialization, message: "Algo de errado está acontecendo em nosso servidor, tente novamente mais tarde"))
264+
}
265+
266+
} catch let error {
267+
if API.isEnabledAssertion { assert(false, "Erro ao serializar dados, error: \\(error)") }
268+
responseResult = Result.failure(Error(type: API.ErrorType.Serialization, message: "Erro ao carregar seus dados, tente novamente mais tarde"))
269+
}
270+
271+
case .failure:
272+
responseResult = Result.failure(Error(type: API.ErrorType.Connection, message: "Erro de Conexão, tente novamente mais tarde"))
273+
}
275274
276-
this.globalCallback(result: responseResult, method: name, callback: callback)
275+
this.globalCallback(result: responseResult, method: name, callback: callback)
276+
}
277277
}
278278
}
279279
}
280-
281280
protocol DisplayableValue: RawRepresentable {
282281
var displayableValue: String { get }
283282
}

0 commit comments

Comments
 (0)