GTLRService.h 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879
  1. /* Copyright (c) 2016 Google Inc.
  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. */
  15. // Service object documentation:
  16. // https://github.com/google/google-api-objectivec-client-for-rest/wiki#services-and-tickets
  17. #import <Foundation/Foundation.h>
  18. #import "GTLRDefines.h"
  19. #import "GTLRBatchQuery.h"
  20. #import "GTLRBatchResult.h"
  21. #import "GTLRDateTime.h"
  22. #import "GTLRDuration.h"
  23. #import "GTLRErrorObject.h"
  24. #import "GTLRObject.h"
  25. #import "GTLRQuery.h"
  26. @class GTMSessionFetcher;
  27. @class GTMSessionFetcherService;
  28. @protocol GTMFetcherAuthorizationProtocol;
  29. NS_ASSUME_NONNULL_BEGIN
  30. /**
  31. * The domain used used for NSErrors created by GTLRService query execution.
  32. */
  33. extern NSString *const kGTLRServiceErrorDomain;
  34. typedef NS_ENUM(NSInteger, GTLRServiceError) {
  35. GTLRServiceErrorQueryResultMissing = -3000,
  36. GTLRServiceErrorBatchResponseUnexpected = -3001,
  37. GTLRServiceErrorBatchResponseStatusCode = -3002
  38. };
  39. /**
  40. * The kGTLRServiceErrorDomain userInfo key for the server response body.
  41. */
  42. extern NSString *const kGTLRServiceErrorBodyDataKey;
  43. /**
  44. * The kGTLRServiceErrorDomain userInfo key for the response content ID, if appropriate.
  45. */
  46. extern NSString *const kGTLRServiceErrorContentIDKey;
  47. /**
  48. * The domain used for foundation errors created from GTLRErrorObjects that
  49. * were not originally foundation errors.
  50. */
  51. extern NSString *const kGTLRErrorObjectDomain;
  52. /**
  53. * The userInfo key for a GTLRErrorObject for errors with domain kGTLRErrorObjectDomain
  54. * when the error was created from a structured JSON error response body.
  55. */
  56. extern NSString *const kGTLRStructuredErrorKey;
  57. /**
  58. * A constant ETag for when updating or deleting a single entry, telling
  59. * the server to replace the current value unconditionally.
  60. *
  61. * Do not use this in entries in a batch feed.
  62. */
  63. extern NSString *const kGTLRETagWildcard;
  64. /**
  65. * Notification of a ticket starting. The notification object is the ticket.
  66. * This is posted on the main thread.
  67. *
  68. * Use the stopped notification to log all requests made by the library.
  69. */
  70. extern NSString *const kGTLRServiceTicketStartedNotification;
  71. /**
  72. * Notification of a ticket stopping. The notification object is the ticket.
  73. * This is posted on the main thread.
  74. */
  75. extern NSString *const kGTLRServiceTicketStoppedNotification;
  76. /**
  77. * Notifications when parsing of a server response or entry begins.
  78. * This is posted on the main thread.
  79. */
  80. extern NSString *const kGTLRServiceTicketParsingStartedNotification;
  81. /**
  82. * Notifications when parsing of a server response or entry ends.
  83. * This is posted on the main thread.
  84. */
  85. extern NSString *const kGTLRServiceTicketParsingStoppedNotification;
  86. /**
  87. * The header name used to send an Application's Bundle Identifier.
  88. * For more information on adding API restrictions see the docs:
  89. * https://cloud.google.com/docs/authentication/api-keys#api_key_restrictions
  90. */
  91. extern NSString *const kXIosBundleIdHeader;
  92. @class GTLRServiceTicket;
  93. /**
  94. * Callback block for query execution.
  95. *
  96. * @param callbackTicket The ticket that tracked query execution.
  97. * @param object The result of query execution. This will be derived from
  98. * GTLRObject. The object may be nil for operations such as DELETE which
  99. * do not return an object. The object will be a GTLRBatchResult for
  100. * batch operations, and GTLRDataObject for media downloads.
  101. * @param callbackError If non-nil, the query execution failed. For batch requests,
  102. * this may be nil even if individual queries in the batch have failed.
  103. */
  104. typedef void (^GTLRServiceCompletionHandler)(GTLRServiceTicket *callbackTicket,
  105. id _Nullable object,
  106. NSError * _Nullable callbackError);
  107. /**
  108. * Callback block for upload of query data.
  109. *
  110. * @param progressTicket The ticket that tracks query execution.
  111. * @param totalBytesUploaded Number of bytes uploaded so far.
  112. * @param totalBytesExpectedToUpload Number of bytes expected to be uploaded.
  113. */
  114. typedef void (^GTLRServiceUploadProgressBlock)(GTLRServiceTicket *progressTicket,
  115. unsigned long long totalBytesUploaded,
  116. unsigned long long totalBytesExpectedToUpload);
  117. /**
  118. * Callback block invoked when an eror occurs during query execution.
  119. *
  120. * @param retryTicket The ticket that tracks query execution.
  121. * @param suggestedWillRetry Flag indicating if the library would retry this without a retry block.
  122. * @param fetchError The error that occurred. If the domain is
  123. * kGTMSessionFetcherStatusDomain then the error's code is the server
  124. * response status. Details on the error from the server are available
  125. * in the userInfo via the keys kGTLRStructuredErrorKey and
  126. * NSLocalizedDescriptionKey.
  127. *
  128. * @return YES if the request should be retried.
  129. */
  130. typedef BOOL (^GTLRServiceRetryBlock)(GTLRServiceTicket *retryTicket,
  131. BOOL suggestedWillRetry,
  132. NSError * _Nullable fetchError);
  133. /**
  134. * Block to be invoked by a test block.
  135. *
  136. * @param object The faked object, if any, to be passed to the test code's completion handler.
  137. * @param error The faked error if any, to be passed to the test code's completion handler.
  138. */
  139. typedef void (^GTLRServiceTestResponse)(id _Nullable object, NSError *_Nullable error);
  140. /**
  141. * A test block enables testing of query execution without any network activity.
  142. *
  143. * The test block must finish by calling the response block, passing either an object
  144. * (GTLRObject or GTLRBatchResult) or an NSError.
  145. *
  146. * The query is available to the test block code as testTicket.originalQuery.
  147. *
  148. * Because query execution is asynchronous, the test code must wait for a callback,
  149. * either with GTLRService's waitForTicket:timeout:fetchedObject:error: or with
  150. * XCTestCase's waitForExpectationsWithTimeout:
  151. *
  152. * Example usage is available in GTLRServiceTest.
  153. *
  154. * @param testTicket The ticket that tracks query execution.
  155. * @param testResponse A block that must be invoked by the test block. This may be invoked
  156. * synchronously or asynchornously.
  157. */
  158. typedef void (^GTLRServiceTestBlock)(GTLRServiceTicket *testTicket,
  159. GTLRServiceTestResponse testResponse);
  160. #pragma mark -
  161. /**
  162. * Base class for the service that executes queries and manages tickets.
  163. *
  164. * Client apps will typically use a generated subclass of GTLRService.
  165. */
  166. @interface GTLRService : NSObject
  167. #pragma mark Query Execution
  168. /**
  169. * Executes the supplied query
  170. *
  171. * Success is indicated in the completion handler by a nil error parameter, not by a non-nil
  172. * object parameter.
  173. *
  174. * The callback block is invoked exactly once unless the ticket is cancelled.
  175. * The callback will be called on the service's callback queue.
  176. *
  177. * Various execution parameters will be taken from the service's properties, unless overridden
  178. * in the query's @c executionParameters property.
  179. *
  180. * A query may only be executed a single time. To reuse a query, make a copy before executing
  181. * it.
  182. *
  183. * To get a NSURLRequest that represents the query, use @c -[GTLRService requestForQuery:]
  184. *
  185. * @param query The API query, either a subclass of GTLRQuery, or a GTLRBatchQuery.
  186. * @param handler The execution callback block.
  187. *
  188. * @return A ticket for tracking or canceling query execution.
  189. */
  190. - (GTLRServiceTicket *)executeQuery:(id<GTLRQueryProtocol>)query
  191. completionHandler:(nullable GTLRServiceCompletionHandler)handler;
  192. /**
  193. * Executes the supplied query
  194. *
  195. * The callback is invoked exactly once unless the ticket is cancelled.
  196. * The callback will be called on the service's callbackQueue.
  197. * Various execution parameters will be taken from the service's properties, unless overridden
  198. * in the query's @c executionParameters property.
  199. *
  200. * The selector should have a signature matching:
  201. * @code
  202. * - (void)serviceTicket:(GTLRServiceTicket *)callbackTicket
  203. * finishedWithObject:(GTLRObject *)object
  204. * error:(NSError *)callbackError
  205. * @endcode
  206. *
  207. * @param query The API query, either a subclass of GTLRQuery, or a GTLRBatchQuery.
  208. * @param delegate The object to be with the selector to be invoked upon completion.
  209. * @param finishedSelector The selector to be invoked upon completion.
  210. *
  211. * @return A ticket for tracking or canceling query execution.
  212. */
  213. - (GTLRServiceTicket *)executeQuery:(id<GTLRQueryProtocol>)query
  214. delegate:(nullable id)delegate
  215. didFinishSelector:(nullable SEL)finishedSelector;
  216. /**
  217. * Enable automatic pagination.
  218. *
  219. * A ticket can optionally do a sequence of fetches for queries where repeated requests
  220. * with a @c nextPageToken query parameter is required to retrieve all pages of
  221. * the response collection. The client's callback is invoked only when all items have
  222. * been retrieved, or an error has occurred.
  223. *
  224. * The final object may be a combination of multiple page responses
  225. * so it may not be the same as if all results had been returned in a single
  226. * page. Some fields of the response may reflect only the final page's values.
  227. *
  228. * Automatic page fetches will return an error if more than 25 page fetches are
  229. * required. For debug builds, this will log a warning to the console when more
  230. * than 2 page fetches occur, as a reminder that the query's @c maxResults parameter
  231. * should probably be increased to specify more items returned per page.
  232. *
  233. * Automatic page accumulation is available for query result objects that are derived
  234. * from GTLRCollectionObject.
  235. *
  236. * This may also be specified for a single query in the query's @c executionParameters property.
  237. *
  238. * Default value is NO.
  239. */
  240. @property(nonatomic, assign) BOOL shouldFetchNextPages;
  241. /**
  242. * Some services require a developer key for quotas and limits.
  243. *
  244. * If you have enabled the iOS API Key Restriction, you will want
  245. * to manually set the @c APIKeyRestrictionBundleID property, or
  246. * use -setMainBundleIDRestrictionWithAPIKey: to set your API key
  247. * and set the restriction to the main bundle's bundle id.
  248. */
  249. @property(nonatomic, copy, nullable) NSString *APIKey;
  250. /**
  251. * The Bundle Identifier to use for the API key restriction. This will be
  252. * sent in an X-Ios-Bundle-Identifier header; for more information see
  253. * the API key documentation
  254. * https://cloud.google.com/docs/authentication/api-keys#api_key_restrictions
  255. */
  256. @property(nonatomic, copy, nullable) NSString *APIKeyRestrictionBundleID;
  257. /**
  258. * Helper method to set the @c APIKey to the given value and set the
  259. * @c APIKeyRestrictionBundleID to the main bundle's bundle identifier.
  260. */
  261. - (void)setMainBundleIDRestrictionWithAPIKey:(NSString *)apiKey;
  262. /**
  263. * An authorizer adds user authentication headers to the request as needed.
  264. *
  265. * This may be overridden on individual queries with the @c shouldSkipAuthorization property.
  266. */
  267. @property(nonatomic, retain, nullable) id <GTMFetcherAuthorizationProtocol> authorizer;
  268. /**
  269. * Enable fetcher retry support. See the explanation of retry support in @c GTMSessionFetcher.h
  270. *
  271. * Default value is NO, but retry is also enabled if the retryBlock is not nil.
  272. *
  273. * This may also be specified for a single query in the query's @c executionParameters property.
  274. */
  275. @property(nonatomic, assign, getter=isRetryEnabled) BOOL retryEnabled;
  276. /**
  277. * A retry block may be provided to inspect and change retry criteria.
  278. *
  279. * This may also be specified for a single query in the query's @c executionParameters property.
  280. */
  281. @property(atomic, copy, nullable) GTLRServiceRetryBlock retryBlock;
  282. /**
  283. * The maximum retry interval. Retries occur at increasing intervals, up to the specified maximum.
  284. *
  285. * This may also be specified for a single query in the query's @c executionParameters property.
  286. */
  287. @property(nonatomic, assign) NSTimeInterval maxRetryInterval;
  288. #pragma mark Fetch Object by Resource URL
  289. /**
  290. * Fetch an object given the resource URL. This is appropriate when the object's
  291. * full link is known, such as from a selfLink response property.
  292. *
  293. * @param resourceURL The URL of the object to be fetched.
  294. * @param objectClass The GTLRObject subclass to be instantiated. If nil, the library
  295. * will try to infer the class from the object's "kind" string property.
  296. * @param executionParameters Values to override the service's properties when executing the
  297. * ticket.
  298. * @param handler The execution callback block.
  299. *
  300. * @return A ticket for tracking or canceling query execution.
  301. */
  302. - (GTLRServiceTicket *)fetchObjectWithURL:(NSURL *)resourceURL
  303. objectClass:(nullable Class)objectClass
  304. executionParameters:(nullable GTLRServiceExecutionParameters *)executionParameters
  305. completionHandler:(nullable GTLRServiceCompletionHandler)handler;
  306. #pragma mark Support for Client Tests
  307. /**
  308. * A test block can be provided to test service calls without any network activity.
  309. *
  310. * See the description of @c GTLRServiceTestBlock for additional details.
  311. *
  312. * This may also be specified for a single query in the query's @c executionParameters property.
  313. *
  314. * A service instance for testing can also be created with @c +mockServiceWithFakedObject
  315. */
  316. @property(nonatomic, copy, nullable) GTLRServiceTestBlock testBlock;
  317. #pragma mark Converting a Query to an NSURLRequest
  318. /**
  319. * Creates a NSURLRequest from the query object and from properties on this service
  320. * (additionalHTTPHeaders, additionalURLQueryParameters, APIKey) without executing
  321. * it. This can be useful for using @c GTMSessionFetcher or @c NSURLSession to
  322. * perform the fetch.
  323. *
  324. * For requests to non-public resources, the request will not yet be authorized;
  325. * that can be done using the GTLR service's authorizer. Creating a @c GTMSessionFetcher
  326. * from the GTLRService's @c fetcherService will take care of authorization as well.
  327. *
  328. * This works only for GET queries, and only for an individual query, not a batch query.
  329. *
  330. * @note @c Unlike executeQuery:, requestForQuery: does not release the query's callback blocks.
  331. *
  332. * @param query The query used to create the request.
  333. *
  334. * @return A request suitable for use with @c GTMSessionFetcher or @c NSURLSession
  335. */
  336. - (NSMutableURLRequest *)requestForQuery:(GTLRQuery *)query;
  337. #pragma mark User Properties
  338. /**
  339. * The service properties dictionary is copied to become the initial property dictionary
  340. * for each ticket, augmented by a query's execution parameter's properties.
  341. */
  342. @property(nonatomic, copy, nullable) NSDictionary<NSString *, id> *serviceProperties;
  343. #pragma mark JSON to GTLRObject Mapping
  344. /**
  345. * Specifies subclasses to be created instead of standard library objects, allowing
  346. * an app to add properties and methods to GTLR objects.
  347. *
  348. * This is just a helper method that sets the service's objectClassResolver:.
  349. *
  350. * Example:
  351. * @code
  352. * NSDictionary *surrogates = @{
  353. * [MyDriveFile class] : [GTLRDrive_File_Surrogate class],
  354. * [MyDriveFileList class] : [GTLRDrive_FileList_Surrogate class]
  355. * };
  356. * [service setSurrogates:surrogates];
  357. * @endcode
  358. */
  359. - (void)setSurrogates:(NSDictionary <Class, Class>*)surrogates;
  360. /**
  361. * Used to decide what GTLRObject subclass to make from the received JSON.
  362. *
  363. * This defaults to a resolver that will use any kindStringToClassMap the service
  364. * provides.
  365. *
  366. * To use a standard resolver with a surrogates dictionary, invoke setSurrogates: instead
  367. * of setting this property.
  368. */
  369. @property(nonatomic, strong) id<GTLRObjectClassResolver> objectClassResolver;
  370. /**
  371. * A dictionary mapping "kind" strings to the GTLObject subclasses that should
  372. * be created for JSON with the given kind.
  373. */
  374. + (NSDictionary<NSString *, Class> *)kindStringToClassMap;
  375. #pragma mark Request Settings
  376. /**
  377. * The queue used to invoked callbacks. By default, the main queue is used for callbacks.
  378. */
  379. @property(nonatomic, retain) dispatch_queue_t callbackQueue;
  380. /**
  381. * Allows the application to make non-SSL and localhost requests for testing.
  382. *
  383. * Default value is NO.
  384. */
  385. @property(nonatomic, assign) BOOL allowInsecureQueries;
  386. /**
  387. * The fetcher service creates the fetcher instances for this API service.
  388. *
  389. * Applications may set this to an authorized fetcher service created elsewhere
  390. * in the app, or may take the fetcher service created by this GTLRService and use it
  391. * to create fetchers independent of this service.
  392. */
  393. @property(nonatomic, retain) GTMSessionFetcherService *fetcherService;
  394. #pragma mark Custom User Agents
  395. /**
  396. * Applications needing an additional identifier in the server logs may specify one
  397. * through this property and it will be added to the existing UserAgent. It should
  398. * already be a valid identifier as no cleaning/validation is done.
  399. */
  400. @property(nonatomic, copy, nullable) NSString *userAgentAddition;
  401. /**
  402. * A base user-agent based on the application signature in the Info.plist settings.
  403. *
  404. * Most applications should not explicitly set this property. Any string provided will
  405. * be cleaned of inappropriate characters.
  406. */
  407. @property(nonatomic, copy, nullable) NSString *userAgent;
  408. /**
  409. * The request user agent includes the library and OS version appended to the
  410. * base userAgent, along with the optional addition string.
  411. */
  412. @property(nonatomic, readonly, nullable) NSString *requestUserAgent;
  413. /**
  414. * A precise base userAgent string identifying the application. No cleaning of characters
  415. * is done. Library-specific details will be appended.
  416. *
  417. * @param userAgent A wire-ready user agent string.
  418. */
  419. - (void)setExactUserAgent:(nullable NSString *)userAgent;
  420. /**
  421. * A precise userAgent string to send on requests; no cleaning is done. When
  422. * set, requestUserAgent will be exactly this, no library or system information
  423. * will be auto added.
  424. *
  425. * @param requestUserAgent A wire-ready user agent string.
  426. */
  427. - (void)overrideRequestUserAgent:(nullable NSString *)requestUserAgent;
  428. /**
  429. * Any additional URL query parameters for the queries executed by this service.
  430. *
  431. * Individual queries may have additionalURLQueryParameters specified as well.
  432. */
  433. @property(atomic, copy, nullable) NSDictionary<NSString *, NSString *> *additionalURLQueryParameters;
  434. /**
  435. * Any additional HTTP headers for this queries executed by this service.
  436. *
  437. * Individual queries may have additionalHTTPHeaders specified as well.
  438. */
  439. @property(atomic, copy, nullable) NSDictionary<NSString *, NSString *> *additionalHTTPHeaders;
  440. #pragma mark Request URL Construction
  441. /*
  442. * The URL for where to send a Query is built out of these parts
  443. * ( https://developers.google.com/discovery/v1/using#build-compose ) :
  444. *
  445. * service.rootURLString + service.servicePath + query.pathURITemplate
  446. *
  447. * Note: odds are these both should end in a '/', so make sure any value you
  448. * provide will combine correctly with the above rules.
  449. */
  450. /**
  451. * The scheme and host for the API server. This may be modified to point at a test server.
  452. */
  453. @property(nonatomic, copy) NSString *rootURLString;
  454. /**
  455. * The path for the specific API service instance, relative to the rootURLString.
  456. */
  457. @property(nonatomic, copy) NSString *servicePath;
  458. /**
  459. * A path fragment added in to URLs before "servicePath" to build
  460. * the full URL used for resumable media uploads.
  461. */
  462. @property(nonatomic, copy) NSString *resumableUploadPath;
  463. /**
  464. * A path fragment added in to URLs before "servicePath" to build
  465. * the full URL used for simple and multipart media uploads.
  466. */
  467. @property(nonatomic, copy) NSString *simpleUploadPath;
  468. /**
  469. * A path fragment added in to URLs before "servicePath" to build
  470. * the full URL used for batch requests.
  471. */
  472. @property(nonatomic, copy) NSString *batchPath;
  473. #pragma mark Resumable Uploads
  474. /**
  475. * A block called to track upload progress.
  476. *
  477. * A query's service execution parameters may be used to override this.
  478. */
  479. @property(nonatomic, copy, nullable) GTLRServiceUploadProgressBlock uploadProgressBlock;
  480. /**
  481. * The default chunk size for resumable uploads. This defaults to kGTLRStandardUploadChunkSize
  482. * for service subclasses that support chunked uploads.
  483. */
  484. @property(nonatomic, assign) NSUInteger serviceUploadChunkSize;
  485. /**
  486. * Service subclasses may override this to specify their own default chunk size for
  487. * resumable uploads.
  488. */
  489. + (NSUInteger)defaultServiceUploadChunkSize;
  490. #pragma mark Internal
  491. /////////////////////////////////////////////////////////////////////////////////////////////
  492. //
  493. // Properties below are used by the library and should not typically be set by client apps.
  494. //
  495. /////////////////////////////////////////////////////////////////////////////////////////////
  496. /**
  497. * The queue used for parsing JSON responses.
  498. *
  499. * Applications should typically not change this.
  500. */
  501. @property(nonatomic, retain) dispatch_queue_t parseQueue;
  502. /**
  503. * If this service supports pretty printing the JSON on the wire, these are
  504. * the names of the query params that enable it. If there are any values,
  505. * the library disables pretty printing to save on bandwidth.
  506. *
  507. * Applications should typically not need change this; the ServiceGenerator
  508. * will set this up when generating the custom subclass.
  509. */
  510. @property(nonatomic, strong, nullable) NSArray<NSString *> *prettyPrintQueryParameterNames;
  511. /**
  512. * This indicates if the API requires a "data" JSON element to wrap the payload
  513. * on requests and responses.
  514. *
  515. * Applications should typically not change this.
  516. */
  517. @property(nonatomic, assign, getter=isDataWrapperRequired) BOOL dataWrapperRequired;
  518. @end
  519. @interface GTLRService (TestingSupport)
  520. /**
  521. * Convenience method to create a mock GTLR service just for testing.
  522. *
  523. * Queries executed by this mock service will not perform any network operation,
  524. * but will invoke callbacks and provide the supplied object or error to the
  525. * completion handler.
  526. *
  527. * You can make more customized mocks by setting the test block property of a service
  528. * or a query's execution parameters. The test block can inspect the query as ticket.originalQuery
  529. * to customize test behavior.
  530. *
  531. * See the description of @c GTLRServiceTestBlock for more details on customized testing.
  532. *
  533. * Example usage is in the unit test method @c testService_MockService_Succeeding
  534. *
  535. * @param object An object derived from GTLRObject to be passed to query completion handlers.
  536. * @param error An error to be passed to query completion handlers.
  537. *
  538. * @return A mock instance of the service, suitable for unit testing.
  539. */
  540. + (instancetype)mockServiceWithFakedObject:(nullable id)object
  541. fakedError:(nullable NSError *)error;
  542. /**
  543. * Wait synchronously for fetch to complete (strongly discouraged)
  544. *
  545. * This method is intended for use only in unit tests and command-line tools.
  546. * Unit tests may also use XCTest's waitForExpectationsWithTimeout: instead of
  547. * or after this method.
  548. *
  549. * This method just runs the current event loop until the fetch completes
  550. * or the timout limit is reached. This may discard unexpected events
  551. * that occur while spinning, so it's really not appropriate for use
  552. * in serious applications.
  553. *
  554. * Returns YES if an object was successfully fetched. If the wait
  555. * timed out, returns NO and the returned error is nil.
  556. *
  557. * @param ticket The ticket being executed.
  558. * @param timeoutInSeconds Maximum duration to wait.
  559. *
  560. * @return YES if the ticket completed or was cancelled; NO if the wait timed out.
  561. */
  562. - (BOOL)waitForTicket:(GTLRServiceTicket *)ticket
  563. timeout:(NSTimeInterval)timeoutInSeconds;
  564. @end
  565. #pragma mark -
  566. /**
  567. * Service execution parameters may be set on an individual query
  568. * to alter the service's settings.
  569. */
  570. @interface GTLRServiceExecutionParameters : NSObject<NSCopying>
  571. /**
  572. * Override the service's property @c shouldFetchNextPages for automatic pagination.
  573. *
  574. * A BOOL value should be specified.
  575. */
  576. @property(atomic, strong, nullable) NSNumber *shouldFetchNextPages;
  577. /**
  578. * Override the service's property @c shouldFetchNextPages for enabling automatic retries.
  579. *
  580. * A BOOL value should be specified.
  581. *
  582. * Retry is also enabled if the retryBlock is not nil
  583. */
  584. @property(atomic, strong, nullable, getter=isRetryEnabled) NSNumber *retryEnabled;
  585. /**
  586. * Override the service's property @c retryBlock for customizing automatic retries.
  587. */
  588. @property(atomic, copy, nullable) GTLRServiceRetryBlock retryBlock;
  589. /**
  590. * Override the service's property @c maxRetryInterval for customizing automatic retries.
  591. *
  592. * A NSTimeInterval (double) value should be specified.
  593. */
  594. @property(atomic, strong, nullable) NSNumber *maxRetryInterval;
  595. /**
  596. * Override the service's property @c uploadProgressBlock for monitoring upload progress.
  597. */
  598. @property(atomic, copy, nullable) GTLRServiceUploadProgressBlock uploadProgressBlock;
  599. /**
  600. * Override the service's property @c callbackQueue for invoking callbacks.
  601. */
  602. @property(atomic, retain, nullable) dispatch_queue_t callbackQueue;
  603. /**
  604. * Override the service's property @c testBlock for simulating query execution.
  605. *
  606. * See the description of @c GTLRServiceTestBlock for additional details.
  607. */
  608. @property(atomic, copy, nullable) GTLRServiceTestBlock testBlock;
  609. /**
  610. * Override the service's property @c objectClassResolver for controlling object class selection.
  611. */
  612. @property(atomic, strong, nullable) id<GTLRObjectClassResolver> objectClassResolver;
  613. /**
  614. * The ticket's properties are the service properties, with the execution parameter's
  615. * ticketProperties added (replacing any keys already present from the service.)
  616. */
  617. @property(atomic, copy, nullable) NSDictionary<NSString *, id> *ticketProperties;
  618. /**
  619. * Indicates if any of the execution parameters properties are set.
  620. */
  621. @property(nonatomic, readonly) BOOL hasParameters;
  622. @end
  623. /**
  624. * A ticket tracks the progress of a query being executed.
  625. */
  626. @interface GTLRServiceTicket : NSObject
  627. - (instancetype)init NS_UNAVAILABLE;
  628. /**
  629. * The service that issued this ticket.
  630. *
  631. * This method may be invoked from any thread.
  632. */
  633. @property(atomic, readonly) GTLRService *service;
  634. #pragma mark Execution Control
  635. /**
  636. * Invoking cancelTicket stops the fetch if it is in progress. The query callbacks
  637. * will not be invoked.
  638. *
  639. * This method may be invoked from any thread.
  640. */
  641. - (void)cancelTicket;
  642. /**
  643. * The time the ticket was created.
  644. */
  645. @property(atomic, readonly) NSDate *creationDate;
  646. /**
  647. * Pause the ticket execution. This is valid only for chunked, resumable upload queries.
  648. */
  649. - (void)pauseUpload;
  650. /**
  651. * Resume the ticket execution. This is valid only for chunked, resumable upload queries.
  652. */
  653. - (void)resumeUpload;
  654. /**
  655. * Checks if the ticket execution is paused.
  656. */
  657. @property(nonatomic, readonly, getter=isUploadPaused) BOOL uploadPaused;
  658. /**
  659. * The request being fetched for the query.
  660. */
  661. @property(nonatomic, readonly, nullable) NSURLRequest *fetchRequest;
  662. /**
  663. * The fetcher being used for the query request.
  664. */
  665. @property(atomic, readonly, nullable) GTMSessionFetcher *objectFetcher;
  666. /**
  667. * The queue used for query callbacks.
  668. */
  669. @property(atomic, readonly) dispatch_queue_t callbackQueue;
  670. /**
  671. * The API key used for the query requeat.
  672. */
  673. @property(atomic, readonly, nullable) NSString *APIKey;
  674. /**
  675. * The Bundle Identifier to use for the API key restriciton.
  676. */
  677. @property(atomic, readonly, nullable) NSString *APIKeyRestrictionBundleID;
  678. #pragma mark Status
  679. /**
  680. * The server's response status for the query's fetch, if available.
  681. */
  682. @property(nonatomic, readonly) NSInteger statusCode;
  683. /**
  684. * The error resulting from the query's fetch, if available.
  685. */
  686. @property(nonatomic, readonly, nullable) NSError *fetchError;
  687. /**
  688. * A flag indicating if the query's callbacks have been invoked.
  689. */
  690. @property(nonatomic, readonly) BOOL hasCalledCallback;
  691. /**
  692. * A flag indicating if the query execution was cancelled by the client app.
  693. */
  694. @property(atomic, readonly, getter=isCancelled) BOOL cancelled;
  695. #pragma mark Pagination
  696. /**
  697. * A flag indicating if automatic pagination is enabled for the query.
  698. */
  699. @property(nonatomic, readonly) BOOL shouldFetchNextPages;
  700. /**
  701. * The number of pages fetched, if automatic pagination is enabled for the query and multiple
  702. * pages have been fetched.
  703. */
  704. @property(nonatomic, readonly) NSUInteger pagesFetchedCounter;
  705. #pragma mark User Properties
  706. /**
  707. * Ticket properties a way to pass values via the ticket for the convenience of the client app.
  708. *
  709. * Ticket properties are initialized from serviceProperties and augmented by the ticketProperties
  710. * of the query's execution parameters.
  711. */
  712. @property(nonatomic, readonly, nullable) NSDictionary<NSString *, id> *ticketProperties;
  713. #pragma mark Payload
  714. /**
  715. * The object being uploaded via POST, PUT, or PATCH.
  716. */
  717. @property(nonatomic, readonly, nullable) GTLRObject *postedObject;
  718. /**
  719. * The object downloaded for the query, after parsing.
  720. */
  721. @property(nonatomic, readonly, nullable) GTLRObject *fetchedObject;
  722. /**
  723. * The query currently being fetched by this ticket. This may not be the original query when
  724. * fetching a second or later pages.
  725. */
  726. @property(atomic, readonly, nullable) id<GTLRQueryProtocol> executingQuery;
  727. /**
  728. * The query used to create this ticket
  729. */
  730. @property(atomic, readonly, nullable) id<GTLRQueryProtocol> originalQuery;
  731. /**
  732. * The @c GTLRObjectClassResolver for controlling object class selection.
  733. */
  734. @property(atomic, readonly, strong) id<GTLRObjectClassResolver> objectClassResolver;
  735. /**
  736. * The query from within the ticket's batch request with the given ID.
  737. *
  738. * @param requestID The desired ticket's request ID.
  739. *
  740. * @return The query with the specified ID, if found.
  741. */
  742. - (nullable GTLRQuery *)queryForRequestID:(NSString *)requestID;
  743. @end
  744. /**
  745. * The library doesn't use GTLRObjectCollectionImpl, but it provides a concrete implementation
  746. * so the methods do not cause private method errors in Xcode/AppStore review.
  747. */
  748. @interface GTLRObjectCollectionImpl : GTLRObject
  749. @property(nonatomic, copy) NSString *nextPageToken;
  750. @end
  751. NS_ASSUME_NONNULL_END