Callable+Codable.swift 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  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 information
  47. /// regarding the app instance. To stop this, see `Messaging.deleteData()`. It
  48. /// resumes with a new FCM Token the next time you call this method.
  49. ///
  50. /// - Parameter data: Parameters to pass to the trigger.
  51. /// - Parameter completion: The block to call when the HTTPS request has completed.
  52. public func call(_ data: Request,
  53. completion: @escaping (Result<Response, Error>)
  54. -> Void) {
  55. do {
  56. let encoded = try encoder.encode(data)
  57. callable.call(encoded) { result, error in
  58. do {
  59. if let result = result {
  60. let decoded = try decoder.decode(Response.self, from: result.data)
  61. completion(.success(decoded))
  62. } else if let error = error {
  63. completion(.failure(error))
  64. } else {
  65. completion(.failure(CallableError.internalError))
  66. }
  67. } catch {
  68. completion(.failure(error))
  69. }
  70. }
  71. } catch {
  72. completion(.failure(error))
  73. }
  74. }
  75. /// Creates a directly callable function.
  76. ///
  77. /// This allows users to call a HTTPS Callable Function like a normal Swift function:
  78. /// ```swift
  79. /// let greeter = functions.httpsCallable("greeter",
  80. /// requestType: GreetingRequest.self,
  81. /// responseType: GreetingResponse.self)
  82. /// greeter(data) { result in
  83. /// print(result.greeting)
  84. /// }
  85. /// ```
  86. /// You can also call a HTTPS Callable function using the following syntax:
  87. /// ```swift
  88. /// let greeter: Callable<GreetingRequest, GreetingResponse> = functions.httpsCallable("greeter")
  89. /// greeter(data) { result in
  90. /// print(result.greeting)
  91. /// }
  92. /// ```
  93. /// - Parameters:
  94. /// - data: Parameters to pass to the trigger.
  95. /// - completion: The block to call when the HTTPS request has completed.
  96. public func callAsFunction(_ data: Request,
  97. completion: @escaping (Result<Response, Error>)
  98. -> Void) {
  99. call(data, completion: completion)
  100. }
  101. #if compiler(>=5.5.2) && canImport(_Concurrency)
  102. /// Executes this Callable HTTPS trigger asynchronously.
  103. ///
  104. /// The data passed into the trigger must be of the generic `Request` type:
  105. ///
  106. /// The request to the Cloud Functions backend made by this method automatically includes a
  107. /// FCM token to identify the app instance. If a user is logged in with Firebase
  108. /// Auth, an auth ID token for the user is also automatically included.
  109. ///
  110. /// Firebase Cloud Messaging sends data to the Firebase backend periodically to collect information
  111. /// regarding the app instance. To stop this, see `Messaging.deleteData()`. It
  112. /// resumes with a new FCM Token the next time you call this method.
  113. ///
  114. /// - Parameter data: The `Request` representing the data to pass to the trigger.
  115. /// - Parameter encoder: The encoder instance to use to run the encoding.
  116. /// - Parameter decoder: The decoder instance to use to run the decoding.
  117. ///
  118. /// - Throws: An error if any value throws an error during encoding or decoding.
  119. /// - Throws: An error if the callable fails to complete
  120. ///
  121. /// - Returns: The decoded `Response` value
  122. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  123. public func call(_ data: Request,
  124. encoder: FirebaseDataEncoder = FirebaseDataEncoder(),
  125. decoder: FirebaseDataDecoder =
  126. FirebaseDataDecoder()) async throws -> Response {
  127. let encoded = try encoder.encode(data)
  128. let result = try await callable.call(encoded)
  129. return try decoder.decode(Response.self, from: result.data)
  130. }
  131. /// Creates a directly callable function.
  132. ///
  133. /// This allows users to call a HTTPS Callable Function like a normal Swift function:
  134. /// ```swift
  135. /// let greeter = functions.httpsCallable("greeter",
  136. /// requestType: GreetingRequest.self,
  137. /// responseType: GreetingResponse.self)
  138. /// let result = try await greeter(data)
  139. /// print(result.greeting)
  140. /// ```
  141. /// You can also call a HTTPS Callable function using the following syntax:
  142. /// ```swift
  143. /// let greeter: Callable<GreetingRequest, GreetingResponse> = functions.httpsCallable("greeter")
  144. /// let result = try await greeter(data)
  145. /// print(result.greeting)
  146. /// ```
  147. /// - Parameters:
  148. /// - data: Parameters to pass to the trigger.
  149. /// - Returns: The decoded `Response` value
  150. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  151. public func callAsFunction(_ data: Request) async throws -> Response {
  152. return try await call(data)
  153. }
  154. #endif
  155. }