Callable+Codable.swift 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  1. // Copyright 2021 Google LLC
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. import Foundation
  15. import FirebaseSharedSwift
  16. // A `Callable` is reference to a particular Callable HTTPS trigger in Cloud Functions.
  17. public struct Callable<Request: Encodable, Response: Decodable> {
  18. /// The timeout to use when calling the function. Defaults to 60 seconds.
  19. public var timeoutInterval: TimeInterval {
  20. get {
  21. callable.timeoutInterval
  22. }
  23. set {
  24. callable.timeoutInterval = newValue
  25. }
  26. }
  27. enum CallableError: Error {
  28. case internalError
  29. }
  30. private let callable: HTTPSCallable
  31. private let encoder: FirebaseDataEncoder
  32. private let decoder: FirebaseDataDecoder
  33. init(callable: HTTPSCallable, encoder: FirebaseDataEncoder, decoder: FirebaseDataDecoder) {
  34. self.callable = callable
  35. self.encoder = encoder
  36. self.decoder = decoder
  37. }
  38. /// Executes this Callable HTTPS trigger asynchronously.
  39. ///
  40. /// The data passed into the trigger must be of the generic `Request` type:
  41. ///
  42. /// The request to the Cloud Functions backend made by this method automatically includes a
  43. /// FCM token to identify the app instance. If a user is logged in with Firebase
  44. /// Auth, an auth ID token for the user is also automatically included.
  45. ///
  46. /// Firebase Cloud Messaging sends data to the Firebase backend periodically to collect
  47. /// information
  48. /// regarding the app instance. To stop this, see `Messaging.deleteData()`. It
  49. /// resumes with a new FCM Token the next time you call this method.
  50. ///
  51. /// - Parameter data: Parameters to pass to the trigger.
  52. /// - Parameter completion: The block to call when the HTTPS request has completed.
  53. public func call(_ data: Request,
  54. completion: @escaping (Result<Response, Error>)
  55. -> Void) {
  56. do {
  57. let encoded = try encoder.encode(data)
  58. callable.call(encoded) { result, error in
  59. do {
  60. if let result = result {
  61. let decoded = try decoder.decode(Response.self, from: result.data)
  62. completion(.success(decoded))
  63. } else if let error = error {
  64. completion(.failure(error))
  65. } else {
  66. completion(.failure(CallableError.internalError))
  67. }
  68. } catch {
  69. completion(.failure(error))
  70. }
  71. }
  72. } catch {
  73. completion(.failure(error))
  74. }
  75. }
  76. /// Creates a directly callable function.
  77. ///
  78. /// This allows users to call a HTTPS Callable Function like a normal Swift function:
  79. /// ```swift
  80. /// let greeter = functions.httpsCallable("greeter",
  81. /// requestType: GreetingRequest.self,
  82. /// responseType: GreetingResponse.self)
  83. /// greeter(data) { result in
  84. /// print(result.greeting)
  85. /// }
  86. /// ```
  87. /// You can also call a HTTPS Callable function using the following syntax:
  88. /// ```swift
  89. /// let greeter: Callable<GreetingRequest, GreetingResponse> =
  90. /// functions.httpsCallable("greeter")
  91. /// greeter(data) { result in
  92. /// print(result.greeting)
  93. /// }
  94. /// ```
  95. /// - Parameters:
  96. /// - data: Parameters to pass to the trigger.
  97. /// - completion: The block to call when the HTTPS request has completed.
  98. public func callAsFunction(_ data: Request,
  99. completion: @escaping (Result<Response, Error>)
  100. -> Void) {
  101. call(data, completion: completion)
  102. }
  103. #if compiler(>=5.5.2) && canImport(_Concurrency)
  104. /// Executes this Callable HTTPS trigger asynchronously.
  105. ///
  106. /// The data passed into the trigger must be of the generic `Request` type:
  107. ///
  108. /// The request to the Cloud Functions backend made by this method automatically includes a
  109. /// FCM token to identify the app instance. If a user is logged in with Firebase
  110. /// Auth, an auth ID token for the user is also automatically included.
  111. ///
  112. /// Firebase Cloud Messaging sends data to the Firebase backend periodically to collect
  113. /// information
  114. /// regarding the app instance. To stop this, see `Messaging.deleteData()`. It
  115. /// resumes with a new FCM Token the next time you call this method.
  116. ///
  117. /// - Parameter data: The `Request` representing the data to pass to the trigger.
  118. ///
  119. /// - Throws: An error if any value throws an error during encoding or decoding.
  120. /// - Throws: An error if the callable fails to complete
  121. ///
  122. /// - Returns: The decoded `Response` value
  123. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  124. public func call(_ data: Request) async throws -> Response {
  125. let encoded = try encoder.encode(data)
  126. let result = try await callable.call(encoded)
  127. return try decoder.decode(Response.self, from: result.data)
  128. }
  129. /// Creates a directly callable function.
  130. ///
  131. /// This allows users to call a HTTPS Callable Function like a normal Swift function:
  132. /// ```swift
  133. /// let greeter = functions.httpsCallable("greeter",
  134. /// requestType: GreetingRequest.self,
  135. /// responseType: GreetingResponse.self)
  136. /// let result = try await greeter(data)
  137. /// print(result.greeting)
  138. /// ```
  139. /// You can also call a HTTPS Callable function using the following syntax:
  140. /// ```swift
  141. /// let greeter: Callable<GreetingRequest, GreetingResponse> =
  142. /// functions.httpsCallable("greeter")
  143. /// let result = try await greeter(data)
  144. /// print(result.greeting)
  145. /// ```
  146. /// - Parameters:
  147. /// - data: Parameters to pass to the trigger.
  148. /// - Returns: The decoded `Response` value
  149. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  150. public func callAsFunction(_ data: Request) async throws -> Response {
  151. return try await call(data)
  152. }
  153. #endif
  154. }