FIRFunctions.m 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. // Copyright 2017 Google
  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 "FIRFunctions.h"
  15. #import "FIRFunctions+Internal.h"
  16. #import "FIRError.h"
  17. #import "FIRHTTPSCallable+Internal.h"
  18. #import "FIRHTTPSCallable.h"
  19. #import "FUNContext.h"
  20. #import "FUNError.h"
  21. #import "FUNSerializer.h"
  22. #import "FUNUsageValidation.h"
  23. #import "FIRApp.h"
  24. #import "FIRAppInternal.h"
  25. #import "FIROptions.h"
  26. #import "GTMSessionFetcherService.h"
  27. NS_ASSUME_NONNULL_BEGIN
  28. NSString *const kFUNInstanceIDTokenHeader = @"Firebase-Instance-ID-Token";
  29. @interface FIRFunctions () {
  30. // The network client to use for http requests.
  31. GTMSessionFetcherService *_fetcherService;
  32. // The projectID to use for all function references.
  33. FIRApp *_app;
  34. // The region to use for all function references.
  35. NSString *_region;
  36. // A serializer to encode/decode data and return values.
  37. FUNSerializer *_serializer;
  38. // A factory for getting the metadata to include with function calls.
  39. FUNContextProvider *_contextProvider;
  40. // For testing only. If this is set, functions will be called against it instead of Firebase.
  41. NSString *_emulatorOrigin;
  42. }
  43. /**
  44. * Initialize the Cloud Functions client with the given app and region.
  45. * @param app The app for the Firebase project.
  46. * @param region The region for the http trigger, such as "us-central1".
  47. */
  48. - (id)initWithApp:(FIRApp *)app region:(NSString *)region NS_DESIGNATED_INITIALIZER;
  49. @end
  50. @implementation FIRFunctions
  51. + (instancetype)functions {
  52. return [[self alloc] initWithApp:[FIRApp defaultApp] region:@"us-central1"];
  53. }
  54. + (instancetype)functionsForApp:(FIRApp *)app {
  55. return [[self alloc] initWithApp:app region:@"us-central1"];
  56. }
  57. + (instancetype)functionsForRegion:(NSString *)region {
  58. return [[self alloc] initWithApp:[FIRApp defaultApp] region:region];
  59. }
  60. + (instancetype)functionsForApp:(FIRApp *)app region:(NSString *)region {
  61. return [[self alloc] initWithApp:app region:region];
  62. }
  63. - (instancetype)initWithApp:(FIRApp *)app region:(NSString *)region {
  64. self = [super init];
  65. if (self) {
  66. if (!region) {
  67. FUNThrowInvalidArgument(@"FIRFunctions region cannot be nil.");
  68. }
  69. _fetcherService = [[GTMSessionFetcherService alloc] init];
  70. _app = app;
  71. _region = [region copy];
  72. _serializer = [[FUNSerializer alloc] init];
  73. _contextProvider = [[FUNContextProvider alloc] initWithApp:app];
  74. _emulatorOrigin = nil;
  75. }
  76. return self;
  77. }
  78. - (void)useLocalhost {
  79. [self useFunctionsEmulatorOrigin:@"http://localhost:5005"];
  80. }
  81. - (void)useFunctionsEmulatorOrigin:(NSString *)origin {
  82. _emulatorOrigin = origin;
  83. }
  84. - (NSString *)URLWithName:(NSString *)name {
  85. if (!name) {
  86. FUNThrowInvalidArgument(@"FIRFunctions function name cannot be nil.");
  87. }
  88. NSString *projectID = _app.options.projectID;
  89. if (!projectID) {
  90. FUNThrowInvalidArgument(@"FIRFunctions app projectID cannot be nil.");
  91. }
  92. if (_emulatorOrigin) {
  93. return [NSString stringWithFormat:@"%@/%@/%@/%@", _emulatorOrigin, projectID, _region, name];
  94. }
  95. return
  96. [NSString stringWithFormat:@"https://%@-%@.cloudfunctions.net/%@", _region, projectID, name];
  97. }
  98. - (void)callFunction:(NSString *)name
  99. withObject:(nullable id)data
  100. completion:(void (^)(FIRHTTPSCallableResult *_Nullable result,
  101. NSError *_Nullable error))completion {
  102. [_contextProvider getContext:^(FUNContext *_Nullable context, NSError *_Nullable error) {
  103. if (error) {
  104. if (completion) {
  105. completion(nil, error);
  106. }
  107. return;
  108. }
  109. return [self callFunction:name withObject:data context:context completion:completion];
  110. }];
  111. }
  112. - (void)callFunction:(NSString *)name
  113. withObject:(nullable id)data
  114. context:(FUNContext *)context
  115. completion:(void (^)(FIRHTTPSCallableResult *_Nullable result,
  116. NSError *_Nullable error))completion {
  117. GTMSessionFetcher *fetcher = [_fetcherService fetcherWithURLString:[self URLWithName:name]];
  118. NSMutableDictionary *body = [NSMutableDictionary dictionary];
  119. // Encode the data in the body.
  120. if (!data) {
  121. data = [NSNull null];
  122. }
  123. id encoded = [_serializer encode:data];
  124. if (!encoded) {
  125. FUNThrowInvalidArgument(@"FIRFunctions data encoded as nil. This should not happen.");
  126. }
  127. body[@"data"] = encoded;
  128. NSError *error = nil;
  129. NSData *payload = [NSJSONSerialization dataWithJSONObject:body options:0 error:&error];
  130. if (error) {
  131. if (completion) {
  132. dispatch_async(dispatch_get_main_queue(), ^{
  133. completion(nil, error);
  134. });
  135. }
  136. return;
  137. }
  138. fetcher.bodyData = payload;
  139. // Set the headers.
  140. [fetcher setRequestValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
  141. if (context.authToken) {
  142. NSString *value = [NSString stringWithFormat:@"Bearer %@", context.authToken];
  143. [fetcher setRequestValue:value forHTTPHeaderField:@"Authorization"];
  144. }
  145. if (context.instanceIDToken) {
  146. [fetcher setRequestValue:context.instanceIDToken forHTTPHeaderField:kFUNInstanceIDTokenHeader];
  147. }
  148. // Override normal security rules if this is a local test.
  149. if (_emulatorOrigin) {
  150. fetcher.allowLocalhostRequest = YES;
  151. fetcher.allowedInsecureSchemes = @[ @"http" ];
  152. }
  153. FUNSerializer *serializer = _serializer;
  154. [fetcher beginFetchWithCompletionHandler:^(NSData *_Nullable data, NSError *_Nullable error) {
  155. // If there was an HTTP error, convert it to our own error domain.
  156. if (error) {
  157. if ([error.domain isEqualToString:kGTMSessionFetcherStatusDomain]) {
  158. error = FUNErrorForResponse(error.code, data, serializer);
  159. }
  160. } else {
  161. // If there wasn't an HTTP error, see if there was an error in the body.
  162. error = FUNErrorForResponse(200, data, serializer);
  163. }
  164. // If there was an error, report it to the user and stop.
  165. if (error) {
  166. if (completion) {
  167. completion(nil, error);
  168. }
  169. return;
  170. }
  171. id responseJSON = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
  172. if (error) {
  173. if (completion) {
  174. completion(nil, error);
  175. }
  176. return;
  177. }
  178. if (![responseJSON isKindOfClass:[NSDictionary class]]) {
  179. NSDictionary *userInfo = @{NSLocalizedDescriptionKey : @"Response was not a dictionary."};
  180. error = [NSError errorWithDomain:FIRFunctionsErrorDomain
  181. code:FIRFunctionsErrorCodeInternal
  182. userInfo:userInfo];
  183. if (completion) {
  184. completion(nil, error);
  185. }
  186. return;
  187. }
  188. id dataJSON = responseJSON[@"data"];
  189. // TODO(klimt): Allow "result" instead of "data" for now, for backwards compatibility.
  190. if (!dataJSON) {
  191. dataJSON = responseJSON[@"result"];
  192. }
  193. if (!dataJSON) {
  194. NSDictionary *userInfo =
  195. @{NSLocalizedDescriptionKey : @"Response did not include data field."};
  196. error = [NSError errorWithDomain:FIRFunctionsErrorDomain
  197. code:FIRFunctionsErrorCodeInternal
  198. userInfo:userInfo];
  199. if (completion) {
  200. completion(nil, error);
  201. }
  202. return;
  203. }
  204. id resultData = [serializer decode:dataJSON error:&error];
  205. if (error) {
  206. if (completion) {
  207. completion(nil, error);
  208. }
  209. return;
  210. }
  211. id result = [[FIRHTTPSCallableResult alloc] initWithData:resultData];
  212. if (completion) {
  213. // If there's no result field, this will return nil, which is fine.
  214. completion(result, nil);
  215. }
  216. }];
  217. }
  218. - (FIRHTTPSCallable *)HTTPSCallableWithName:(NSString *)name {
  219. return [[FIRHTTPSCallable alloc] initWithFunctions:self name:name];
  220. }
  221. @end
  222. NS_ASSUME_NONNULL_END