Skip to content

Commit 2bc7a26

Browse files
author
jacob.aronoff
committed
Initial restructure, better protocols
1 parent 9f77e28 commit 2bc7a26

File tree

6 files changed

+105
-61
lines changed

6 files changed

+105
-61
lines changed

Example/Pods/Pods.xcodeproj/project.pbxproj

+4
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

SwiftDog/Classes/Authentication.swift

+62
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
//
2+
// Authentication.swift
3+
// SwiftDog
4+
//
5+
// Created by jacob.aronoff on 5/18/18.
6+
//
7+
8+
import Foundation
9+
import KeychainAccess
10+
11+
internal struct DatadogAuthentication {
12+
private let keychain = Keychain(service: "api.datadoghq.com")
13+
internal var authenticated = false
14+
internal var app_key: String? {
15+
return self.keychain[string: "app_key"]
16+
}
17+
internal var api_key: String? {
18+
return self.keychain[string: "api_key"]
19+
}
20+
21+
private mutating func get_credentials_from_plist() throws {
22+
var myDict: NSDictionary?
23+
if let path = Bundle.main.url(forResource: "datadog_config", withExtension: "plist") {
24+
myDict = NSDictionary(contentsOf: path)
25+
}
26+
if let dict = myDict {
27+
guard let api_key = dict["api_key"] as? String, let app_key = dict["app_key"] as? String else {
28+
throw DatadogAPIError.keyNotSet("API OR APP KEY NOT SET")
29+
}
30+
if keychain["api_key"] == nil || keychain["app_key"] == nil {
31+
do {
32+
try keychain.set(api_key, key: "api_key")
33+
try keychain.set(app_key, key: "app_key")
34+
self.authenticated = true
35+
print("finished setting credentials")
36+
} catch {
37+
throw DatadogAPIError.keyNotSet("Failed to set app or api key")
38+
}
39+
40+
}
41+
}
42+
}
43+
44+
internal init() {
45+
do {
46+
try self.get_credentials_from_plist()
47+
} catch {
48+
fatalError(error.localizedDescription)
49+
}
50+
}
51+
52+
internal mutating func resetCredentials() {
53+
keychain["api_key"] = nil
54+
keychain["app_key"] = nil
55+
do {
56+
try self.get_credentials_from_plist()
57+
} catch {
58+
print(error)
59+
}
60+
61+
}
62+
}

SwiftDog/Classes/Datadog.swift

+13-45
Original file line numberDiff line numberDiff line change
@@ -1,74 +1,37 @@
1-
import KeychainAccess
1+
22

33
public class Datadog: API {
4+
45
internal var base_url: String = "api.datadoghq.com/api/v1/"
56
internal var interval_seconds: TimeInterval = TimeInterval(10)
67
public var metric: Metric = Metric.metric
78
public var event: Event = Event.event
89
private var timer: Timer = Timer()
9-
internal let keychain = Keychain(service: "api.datadoghq.com")
1010
public static let dd = Datadog()
1111
internal let host = UIDevice.current.identifierForVendor!.uuidString
1212
internal let model = UIDevice.current.model
1313
internal var use_agent = false
14+
internal var auth:DatadogAuthentication? = nil
1415

1516
@objc private func sendData() {
1617
print("Sending metrics to the Datadog API.")
1718
if use_agent {
1819
IOSAgent.send_agent_metrics()
1920
}
2021
do {
21-
try self.metric._send(url: base_url) { (error: Error?) in
22-
print(error!)
23-
}
24-
try self.event._send(url: base_url, completion: { (error: Error?) in
25-
print(error!)
26-
})
27-
} catch {
28-
fatalError(error.localizedDescription)
29-
}
30-
31-
}
32-
33-
private func get_credentials_from_plist() throws {
34-
var myDict: NSDictionary?
35-
if let path = Bundle.main.url(forResource: "datadog_config", withExtension: "plist") {
36-
myDict = NSDictionary(contentsOf: path)
37-
}
38-
if let dict = myDict {
39-
guard let api_key = dict["api_key"] as? String, let app_key = dict["app_key"] as? String else {
40-
throw DatadogAPIError.keyNotSet("API OR APP KEY NOT SET")
41-
}
42-
if keychain["api_key"] == nil || keychain["app_key"] == nil {
43-
do {
44-
try keychain.set(api_key, key: "api_key")
45-
try keychain.set(app_key, key: "app_key")
46-
print("finished setting credentials")
47-
} catch {
48-
throw DatadogAPIError.keyNotSet("Failed to set app or api key")
22+
for var endpoint in [self.metric, self.event] as [DataProducer] {
23+
try endpoint._send_data(url: base_url) { (error: Error?) in
24+
print(error!)
4925
}
50-
5126
}
52-
}
53-
}
54-
55-
public func resetCredentials() {
56-
keychain["api_key"] = nil
57-
keychain["app_key"] = nil
58-
do {
59-
try get_credentials_from_plist()
6027
} catch {
61-
print(error)
28+
fatalError(error.localizedDescription)
6229
}
6330

6431
}
6532

6633
public func initialize_api(with agent:Bool=false, default_tags:Bool=false) {
67-
do {
68-
try get_credentials_from_plist()
69-
} catch {
70-
fatalError(error.localizedDescription)
71-
}
34+
self.auth = DatadogAuthentication()
7235
self.use_agent = agent
7336
if default_tags {
7437
self.metric.addTags(tags: ["agent:ios", "model:\(IOSAgent.modelIdentifier())"])
@@ -77,6 +40,11 @@ public class Datadog: API {
7740
self.timer = Timer.scheduledTimer(timeInterval: self.interval_seconds, target: self, selector: #selector(Datadog.sendData), userInfo: nil, repeats: true)
7841
}
7942

43+
public func resetCredentials() {
44+
if self.auth != nil {
45+
self.auth!.resetCredentials()
46+
}
47+
}
8048

8149
private init() {
8250

SwiftDog/Classes/Event.swift

+2-2
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
//
77

88

9-
public struct Event: Endpoint {
9+
public struct Event: DataProducer {
1010
static let event = Event()
1111
public typealias EndpointDataType = EventData
1212
public var endpoint: String = "events"
@@ -17,7 +17,7 @@ public struct Event: Endpoint {
1717

1818
}
1919

20-
internal mutating func _send(url: String, completion:((Error?) -> Void)?) throws {
20+
internal mutating func _send_data(url: String, completion:((Error?) -> Void)?) throws {
2121
let url_to_post = try self.create_url(url: url)
2222
let encoder = JSONEncoder()
2323
do {

SwiftDog/Classes/Metric.swift

+2-2
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
//
77

88

9-
public struct Metric: Endpoint, Encodable {
9+
public struct Metric: DataProducer, Encodable {
1010

1111
static let metric = Metric()
1212
public typealias EndpointDataType = MetricData
@@ -27,7 +27,7 @@ public struct Metric: Endpoint, Encodable {
2727

2828
}
2929

30-
internal mutating func _send(url: String, completion:((Error?) -> Void)?) throws {
30+
internal mutating func _send_data(url: String, completion:((Error?) -> Void)?) throws {
3131
let url_to_post = try self.create_url(url: url)
3232
let encoder = JSONEncoder()
3333
do {

SwiftDog/Classes/Types.swift

+22-12
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,9 @@ public protocol DataType: Encodable {
2727
var tags: [String] { get set }
2828
}
2929

30+
31+
32+
3033
public protocol Endpoint {
3134
associatedtype EndpointDataType: DataType
3235
var endpoint: String { get }
@@ -35,10 +38,26 @@ public protocol Endpoint {
3538
}
3639

3740
extension Endpoint {
41+
public mutating func send(series: [EndpointDataType]) {
42+
_ = series.map { (item: EndpointDataType) in
43+
var it = item
44+
it.tags.append(contentsOf: self.tags)
45+
endpoint_data.append(it)
46+
}
47+
}
48+
}
49+
50+
internal protocol DataProducer: Endpoint {
51+
func create_url(url: String) throws -> URL
52+
mutating func _send_data(url: String, completion:((Error?) -> Void)?) throws
53+
}
54+
55+
extension DataProducer {
3856
internal func create_url(url: String) throws -> URL {
39-
let api_key = Datadog.dd.keychain[string: "api_key"]
40-
let app_key = Datadog.dd.keychain[string: "app_key"]
41-
return URL(string: "https://"+url+self.endpoint + "?api_key=\(api_key!)&application_key=\(app_key!)")!
57+
guard let api_key = Datadog.dd.auth?.api_key, let app_key = Datadog.dd.auth?.app_key else {
58+
throw DatadogAPIError.keyNotSet("Not Authenticated")
59+
}
60+
return URL(string: "https://"+url+self.endpoint + "?api_key=\(api_key)&application_key=\(app_key)")!
4261
}
4362
internal func _send(url_to_post: URL, json: Data, completion:((Error?) -> Void)?) throws {
4463
guard json.count > 0, self.endpoint_data.count > 0 else {
@@ -75,15 +94,6 @@ extension Endpoint {
7594
internal mutating func addTags(tags: [String]) {
7695
self.tags.append(contentsOf: tags)
7796
}
78-
79-
public mutating func send(series: [EndpointDataType]) {
80-
_ = series.map { (item: EndpointDataType) in
81-
var it = item
82-
it.tags.append(contentsOf: self.tags)
83-
// it.host = it.host ?? Datadog.dd.host
84-
endpoint_data.append(it)
85-
}
86-
}
8797
}
8898
enum DatadogAPIError: Error {
8999
case keyNotSet(String)

0 commit comments

Comments
 (0)