FIRFunctions.m 7.9 KB

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