Actions.swift 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import Foundation
  2. struct Actions {
  3. static let shared = Actions()
  4. private let tag = "Actions"
  5. func parse(_ actions: String?) -> [Action]? {
  6. guard let actions = actions,
  7. let data = actions.data(using: .utf8) else { return nil }
  8. do {
  9. return try JSONDecoder().decode([Action].self, from: data)
  10. .filter { supportedActions.contains($0.action) }
  11. } catch {
  12. Log.e(tag, "Unable to parse actions: \(error.localizedDescription)", error)
  13. return nil
  14. }
  15. }
  16. func http(_ action: Action) {
  17. guard let actionUrl = action.url, let url = URL(string: actionUrl) else {
  18. Log.w(tag, "Unable to execute HTTP action, no or invalid URL", action)
  19. return
  20. }
  21. let method = action.method ?? "POST" // POST is the default!!
  22. let body = action.body ?? ""
  23. Log.d(tag, "Performing HTTP \(method) \(url)")
  24. var request = URLRequest(url: url)
  25. request.httpMethod = method
  26. action.headers?.forEach { key, value in
  27. request.setValue(value, forHTTPHeaderField: key)
  28. }
  29. if !["GET", "HEAD"].contains(method) {
  30. request.httpBody = body.data(using: .utf8)
  31. }
  32. URLSession.shared.dataTask(with: request) { (data, response, error) in
  33. guard error == nil else {
  34. Log.e(self.tag, "Error performing HTTP \(method)", error!)
  35. return
  36. }
  37. Log.d(self.tag, "HTTP \(method) succeeded", response)
  38. }.resume()
  39. }
  40. }